typeload.ml 67 KB

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