typeload.ml 99 KB

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