typeload.ml 68 KB

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