typeload.ml 99 KB

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