typeload.ml 84 KB

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