typeload.ml 88 KB

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