typeload.ml 96 KB

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