2
0

typeload.ml 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260
  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 "Please ensure correct initialization of cascading signatures" 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 ((if get then "get_" else "set_") ^ n)
  457. | "get" when get -> AccCall ("get_" ^ n)
  458. | "set" when not get -> AccCall ("set_" ^ n)
  459. | x when get && x = "get_" ^ n -> AccCall x
  460. | x when not get && x = "set_" ^ n -> AccCall x
  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. (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. match follow (apply_params f1.cf_params (List.map (fun (_,t) -> t) f2.cf_params) t1), follow t2 with
  643. | TFun(a1,_), TFun(a2,_) ->
  644. (try
  645. List.for_all2 (fun (_,_,t1) (_,_,t2) -> type_iseq t1 t2) a1 a2
  646. with | Invalid_argument("List.for_all2") ->
  647. false)
  648. | _ -> assert false
  649. let check_overriding ctx c =
  650. let p = c.cl_pos in
  651. match c.cl_super with
  652. | None ->
  653. (match c.cl_overrides with
  654. | [] -> ()
  655. | i :: _ ->
  656. display_error ctx ("Field " ^ i.cf_name ^ " is declared 'override' but doesn't override any field") p)
  657. | Some (csup,params) ->
  658. PMap.iter (fun i f ->
  659. let check_field f get_super_field is_overload = try
  660. let p = f.cf_pos in
  661. (if is_overload && not (Meta.has Meta.Overload f.cf_meta) then
  662. display_error ctx ("Missing @:overload declaration for field " ^ i) p);
  663. let t, f2 = get_super_field csup i in
  664. (* allow to define fields that are not defined for this platform version in superclass *)
  665. (match f2.cf_kind with
  666. | Var { v_read = AccRequire _ } -> raise Not_found;
  667. | _ -> ());
  668. if ctx.com.config.pf_overload && (Meta.has Meta.Overload f2.cf_meta && not (Meta.has Meta.Overload f.cf_meta)) then
  669. display_error ctx ("Field " ^ i ^ " should be declared with @:overload since it was already declared as @:overload in superclass") p
  670. else if not (List.memq f c.cl_overrides) then
  671. display_error ctx ("Field " ^ i ^ " should be declared with 'override' since it is inherited from superclass") p
  672. else if not f.cf_public && f2.cf_public then
  673. display_error ctx ("Field " ^ i ^ " has less visibility (public/private) than superclass one") p
  674. else (match f.cf_kind, f2.cf_kind with
  675. | _, Method MethInline ->
  676. display_error ctx ("Field " ^ i ^ " is inlined and cannot be overridden") p
  677. | a, b when a = b -> ()
  678. | Method MethInline, Method MethNormal ->
  679. () (* allow to redefine a method as inlined *)
  680. | _ ->
  681. display_error ctx ("Field " ^ i ^ " has different property access than in superclass") p);
  682. try
  683. let t = apply_params csup.cl_types params t in
  684. valid_redefinition ctx f f.cf_type f2 t
  685. with
  686. Unify_error l ->
  687. display_error ctx ("Field " ^ i ^ " overloads parent class with different or incomplete type") p;
  688. display_error ctx (error_msg (Unify l)) p;
  689. with
  690. Not_found ->
  691. if List.memq f c.cl_overrides then
  692. let msg = if is_overload then
  693. ("Field " ^ i ^ " is declared 'override' but no compatible overload was found")
  694. else
  695. ("Field " ^ i ^ " is declared 'override' but doesn't override any field")
  696. in
  697. display_error ctx msg p
  698. in
  699. if ctx.com.config.pf_overload && Meta.has Meta.Overload f.cf_meta then begin
  700. (* check if field with same signature was declared more than once *)
  701. List.iter (fun f2 ->
  702. try
  703. ignore (List.find (fun f3 -> f3 != f2 && same_overload_args f2.cf_type f3.cf_type f2 f3) (f :: f.cf_overloads));
  704. display_error ctx ("Another overloaded field of same signature was already declared : " ^ f2.cf_name) f2.cf_pos
  705. with | Not_found -> ()
  706. ) (f :: f.cf_overloads);
  707. let overloads = get_overloads csup i in
  708. List.iter (fun f ->
  709. (* find the exact field being overridden *)
  710. check_field f (fun csup i ->
  711. List.find (fun (t,f2) ->
  712. same_overload_args f.cf_type (apply_params csup.cl_types params t) f f2
  713. ) overloads
  714. ) true
  715. ) f.cf_overloads
  716. end else
  717. check_field f (fun csup i ->
  718. let _, t, f2 = raw_class_field (fun f -> f.cf_type) csup i in
  719. t, f2) false
  720. ) c.cl_fields
  721. let class_field_no_interf c i =
  722. try
  723. let f = PMap.find i c.cl_fields in
  724. f.cf_type , f
  725. with Not_found ->
  726. match c.cl_super with
  727. | None ->
  728. raise Not_found
  729. | Some (c,tl) ->
  730. (* rec over class_field *)
  731. let _, t , f = raw_class_field (fun f -> f.cf_type) c i in
  732. apply_params c.cl_types tl t , f
  733. let rec check_interface ctx c intf params =
  734. let p = c.cl_pos in
  735. let rec check_field i f =
  736. (if ctx.com.config.pf_overload then
  737. List.iter (function
  738. | f2 when f != f2 ->
  739. check_field i f2
  740. | _ -> ()) f.cf_overloads);
  741. let is_overload = ref false in
  742. try
  743. let t2, f2 = class_field_no_interf c i in
  744. let t2, f2 =
  745. if ctx.com.config.pf_overload && (f2.cf_overloads <> [] || Meta.has Meta.Overload f2.cf_meta) then
  746. let overloads = get_overloads c i in
  747. is_overload := true;
  748. let t = (apply_params intf.cl_types params f.cf_type) in
  749. List.find (fun (t1,f1) -> same_overload_args t t1 f f1) overloads
  750. else
  751. t2, f2
  752. in
  753. ignore(follow f2.cf_type); (* force evaluation *)
  754. let p = (match f2.cf_expr with None -> p | Some e -> e.epos) in
  755. let mkind = function
  756. | MethNormal | MethInline -> 0
  757. | MethDynamic -> 1
  758. | MethMacro -> 2
  759. in
  760. if f.cf_public && not f2.cf_public then
  761. display_error ctx ("Field " ^ i ^ " should be public as requested by " ^ s_type_path intf.cl_path) p
  762. 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
  763. 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
  764. else try
  765. valid_redefinition ctx f2 t2 f (apply_params intf.cl_types params f.cf_type)
  766. with
  767. Unify_error l ->
  768. display_error ctx ("Field " ^ i ^ " has different type than in " ^ s_type_path intf.cl_path) p;
  769. display_error ctx (error_msg (Unify l)) p;
  770. with
  771. | Not_found when not c.cl_interface ->
  772. let msg = if !is_overload then
  773. let ctx = print_context() in
  774. 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
  775. "No suitable overload for " ^ i ^ "( " ^ args ^ " ), as needed by " ^ s_type_path intf.cl_path ^ " was found"
  776. else
  777. ("Field " ^ i ^ " needed by " ^ s_type_path intf.cl_path ^ " is missing")
  778. in
  779. display_error ctx msg p
  780. | Not_found -> ()
  781. in
  782. PMap.iter check_field intf.cl_fields;
  783. List.iter (fun (i2,p2) ->
  784. check_interface ctx c i2 (List.map (apply_params intf.cl_types params) p2)
  785. ) intf.cl_implements
  786. let check_interfaces ctx c =
  787. match c.cl_path with
  788. | "Proxy" :: _ , _ -> ()
  789. | _ ->
  790. List.iter (fun (intf,params) -> check_interface ctx c intf params) c.cl_implements
  791. let rec return_flow ctx e =
  792. let error() = display_error ctx "A return is missing here" e.epos; raise Exit in
  793. let return_flow = return_flow ctx in
  794. match e.eexpr with
  795. | TReturn _ | TThrow _ -> ()
  796. | TParenthesis e ->
  797. return_flow e
  798. | TBlock el ->
  799. let rec loop = function
  800. | [] -> error()
  801. | [e] -> return_flow e
  802. | { eexpr = TReturn _ } :: _ | { eexpr = TThrow _ } :: _ -> ()
  803. | _ :: l -> loop l
  804. in
  805. loop el
  806. | TIf (_,e1,Some e2) ->
  807. return_flow e1;
  808. return_flow e2;
  809. | TSwitch (v,cases,Some e) ->
  810. List.iter (fun (_,e) -> return_flow e) cases;
  811. return_flow e
  812. | TSwitch (e,cases,None) when (match follow e.etype with TEnum _ -> true | _ -> false) ->
  813. List.iter (fun (_,e) -> return_flow e) cases;
  814. | TMatch (_,_,cases,def) ->
  815. List.iter (fun (_,_,e) -> return_flow e) cases;
  816. (match def with None -> () | Some e -> return_flow e)
  817. | TTry (e,cases) ->
  818. return_flow e;
  819. List.iter (fun (_,e) -> return_flow e) cases;
  820. | TWhile({eexpr = (TConst (TBool true))},e,_) ->
  821. (* a special case for "inifite" while loops that have no break *)
  822. let rec loop e = match e.eexpr with
  823. (* ignore nested loops to not accidentally get one of its breaks *)
  824. | TWhile _ | TFor _ -> ()
  825. | TBreak -> error()
  826. | _ -> Type.iter loop e
  827. in
  828. loop e
  829. | _ ->
  830. error()
  831. (* ---------------------------------------------------------------------- *)
  832. (* PASS 1 & 2 : Module and Class Structure *)
  833. let set_heritance ctx c herits p =
  834. let ctx = { ctx with curclass = c; type_params = c.cl_types; } in
  835. let process_meta csup =
  836. List.iter (fun m ->
  837. match m with
  838. | 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;
  839. | Meta.AutoBuild, el, p -> c.cl_meta <- (Meta.Build,el,p) :: m :: c.cl_meta
  840. | _ -> ()
  841. ) csup.cl_meta
  842. in
  843. let has_interf = ref false in
  844. let rec loop = function
  845. | HPrivate | HExtern | HInterface ->
  846. ()
  847. | HExtends t ->
  848. if c.cl_super <> None then error "Cannot extend several classes" p;
  849. let t = load_instance ctx t p false in
  850. (match follow t with
  851. | TInst ({ cl_path = [],"Array" },_)
  852. | TInst ({ cl_path = [],"String" },_)
  853. | TInst ({ cl_path = [],"Date" },_)
  854. | TInst ({ cl_path = [],"Xml" },_) when ((not (platform ctx.com Cpp)) && (match c.cl_path with "mt" :: _ , _ -> false | _ -> true)) ->
  855. error "Cannot extend basic class" p;
  856. | TInst (csup,params) ->
  857. csup.cl_build();
  858. if is_parent c csup then error "Recursive class" p;
  859. process_meta csup;
  860. (* interface extends are listed in cl_implements ! *)
  861. if c.cl_interface then begin
  862. if not csup.cl_interface then error "Cannot extend by using a class" p;
  863. c.cl_implements <- (csup,params) :: c.cl_implements
  864. end else begin
  865. if csup.cl_interface then error "Cannot extend by using an interface" p;
  866. c.cl_super <- Some (csup,params)
  867. end
  868. | _ -> error "Should extend by using a class" p)
  869. | HImplements t ->
  870. let t = load_instance ctx t p false in
  871. (match follow t with
  872. | TInst ({ cl_path = [],"ArrayAccess"; cl_extern = true; },[t]) ->
  873. if c.cl_array_access <> None then error "Duplicate array access" p;
  874. c.cl_array_access <- Some t
  875. | TInst (intf,params) ->
  876. intf.cl_build();
  877. if is_parent c intf then error "Recursive class" p;
  878. if c.cl_interface then error "Interfaces cannot implement another interface (use extends instead)" p;
  879. if not intf.cl_interface then error "You can only implements an interface" p;
  880. process_meta intf;
  881. c.cl_implements <- (intf, params) :: c.cl_implements;
  882. if not !has_interf then begin
  883. delay ctx PForce (fun() -> check_interfaces ctx c);
  884. has_interf := true;
  885. end
  886. | TDynamic t ->
  887. if c.cl_dynamic <> None then error "Cannot have several dynamics" p;
  888. c.cl_dynamic <- Some t
  889. | _ -> error "Should implement by using an interface" p)
  890. in
  891. (*
  892. resolve imports before calling build_inheritance, since it requires full paths.
  893. that means that typedefs are not working, but that's a fair limitation
  894. *)
  895. let rec resolve_imports t =
  896. match t.tpackage with
  897. | _ :: _ -> t
  898. | [] ->
  899. try
  900. let find = List.find (fun lt -> snd (t_path lt) = t.tname) in
  901. let lt = try find ctx.m.curmod.m_types with Not_found -> find ctx.m.module_types in
  902. { t with tpackage = fst (t_path lt) }
  903. with
  904. Not_found -> t
  905. in
  906. let herits = List.map (function
  907. | HExtends t -> HExtends (resolve_imports t)
  908. | HImplements t -> HImplements (resolve_imports t)
  909. | h -> h
  910. ) herits in
  911. List.iter loop (List.filter (ctx.g.do_inherit ctx c p) herits)
  912. let rec type_type_params ctx path get_params p tp =
  913. let n = tp.tp_name in
  914. let c = mk_class ctx.m.curmod (fst path @ [snd path],n) p in
  915. c.cl_types <- List.map (type_type_params ctx c.cl_path get_params p) tp.tp_params;
  916. let t = TInst (c,List.map snd c.cl_types) in
  917. match tp.tp_constraints with
  918. | [] ->
  919. c.cl_kind <- KTypeParameter [];
  920. n, t
  921. | _ ->
  922. let r = exc_protect ctx (fun r ->
  923. r := (fun _ -> error "Recursive constraint parameter is not allowed" p);
  924. let ctx = { ctx with type_params = ctx.type_params @ get_params() } in
  925. let constr = List.map (load_complex_type ctx p) tp.tp_constraints in
  926. List.iter (fun t -> ignore(follow t)) constr; (* force other constraints evaluation to check recursion *)
  927. c.cl_kind <- KTypeParameter constr;
  928. r := (fun _ -> t);
  929. t
  930. ) "constraint" in
  931. delay ctx PForce (fun () -> ignore(!r()));
  932. n, TLazy r
  933. let type_function_params ctx fd fname p =
  934. let params = ref [] in
  935. params := List.map (fun tp ->
  936. type_type_params ctx ([],fname) (fun() -> !params) p tp
  937. ) fd.f_params;
  938. !params
  939. let type_function ctx args ret fmode f p =
  940. let locals = save_locals ctx in
  941. let fargs = List.map (fun (n,c,t) ->
  942. let c = (match c with
  943. | None -> None
  944. | Some e ->
  945. let p = pos e in
  946. let e = ctx.g.do_optimize ctx (type_expr ctx e (WithType t)) in
  947. unify ctx e.etype t p;
  948. match e.eexpr with
  949. | TConst c -> Some c
  950. | _ -> display_error ctx "Parameter default value should be constant" p; None
  951. ) in
  952. add_local ctx n t, c
  953. ) args in
  954. let old_ret = ctx.ret in
  955. let old_fun = ctx.curfun in
  956. let old_opened = ctx.opened in
  957. ctx.curfun <- fmode;
  958. ctx.ret <- ret;
  959. ctx.opened <- [];
  960. let e = type_expr ctx (match f.f_expr with None -> error "Function body required" p | Some e -> e) NoValue in
  961. let rec loop e =
  962. match e.eexpr with
  963. | TReturn (Some _) -> raise Exit
  964. | TFunction _ -> ()
  965. | _ -> Type.iter loop e
  966. in
  967. let have_ret = (try loop e; false with Exit -> true) in
  968. if have_ret then
  969. (try return_flow ctx e with Exit -> ())
  970. else (try type_eq EqStrict ret ctx.t.tvoid with Unify_error _ -> display_error ctx ("Missing return " ^ (s_type (print_context()) ret)) p);
  971. let rec loop e =
  972. match e.eexpr with
  973. | TCall ({ eexpr = TConst TSuper },_) -> raise Exit
  974. | TFunction _ -> ()
  975. | _ -> Type.iter loop e
  976. in
  977. let has_super_constr() =
  978. match ctx.curclass.cl_super with
  979. | None -> false
  980. | Some (csup,_) ->
  981. try ignore(get_constructor (fun f->f.cf_type) csup); true with Not_found -> false
  982. in
  983. if fmode = FunConstructor && has_super_constr() then
  984. (try
  985. loop e;
  986. display_error ctx "Missing super constructor call" p
  987. with
  988. Exit -> ());
  989. locals();
  990. let e = match ctx.curfun, ctx.vthis with
  991. | (FunMember|FunConstructor), Some v ->
  992. let ev = mk (TVars [v,Some (mk (TConst TThis) ctx.tthis p)]) ctx.t.tvoid p in
  993. (match e.eexpr with
  994. | TBlock l -> { e with eexpr = TBlock (ev::l) }
  995. | _ -> mk (TBlock [ev;e]) e.etype p)
  996. | _ -> e
  997. in
  998. List.iter (fun r -> r := Closed) ctx.opened;
  999. ctx.ret <- old_ret;
  1000. ctx.curfun <- old_fun;
  1001. ctx.opened <- old_opened;
  1002. e , fargs
  1003. let init_core_api ctx c =
  1004. let ctx2 = (match ctx.g.core_api with
  1005. | None ->
  1006. let com2 = Common.clone ctx.com in
  1007. com2.defines <- PMap.empty;
  1008. Common.define com2 Define.CoreApi;
  1009. Common.define com2 Define.Sys;
  1010. if ctx.in_macro then Common.define com2 Define.Macro;
  1011. com2.class_path <- ctx.com.std_path;
  1012. let ctx2 = ctx.g.do_create com2 in
  1013. ctx.g.core_api <- Some ctx2;
  1014. ctx2
  1015. | Some c ->
  1016. c
  1017. ) in
  1018. let t = load_instance ctx2 { tpackage = fst c.cl_path; tname = snd c.cl_path; tparams = []; tsub = None; } c.cl_pos true in
  1019. flush_pass ctx2 PFinal "core_final";
  1020. match t with
  1021. | TInst (ccore,_) ->
  1022. (match c.cl_doc with
  1023. | None -> c.cl_doc <- ccore.cl_doc
  1024. | Some _ -> ());
  1025. let compare_fields f f2 =
  1026. let p = (match f2.cf_expr with None -> c.cl_pos | Some e -> e.epos) in
  1027. (try
  1028. type_eq EqCoreType (apply_params ccore.cl_types (List.map snd c.cl_types) f.cf_type) f2.cf_type
  1029. with Unify_error l ->
  1030. display_error ctx ("Field " ^ f.cf_name ^ " has different type than in core type") p;
  1031. display_error ctx (error_msg (Unify l)) p);
  1032. if f2.cf_public <> f.cf_public then error ("Field " ^ f.cf_name ^ " has different visibility than core type") p;
  1033. (match f2.cf_doc with
  1034. | None -> f2.cf_doc <- f.cf_doc
  1035. | Some _ -> ());
  1036. if f2.cf_kind <> f.cf_kind then begin
  1037. match f2.cf_kind, f.cf_kind with
  1038. | Method MethInline, Method MethNormal -> () (* allow to add 'inline' *)
  1039. | Method MethNormal, Method MethInline -> () (* allow to disable 'inline' *)
  1040. | _ ->
  1041. error ("Field " ^ f.cf_name ^ " has different property access than core type") p;
  1042. end;
  1043. (match follow f.cf_type, follow f2.cf_type with
  1044. | TFun (pl1,_), TFun (pl2,_) ->
  1045. if List.length pl1 != List.length pl2 then error "Argument count mismatch" p;
  1046. List.iter2 (fun (n1,_,_) (n2,_,_) ->
  1047. if n1 <> n2 then error ("Method parameter name '" ^ n2 ^ "' should be '" ^ n1 ^ "'") p;
  1048. ) pl1 pl2;
  1049. | _ -> ());
  1050. in
  1051. let check_fields fcore fl =
  1052. PMap.iter (fun i f ->
  1053. if not f.cf_public then () else
  1054. let f2 = try PMap.find f.cf_name fl with Not_found -> error ("Missing field " ^ i ^ " required by core type") c.cl_pos in
  1055. compare_fields f f2;
  1056. ) fcore;
  1057. PMap.iter (fun i f ->
  1058. let p = (match f.cf_expr with None -> c.cl_pos | Some e -> e.epos) in
  1059. 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;
  1060. ) fl;
  1061. in
  1062. check_fields ccore.cl_fields c.cl_fields;
  1063. check_fields ccore.cl_statics c.cl_statics;
  1064. (match ccore.cl_constructor, c.cl_constructor with
  1065. | None, None -> ()
  1066. | Some { cf_public = false }, _ -> ()
  1067. | Some f, Some f2 -> compare_fields f f2
  1068. | None, Some { cf_public = false } -> ()
  1069. | _ -> error "Constructor differs from core type" c.cl_pos)
  1070. | _ -> assert false
  1071. let patch_class ctx c fields =
  1072. let h = (try Some (Hashtbl.find ctx.g.type_patches c.cl_path) with Not_found -> None) in
  1073. match h with
  1074. | None -> fields
  1075. | Some (h,hcl) ->
  1076. c.cl_meta <- c.cl_meta @ hcl.tp_meta;
  1077. let rec loop acc = function
  1078. | [] -> acc
  1079. | f :: l ->
  1080. (* patch arguments types *)
  1081. (match f.cff_kind with
  1082. | FFun ff ->
  1083. let param ((n,opt,t,e) as p) =
  1084. try
  1085. let t2 = (try Hashtbl.find h (("$" ^ f.cff_name ^ "__" ^ n),false) with Not_found -> Hashtbl.find h (("$" ^ n),false)) in
  1086. n, opt, t2.tp_type, e
  1087. with Not_found ->
  1088. p
  1089. in
  1090. f.cff_kind <- FFun { ff with f_args = List.map param ff.f_args }
  1091. | _ -> ());
  1092. (* other patches *)
  1093. match (try Some (Hashtbl.find h (f.cff_name,List.mem AStatic f.cff_access)) with Not_found -> None) with
  1094. | None -> loop (f :: acc) l
  1095. | Some { tp_remove = true } -> loop acc l
  1096. | Some p ->
  1097. f.cff_meta <- f.cff_meta @ p.tp_meta;
  1098. (match p.tp_type with
  1099. | None -> ()
  1100. | Some t ->
  1101. f.cff_kind <- match f.cff_kind with
  1102. | FVar (_,e) -> FVar (Some t,e)
  1103. | FProp (get,set,_,eo) -> FProp (get,set,Some t,eo)
  1104. | FFun f -> FFun { f with f_type = Some t });
  1105. loop (f :: acc) l
  1106. in
  1107. List.rev (loop [] fields)
  1108. let rec string_list_of_expr_path (e,p) =
  1109. match e with
  1110. | EConst (Ident i) -> [i]
  1111. | EField (e,f) -> f :: string_list_of_expr_path e
  1112. | _ -> error "Invalid path" p
  1113. let build_module_def ctx mt meta fvars context_init fbuild =
  1114. let rec loop = function
  1115. | (Meta.Build,args,p) :: l ->
  1116. let epath, el = (match args with
  1117. | [ECall (epath,el),p] -> epath, el
  1118. | _ -> error "Invalid build parameters" p
  1119. ) in
  1120. 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
  1121. if ctx.in_macro then error "You cannot use @:build inside a macro : make sure that your enum is not used in macro" p;
  1122. let old = ctx.g.get_build_infos in
  1123. ctx.g.get_build_infos <- (fun() -> Some (mt, fvars()));
  1124. context_init();
  1125. let r = try apply_macro ctx MBuild s el p with e -> ctx.g.get_build_infos <- old; raise e in
  1126. ctx.g.get_build_infos <- old;
  1127. (match r with
  1128. | None -> error "Build failure" p
  1129. | Some e -> fbuild e; loop l)
  1130. | _ :: l -> loop l
  1131. | [] -> ()
  1132. in
  1133. (* let errors go through to prevent resume if build fails *)
  1134. loop meta
  1135. let init_class ctx c p context_init herits fields =
  1136. let ctx = {
  1137. ctx with
  1138. curclass = c;
  1139. type_params = c.cl_types;
  1140. pass = PBuildClass;
  1141. tthis = (match c.cl_kind with
  1142. | KAbstractImpl a ->
  1143. (match a.a_this with
  1144. | TMono r when !r = None -> TAbstract (a,List.map snd c.cl_types)
  1145. | t -> t)
  1146. | _ -> TInst (c,List.map snd c.cl_types));
  1147. on_error = (fun ctx msg ep ->
  1148. ctx.com.error msg ep;
  1149. (* macros expressions might reference other code, let's recall which class we are actually compiling *)
  1150. if ep.pfile <> c.cl_pos.pfile then ctx.com.error "Defined in this class" c.cl_pos
  1151. );
  1152. } in
  1153. incr stats.s_classes_built;
  1154. let fields = patch_class ctx c fields in
  1155. let fields = ref fields in
  1156. let get_fields() = !fields in
  1157. build_module_def ctx (TClassDecl c) c.cl_meta get_fields context_init (fun (e,p) ->
  1158. match e with
  1159. | EVars [_,Some (CTAnonymous f),None] ->
  1160. List.iter (fun f ->
  1161. if List.mem AMacro f.cff_access then
  1162. (match ctx.g.macros with
  1163. | Some (_,mctx) when Hashtbl.mem mctx.g.types_module c.cl_path ->
  1164. (* assume that if we had already a macro with the same name, it has not been changed during the @:build operation *)
  1165. if not (List.exists (fun f2 -> f2.cff_name = f.cff_name && List.mem AMacro f2.cff_access) (!fields)) then
  1166. error "Class build macro cannot return a macro function when the class has already been compiled into the macro context" p
  1167. | _ -> ())
  1168. ) f;
  1169. fields := f
  1170. | _ -> error "Class build macro must return a single variable with anonymous fields" p
  1171. );
  1172. let fields = !fields in
  1173. let core_api = Meta.has Meta.CoreApi c.cl_meta in
  1174. let is_class_macro = Meta.has Meta.Macro c.cl_meta in
  1175. if is_class_macro then display_error ctx "Macro classes are no longer allowed in haxe 3" p;
  1176. let fields, herits = if is_class_macro && not ctx.in_macro then begin
  1177. c.cl_extern <- true;
  1178. List.filter (fun f -> List.mem AStatic f.cff_access) fields, []
  1179. end else fields, herits in
  1180. if core_api && not ctx.com.display then delay ctx PForce (fun() -> init_core_api ctx c);
  1181. let rec extends_public c =
  1182. Meta.has Meta.PublicFields c.cl_meta ||
  1183. match c.cl_super with
  1184. | None -> false
  1185. | Some (c,_) -> extends_public c
  1186. in
  1187. let extends_public = extends_public c in
  1188. let is_public access parent =
  1189. if List.mem APrivate access then
  1190. false
  1191. else if List.mem APublic access then
  1192. true
  1193. else match parent with
  1194. | Some { cf_public = p } -> p
  1195. | _ -> c.cl_extern || c.cl_interface || extends_public
  1196. in
  1197. let rec get_parent c name =
  1198. match c.cl_super with
  1199. | None -> None
  1200. | Some (csup,_) ->
  1201. try
  1202. Some (PMap.find name csup.cl_fields)
  1203. with
  1204. Not_found -> get_parent csup name
  1205. in
  1206. let type_opt ctx p t =
  1207. match t with
  1208. | None when c.cl_extern || c.cl_interface ->
  1209. display_error ctx "Type required for extern classes and interfaces" p;
  1210. t_dynamic
  1211. | None when core_api ->
  1212. display_error ctx "Type required for core api classes" p;
  1213. t_dynamic
  1214. | _ ->
  1215. load_type_opt ctx p t
  1216. in
  1217. let rec has_field f = function
  1218. | None -> false
  1219. | Some (c,_) ->
  1220. PMap.exists f c.cl_fields || has_field f c.cl_super || List.exists (fun i -> has_field f (Some i)) c.cl_implements
  1221. in
  1222. (match c.cl_super with None -> () | Some _ -> delay ctx PForce (fun() -> check_overriding ctx c));
  1223. (* ----------------------- COMPLETION ----------------------------- *)
  1224. let display_file = if ctx.com.display then Common.unique_full_path p.pfile = (!Parser.resume_display).pfile else false in
  1225. let fields = if not display_file || Common.defined ctx.com Define.NoCOpt then fields else Optimizer.optimize_completion c fields in
  1226. let delayed_expr = ref [] in
  1227. let rec is_full_type t =
  1228. match t with
  1229. | TFun (args,ret) -> is_full_type ret && List.for_all (fun (_,_,t) -> is_full_type t) args
  1230. | TMono r -> (match !r with None -> false | Some t -> is_full_type t)
  1231. | TAbstract _ | TInst _ | TEnum _ | TLazy _ | TDynamic _ | TAnon _ | TType _ -> true
  1232. in
  1233. let bind_type ctx cf r p macro =
  1234. if ctx.com.display then begin
  1235. let cp = !Parser.resume_display in
  1236. if display_file && (cp.pmin = 0 || (p.pmin <= cp.pmin && p.pmax >= cp.pmax)) then begin
  1237. if macro && not ctx.in_macro then
  1238. (* force macro system loading of this class in order to get completion *)
  1239. delay ctx PTypeField (fun() -> ignore(ctx.g.do_macro ctx MExpr c.cl_path cf.cf_name [] p))
  1240. else begin
  1241. cf.cf_type <- TLazy r;
  1242. delayed_expr := (ctx,r) :: !delayed_expr;
  1243. end
  1244. end else begin
  1245. if not (is_full_type cf.cf_type) then cf.cf_type <- TLazy r;
  1246. end
  1247. end else if macro && not ctx.in_macro then
  1248. ()
  1249. else begin
  1250. cf.cf_type <- TLazy r;
  1251. delayed_expr := (ctx,r) :: !delayed_expr;
  1252. end
  1253. in
  1254. let bind_var ctx cf e stat inline =
  1255. let p = cf.cf_pos in
  1256. 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;
  1257. let t = cf.cf_type in
  1258. match e with
  1259. | None -> ()
  1260. | Some e ->
  1261. let r = exc_protect ctx (fun r ->
  1262. if not !return_partial_type then begin
  1263. r := (fun() -> t);
  1264. context_init();
  1265. 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);
  1266. let e = type_var_field ctx t e stat p in
  1267. let e = (match cf.cf_kind with
  1268. | Var v when c.cl_extern || Meta.has Meta.Extern cf.cf_meta ->
  1269. if not stat then begin
  1270. display_error ctx "Extern non-static variables may not be initialized" p;
  1271. e
  1272. end else if v.v_read <> AccInline then begin
  1273. display_error ctx "Extern non-inline variables may not be initialized" p;
  1274. e
  1275. end else begin
  1276. match Optimizer.make_constant_expression ctx e with
  1277. | Some e -> e
  1278. | None -> display_error ctx "Extern variable initialization must be a constant value" p; e
  1279. end
  1280. | Var v when not stat || (v.v_read = AccInline) ->
  1281. 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
  1282. e
  1283. | _ ->
  1284. e
  1285. ) in
  1286. cf.cf_expr <- Some e;
  1287. cf.cf_type <- t;
  1288. end;
  1289. t
  1290. ) "bind_var" in
  1291. bind_type ctx cf r (snd e) false
  1292. in
  1293. (* ----------------------- FIELD INIT ----------------------------- *)
  1294. let loop_cf f =
  1295. let name = f.cff_name in
  1296. let p = f.cff_pos in
  1297. let stat = List.mem AStatic f.cff_access in
  1298. let extern = Meta.has Meta.Extern f.cff_meta || c.cl_extern in
  1299. let allow_inline() =
  1300. match c.cl_kind, f.cff_kind with
  1301. | KAbstractImpl _, _ -> true
  1302. |_, FFun _ -> ctx.g.doinline || extern
  1303. | _ -> true
  1304. in
  1305. let inline = List.mem AInline f.cff_access && allow_inline() in
  1306. let override = List.mem AOverride f.cff_access in
  1307. let is_macro = Meta.has Meta.Macro f.cff_meta in
  1308. if is_macro then ctx.com.warning "@:macro should now be 'macro' accessor'" p;
  1309. let is_macro = is_macro || List.mem AMacro f.cff_access in
  1310. List.iter (fun acc ->
  1311. match (acc, f.cff_kind) with
  1312. | APublic, _ | APrivate, _ | AStatic, _ -> ()
  1313. | ADynamic, FFun _ | AOverride, FFun _ | AMacro, FFun _ | AInline, FFun _ | AInline, FVar _ -> ()
  1314. | _, FVar _ -> error ("Invalid accessor '" ^ Ast.s_access acc ^ "' for variable " ^ name) p
  1315. | _, FProp _ -> error ("Invalid accessor '" ^ Ast.s_access acc ^ "' for property " ^ name) p
  1316. ) f.cff_access;
  1317. if override then (match c.cl_super with None -> error "Invalid override: class has no super class" p | _ -> ());
  1318. (* build the per-field context *)
  1319. let ctx = {
  1320. ctx with
  1321. pass = PBuildClass; (* will be set later to PTypeExpr *)
  1322. } in
  1323. match f.cff_kind with
  1324. | FVar (t,e) ->
  1325. if inline && not stat then error "Inline variable must be static" p;
  1326. if inline && e = None then error "Inline variable must be initialized" p;
  1327. let t = (match t with
  1328. | None when not stat && e = None ->
  1329. error ("Type required for member variable " ^ name) p;
  1330. | None ->
  1331. mk_mono()
  1332. | Some t ->
  1333. let old = ctx.type_params in
  1334. if stat then ctx.type_params <- [];
  1335. let t = load_complex_type ctx p t in
  1336. if stat then ctx.type_params <- old;
  1337. t
  1338. ) in
  1339. let cf = {
  1340. cf_name = name;
  1341. cf_doc = f.cff_doc;
  1342. cf_meta = f.cff_meta;
  1343. cf_type = t;
  1344. cf_pos = f.cff_pos;
  1345. cf_kind = Var (if inline then { v_read = AccInline ; v_write = AccNever } else { v_read = AccNormal; v_write = AccNormal });
  1346. cf_expr = None;
  1347. cf_public = is_public f.cff_access None;
  1348. cf_params = [];
  1349. cf_overloads = [];
  1350. } in
  1351. ctx.curfield <- cf;
  1352. bind_var ctx cf e stat inline;
  1353. f, false, cf
  1354. | FFun fd ->
  1355. let params = type_function_params ctx fd f.cff_name p in
  1356. if inline && c.cl_interface then error "You can't declare inline methods in interfaces" p;
  1357. let is_macro = is_macro || (is_class_macro && stat) in
  1358. let f, stat, fd = if not is_macro || stat then
  1359. f, stat, fd
  1360. else if ctx.in_macro then
  1361. (* non-static macros methods are turned into static when we are running the macro *)
  1362. { f with cff_access = AStatic :: f.cff_access }, true, fd
  1363. else
  1364. (* remove display of first argument which will contain the "this" expression *)
  1365. f, stat, { fd with f_args = match fd.f_args with [] -> [] | _ :: l -> l }
  1366. in
  1367. let fd = if not is_macro then
  1368. fd
  1369. else if ctx.in_macro then
  1370. let texpr = CTPath { tpackage = ["haxe";"macro"]; tname = "Expr"; tparams = []; tsub = None } in
  1371. {
  1372. f_params = fd.f_params;
  1373. f_type = (match fd.f_type with None -> Some texpr | t -> t);
  1374. f_args = List.map (fun (a,o,t,e) -> a,o,(match t with None -> Some texpr | _ -> t),e) fd.f_args;
  1375. f_expr = fd.f_expr;
  1376. }
  1377. else
  1378. let tdyn = Some (CTPath { tpackage = []; tname = "Dynamic"; tparams = []; tsub = None }) in
  1379. let to_dyn = function
  1380. | { tpackage = ["haxe";"macro"]; tname = "Expr"; tsub = Some ("ExprOf"); tparams = [TPType t] } -> Some t
  1381. | { tpackage = []; tname = ("ExprOf"); tsub = None; tparams = [TPType t] } -> Some t
  1382. | { tpackage = ["haxe"]; tname = ("PosInfos"); tsub = None; tparams = [] } -> error "haxe.PosInfos is not allowed on macro functions, use Context.currentPos() instead" p
  1383. | _ -> tdyn
  1384. in
  1385. {
  1386. f_params = fd.f_params;
  1387. f_type = (match fd.f_type with Some (CTPath t) -> to_dyn t | _ -> tdyn);
  1388. f_args = List.map (fun (a,o,t,_) -> a,o,(match t with Some (CTPath t) -> to_dyn t | _ -> tdyn),None) fd.f_args;
  1389. f_expr = None;
  1390. }
  1391. in
  1392. let parent = (if not stat then get_parent c name else None) in
  1393. let dynamic = List.mem ADynamic f.cff_access || (match parent with Some { cf_kind = Method MethDynamic } -> true | _ -> false) in
  1394. if inline && dynamic then error "You can't have both 'inline' and 'dynamic'" p;
  1395. ctx.type_params <- (match c.cl_kind with
  1396. | 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 ->
  1397. params @ a.a_types
  1398. | _ ->
  1399. if stat then params else params @ ctx.type_params);
  1400. let constr = (name = "new") in
  1401. let ret = if constr then ctx.t.tvoid else type_opt ctx p fd.f_type in
  1402. let args = List.map (fun (name,opt,t,c) ->
  1403. let t, c = type_function_param ctx (type_opt ctx p t) c opt p in
  1404. name, c, t
  1405. ) fd.f_args in
  1406. let t = TFun (fun_args args,ret) in
  1407. if constr && c.cl_interface then error "An interface cannot have a constructor" p;
  1408. if c.cl_interface && not stat && fd.f_expr <> None then error "An interface method cannot have a body" p;
  1409. if constr then (match fd.f_type with
  1410. | None | Some (CTPath { tpackage = []; tname = "Void" }) -> ()
  1411. | _ -> error "A class constructor can't have a return value" p
  1412. );
  1413. let cf = {
  1414. cf_name = name;
  1415. cf_doc = f.cff_doc;
  1416. cf_meta = f.cff_meta;
  1417. cf_type = t;
  1418. cf_pos = f.cff_pos;
  1419. cf_kind = Method (if is_macro then MethMacro else if inline then MethInline else if dynamic then MethDynamic else MethNormal);
  1420. cf_expr = None;
  1421. cf_public = is_public f.cff_access parent;
  1422. cf_params = params;
  1423. cf_overloads = [];
  1424. } in
  1425. let do_bind = ref (not (cf.cf_name <> "__init__" && (c.cl_extern && not inline) || c.cl_interface)) in
  1426. (match c.cl_kind with
  1427. | KAbstractImpl a ->
  1428. let m = mk_mono() in
  1429. if Meta.has Meta.From f.cff_meta then begin
  1430. let ta = TAbstract(a, List.map (fun _ -> mk_mono()) a.a_types) in
  1431. if not (type_iseq ret ta) then raise (Error (Unify [Cannot_unify (ret,ta)],p));
  1432. (try unify_raise ctx t (tfun [m] ta) f.cff_pos with Error (Unify l,p) -> error (error_msg (Unify l)) p);
  1433. a.a_from <- (follow m, Some cf) :: a.a_from
  1434. end else if Meta.has Meta.To f.cff_meta then begin
  1435. let ta = monomorphs a.a_types (monomorphs params a.a_this) in
  1436. (try unify_raise ctx t (tfun [ta] m) f.cff_pos with Error (Unify l,p) -> error (error_msg (Unify l)) p);
  1437. if not (Meta.has Meta.Impl cf.cf_meta) then cf.cf_meta <- (Meta.Impl,[],cf.cf_pos) :: cf.cf_meta;
  1438. a.a_to <- (follow m, Some cf) :: a.a_to
  1439. end else if Meta.has Meta.ArrayAccess f.cff_meta then begin
  1440. a.a_array <- cf :: a.a_array;
  1441. end else if f.cff_name = "_new" && Meta.has Meta.MultiType a.a_meta then
  1442. do_bind := false
  1443. else (try match Meta.get Meta.Op cf.cf_meta with
  1444. | _,[EBinop(op,_,_),_],_ ->
  1445. a.a_ops <- (op,cf) :: a.a_ops;
  1446. if fd.f_expr = None then do_bind := false;
  1447. | _,[EUnop(op,flag,_),_],_ ->
  1448. a.a_unops <- (op,flag,cf) :: a.a_unops;
  1449. if fd.f_expr = None then do_bind := false;
  1450. | _ -> ()
  1451. with Not_found -> ())
  1452. | _ ->
  1453. ());
  1454. init_meta_overloads ctx cf;
  1455. ctx.curfield <- cf;
  1456. let r = exc_protect ctx (fun r ->
  1457. if not !return_partial_type then begin
  1458. r := (fun() -> t);
  1459. context_init();
  1460. incr stats.s_methods_typed;
  1461. if ctx.com.verbose then Common.log ctx.com ("Typing " ^ (if ctx.in_macro then "macro " else "") ^ s_type_path c.cl_path ^ "." ^ name);
  1462. let fmode = (match c.cl_kind with
  1463. | KAbstractImpl _ ->
  1464. (match args with
  1465. | ("this",_,_) :: _ -> FunMemberAbstract
  1466. | _ when name = "_new" -> FunMemberAbstract
  1467. | _ -> FunStatic)
  1468. | _ ->
  1469. if constr then FunConstructor else if stat then FunStatic else FunMember
  1470. ) in
  1471. let e , fargs = type_function ctx args ret fmode fd p in
  1472. let f = {
  1473. tf_args = fargs;
  1474. tf_type = ret;
  1475. tf_expr = e;
  1476. } in
  1477. if stat && name = "__init__" then
  1478. (match e.eexpr with
  1479. | TBlock [] | TBlock [{ eexpr = TConst _ }] | TConst _ | TObjectDecl [] -> ()
  1480. | _ -> c.cl_init <- Some e);
  1481. cf.cf_expr <- Some (mk (TFunction f) t p);
  1482. cf.cf_type <- t;
  1483. end;
  1484. t
  1485. ) "type_fun" in
  1486. if !do_bind then bind_type ctx cf r (match fd.f_expr with Some e -> snd e | None -> f.cff_pos) is_macro;
  1487. f, constr, cf
  1488. | FProp (get,set,t,eo) ->
  1489. let ret = (match t, eo with
  1490. | None, None -> error "Property must either define a type or a default value" p;
  1491. | None, _ -> mk_mono()
  1492. | Some t, _ -> load_complex_type ctx p t
  1493. ) in
  1494. let t_get,t_set = match c.cl_kind with
  1495. | KAbstractImpl a ->
  1496. if Meta.has Meta.IsVar f.cff_meta then error "Abstract properties cannot be real variables" f.cff_pos;
  1497. let ta = apply_params a.a_types (List.map snd a.a_types) a.a_this in
  1498. tfun [ta] ret, tfun [ta;ret] ret
  1499. | _ -> tfun [] ret, tfun [ret] ret
  1500. in
  1501. let check_method m t req_name =
  1502. if ctx.com.display then () else
  1503. try
  1504. 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
  1505. (match f.cf_kind with
  1506. | Method MethMacro ->
  1507. display_error ctx "Macro methods cannot be used as property accessor" p;
  1508. display_error ctx "Accessor method is here" f.cf_pos;
  1509. | _ -> ());
  1510. unify_raise ctx t2 t f.cf_pos;
  1511. (match req_name with None -> () | Some n -> display_error ctx ("Please use " ^ n ^ " to name your property access method") f.cf_pos);
  1512. with
  1513. | Error (Unify l,p) -> raise (Error (Stack (Custom ("In method " ^ m ^ " required by property " ^ name),Unify l),p))
  1514. | Not_found ->
  1515. if req_name <> None then display_error ctx "Custom property accessor is no longer supported, please use get/set" p else
  1516. if not (c.cl_interface || c.cl_extern) then display_error ctx ("Method " ^ m ^ " required by property " ^ name ^ " is missing") p
  1517. in
  1518. let get = (match get with
  1519. | "null" -> AccNo
  1520. | "dynamic" -> AccCall ("get_" ^ name)
  1521. | "never" -> AccNever
  1522. | "default" -> AccNormal
  1523. | _ ->
  1524. let get = if get = "get" then "get_" ^ name else get in
  1525. delay ctx PForce (fun() -> check_method get t_get (if get <> "get" && get <> "get_" ^ name then Some ("get_" ^ name) else None));
  1526. AccCall get
  1527. ) in
  1528. let set = (match set with
  1529. | "null" ->
  1530. (* standard flash library read-only variables can't be accessed for writing, even in subclasses *)
  1531. if c.cl_extern && (match c.cl_path with "flash" :: _ , _ -> true | _ -> false) && ctx.com.platform = Flash then
  1532. AccNever
  1533. else
  1534. AccNo
  1535. | "never" -> AccNever
  1536. | "dynamic" -> AccCall ("set_" ^ name)
  1537. | "default" -> AccNormal
  1538. | _ ->
  1539. let set = if set = "set" then "set_" ^ name else set in
  1540. delay ctx PForce (fun() -> check_method set t_set (if set <> "set" && set <> "set_" ^ name then Some ("set_" ^ name) else None));
  1541. AccCall set
  1542. ) in
  1543. if set = AccNormal && (match get with AccCall _ -> true | _ -> false) then error "Unsupported property combination" p;
  1544. let cf = {
  1545. cf_name = name;
  1546. cf_doc = f.cff_doc;
  1547. cf_meta = f.cff_meta;
  1548. cf_pos = f.cff_pos;
  1549. cf_kind = Var { v_read = get; v_write = set };
  1550. cf_expr = None;
  1551. cf_type = ret;
  1552. cf_public = is_public f.cff_access None;
  1553. cf_params = [];
  1554. cf_overloads = [];
  1555. } in
  1556. ctx.curfield <- cf;
  1557. bind_var ctx cf eo stat inline;
  1558. f, false, cf
  1559. in
  1560. let rec check_require = function
  1561. | [] -> None
  1562. | (Meta.Require,conds,_) :: l ->
  1563. let rec loop = function
  1564. | [] -> check_require l
  1565. | [EConst (String _),_] -> check_require l
  1566. | (EConst (Ident i),_) :: l ->
  1567. if not (Common.raw_defined ctx.com i) then
  1568. Some (i,(match List.rev l with (EConst (String msg),_) :: _ -> Some msg | _ -> None))
  1569. else
  1570. loop l
  1571. | _ -> error "Invalid require identifier" p
  1572. in
  1573. loop conds
  1574. | _ :: l ->
  1575. check_require l
  1576. in
  1577. let cl_req = check_require c.cl_meta in
  1578. List.iter (fun f ->
  1579. let p = f.cff_pos in
  1580. try
  1581. let fd , constr, f = loop_cf f in
  1582. let is_static = List.mem AStatic fd.cff_access in
  1583. if (is_static || constr) && c.cl_interface && f.cf_name <> "__init__" then error "You can't declare static fields in interfaces" p;
  1584. let req = check_require fd.cff_meta in
  1585. let req = (match req with None -> if is_static || constr then cl_req else None | _ -> req) in
  1586. (match req with
  1587. | None -> ()
  1588. | Some r -> f.cf_kind <- Var { v_read = AccRequire (fst r, snd r); v_write = AccRequire (fst r, snd r) });
  1589. if constr then begin
  1590. match c.cl_constructor with
  1591. | None ->
  1592. c.cl_constructor <- Some f
  1593. | Some ctor when ctx.com.config.pf_overload ->
  1594. if Meta.has Meta.Overload f.cf_meta && Meta.has Meta.Overload ctor.cf_meta then
  1595. ctor.cf_overloads <- f :: ctor.cf_overloads
  1596. else if Meta.has Meta.Overload f.cf_meta <> Meta.has Meta.Overload ctor.cf_meta then
  1597. 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)
  1598. | Some ctor ->
  1599. display_error ctx "Duplicate constructor" p
  1600. end else if not is_static || f.cf_name <> "__init__" then begin
  1601. 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
  1602. if dup then error ("Same field name can't be use for both static and instance : " ^ f.cf_name) p;
  1603. if List.mem AOverride fd.cff_access then c.cl_overrides <- f :: c.cl_overrides;
  1604. if PMap.mem f.cf_name (if is_static then c.cl_statics else c.cl_fields) then
  1605. if ctx.com.config.pf_overload && Meta.has Meta.Overload f.cf_meta then
  1606. let mainf = PMap.find f.cf_name (if is_static then c.cl_statics else c.cl_fields) in
  1607. (if not (Meta.has Meta.Overload mainf.cf_meta) then display_error ctx ("Overloaded methods must have @:overload metadata") mainf.cf_pos);
  1608. mainf.cf_overloads <- f :: mainf.cf_overloads
  1609. else
  1610. display_error ctx ("Duplicate class field declaration : " ^ f.cf_name) p
  1611. else
  1612. if is_static then begin
  1613. c.cl_statics <- PMap.add f.cf_name f c.cl_statics;
  1614. c.cl_ordered_statics <- f :: c.cl_ordered_statics;
  1615. end else begin
  1616. c.cl_fields <- PMap.add f.cf_name f c.cl_fields;
  1617. c.cl_ordered_fields <- f :: c.cl_ordered_fields;
  1618. end;
  1619. end
  1620. with Error (Custom str,p2) when p = p2 ->
  1621. display_error ctx str p
  1622. ) fields;
  1623. (match c.cl_kind with
  1624. | KAbstractImpl a ->
  1625. a.a_to <- List.rev a.a_to;
  1626. a.a_from <- List.rev a.a_from;
  1627. a.a_ops <- List.rev a.a_ops;
  1628. | _ -> ());
  1629. c.cl_ordered_statics <- List.rev c.cl_ordered_statics;
  1630. c.cl_ordered_fields <- List.rev c.cl_ordered_fields;
  1631. (*
  1632. make sure a default contructor with same access as super one will be added to the class structure at some point.
  1633. *)
  1634. let rec add_constructor c =
  1635. match c.cl_constructor, c.cl_super with
  1636. | None, Some ({ cl_constructor = Some cfsup } as csup,cparams) when not c.cl_extern ->
  1637. let cf = {
  1638. cfsup with
  1639. cf_pos = p;
  1640. cf_meta = [];
  1641. cf_doc = None;
  1642. cf_expr = None;
  1643. } in
  1644. let r = exc_protect ctx (fun r ->
  1645. let t = mk_mono() in
  1646. r := (fun() -> t);
  1647. let ctx = { ctx with
  1648. curfield = cf;
  1649. pass = PTypeField;
  1650. } in
  1651. ignore (follow cfsup.cf_type); (* make sure it's typed *)
  1652. (if ctx.com.config.pf_overload then List.iter (fun cf -> ignore (follow cf.cf_type)) cf.cf_overloads);
  1653. let args = (match cfsup.cf_expr with
  1654. | Some { eexpr = TFunction f } ->
  1655. List.map (fun (v,def) ->
  1656. (*
  1657. let's optimize a bit the output by not always copying the default value
  1658. into the inherited constructor when it's not necessary for the platform
  1659. *)
  1660. match ctx.com.platform, def with
  1661. | _, Some _ when not ctx.com.config.pf_static -> v, (Some TNull)
  1662. | Flash, Some (TString _) -> v, (Some TNull)
  1663. | Cpp, Some (TString _) -> v, def
  1664. | Cpp, Some _ -> { v with v_type = ctx.t.tnull v.v_type }, (Some TNull)
  1665. | _ -> v, def
  1666. ) f.tf_args
  1667. | _ ->
  1668. match follow cfsup.cf_type with
  1669. | 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
  1670. | _ -> assert false
  1671. ) in
  1672. let p = c.cl_pos in
  1673. let vars = List.map (fun (v,def) -> alloc_var v.v_name (apply_params csup.cl_types cparams v.v_type), def) args in
  1674. 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
  1675. let constr = mk (TFunction {
  1676. tf_args = vars;
  1677. tf_type = ctx.t.tvoid;
  1678. tf_expr = super_call;
  1679. }) (TFun (List.map (fun (v,c) -> v.v_name, c <> None, v.v_type) vars,ctx.t.tvoid)) p in
  1680. cf.cf_expr <- Some constr;
  1681. cf.cf_type <- t;
  1682. unify ctx t constr.etype p;
  1683. t
  1684. ) "add_constructor" in
  1685. cf.cf_type <- TLazy r;
  1686. c.cl_constructor <- Some cf;
  1687. delay ctx PForce (fun() -> ignore((!r)()));
  1688. | _ ->
  1689. (* nothing to do *)
  1690. ()
  1691. in
  1692. add_constructor c;
  1693. (* check overloaded constructors *)
  1694. (if ctx.com.config.pf_overload then match c.cl_constructor with
  1695. | Some ctor ->
  1696. List.iter (fun f ->
  1697. try
  1698. (* TODO: consider making a broader check, and treat some types, like TAnon and type parameters as Dynamic *)
  1699. ignore(List.find (fun f2 -> f != f2 && same_overload_args f.cf_type f2.cf_type f f2) (ctor :: ctor.cf_overloads));
  1700. display_error ctx ("Another overloaded field of same signature was already declared : " ^ f.cf_name) f.cf_pos;
  1701. with Not_found -> ()
  1702. ) (ctor :: ctor.cf_overloads)
  1703. | _ -> ());
  1704. (* push delays in reverse order so they will be run in correct order *)
  1705. List.iter (fun (ctx,r) ->
  1706. ctx.pass <- PTypeField;
  1707. delay ctx PTypeField (fun() -> ignore((!r)()))
  1708. ) !delayed_expr
  1709. let resolve_typedef t =
  1710. match t with
  1711. | TClassDecl _ | TEnumDecl _ | TAbstractDecl _ -> t
  1712. | TTypeDecl td ->
  1713. match follow td.t_type with
  1714. | TEnum (e,_) -> TEnumDecl e
  1715. | TInst (c,_) -> TClassDecl c
  1716. | TAbstract (a,_) -> TAbstractDecl a
  1717. | _ -> t
  1718. let add_module ctx m p =
  1719. let decl_type t =
  1720. let t = t_infos t in
  1721. try
  1722. let m2 = Hashtbl.find ctx.g.types_module t.mt_path in
  1723. 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;
  1724. error ("Type name " ^ s_type_path t.mt_path ^ " is redefined from module " ^ s_type_path m2) p
  1725. with
  1726. Not_found ->
  1727. Hashtbl.add ctx.g.types_module t.mt_path m.m_path
  1728. in
  1729. List.iter decl_type m.m_types;
  1730. Hashtbl.add ctx.g.modules m.m_path m
  1731. (*
  1732. In this pass, we can access load and access other modules types, but we cannot follow them or access their structure
  1733. since they have not been setup. We also build a context_init list that will be evaluated the first time we evaluate
  1734. an expression into the context
  1735. *)
  1736. let rec init_module_type ctx context_init do_init (decl,p) =
  1737. let get_type name =
  1738. try List.find (fun t -> snd (t_infos t).mt_path = name) ctx.m.curmod.m_types with Not_found -> assert false
  1739. in
  1740. match decl with
  1741. | EImport (path,mode) ->
  1742. let rec loop acc = function
  1743. | x :: l when is_lower_ident (fst x) -> loop (x::acc) l
  1744. | rest -> List.rev acc, rest
  1745. in
  1746. let pack, rest = loop [] path in
  1747. (match rest with
  1748. | [] ->
  1749. (match mode with
  1750. | IAll ->
  1751. ctx.m.wildcard_packages <- List.map fst pack :: ctx.m.wildcard_packages
  1752. | _ ->
  1753. (match List.rev path with
  1754. | [] -> assert false
  1755. | (_,p) :: _ -> error "Module name must start with an uppercase letter" p))
  1756. | (tname,p2) :: rest ->
  1757. let p1 = (match pack with [] -> p2 | (_,p1) :: _ -> p1) in
  1758. let p = punion p1 p2 in
  1759. let md = ctx.g.do_load_module ctx (List.map fst pack,tname) p in
  1760. let types = md.m_types in
  1761. let no_private t = not (t_infos t).mt_private in
  1762. let chk_private t p = if (t_infos t).mt_private then error "You can't import a private type" p in
  1763. let has_name name t = snd (t_infos t).mt_path = name in
  1764. let get_type tname =
  1765. 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
  1766. chk_private t p;
  1767. t
  1768. in
  1769. let rebind t name =
  1770. let _, _, f = ctx.g.do_build_instance ctx t p in
  1771. (* create a temp private typedef, does not register it in module *)
  1772. TTypeDecl {
  1773. t_path = (fst md.m_path @ ["_" ^ snd md.m_path],name);
  1774. t_module = md;
  1775. t_pos = p;
  1776. t_private = true;
  1777. t_doc = None;
  1778. t_meta = [];
  1779. t_types = (t_infos t).mt_types;
  1780. t_type = f (List.map snd (t_infos t).mt_types);
  1781. }
  1782. in
  1783. let add_static_init t name s =
  1784. let name = (match name with None -> s | Some n -> n) in
  1785. match resolve_typedef t with
  1786. | TClassDecl c ->
  1787. c.cl_build();
  1788. ignore(PMap.find s c.cl_statics);
  1789. ctx.m.module_globals <- PMap.add name (TClassDecl c,s) ctx.m.module_globals
  1790. | TEnumDecl e ->
  1791. ignore(PMap.find s e.e_constrs);
  1792. ctx.m.module_globals <- PMap.add name (TEnumDecl e,s) ctx.m.module_globals
  1793. | _ ->
  1794. raise Not_found
  1795. in
  1796. (match mode with
  1797. | INormal | IAsName _ ->
  1798. let name = (match mode with IAsName n -> Some n | _ -> None) in
  1799. (match rest with
  1800. | [] ->
  1801. (match name with
  1802. | None ->
  1803. ctx.m.module_types <- List.filter no_private types @ ctx.m.module_types
  1804. | Some newname ->
  1805. ctx.m.module_types <- rebind (get_type tname) newname :: ctx.m.module_types);
  1806. | [tsub,p2] ->
  1807. let p = punion p1 p2 in
  1808. (try
  1809. let tsub = List.find (has_name tsub) types in
  1810. chk_private tsub p;
  1811. ctx.m.module_types <- (match name with None -> tsub | Some n -> rebind tsub n) :: ctx.m.module_types
  1812. with Not_found ->
  1813. (* this might be a static property, wait later to check *)
  1814. let tmain = get_type tname in
  1815. context_init := (fun() ->
  1816. try
  1817. add_static_init tmain name tsub
  1818. with Not_found ->
  1819. error (s_type_path (t_infos tmain).mt_path ^ " has no field or subtype " ^ tsub) p
  1820. ) :: !context_init)
  1821. | (tsub,p2) :: (fname,p3) :: rest ->
  1822. (match rest with
  1823. | [] -> ()
  1824. | (n,p) :: _ -> error ("Unexpected " ^ n) p);
  1825. let tsub = get_type tsub in
  1826. context_init := (fun() ->
  1827. try
  1828. add_static_init tsub name fname
  1829. with Not_found ->
  1830. error (s_type_path (t_infos tsub).mt_path ^ " has no field " ^ fname) (punion p p3)
  1831. ) :: !context_init;
  1832. )
  1833. | IAll ->
  1834. let t = (match rest with
  1835. | [] -> get_type tname
  1836. | [tsub,_] -> get_type tsub
  1837. | _ :: (n,p) :: _ -> error ("Unexpected " ^ n) p
  1838. ) in
  1839. context_init := (fun() ->
  1840. match resolve_typedef t with
  1841. | TClassDecl c
  1842. | TAbstractDecl {a_impl = Some c} ->
  1843. c.cl_build();
  1844. PMap.iter (fun _ cf -> ctx.m.module_globals <- PMap.add cf.cf_name (TClassDecl c,cf.cf_name) ctx.m.module_globals) c.cl_statics
  1845. | TEnumDecl e ->
  1846. PMap.iter (fun _ c -> ctx.m.module_globals <- PMap.add c.ef_name (TEnumDecl e,c.ef_name) ctx.m.module_globals) e.e_constrs
  1847. | _ ->
  1848. error "No statics to import from this type" p
  1849. ) :: !context_init
  1850. ))
  1851. | EUsing t ->
  1852. (* do the import first *)
  1853. let types = (match t.tsub with
  1854. | None ->
  1855. let md = ctx.g.do_load_module ctx (t.tpackage,t.tname) p in
  1856. let types = List.filter (fun t -> not (t_infos t).mt_private) md.m_types in
  1857. ctx.m.module_types <- types @ ctx.m.module_types;
  1858. types
  1859. | Some _ ->
  1860. let t = load_type_def ctx p t in
  1861. ctx.m.module_types <- t :: ctx.m.module_types;
  1862. [t]
  1863. ) in
  1864. (* delay the using since we need to resolve typedefs *)
  1865. let filter_classes types =
  1866. let rec loop acc types = match types with
  1867. | td :: l ->
  1868. (match resolve_typedef td with
  1869. | TClassDecl c ->
  1870. loop (c :: acc) l
  1871. | td ->
  1872. loop acc l)
  1873. | [] ->
  1874. acc
  1875. in
  1876. loop [] types
  1877. in
  1878. context_init := (fun() -> ctx.m.module_using <- filter_classes types @ ctx.m.module_using) :: !context_init
  1879. | EClass d ->
  1880. let c = (match get_type d.d_name with TClassDecl c -> c | _ -> assert false) in
  1881. let herits = d.d_flags in
  1882. if Meta.has Meta.Generic c.cl_meta && c.cl_types <> [] then c.cl_kind <- KGeneric;
  1883. if c.cl_path = (["haxe";"macro"],"MacroType") then c.cl_kind <- KMacroType;
  1884. c.cl_extern <- List.mem HExtern herits;
  1885. c.cl_interface <- List.mem HInterface herits;
  1886. let build() =
  1887. c.cl_build <- (fun()->());
  1888. set_heritance ctx c herits p;
  1889. init_class ctx c p do_init d.d_flags d.d_data
  1890. in
  1891. ctx.pass <- PBuildClass;
  1892. ctx.curclass <- c;
  1893. c.cl_build <- make_pass ctx build;
  1894. ctx.pass <- PBuildModule;
  1895. ctx.curclass <- null_class;
  1896. delay ctx PBuildClass (fun() -> c.cl_build());
  1897. | EEnum d ->
  1898. let e = (match get_type d.d_name with TEnumDecl e -> e | _ -> assert false) in
  1899. let ctx = { ctx with type_params = e.e_types } in
  1900. let h = (try Some (Hashtbl.find ctx.g.type_patches e.e_path) with Not_found -> None) in
  1901. (match h with
  1902. | None -> ()
  1903. | Some (h,hcl) ->
  1904. Hashtbl.iter (fun _ _ -> error "Field type patch not supported for enums" e.e_pos) h;
  1905. e.e_meta <- e.e_meta @ hcl.tp_meta);
  1906. let constructs = ref d.d_data in
  1907. let get_constructs() =
  1908. List.map (fun c ->
  1909. {
  1910. cff_name = c.ec_name;
  1911. cff_doc = c.ec_doc;
  1912. cff_meta = c.ec_meta;
  1913. cff_pos = c.ec_pos;
  1914. cff_access = [];
  1915. cff_kind = (match c.ec_args, c.ec_params with
  1916. | [], [] -> FVar (c.ec_type,None)
  1917. | _ -> 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 });
  1918. }
  1919. ) (!constructs)
  1920. in
  1921. let init () = List.iter (fun f -> f()) !context_init in
  1922. build_module_def ctx (TEnumDecl e) e.e_meta get_constructs init (fun (e,p) ->
  1923. match e with
  1924. | EVars [_,Some (CTAnonymous fields),None] ->
  1925. constructs := List.map (fun f ->
  1926. let args, params, t = (match f.cff_kind with
  1927. | FVar (t,None) -> [], [], t
  1928. | FFun { f_params = pl; f_type = t; f_expr = (None|Some (EBlock [],_)); f_args = al } ->
  1929. 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
  1930. al, pl, t
  1931. | _ ->
  1932. error "Invalid enum constructor in @:build result" p
  1933. ) in
  1934. {
  1935. ec_name = f.cff_name;
  1936. ec_doc = f.cff_doc;
  1937. ec_meta = f.cff_meta;
  1938. ec_pos = f.cff_pos;
  1939. ec_args = args;
  1940. ec_params = params;
  1941. ec_type = t;
  1942. }
  1943. ) fields
  1944. | _ -> error "Enum build macro must return a single variable with anonymous object fields" p
  1945. );
  1946. let et = TEnum (e,List.map snd e.e_types) in
  1947. let names = ref [] in
  1948. let index = ref 0 in
  1949. List.iter (fun c ->
  1950. let p = c.ec_pos in
  1951. let params = ref [] in
  1952. params := List.map (fun tp -> type_type_params ctx ([],c.ec_name) (fun() -> !params) c.ec_pos tp) c.ec_params;
  1953. let params = !params in
  1954. let ctx = { ctx with type_params = params @ ctx.type_params } in
  1955. let rt = (match c.ec_type with
  1956. | None -> et
  1957. | Some t ->
  1958. let t = load_complex_type ctx p t in
  1959. (match follow t with
  1960. | TEnum (te,_) when te == e ->
  1961. ()
  1962. | _ ->
  1963. error "Explicit enum type must be of the same enum type" p);
  1964. t
  1965. ) in
  1966. let t = (match c.ec_args with
  1967. | [] -> rt
  1968. | l ->
  1969. let pnames = ref PMap.empty in
  1970. TFun (List.map (fun (s,opt,t) ->
  1971. (match t with CTPath({tpackage=[];tname="Void"}) -> error "Arguments of type Void are not allowed in enum constructors" c.ec_pos | _ -> ());
  1972. if PMap.mem s (!pnames) then error ("Duplicate parameter '" ^ s ^ "' in enum constructor " ^ c.ec_name) p;
  1973. pnames := PMap.add s () (!pnames);
  1974. s, opt, load_type_opt ~opt ctx p (Some t)
  1975. ) l, rt)
  1976. ) in
  1977. if PMap.mem c.ec_name e.e_constrs then error ("Duplicate constructor " ^ c.ec_name) p;
  1978. e.e_constrs <- PMap.add c.ec_name {
  1979. ef_name = c.ec_name;
  1980. ef_type = t;
  1981. ef_pos = p;
  1982. ef_doc = c.ec_doc;
  1983. ef_index = !index;
  1984. ef_params = params;
  1985. ef_meta = c.ec_meta;
  1986. } e.e_constrs;
  1987. incr index;
  1988. names := c.ec_name :: !names;
  1989. ) (!constructs);
  1990. e.e_names <- List.rev !names;
  1991. e.e_extern <- e.e_extern
  1992. | ETypedef d ->
  1993. let t = (match get_type d.d_name with TTypeDecl t -> t | _ -> assert false) in
  1994. let ctx = { ctx with type_params = t.t_types } in
  1995. let tt = load_complex_type ctx p d.d_data in
  1996. (*
  1997. we exceptionnaly allow follow here because we don't care the type we get as long as it's not our own
  1998. *)
  1999. if t.t_type == follow tt then error "Recursive typedef is not allowed" p;
  2000. (match t.t_type with
  2001. | TMono r ->
  2002. (match !r with
  2003. | None -> r := Some tt;
  2004. | Some _ -> assert false);
  2005. | _ -> assert false);
  2006. | EAbstract d ->
  2007. let a = (match get_type d.d_name with TAbstractDecl a -> a | _ -> assert false) in
  2008. let ctx = { ctx with type_params = a.a_types } in
  2009. let is_type = ref false in
  2010. let load_type t =
  2011. let t = load_complex_type ctx p t in
  2012. if not (Meta.has Meta.CoreType a.a_meta) then begin
  2013. if !is_type then begin
  2014. delay ctx PFinal (fun () ->
  2015. (try type_eq EqStrict a.a_this t with Unify_error _ -> error "You can only declare from/to with your underlying type" p)
  2016. );
  2017. end else
  2018. error "Missing underlying type declaration or @:coreType declaration" p;
  2019. end;
  2020. t
  2021. in
  2022. List.iter (function
  2023. | AFromType t -> a.a_from <- (load_type t, None) :: a.a_from
  2024. | AToType t -> a.a_to <- (load_type t, None) :: a.a_to
  2025. | AIsType t ->
  2026. if a.a_impl = None then error "Abstracts with underlying type must have an implementation" a.a_pos;
  2027. let at = load_complex_type ctx p t in
  2028. (match at with TAbstract(a2,_) when a == a2 -> error "Abstract underlying type cannot be recursive" a.a_pos | _ -> ());
  2029. a.a_this <- at;
  2030. is_type := true;
  2031. | APrivAbstract -> ()
  2032. ) d.d_flags;
  2033. if not !is_type && (match a.a_impl with Some _ -> true | None -> not (Meta.has Meta.CoreType a.a_meta)) then
  2034. error "Abstract is missing underlying type declaration" a.a_pos
  2035. let type_module ctx m file tdecls p =
  2036. let m, decls, tdecls = make_module ctx m file tdecls p in
  2037. add_module ctx m p;
  2038. (* define the per-module context for the next pass *)
  2039. let ctx = {
  2040. com = ctx.com;
  2041. g = ctx.g;
  2042. t = ctx.t;
  2043. m = {
  2044. curmod = m;
  2045. module_types = ctx.g.std.m_types;
  2046. module_using = [];
  2047. module_globals = PMap.empty;
  2048. wildcard_packages = [];
  2049. };
  2050. meta = [];
  2051. pass = PBuildModule;
  2052. on_error = (fun ctx msg p -> ctx.com.error msg p);
  2053. macro_depth = ctx.macro_depth;
  2054. curclass = null_class;
  2055. curfield = null_field;
  2056. tthis = ctx.tthis;
  2057. ret = ctx.ret;
  2058. locals = PMap.empty;
  2059. type_params = [];
  2060. curfun = FunStatic;
  2061. untyped = false;
  2062. in_super_call = false;
  2063. in_macro = ctx.in_macro;
  2064. in_display = false;
  2065. in_loop = false;
  2066. opened = [];
  2067. vthis = None;
  2068. } in
  2069. (* here is an additional PASS 1 phase, which define the type parameters for all module types.
  2070. Constraints are handled lazily (no other type is loaded) because they might be recursive anyway *)
  2071. List.iter (fun d ->
  2072. match d with
  2073. | (TClassDecl c, (EClass d, p)) ->
  2074. c.cl_types <- List.map (type_type_params ctx c.cl_path (fun() -> c.cl_types) p) d.d_params;
  2075. | (TEnumDecl e, (EEnum d, p)) ->
  2076. e.e_types <- List.map (type_type_params ctx e.e_path (fun() -> e.e_types) p) d.d_params;
  2077. | (TTypeDecl t, (ETypedef d, p)) ->
  2078. t.t_types <- List.map (type_type_params ctx t.t_path (fun() -> t.t_types) p) d.d_params;
  2079. | (TAbstractDecl a, (EAbstract d, p)) ->
  2080. a.a_types <- List.map (type_type_params ctx a.a_path (fun() -> a.a_types) p) d.d_params;
  2081. | _ ->
  2082. assert false
  2083. ) decls;
  2084. (* setup module types *)
  2085. let context_init = ref [] in
  2086. let do_init() =
  2087. match !context_init with
  2088. | [] -> ()
  2089. | l -> context_init := []; List.iter (fun f -> f()) (List.rev l)
  2090. in
  2091. List.iter (init_module_type ctx context_init do_init) tdecls;
  2092. m
  2093. let resolve_module_file com m remap p =
  2094. let forbid = ref false in
  2095. let file = (match m with
  2096. | [] , name -> name
  2097. | x :: l , name ->
  2098. let x = (try
  2099. match PMap.find x com.package_rules with
  2100. | Forbidden -> forbid := true; x
  2101. | Directory d -> d
  2102. | Remap d -> remap := d :: l; d
  2103. with Not_found -> x
  2104. ) in
  2105. String.concat "/" (x :: l) ^ "/" ^ name
  2106. ) ^ ".hx" in
  2107. let file = Common.find_file com file in
  2108. let file = (match String.lowercase (snd m) with
  2109. | "con" | "aux" | "prn" | "nul" | "com1" | "com2" | "com3" | "lpt1" | "lpt2" | "lpt3" when Sys.os_type = "Win32" ->
  2110. (* these names are reserved by the OS - old DOS legacy, such files cannot be easily created but are reported as visible *)
  2111. if (try (Unix.stat file).Unix.st_size with _ -> 0) > 0 then file else raise Not_found
  2112. | _ -> file
  2113. ) in
  2114. if !forbid then begin
  2115. let _, decls = (!parse_hook) com file p in
  2116. let meta = (match decls with
  2117. | (EClass d,_) :: _ -> d.d_meta
  2118. | (EEnum d,_) :: _ -> d.d_meta
  2119. | (EAbstract d,_) :: _ -> d.d_meta
  2120. | (ETypedef d,_) :: _ -> d.d_meta
  2121. | _ -> []
  2122. ) in
  2123. if not (Meta.has Meta.NoPackageRestrict meta) then begin
  2124. let x = (match fst m with [] -> assert false | x :: _ -> x) in
  2125. raise (Forbid_package ((x,m,p),[],if Common.defined com Define.Macro then "macro" else platform_name com.platform));
  2126. end;
  2127. end;
  2128. file
  2129. let parse_module ctx m p =
  2130. let remap = ref (fst m) in
  2131. let file = resolve_module_file ctx.com m remap p in
  2132. let pack, decls = (!parse_hook) ctx.com file p in
  2133. if pack <> !remap then begin
  2134. let spack m = if m = [] then "<empty>" else String.concat "." m in
  2135. if p == Ast.null_pos then
  2136. display_error ctx ("Invalid commandline class : " ^ s_type_path m ^ " should be " ^ s_type_path (pack,snd m)) p
  2137. else
  2138. display_error ctx ("Invalid package : " ^ spack (fst m) ^ " should be " ^ spack pack) p
  2139. end;
  2140. file, if !remap <> fst m then
  2141. (* build typedefs to redirect to real package *)
  2142. List.rev (List.fold_left (fun acc (t,p) ->
  2143. let build f d =
  2144. let priv = List.mem f d.d_flags in
  2145. (ETypedef {
  2146. d_name = d.d_name;
  2147. d_doc = None;
  2148. d_meta = [];
  2149. d_params = d.d_params;
  2150. d_flags = if priv then [EPrivate] else [];
  2151. d_data = CTPath (if priv then { tpackage = []; tname = "Dynamic"; tparams = []; tsub = None; } else
  2152. {
  2153. tpackage = !remap;
  2154. tname = d.d_name;
  2155. tparams = List.map (fun tp ->
  2156. TPType (CTPath { tpackage = []; tname = tp.tp_name; tparams = []; tsub = None; })
  2157. ) d.d_params;
  2158. tsub = None;
  2159. });
  2160. },p) :: acc
  2161. in
  2162. match t with
  2163. | EClass d -> build HPrivate d
  2164. | EEnum d -> build EPrivate d
  2165. | ETypedef d -> build EPrivate d
  2166. | EAbstract d -> build APrivAbstract d
  2167. | EImport _ | EUsing _ -> acc
  2168. ) [(EImport (List.map (fun s -> s,null_pos) (!remap @ [snd m]),INormal),null_pos)] decls)
  2169. else
  2170. decls
  2171. let load_module ctx m p =
  2172. let m2 = (try
  2173. Hashtbl.find ctx.g.modules m
  2174. with
  2175. Not_found ->
  2176. match !type_module_hook ctx m p with
  2177. | Some m -> m
  2178. | None ->
  2179. let file, decls = (try
  2180. parse_module ctx m p
  2181. with Not_found ->
  2182. let rec loop = function
  2183. | [] ->
  2184. raise (Error (Module_not_found m,p))
  2185. | load :: l ->
  2186. match load m p with
  2187. | None -> loop l
  2188. | Some (file,(_,a)) -> file, a
  2189. in
  2190. loop ctx.com.load_extern_type
  2191. ) in
  2192. try
  2193. type_module ctx m file decls p
  2194. with Forbid_package (inf,pl,pf) when p <> Ast.null_pos ->
  2195. raise (Forbid_package (inf,p::pl,pf))
  2196. ) in
  2197. add_dependency ctx.m.curmod m2;
  2198. if ctx.pass = PTypeField then flush_pass ctx PBuildClass "load_module";
  2199. m2
  2200. ;;
  2201. type_function_params_rec := type_function_params