typeload.ml 69 KB

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