typeload.ml 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  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. let parse_file com file p =
  24. let ch = (try open_in_bin file with _ -> error ("Could not open " ^ file) p) in
  25. let t = Common.timer "parsing" in
  26. Lexer.init file;
  27. incr stats.s_files_parsed;
  28. let data = (try Parser.parse com (Lexing.from_channel ch) with e -> close_in ch; t(); raise e) in
  29. close_in ch;
  30. t();
  31. Common.log com ("Parsed " ^ file);
  32. data
  33. let parse_hook = ref parse_file
  34. let type_module_hook = ref (fun _ _ _ -> None)
  35. let return_partial_type = ref false
  36. let type_function_param ctx t e opt p =
  37. match e with
  38. | None ->
  39. if opt then ctx.t.tnull t, Some (EConst (Ident "null"),p) else t, None
  40. | Some e ->
  41. t, Some e
  42. let type_static_var ctx t e p =
  43. ctx.curfun <- FStatic;
  44. let e = type_expr ctx e true in
  45. unify ctx e.etype t p;
  46. (* specific case for UInt statics *)
  47. match t with
  48. | TType ({ t_path = ([],"UInt") },[]) -> { e with etype = t }
  49. | _ -> e
  50. let apply_macro ctx mode path el p =
  51. let cpath, meth = (match List.rev (ExtString.String.nsplit path ".") with
  52. | meth :: name :: pack -> (List.rev pack,name), meth
  53. | _ -> error "Invalid macro path" p
  54. ) in
  55. ctx.g.do_macro ctx mode cpath meth el p
  56. (** since load_type_def and load_instance are used in PASS2, they should not access the structure of a type **)
  57. (*
  58. load a type or a subtype definition
  59. *)
  60. let rec load_type_def ctx p t =
  61. let no_pack = t.tpackage = [] in
  62. let tname = (match t.tsub with None -> t.tname | Some n -> n) in
  63. try
  64. if t.tsub <> None then raise Not_found;
  65. List.find (fun t2 ->
  66. let tp = t_path t2 in
  67. tp = (t.tpackage,tname) || (no_pack && snd tp = tname)
  68. ) ctx.local_types
  69. with
  70. Not_found ->
  71. let next() =
  72. let t, m = (try
  73. t, ctx.g.do_load_module ctx (t.tpackage,t.tname) p
  74. with Error (Module_not_found _,p2) as e when p == p2 ->
  75. match t.tpackage with
  76. | "std" :: l ->
  77. let t = { t with tpackage = l } in
  78. t, ctx.g.do_load_module ctx (t.tpackage,t.tname) p
  79. | _ -> raise e
  80. ) in
  81. let tpath = (t.tpackage,tname) in
  82. try
  83. List.find (fun t -> not (t_infos t).mt_private && t_path t = tpath) m.m_types
  84. with
  85. Not_found -> raise (Error (Type_not_found (m.m_path,tname),p))
  86. in
  87. let rec loop = function
  88. | [] -> raise Exit
  89. | (_ :: lnext) as l ->
  90. try
  91. load_type_def ctx p { t with tpackage = List.rev l }
  92. with
  93. | Error (Module_not_found _,p2)
  94. | Error (Type_not_found _,p2) when p == p2 -> loop lnext
  95. in
  96. try
  97. if not no_pack then raise Exit;
  98. (match fst ctx.current.m_path with
  99. | [] -> raise Exit
  100. | x :: _ ->
  101. (* this can occur due to haxe remoting : a module can be
  102. already defined in the "js" package and is not allowed
  103. to access the js classes *)
  104. try
  105. (match PMap.find x ctx.com.package_rules with
  106. | Forbidden -> raise Exit
  107. | _ -> ())
  108. with Not_found -> ());
  109. loop (List.rev (fst ctx.current.m_path));
  110. with
  111. Exit -> next()
  112. let check_param_constraints ctx types t pl c p =
  113. List.iter (fun (i,tl) ->
  114. 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
  115. let ti = apply_params types pl ti in
  116. unify ctx t ti p
  117. ) c.cl_implements
  118. (* build an instance from a full type *)
  119. let rec load_instance ctx t p allow_no_params =
  120. try
  121. if t.tpackage <> [] || t.tsub <> None then raise Not_found;
  122. let pt = List.assoc t.tname ctx.type_params in
  123. if t.tparams <> [] then error ("Class type parameter " ^ t.tname ^ " can't have parameters") p;
  124. pt
  125. with Not_found ->
  126. let types , path , f = ctx.g.do_build_instance ctx (load_type_def ctx p t) p in
  127. if allow_no_params && t.tparams = [] then begin
  128. let pl = ref [] in
  129. pl := List.map (fun (name,t) ->
  130. match follow t with
  131. | TInst (c,_) ->
  132. let t = mk_mono() in
  133. if c.cl_implements <> [] then delay ctx (fun() -> check_param_constraints ctx types t (!pl) c p);
  134. t;
  135. | _ -> assert false
  136. ) types;
  137. f (!pl)
  138. end else if path = ([],"Dynamic") then
  139. match t.tparams with
  140. | [] -> t_dynamic
  141. | [TPType t] -> TDynamic (load_complex_type ctx p t)
  142. | _ -> error "Too many parameters for Dynamic" p
  143. else begin
  144. if List.length types <> List.length t.tparams then error ("Invalid number of type parameters for " ^ s_type_path path) p;
  145. let tparams = List.map (fun t ->
  146. match t with
  147. | TPExpr e ->
  148. let name = (match fst e with
  149. | EConst (String s) -> "S" ^ s
  150. | EConst (Int i) -> "I" ^ i
  151. | EConst (Float f) -> "F" ^ f
  152. | _ -> "Expr"
  153. ) in
  154. let c = mk_class null_module ([],name) p in
  155. c.cl_kind <- KExpr e;
  156. TInst (c,[])
  157. | TPType t -> load_complex_type ctx p t
  158. ) t.tparams in
  159. let params = List.map2 (fun t (name,t2) ->
  160. let isconst = (match t with TInst ({ cl_kind = KExpr _ },_) -> true | _ -> false) in
  161. if isconst <> (name = "Const") && t != t_dynamic then error (if isconst then "Constant value unexpected here" else "Constant value excepted as type parameter") p;
  162. match follow t2 with
  163. | TInst ({ cl_implements = [] }, []) ->
  164. t
  165. | TInst (c,[]) ->
  166. let r = exc_protect (fun r ->
  167. r := (fun() -> t);
  168. check_param_constraints ctx types t tparams c p;
  169. t
  170. ) in
  171. delay ctx (fun () -> ignore(!r()));
  172. TLazy r
  173. | _ -> assert false
  174. ) tparams types in
  175. f params
  176. end
  177. (*
  178. build an instance from a complex type
  179. *)
  180. and load_complex_type ctx p t =
  181. match t with
  182. | CTParent t -> load_complex_type ctx p t
  183. | CTPath t -> load_instance ctx t p false
  184. | CTOptional _ -> error "Optional type not allowed here" p
  185. | CTExtend (t,l) ->
  186. (match load_complex_type ctx p (CTAnonymous l) with
  187. | TAnon a ->
  188. let rec loop t =
  189. match follow t with
  190. | TInst (c,tl) ->
  191. let c2 = mk_class null_module (fst c.cl_path,"+" ^ snd c.cl_path) p in
  192. c2.cl_private <- true;
  193. PMap.iter (fun f _ ->
  194. try
  195. ignore(class_field c f);
  196. error ("Cannot redefine field " ^ f) p
  197. with
  198. Not_found -> ()
  199. ) a.a_fields;
  200. (* do NOT tag as extern - for protect *)
  201. c2.cl_kind <- KExtension (c,tl);
  202. c2.cl_super <- Some (c,tl);
  203. c2.cl_fields <- a.a_fields;
  204. TInst (c2,[])
  205. | TMono _ ->
  206. error "Please ensure correct initialization of cascading signatures" p
  207. | TAnon a2 ->
  208. PMap.iter (fun f _ ->
  209. if PMap.mem f a2.a_fields then error ("Cannot redefine field " ^ f) p
  210. ) a.a_fields;
  211. mk_anon (PMap.foldi PMap.add a.a_fields a2.a_fields)
  212. | _ -> error "Cannot only extend classes and anonymous" p
  213. in
  214. loop (load_instance ctx t p false)
  215. | _ -> assert false)
  216. | CTAnonymous l ->
  217. let rec loop acc f =
  218. let n = f.cff_name in
  219. let p = f.cff_pos in
  220. if PMap.mem n acc then error ("Duplicate field declaration : " ^ n) p;
  221. let topt = function
  222. | None -> error ("Explicit type required for field " ^ n) p
  223. | Some t -> load_complex_type ctx p t
  224. in
  225. let no_expr = function
  226. | None -> ()
  227. | Some (_,p) -> error "Expression not allowed here" p
  228. in
  229. let pub = ref true in
  230. let dyn = ref false in
  231. List.iter (fun a ->
  232. match a with
  233. | APublic -> ()
  234. | APrivate -> pub := false;
  235. | ADynamic when (match f.cff_kind with FFun _ -> true | _ -> false) -> dyn := true
  236. | AStatic | AOverride | AInline | ADynamic -> error ("Invalid access " ^ Ast.s_access a) p
  237. ) f.cff_access;
  238. let t , access = (match f.cff_kind with
  239. | FVar (t, e) ->
  240. no_expr e;
  241. topt t, Var { v_read = AccNormal; v_write = AccNormal }
  242. | FFun f ->
  243. if f.f_params <> [] then error "Type parameters are not allowed in structures" p;
  244. no_expr f.f_expr;
  245. let args = List.map (fun (name,o,t,e) -> no_expr e; name, o, topt t) f.f_args in
  246. TFun (args,topt f.f_type), Method (if !dyn then MethDynamic else MethNormal)
  247. | FProp (i1,i2,t,e) ->
  248. no_expr e;
  249. let access m get =
  250. match m with
  251. | "null" -> AccNo
  252. | "never" -> AccNever
  253. | "default" -> AccNormal
  254. | "dynamic" -> AccCall ((if get then "get_" else "set_") ^ n)
  255. | _ -> AccCall m
  256. in
  257. load_complex_type ctx p t, Var { v_read = access i1 true; v_write = access i2 false }
  258. ) in
  259. PMap.add n {
  260. cf_name = n;
  261. cf_type = t;
  262. cf_pos = p;
  263. cf_public = !pub;
  264. cf_kind = access;
  265. cf_params = [];
  266. cf_expr = None;
  267. cf_doc = f.cff_doc;
  268. cf_meta = f.cff_meta;
  269. } acc
  270. in
  271. mk_anon (List.fold_left loop PMap.empty l)
  272. | CTFunction (args,r) ->
  273. match args with
  274. | [CTPath { tpackage = []; tparams = []; tname = "Void" }] ->
  275. TFun ([],load_complex_type ctx p r)
  276. | _ ->
  277. TFun (List.map (fun t ->
  278. let t, opt = (match t with CTOptional t -> t, true | _ -> t,false) in
  279. "",opt,load_complex_type ctx p t
  280. ) args,load_complex_type ctx p r)
  281. let hide_types ctx =
  282. let old_locals = ctx.local_types in
  283. let old_type_params = ctx.type_params in
  284. ctx.local_types <- ctx.g.std.m_types;
  285. ctx.type_params <- [];
  286. (fun() ->
  287. ctx.local_types <- old_locals;
  288. ctx.type_params <- old_type_params;
  289. )
  290. (*
  291. load a type while ignoring the current imports or local types
  292. *)
  293. let load_core_type ctx name =
  294. let show = hide_types ctx in
  295. let t = load_instance ctx { tpackage = []; tname = name; tparams = []; tsub = None; } null_pos false in
  296. show();
  297. t
  298. let t_iterator ctx =
  299. let show = hide_types ctx in
  300. match load_type_def ctx null_pos { tpackage = []; tname = "Iterator"; tparams = []; tsub = None } with
  301. | TTypeDecl t ->
  302. show();
  303. if List.length t.t_types <> 1 then assert false;
  304. let pt = mk_mono() in
  305. apply_params t.t_types [pt] t.t_type, pt
  306. | _ ->
  307. assert false
  308. (*
  309. load either a type t or Null<Unknown> if not defined
  310. *)
  311. let load_type_opt ?(opt=false) ctx p t =
  312. let t = (match t with None -> mk_mono() | Some t -> load_complex_type ctx p t) in
  313. if opt then ctx.t.tnull t else t
  314. (* ---------------------------------------------------------------------- *)
  315. (* Structure check *)
  316. let valid_redefinition ctx f1 t1 f2 t2 =
  317. let valid t1 t2 =
  318. type_eq EqStrict t1 t2;
  319. if is_null t1 <> is_null t2 then raise (Unify_error [Cannot_unify (t1,t2)]);
  320. in
  321. let t1, t2 = (match f1.cf_params, f2.cf_params with
  322. | [], [] -> t1, t2
  323. | l1, l2 when List.length l1 = List.length l2 ->
  324. let monos = List.map (fun _ -> mk_mono()) l1 in
  325. apply_params l1 monos t1, apply_params l2 monos t2
  326. | _ -> t1, t2
  327. ) in
  328. match follow t1, follow t2 with
  329. | TFun (args1,r1) , TFun (args2,r2) when List.length args1 = List.length args2 ->
  330. List.iter2 (fun (n,o1,a1) (_,o2,a2) ->
  331. if o1 <> o2 then raise (Unify_error [Not_matching_optional n]);
  332. valid a1 a2;
  333. ) args1 args2;
  334. valid r1 r2;
  335. | _ , _ ->
  336. (* in case args differs, or if an interface var *)
  337. valid t1 t2
  338. let check_overriding ctx c p () =
  339. match c.cl_super with
  340. | None ->
  341. (match c.cl_overrides with
  342. | [] -> ()
  343. | i :: _ ->
  344. display_error ctx ("Field " ^ i ^ " is declared 'override' but doesn't override any field") p)
  345. | Some (csup,params) ->
  346. PMap.iter (fun i f ->
  347. try
  348. let t , f2 = raw_class_field (fun f -> f.cf_type) csup i in
  349. (* allow to define fields that are not defined for this platform version in superclass *)
  350. (match f2.cf_kind with
  351. | Var { v_read = AccRequire _ } -> raise Not_found;
  352. | _ -> ());
  353. ignore(follow f.cf_type); (* force evaluation *)
  354. let p = (match f.cf_expr with None -> p | Some e -> e.epos) in
  355. if not (List.mem i c.cl_overrides) then
  356. display_error ctx ("Field " ^ i ^ " should be declared with 'override' since it is inherited from superclass") p
  357. else if f.cf_public <> f2.cf_public then
  358. display_error ctx ("Field " ^ i ^ " has different visibility (public/private) than superclass one") p
  359. else (match f.cf_kind, f2.cf_kind with
  360. | _, Method MethInline ->
  361. display_error ctx ("Field " ^ i ^ " is inlined and cannot be overridden") p
  362. | a, b when a = b -> ()
  363. | Method MethInline, Method MethNormal ->
  364. () (* allow to redefine a method as inlined *)
  365. | _ ->
  366. display_error ctx ("Field " ^ i ^ " has different property access than in superclass") p);
  367. try
  368. let t = apply_params csup.cl_types params t in
  369. valid_redefinition ctx f f.cf_type f2 t
  370. with
  371. Unify_error l ->
  372. display_error ctx ("Field " ^ i ^ " overload parent class with different or incomplete type") p;
  373. display_error ctx (error_msg (Unify l)) p;
  374. with
  375. Not_found ->
  376. if List.mem i c.cl_overrides then display_error ctx ("Field " ^ i ^ " is declared 'override' but doesn't override any field") p
  377. ) c.cl_fields
  378. let class_field_no_interf c i =
  379. try
  380. let f = PMap.find i c.cl_fields in
  381. f.cf_type , f
  382. with Not_found ->
  383. match c.cl_super with
  384. | None ->
  385. raise Not_found
  386. | Some (c,tl) ->
  387. (* rec over class_field *)
  388. let t , f = raw_class_field (fun f -> f.cf_type) c i in
  389. apply_params c.cl_types tl t , f
  390. let rec check_interface ctx c p intf params =
  391. PMap.iter (fun i f ->
  392. try
  393. let t2, f2 = class_field_no_interf c i in
  394. ignore(follow f2.cf_type); (* force evaluation *)
  395. let p = (match f2.cf_expr with None -> p | Some e -> e.epos) in
  396. let mkind = function
  397. | MethNormal | MethInline -> 0
  398. | MethDynamic -> 1
  399. | MethMacro -> 2
  400. in
  401. if f.cf_public && not f2.cf_public then
  402. display_error ctx ("Field " ^ i ^ " should be public as requested by " ^ s_type_path intf.cl_path) p
  403. 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
  404. 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
  405. else try
  406. valid_redefinition ctx f2 t2 f (apply_params intf.cl_types params f.cf_type)
  407. with
  408. Unify_error l ->
  409. display_error ctx ("Field " ^ i ^ " has different type than in " ^ s_type_path intf.cl_path) p;
  410. display_error ctx (error_msg (Unify l)) p;
  411. with
  412. Not_found ->
  413. if not c.cl_interface then display_error ctx ("Field " ^ i ^ " needed by " ^ s_type_path intf.cl_path ^ " is missing") p
  414. ) intf.cl_fields;
  415. List.iter (fun (i2,p2) ->
  416. check_interface ctx c p i2 (List.map (apply_params intf.cl_types params) p2)
  417. ) intf.cl_implements
  418. let check_interfaces ctx c p () =
  419. match c.cl_path with
  420. | "Proxy" :: _ , _ -> ()
  421. | _ ->
  422. List.iter (fun (intf,params) -> check_interface ctx c p intf params) c.cl_implements
  423. let rec return_flow ctx e =
  424. let error() = display_error ctx "A return is missing here" e.epos; raise Exit in
  425. let return_flow = return_flow ctx in
  426. match e.eexpr with
  427. | TReturn _ | TThrow _ -> ()
  428. | TParenthesis e ->
  429. return_flow e
  430. | TBlock el ->
  431. let rec loop = function
  432. | [] -> error()
  433. | [e] -> return_flow e
  434. | { eexpr = TReturn _ } :: _ | { eexpr = TThrow _ } :: _ -> ()
  435. | _ :: l -> loop l
  436. in
  437. loop el
  438. | TIf (_,e1,Some e2) ->
  439. return_flow e1;
  440. return_flow e2;
  441. | TSwitch (v,cases,Some e) ->
  442. List.iter (fun (_,e) -> return_flow e) cases;
  443. return_flow e
  444. | TSwitch (e,cases,None) when (match follow e.etype with TEnum _ -> true | _ -> false) ->
  445. List.iter (fun (_,e) -> return_flow e) cases;
  446. | TMatch (_,_,cases,def) ->
  447. List.iter (fun (_,_,e) -> return_flow e) cases;
  448. (match def with None -> () | Some e -> return_flow e)
  449. | TTry (e,cases) ->
  450. return_flow e;
  451. List.iter (fun (_,e) -> return_flow e) cases;
  452. | _ ->
  453. error()
  454. (* ---------------------------------------------------------------------- *)
  455. (* PASS 1 & 2 : Module and Class Structure *)
  456. let set_heritance ctx c herits p =
  457. let process_meta csup =
  458. List.iter (fun m ->
  459. match m with
  460. | ":final", _, _ -> if not (Type.has_meta ":hack" c.cl_meta) then error "Cannot extend a final class" p;
  461. | ":autoBuild", el, p -> c.cl_meta <- (":build",el,p) :: m :: c.cl_meta;
  462. | _ -> ()
  463. ) csup.cl_meta
  464. in
  465. let rec loop = function
  466. | HPrivate | HExtern | HInterface ->
  467. ()
  468. | HExtends t ->
  469. if c.cl_super <> None then error "Cannot extend several classes" p;
  470. let t = load_instance ctx t p false in
  471. (match follow t with
  472. | TInst ({ cl_path = [],"Array" },_)
  473. | TInst ({ cl_path = [],"String" },_)
  474. | TInst ({ cl_path = [],"Date" },_)
  475. | TInst ({ cl_path = [],"Xml" },_) when ((not (platform ctx.com Cpp)) && (match c.cl_path with "mt" :: _ , _ -> false | _ -> true)) ->
  476. error "Cannot extend basic class" p;
  477. | TInst (csup,params) ->
  478. if is_parent c csup then error "Recursive class" p;
  479. if c.cl_interface then error "Cannot extend an interface" p;
  480. if csup.cl_interface then error "Cannot extend by using an interface" p;
  481. process_meta csup;
  482. c.cl_super <- Some (csup,params)
  483. | _ -> error "Should extend by using a class" p)
  484. | HImplements t ->
  485. let t = load_instance ctx t p false in
  486. (match follow t with
  487. | TInst ({ cl_path = [],"ArrayAccess"; cl_extern = true; },[t]) ->
  488. if c.cl_array_access <> None then error "Duplicate array access" p;
  489. c.cl_array_access <- Some t
  490. | TInst (intf,params) ->
  491. if is_parent c intf then error "Recursive class" p;
  492. process_meta intf;
  493. c.cl_implements <- (intf, params) :: c.cl_implements
  494. | TDynamic t ->
  495. if c.cl_dynamic <> None then error "Cannot have several dynamics" p;
  496. c.cl_dynamic <- Some t
  497. | _ -> error "Should implement by using an interface or a class" p)
  498. in
  499. (*
  500. resolve imports before calling build_inheritance, since it requires full paths.
  501. that means that typedefs are not working, but that's a fair limitation
  502. *)
  503. let rec resolve_imports t =
  504. match t.tpackage with
  505. | _ :: _ -> t
  506. | [] ->
  507. try
  508. let lt = List.find (fun lt -> snd (t_path lt) = t.tname) ctx.local_types in
  509. { t with tpackage = fst (t_path lt) }
  510. with
  511. Not_found -> t
  512. in
  513. let herits = List.map (function
  514. | HExtends t -> HExtends (resolve_imports t)
  515. | HImplements t -> HImplements (resolve_imports t)
  516. | h -> h
  517. ) herits in
  518. List.iter loop (List.filter (ctx.g.do_inherit ctx c p) herits)
  519. let type_type_params ctx path get_params p (n,flags) =
  520. let c = mk_class ctx.current (fst path @ [snd path],n) p in
  521. c.cl_kind <- KTypeParameter;
  522. let t = TInst (c,[]) in
  523. match flags with
  524. | [] -> n, t
  525. | _ ->
  526. let r = exc_protect (fun r ->
  527. r := (fun _ -> t);
  528. let ctx = { ctx with type_params = ctx.type_params @ get_params() } in
  529. set_heritance ctx c (List.map (fun t -> match t with CTPath t -> HImplements t | _ -> error "Unsupported type constraint" p) flags) p;
  530. t
  531. ) in
  532. delay ctx (fun () -> ignore(!r()));
  533. n, TLazy r
  534. let type_function ctx args ret fmode f p =
  535. let locals = save_locals ctx in
  536. let fargs = List.map (fun (n,c,t) ->
  537. let c = (match c with
  538. | None -> None
  539. | Some e ->
  540. let p = pos e in
  541. let e = ctx.g.do_optimize ctx (type_expr ctx e true) in
  542. unify ctx e.etype t p;
  543. match e.eexpr with
  544. | TConst c -> Some c
  545. | _ -> display_error ctx "Parameter default value should be constant" p; None
  546. ) in
  547. add_local ctx n t, c
  548. ) args in
  549. let old_ret = ctx.ret in
  550. let old_fun = ctx.curfun in
  551. let old_opened = ctx.opened in
  552. ctx.curfun <- fmode;
  553. ctx.ret <- ret;
  554. ctx.opened <- [];
  555. let e = type_expr ctx (match f.f_expr with None -> error "Function body required" p | Some e -> e) false in
  556. let rec loop e =
  557. match e.eexpr with
  558. | TReturn (Some _) -> raise Exit
  559. | TFunction _ -> ()
  560. | _ -> Type.iter loop e
  561. in
  562. let have_ret = (try loop e; false with Exit -> true) in
  563. if have_ret then
  564. (try return_flow ctx e with Exit -> ())
  565. else
  566. unify ctx ret ctx.t.tvoid p;
  567. let rec loop e =
  568. match e.eexpr with
  569. | TCall ({ eexpr = TConst TSuper },_) -> raise Exit
  570. | TFunction _ -> ()
  571. | _ -> Type.iter loop e
  572. in
  573. let has_super_constr() =
  574. match ctx.curclass.cl_super with
  575. | None -> false
  576. | Some (csup,_) ->
  577. try ignore(get_constructor (fun f->f.cf_type) csup); true with Not_found -> false
  578. in
  579. if fmode = FConstructor && has_super_constr() then
  580. (try
  581. loop e;
  582. display_error ctx "Missing super constructor call" p
  583. with
  584. Exit -> ());
  585. locals();
  586. let e = match ctx.curfun, ctx.vthis with
  587. | (FMember|FConstructor), Some v ->
  588. let ev = mk (TVars [v,Some (mk (TConst TThis) ctx.tthis p)]) ctx.t.tvoid p in
  589. (match e.eexpr with
  590. | TBlock l -> { e with eexpr = TBlock (ev::l) }
  591. | _ -> mk (TBlock [ev;e]) e.etype p)
  592. | _ -> e
  593. in
  594. List.iter (fun r -> r := Closed) ctx.opened;
  595. ctx.ret <- old_ret;
  596. ctx.curfun <- old_fun;
  597. ctx.opened <- old_opened;
  598. e , fargs
  599. let init_core_api ctx c =
  600. let ctx2 = (match ctx.g.core_api with
  601. | None ->
  602. let com2 = Common.clone ctx.com in
  603. Common.define com2 "core_api";
  604. com2.class_path <- ctx.com.std_path;
  605. let ctx2 = ctx.g.do_create com2 in
  606. ctx.g.core_api <- Some ctx2;
  607. ctx2
  608. | Some c ->
  609. c
  610. ) in
  611. let t = load_instance ctx2 { tpackage = fst c.cl_path; tname = snd c.cl_path; tparams = []; tsub = None; } c.cl_pos true in
  612. match t with
  613. | TInst (ccore,_) ->
  614. (match c.cl_doc with
  615. | None -> c.cl_doc <- ccore.cl_doc
  616. | Some _ -> ());
  617. let check_fields fcore fl =
  618. PMap.iter (fun i f ->
  619. if not f.cf_public then () else
  620. let f2 = try PMap.find f.cf_name fl with Not_found -> error ("Missing field " ^ i ^ " required by core type") c.cl_pos in
  621. let p = (match f2.cf_expr with None -> c.cl_pos | Some e -> e.epos) in
  622. (try
  623. type_eq EqCoreType (apply_params ccore.cl_types (List.map snd c.cl_types) f.cf_type) f2.cf_type
  624. with Unify_error l ->
  625. display_error ctx ("Field " ^ i ^ " has different type than in core type") p;
  626. display_error ctx (error_msg (Unify l)) p);
  627. if f2.cf_public <> f.cf_public then error ("Field " ^ i ^ " has different visibility than core type") p;
  628. (match f2.cf_doc with
  629. | None -> f2.cf_doc <- f.cf_doc
  630. | Some _ -> ());
  631. if f2.cf_kind <> f.cf_kind then begin
  632. match f2.cf_kind, f.cf_kind with
  633. | Method MethInline, Method MethNormal -> () (* allow to add 'inline' *)
  634. | Method MethNormal, Method MethInline -> () (* allow to disable 'inline' *)
  635. | _ ->
  636. error ("Field " ^ i ^ " has different property access than core type") p;
  637. end;
  638. (match follow f.cf_type, follow f2.cf_type with
  639. | TFun (pl1,_), TFun (pl2,_) ->
  640. if List.length pl1 != List.length pl2 then assert false;
  641. List.iter2 (fun (n1,_,_) (n2,_,_) ->
  642. if n1 <> n2 then error ("Method parameter name '" ^ n2 ^ "' should be '" ^ n1 ^ "'") p;
  643. ) pl1 pl2;
  644. | _ -> ());
  645. ) fcore;
  646. PMap.iter (fun i f ->
  647. let p = (match f.cf_expr with None -> c.cl_pos | Some e -> e.epos) in
  648. if f.cf_public && 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;
  649. ) fl;
  650. in
  651. check_fields ccore.cl_fields c.cl_fields;
  652. check_fields ccore.cl_statics c.cl_statics;
  653. | _ -> assert false
  654. let patch_class ctx c fields =
  655. let h = (try Some (Hashtbl.find ctx.g.type_patches c.cl_path) with Not_found -> None) in
  656. match h with
  657. | None -> fields
  658. | Some (h,hcl) ->
  659. c.cl_meta <- c.cl_meta @ hcl.tp_meta;
  660. let rec loop acc = function
  661. | [] -> acc
  662. | f :: l ->
  663. (* patch arguments types *)
  664. (match f.cff_kind with
  665. | FFun ff ->
  666. let param ((n,opt,t,e) as p) =
  667. try
  668. let t2 = (try Hashtbl.find h (("$" ^ f.cff_name ^ "__" ^ n),false) with Not_found -> Hashtbl.find h (("$" ^ n),false)) in
  669. n, opt, t2.tp_type, e
  670. with Not_found ->
  671. p
  672. in
  673. f.cff_kind <- FFun { ff with f_args = List.map param ff.f_args }
  674. | _ -> ());
  675. (* other patches *)
  676. match (try Some (Hashtbl.find h (f.cff_name,List.mem AStatic f.cff_access)) with Not_found -> None) with
  677. | None -> loop (f :: acc) l
  678. | Some { tp_remove = true } -> loop acc l
  679. | Some p ->
  680. f.cff_meta <- f.cff_meta @ p.tp_meta;
  681. (match p.tp_type with
  682. | None -> ()
  683. | Some t ->
  684. f.cff_kind <- match f.cff_kind with
  685. | FVar (_,e) -> FVar (Some t,e)
  686. | FProp (get,set,_,eo) -> FProp (get,set,t,eo)
  687. | FFun f -> FFun { f with f_type = Some t });
  688. loop (f :: acc) l
  689. in
  690. List.rev (loop [] fields)
  691. let build_module_def ctx mt meta fvars fbuild =
  692. let rec loop = function
  693. | (":build",args,p) :: l ->
  694. let epath, el = (match args with
  695. | [ECall (epath,el),p] -> epath, el
  696. | _ -> error "Invalid build parameters" p
  697. ) in
  698. let rec getpath (e,p) =
  699. match e with
  700. | EConst (Ident i) | EConst (Type i) -> [i]
  701. | EField (e,f) | EType (e,f) -> f :: getpath e
  702. | _ -> error "Build call parameter must be a class path" p
  703. in
  704. let s = String.concat "." (List.rev (getpath epath)) in
  705. if ctx.in_macro then error "You cannot used :build inside a macro : make sure that your enum is not used in macro" p;
  706. let old = ctx.g.get_build_infos in
  707. ctx.g.get_build_infos <- (fun() -> Some (mt, fvars()));
  708. let r = try apply_macro ctx MBuild s el p with e -> ctx.g.get_build_infos <- old; raise e in
  709. ctx.g.get_build_infos <- old;
  710. (match r with
  711. | None -> error "Build failure" p
  712. | Some e -> fbuild e; loop l)
  713. | _ :: l -> loop l
  714. | [] -> ()
  715. in
  716. try
  717. loop meta
  718. with Error (Custom msg,p) ->
  719. display_error ctx msg p
  720. let init_class ctx c p herits fields =
  721. incr stats.s_classes_built;
  722. let fields = patch_class ctx c fields in
  723. let ctx = { ctx with type_params = c.cl_types } in
  724. c.cl_extern <- List.mem HExtern herits;
  725. c.cl_interface <- List.mem HInterface herits;
  726. if c.cl_path = (["haxe";"macro"],"MacroType") then c.cl_kind <- KMacroType;
  727. set_heritance ctx c herits p;
  728. let fields = ref fields in
  729. let get_fields() = !fields in
  730. build_module_def ctx (TClassDecl c) c.cl_meta get_fields (fun (e,p) ->
  731. match e with
  732. | EVars [_,Some (CTAnonymous f),None] -> fields := f
  733. | _ -> error "Class build macro must return a single variable with anonymous fields" p
  734. );
  735. let fields = !fields in
  736. let core_api = has_meta ":core_api" c.cl_meta in
  737. let is_macro = has_meta ":macro" c.cl_meta in
  738. let fields, herits = if is_macro && not ctx.in_macro then begin
  739. c.cl_extern <- true;
  740. List.filter (fun f -> List.mem AStatic f.cff_access) fields, []
  741. end else fields, herits in
  742. if core_api && not (ctx.com.display || ctx.com.dead_code_elimination) then delay ctx (fun() -> init_core_api ctx c);
  743. let tthis = TInst (c,List.map snd c.cl_types) in
  744. let rec extends_public c =
  745. List.exists (fun (c,_) -> c.cl_path = (["haxe"],"Public") || extends_public c) c.cl_implements ||
  746. match c.cl_super with
  747. | None -> false
  748. | Some (c,_) -> extends_public c
  749. in
  750. let extends_public = extends_public c in
  751. let is_public access parent =
  752. if List.mem APrivate access then
  753. false
  754. else if List.mem APublic access then
  755. true
  756. else match parent with
  757. | Some { cf_public = p } -> p
  758. | _ -> c.cl_extern || c.cl_interface || extends_public
  759. in
  760. let rec get_parent c name =
  761. match c.cl_super with
  762. | None -> None
  763. | Some (csup,_) ->
  764. try
  765. Some (PMap.find name csup.cl_fields)
  766. with
  767. Not_found -> get_parent csup name
  768. in
  769. let type_opt ctx p t =
  770. match t with
  771. | None when c.cl_extern || c.cl_interface ->
  772. display_error ctx "Type required for extern classes and interfaces" p;
  773. t_dynamic
  774. | None when core_api ->
  775. display_error ctx "Type required for core api classes" p;
  776. t_dynamic
  777. | _ ->
  778. load_type_opt ctx p t
  779. in
  780. let rec has_field f = function
  781. | None -> false
  782. | Some (c,_) ->
  783. PMap.exists f c.cl_fields || has_field f c.cl_super || List.exists (fun i -> has_field f (Some i)) c.cl_implements
  784. in
  785. (* ----------------------- COMPLETION ----------------------------- *)
  786. let display_file = if ctx.com.display then Common.unique_full_path p.pfile = (!Parser.resume_display).pfile else false in
  787. let fields = if not display_file || Common.defined ctx.com "no-copt" then fields else Optimizer.optimize_completion c fields in
  788. let rec is_full_type t =
  789. match t with
  790. | TFun (args,ret) -> is_full_type ret && List.for_all (fun (_,_,t) -> is_full_type t) args
  791. | TMono r -> (match !r with None -> false | Some t -> is_full_type t)
  792. | TInst _ | TEnum _ | TLazy _ | TDynamic _ | TAnon _ | TType _ -> true
  793. in
  794. let bind_type cf r p macro =
  795. if ctx.com.display then begin
  796. let cp = !Parser.resume_display in
  797. if display_file && (cp.pmin = 0 || (p.pmin <= cp.pmin && p.pmax >= cp.pmax)) then begin
  798. if macro && not ctx.in_macro then
  799. (* force macro system loading of this class in order to get completion *)
  800. (fun() -> ignore(ctx.g.do_macro ctx MExpr c.cl_path cf.cf_name [] p))
  801. else begin
  802. cf.cf_type <- TLazy r;
  803. (fun() -> ignore((!r)()))
  804. end
  805. end else begin
  806. if not (is_full_type cf.cf_type) then cf.cf_type <- TLazy r;
  807. (fun() -> ())
  808. end
  809. end else if macro && not ctx.in_macro then
  810. (fun () -> ())
  811. else begin
  812. cf.cf_type <- TLazy r;
  813. if ctx.com.dead_code_elimination && cf.cf_name <> "__init__" then (fun() -> ()) else (fun () -> ignore(!r()))
  814. end
  815. in
  816. (* ----------------------- FIELD INIT ----------------------------- *)
  817. let loop_cf f =
  818. let name = f.cff_name in
  819. let p = f.cff_pos in
  820. let stat = List.mem AStatic f.cff_access in
  821. let inline = List.mem AInline f.cff_access in
  822. let ctx = { ctx with curclass = c; tthis = tthis } in
  823. let mark_used cf =
  824. if ctx.com.dead_code_elimination then cf.cf_meta <- (":?used",[],p) :: cf.cf_meta
  825. in
  826. match f.cff_kind with
  827. | FVar (t,e) ->
  828. if not stat && has_field name c.cl_super then error ("Redefinition of variable " ^ name ^ " in subclass is not allowed") p;
  829. if inline && not stat then error "Inline variable must be static" p;
  830. (match e with
  831. | None when inline -> error "Inline variable must be initialized" p
  832. | Some (_,p) when not stat -> error "Member variable initialization is not allowed outside of class constructor" p
  833. | _ -> ());
  834. let t = (match t with
  835. | None ->
  836. if not stat then error ("Type required for member variable " ^ name) p;
  837. mk_mono()
  838. | Some t ->
  839. let old = ctx.type_params in
  840. if stat then ctx.type_params <- [];
  841. let t = load_complex_type ctx p t in
  842. if stat then ctx.type_params <- old;
  843. t
  844. ) in
  845. let cf = {
  846. cf_name = name;
  847. cf_doc = f.cff_doc;
  848. cf_meta = f.cff_meta;
  849. cf_type = t;
  850. cf_pos = f.cff_pos;
  851. cf_kind = Var (if inline then { v_read = AccInline ; v_write = AccNever } else { v_read = AccNormal; v_write = AccNormal });
  852. cf_expr = None;
  853. cf_public = is_public f.cff_access None;
  854. cf_params = [];
  855. } in
  856. let delay = (match e with
  857. | None when ctx.com.dead_code_elimination && not ctx.com.display ->
  858. let r = exc_protect (fun r ->
  859. r := (fun() -> t);
  860. mark_used cf;
  861. t
  862. ) in
  863. cf.cf_type <- TLazy r;
  864. (fun() -> ())
  865. | None ->
  866. (fun() -> ())
  867. | Some e ->
  868. let r = exc_protect (fun r ->
  869. if not !return_partial_type then begin
  870. r := (fun() -> t);
  871. if ctx.com.verbose then Common.log ctx.com ("Typing " ^ (if ctx.in_macro then "macro " else "") ^ s_type_path c.cl_path ^ "." ^ name);
  872. mark_used cf;
  873. cf.cf_expr <- Some (type_static_var ctx t e p);
  874. cf.cf_type <- t;
  875. end;
  876. t
  877. ) in
  878. bind_type cf r (snd e) false
  879. ) in
  880. f, false, cf, delay
  881. | FFun fd ->
  882. let params = ref [] in
  883. params := List.map (fun (n,flags) ->
  884. (match flags with
  885. | [] -> ()
  886. | _ ->
  887. (** look if the type is contained into arguments **)
  888. let rec lookup_type t =
  889. match t with
  890. | CTPath { tpackage = []; tname = n2 } when n = n2 -> true
  891. | CTPath p -> List.exists lookup_tparam p.tparams
  892. | CTFunction (cl,r) -> List.exists lookup_type (r::cl)
  893. | CTExtend (_,fl) | CTAnonymous fl -> List.exists lookup_cfield fl
  894. | CTOptional t | CTParent t -> lookup_type t
  895. and lookup_cfield f =
  896. match f.cff_kind with
  897. | FVar (None,_) -> false
  898. | FProp (_,_,t,_) | FVar (Some t,_) -> lookup_type t
  899. | FFun f -> lookup_fun f
  900. and lookup_fun f =
  901. List.exists (fun (_,_,t,_) -> match t with None -> false | Some t -> lookup_type t) f.f_args ||
  902. List.exists (fun (_,tl) -> List.exists lookup_type tl) f.f_params ||
  903. (match f.f_type with None -> false | Some t -> lookup_type t)
  904. and lookup_tparam = function
  905. | TPType t -> lookup_type t
  906. | TPExpr _ -> false
  907. in
  908. if lookup_fun { fd with f_type = None; f_params = [] } && not (has_meta ":allowConstraint" f.cff_meta) then error "This notation is not allowed because it can't be checked" p);
  909. type_type_params ctx ([],name) (fun() -> !params) p (n,flags)
  910. ) fd.f_params;
  911. let params = !params in
  912. if inline && c.cl_interface then error "You can't declare inline methods in interfaces" p;
  913. let is_macro = (is_macro && stat) || has_meta ":macro" f.cff_meta in
  914. let f, stat, fd = if not is_macro || stat then
  915. f, stat, fd
  916. else if ctx.in_macro then
  917. (* non-static macros methods are turned into static when we are running the macro *)
  918. { f with cff_access = AStatic :: f.cff_access }, true, fd
  919. else
  920. (* remove display of first argument which will contain the "this" expression *)
  921. f, stat, { fd with f_args = match fd.f_args with [] -> [] | _ :: l -> l }
  922. in
  923. let fd = if not is_macro then
  924. fd
  925. else if ctx.in_macro then
  926. let texpr = CTPath { tpackage = ["haxe";"macro"]; tname = "Expr"; tparams = []; tsub = None } in
  927. {
  928. f_params = fd.f_params;
  929. f_type = (match fd.f_type with None -> Some texpr | t -> t);
  930. f_args = List.map (fun (a,o,t,e) -> a,o,(match t with None -> Some texpr | _ -> t),e) fd.f_args;
  931. f_expr = fd.f_expr;
  932. }
  933. else
  934. let tdyn = Some (CTPath { tpackage = []; tname = "Dynamic"; tparams = []; tsub = None }) in
  935. let to_dyn = function
  936. | { tpackage = ["haxe";"macro"]; tname = "Expr"; tsub = Some "ExprRequire"; tparams = [TPType t] } -> Some t
  937. | { tpackage = []; tname = "ExprRequire"; tsub = None; tparams = [TPType t] } -> Some t
  938. | _ -> tdyn
  939. in
  940. {
  941. f_params = fd.f_params;
  942. f_type = (match fd.f_type with Some (CTPath t) -> to_dyn t | _ -> tdyn);
  943. f_args = List.map (fun (a,o,t,_) -> a,o,(match t with Some (CTPath t) -> to_dyn t | _ -> tdyn),None) fd.f_args;
  944. f_expr = None;
  945. }
  946. in
  947. let parent = (if not stat then get_parent c name else None) in
  948. let dynamic = List.mem ADynamic f.cff_access || (match parent with Some { cf_kind = Method MethDynamic } -> true | _ -> false) in
  949. if inline && dynamic then error "You can't have both 'inline' and 'dynamic'" p;
  950. ctx.curmethod <- name;
  951. ctx.type_params <- if stat then params else params @ ctx.type_params;
  952. let ret = type_opt ctx p fd.f_type in
  953. let args = List.map (fun (name,opt,t,c) ->
  954. let t, c = type_function_param ctx (type_opt ctx p t) c opt p in
  955. name, c, t
  956. ) fd.f_args in
  957. let t = TFun (fun_args args,ret) in
  958. let constr = (name = "new") in
  959. if constr && c.cl_interface then error "An interface cannot have a constructor" p;
  960. if c.cl_interface && not stat && fd.f_expr <> None then error "An interface method cannot have a body" p;
  961. if constr then (match fd.f_type with
  962. | None | Some (CTPath { tpackage = []; tname = "Void" }) -> ()
  963. | _ -> error "A class constructor can't have a return value" p
  964. );
  965. let cf = {
  966. cf_name = name;
  967. cf_doc = f.cff_doc;
  968. cf_meta = f.cff_meta;
  969. cf_type = t;
  970. cf_pos = f.cff_pos;
  971. cf_kind = Method (if is_macro then MethMacro else if inline then MethInline else if dynamic then MethDynamic else MethNormal);
  972. cf_expr = None;
  973. cf_public = is_public f.cff_access parent;
  974. cf_params = params;
  975. } in
  976. let r = exc_protect (fun r ->
  977. if not !return_partial_type then begin
  978. r := (fun() -> t);
  979. incr stats.s_methods_typed;
  980. if ctx.com.verbose then Common.log ctx.com ("Typing " ^ (if ctx.in_macro then "macro " else "") ^ s_type_path c.cl_path ^ "." ^ name);
  981. let e , fargs = type_function ctx args ret (if constr then FConstructor else if stat then FStatic else FMember) fd p in
  982. let f = {
  983. tf_args = fargs;
  984. tf_type = ret;
  985. tf_expr = e;
  986. } in
  987. if stat && name = "__init__" then
  988. (match e.eexpr with
  989. | TBlock [] | TBlock [{ eexpr = TConst _ }] | TConst _ | TObjectDecl [] -> ()
  990. | _ -> c.cl_init <- Some e);
  991. mark_used cf;
  992. cf.cf_expr <- Some (mk (TFunction f) t p);
  993. cf.cf_type <- t;
  994. end;
  995. t
  996. ) in
  997. let delay = if ((c.cl_extern && not inline) || c.cl_interface) && cf.cf_name <> "__init__" then
  998. (fun() -> ())
  999. else
  1000. bind_type cf r (match fd.f_expr with Some e -> snd e | None -> f.cff_pos) is_macro
  1001. in
  1002. f, constr, cf, delay
  1003. | FProp (get,set,t,eo) ->
  1004. (match eo with
  1005. | None -> ()
  1006. | Some e -> error "Property initialization is not allowed" (snd e));
  1007. let ret = load_complex_type ctx p t in
  1008. let check_get = ref (fun() -> ()) in
  1009. let check_set = ref (fun() -> ()) in
  1010. let check_method m t () =
  1011. if ctx.com.display then () else
  1012. try
  1013. let t2 = (if stat then (PMap.find m c.cl_statics).cf_type else fst (class_field c m)) in
  1014. unify_raise ctx t2 t p;
  1015. with
  1016. | Error (Unify l,_) -> raise (Error (Stack (Custom ("In method " ^ m ^ " required by property " ^ name),Unify l),p))
  1017. | Not_found -> if not (c.cl_interface || c.cl_extern) then display_error ctx ("Method " ^ m ^ " required by property " ^ name ^ " is missing") p
  1018. in
  1019. let get = (match get with
  1020. | "null" -> AccNo
  1021. | "dynamic" -> AccCall ("get_" ^ name)
  1022. | "never" -> AccNever
  1023. | "default" -> AccNormal
  1024. | _ ->
  1025. check_get := check_method get (TFun ([],ret));
  1026. AccCall get
  1027. ) in
  1028. let set = (match set with
  1029. | "null" ->
  1030. (* standard flash library read-only variables can't be accessed for writing, even in subclasses *)
  1031. if c.cl_extern && (match c.cl_path with "flash" :: _ , _ -> true | _ -> false) && Common.defined ctx.com "flash9" then
  1032. AccNever
  1033. else
  1034. AccNo
  1035. | "never" -> AccNever
  1036. | "dynamic" -> AccCall ("set_" ^ name)
  1037. | "default" -> AccNormal
  1038. | _ ->
  1039. check_set := check_method set (TFun (["",false,ret],ret));
  1040. AccCall set
  1041. ) in
  1042. if set = AccNormal && (match get with AccCall _ -> true | _ -> false) then error "Unsupported property combination" p;
  1043. let cf = {
  1044. cf_name = name;
  1045. cf_doc = f.cff_doc;
  1046. cf_meta = f.cff_meta;
  1047. cf_pos = f.cff_pos;
  1048. cf_kind = Var { v_read = get; v_write = set };
  1049. cf_expr = None;
  1050. cf_type = ret;
  1051. cf_public = is_public f.cff_access None;
  1052. cf_params = [];
  1053. } in
  1054. if ctx.com.dead_code_elimination && not ctx.com.display then begin
  1055. let r = exc_protect (fun r ->
  1056. r := (fun() -> ret);
  1057. mark_used cf;
  1058. ret
  1059. ) in
  1060. cf.cf_type <- TLazy r;
  1061. end;
  1062. f, false, cf, (fun() -> (!check_get)(); (!check_set)())
  1063. in
  1064. let rec check_require = function
  1065. | [] -> None
  1066. | (":require",conds,_) :: l ->
  1067. let rec loop = function
  1068. | [] -> check_require l
  1069. | (EConst (Ident i | Type i),_) :: l ->
  1070. if not (Common.defined ctx.com i) then
  1071. Some i
  1072. else
  1073. loop l
  1074. | _ -> error "Invalid require identifier" p
  1075. in
  1076. loop conds
  1077. | _ :: l ->
  1078. check_require l
  1079. in
  1080. let cl_req = check_require c.cl_meta in
  1081. let fl = List.fold_left (fun acc f ->
  1082. try
  1083. let p = f.cff_pos in
  1084. let fd , constr, f , delayed = loop_cf f in
  1085. let is_static = List.mem AStatic fd.cff_access in
  1086. if is_static && f.cf_name = "name" && Common.defined ctx.com "js" then error "This identifier cannot be used in Javascript for statics" p;
  1087. if (is_static || constr) && c.cl_interface && f.cf_name <> "__init__" then error "You can't declare static fields in interfaces" p;
  1088. let req = check_require fd.cff_meta in
  1089. let req = (match req with None -> if is_static || constr then cl_req else None | _ -> req) in
  1090. (match req with
  1091. | None -> ()
  1092. | Some r -> f.cf_kind <- Var { v_read = AccRequire r; v_write = AccRequire r });
  1093. if constr then begin
  1094. if c.cl_constructor <> None then error "Duplicate constructor" p;
  1095. c.cl_constructor <- Some f;
  1096. end else if not is_static || f.cf_name <> "__init__" then begin
  1097. 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;
  1098. 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;
  1099. if is_static then begin
  1100. c.cl_statics <- PMap.add f.cf_name f c.cl_statics;
  1101. c.cl_ordered_statics <- f :: c.cl_ordered_statics;
  1102. end else begin
  1103. c.cl_fields <- PMap.add f.cf_name f c.cl_fields;
  1104. c.cl_ordered_fields <- f :: c.cl_ordered_fields;
  1105. if List.mem AOverride fd.cff_access then c.cl_overrides <- f.cf_name :: c.cl_overrides;
  1106. end;
  1107. end;
  1108. delayed :: acc
  1109. with Error (Custom str,p) ->
  1110. display_error ctx str p;
  1111. acc
  1112. ) [] fields in
  1113. c.cl_ordered_statics <- List.rev c.cl_ordered_statics;
  1114. c.cl_ordered_fields <- List.rev c.cl_ordered_fields;
  1115. (*
  1116. make sure a default contructor with same access as super one will be added to the class structure at some point.
  1117. *)
  1118. let rec add_constructor c =
  1119. match c.cl_constructor, c.cl_super with
  1120. | None, Some (csup,cparams) when not c.cl_extern ->
  1121. add_constructor csup;
  1122. (match csup.cl_constructor with
  1123. | None -> ()
  1124. | Some cf ->
  1125. let args = (match follow (apply_params csup.cl_types cparams cf.cf_type) with
  1126. | TFun (args,_) -> args
  1127. | _ -> assert false
  1128. ) in
  1129. let p = c.cl_pos in
  1130. let vars = List.map (fun (n,o,t) ->
  1131. let t = if o then ctx.t.tnull t else t in
  1132. alloc_var n t, (if o then Some TNull else None)
  1133. ) args in
  1134. 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
  1135. let constr = mk (TFunction {
  1136. tf_args = vars;
  1137. tf_type = ctx.t.tvoid;
  1138. tf_expr = super_call;
  1139. }) (TFun (List.map (fun (v,c) -> v.v_name, c <> None, v.v_type) vars,ctx.t.tvoid)) p in
  1140. c.cl_constructor <- Some { cf with cf_pos = p; cf_type = constr.etype; cf_meta = []; cf_doc = None; cf_expr = Some constr })
  1141. | _ ->
  1142. (* nothing to do *)
  1143. ()
  1144. in
  1145. delay ctx (fun() -> add_constructor c);
  1146. List.rev fl
  1147. let resolve_typedef ctx t =
  1148. match t with
  1149. | TClassDecl _ | TEnumDecl _ -> t
  1150. | TTypeDecl td ->
  1151. match follow td.t_type with
  1152. | TEnum (e,_) -> TEnumDecl e
  1153. | TInst (c,_) -> TClassDecl c
  1154. | _ -> t
  1155. let add_module ctx m p =
  1156. let decl_type t =
  1157. let t = t_infos t in
  1158. try
  1159. let m2 = Hashtbl.find ctx.g.types_module t.mt_path in
  1160. 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;
  1161. error ("Type name " ^ s_type_path t.mt_path ^ " is redefined from module " ^ s_type_path m2) p
  1162. with
  1163. Not_found ->
  1164. Hashtbl.add ctx.g.types_module t.mt_path m.m_path
  1165. in
  1166. List.iter decl_type m.m_types;
  1167. Hashtbl.add ctx.g.modules m.m_path m
  1168. let type_module ctx m file tdecls loadp =
  1169. (* PASS 1 : build module structure - does not load any module or type - should be atomic ! *)
  1170. let decls = ref [] in
  1171. let make_path name priv =
  1172. if List.exists (fun t -> snd (t_path t) = name) (!decls) then error ("Type name " ^ name ^ " is already defined in this module") loadp;
  1173. if priv then (fst m @ ["_" ^ snd m], name) else (fst m, name)
  1174. in
  1175. let m = {
  1176. m_id = alloc_mid();
  1177. m_path = m;
  1178. m_types = [];
  1179. 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);
  1180. } in
  1181. List.iter (fun (d,p) ->
  1182. match d with
  1183. | EImport _ | EUsing _ -> ()
  1184. | EClass d ->
  1185. let priv = List.mem HPrivate d.d_flags in
  1186. let path = make_path d.d_name priv in
  1187. let c = mk_class m path p in
  1188. c.cl_module <- m;
  1189. c.cl_private <- priv;
  1190. c.cl_doc <- d.d_doc;
  1191. c.cl_meta <- d.d_meta;
  1192. decls := TClassDecl c :: !decls
  1193. | EEnum d ->
  1194. let priv = List.mem EPrivate d.d_flags in
  1195. let path = make_path d.d_name priv in
  1196. let e = {
  1197. e_path = path;
  1198. e_module = m;
  1199. e_pos = p;
  1200. e_doc = d.d_doc;
  1201. e_meta = d.d_meta;
  1202. e_types = [];
  1203. e_private = priv;
  1204. e_extern = List.mem EExtern d.d_flags;
  1205. e_constrs = PMap.empty;
  1206. e_names = [];
  1207. } in
  1208. decls := TEnumDecl e :: !decls
  1209. | ETypedef d ->
  1210. let priv = List.mem EPrivate d.d_flags in
  1211. let path = make_path d.d_name priv in
  1212. let t = {
  1213. t_path = path;
  1214. t_module = m;
  1215. t_pos = p;
  1216. t_doc = d.d_doc;
  1217. t_private = priv;
  1218. t_types = [];
  1219. t_type = mk_mono();
  1220. t_meta = d.d_meta;
  1221. } in
  1222. decls := TTypeDecl t :: !decls
  1223. ) tdecls;
  1224. m.m_types <- List.rev !decls;
  1225. add_module ctx m loadp;
  1226. (* PASS 2 : build types structure - does not type any expression ! *)
  1227. let ctx = {
  1228. com = ctx.com;
  1229. g = ctx.g;
  1230. t = ctx.t;
  1231. curclass = ctx.curclass;
  1232. tthis = ctx.tthis;
  1233. ret = ctx.ret;
  1234. current = m;
  1235. locals = PMap.empty;
  1236. local_types = ctx.g.std.m_types @ m.m_types;
  1237. local_using = [];
  1238. type_params = [];
  1239. curmethod = "";
  1240. curfun = FStatic;
  1241. untyped = false;
  1242. in_super_call = false;
  1243. in_macro = ctx.in_macro;
  1244. in_display = false;
  1245. in_loop = false;
  1246. opened = [];
  1247. param_type = None;
  1248. vthis = None;
  1249. } in
  1250. let delays = ref [] in
  1251. let get_class name =
  1252. let c = List.find (fun d -> match d with TClassDecl { cl_path = _ , n } -> n = name | _ -> false) m.m_types in
  1253. match c with TClassDecl c -> c | _ -> assert false
  1254. in
  1255. let get_enum name =
  1256. let e = List.find (fun d -> match d with TEnumDecl { e_path = _ , n } -> n = name | _ -> false) m.m_types in
  1257. match e with TEnumDecl e -> e | _ -> assert false
  1258. in
  1259. let get_tdef name =
  1260. let s = List.find (fun d -> match d with TTypeDecl { t_path = _ , n } -> n = name | _ -> false) m.m_types in
  1261. match s with TTypeDecl s -> s | _ -> assert false
  1262. in
  1263. (* here is an additional PASS 1 phase, which handle the type parameters declaration, with lazy contraints *)
  1264. List.iter (fun (d,p) ->
  1265. match d with
  1266. | EImport _ | EUsing _ -> ()
  1267. | EClass d ->
  1268. let c = get_class d.d_name in
  1269. c.cl_types <- List.map (type_type_params ctx c.cl_path (fun() -> c.cl_types) p) d.d_params;
  1270. | EEnum d ->
  1271. let e = get_enum d.d_name in
  1272. e.e_types <- List.map (type_type_params ctx e.e_path (fun() -> e.e_types) p) d.d_params;
  1273. | ETypedef d ->
  1274. let t = get_tdef d.d_name in
  1275. t.t_types <- List.map (type_type_params ctx t.t_path (fun() -> t.t_types) p) d.d_params;
  1276. ) tdecls;
  1277. (* back to PASS2 *)
  1278. List.iter (fun (d,p) ->
  1279. match d with
  1280. | EImport t ->
  1281. (match t.tsub with
  1282. | None ->
  1283. let md = ctx.g.do_load_module ctx (t.tpackage,t.tname) p in
  1284. let types = List.filter (fun t -> not (t_infos t).mt_private) md.m_types in
  1285. ctx.local_types <- ctx.local_types @ types
  1286. | Some _ ->
  1287. let t = load_type_def ctx p t in
  1288. ctx.local_types <- ctx.local_types @ [t]
  1289. )
  1290. | EUsing t ->
  1291. (match t.tsub with
  1292. | None ->
  1293. let md = ctx.g.do_load_module ctx (t.tpackage,t.tname) p in
  1294. let types = List.filter (fun t -> not (t_infos t).mt_private) md.m_types in
  1295. ctx.local_using <- ctx.local_using @ (List.map (resolve_typedef ctx) types);
  1296. | Some _ ->
  1297. let t = load_type_def ctx p t in
  1298. ctx.local_using<- ctx.local_using @ [resolve_typedef ctx t])
  1299. | EClass d ->
  1300. let c = get_class d.d_name in
  1301. let checks = if not ctx.com.display then [check_overriding ctx c p; check_interfaces ctx c p] else [] in
  1302. delays := !delays @ (checks @ init_class ctx c p d.d_flags d.d_data)
  1303. | EEnum d ->
  1304. let e = get_enum d.d_name in
  1305. let ctx = { ctx with type_params = e.e_types } in
  1306. let h = (try Some (Hashtbl.find ctx.g.type_patches e.e_path) with Not_found -> None) in
  1307. (match h with
  1308. | None -> ()
  1309. | Some (h,hcl) ->
  1310. Hashtbl.iter (fun _ _ -> error "Field type patch not supported for enums" e.e_pos) h;
  1311. e.e_meta <- e.e_meta @ hcl.tp_meta);
  1312. let constructs = ref d.d_data in
  1313. let get_constructs() =
  1314. List.map (fun (c,doc,meta,pl,p) ->
  1315. {
  1316. cff_name = c;
  1317. cff_doc = doc;
  1318. cff_meta = meta;
  1319. cff_pos = p;
  1320. cff_access = [];
  1321. cff_kind = (match pl with
  1322. | [] -> FVar (None,None)
  1323. | _ -> FFun { f_params = []; f_type = None; f_expr = None; f_args = List.map (fun (n,o,t) -> n,o,Some t,None) pl });
  1324. }
  1325. ) (!constructs)
  1326. in
  1327. build_module_def ctx (TEnumDecl e) e.e_meta get_constructs (fun (e,p) ->
  1328. match e with
  1329. | EVars [_,Some (CTAnonymous fields),None] ->
  1330. constructs := List.map (fun f ->
  1331. (f.cff_name,f.cff_doc,f.cff_meta,(match f.cff_kind with
  1332. | FVar (None,None) -> []
  1333. | 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
  1334. | _ -> error "Invalid enum constructor in @:build result" p
  1335. ),f.cff_pos)
  1336. ) fields
  1337. | _ -> error "Enum build macro must return a single variable with anonymous object fields" p
  1338. );
  1339. let et = TEnum (e,List.map snd e.e_types) in
  1340. let names = ref [] in
  1341. let index = ref 0 in
  1342. List.iter (fun (c,doc,meta,t,p) ->
  1343. if c = "name" && Common.defined ctx.com "js" then error "This identifier cannot be used in Javascript" p;
  1344. let t = (match t with
  1345. | [] -> et
  1346. | l ->
  1347. let pnames = ref PMap.empty in
  1348. TFun (List.map (fun (s,opt,t) ->
  1349. if PMap.mem s (!pnames) then error ("Duplicate parameter '" ^ s ^ "' in enum constructor " ^ c) p;
  1350. pnames := PMap.add s () (!pnames);
  1351. s, opt, load_type_opt ~opt ctx p (Some t)
  1352. ) l, et)
  1353. ) in
  1354. if PMap.mem c e.e_constrs then error ("Duplicate constructor " ^ c) p;
  1355. e.e_constrs <- PMap.add c {
  1356. ef_name = c;
  1357. ef_type = t;
  1358. ef_pos = p;
  1359. ef_doc = doc;
  1360. ef_index = !index;
  1361. ef_meta = meta;
  1362. } e.e_constrs;
  1363. incr index;
  1364. names := c :: !names;
  1365. ) (!constructs);
  1366. e.e_names <- List.rev !names;
  1367. e.e_extern <- e.e_extern || e.e_names = [];
  1368. | ETypedef d ->
  1369. let t = get_tdef d.d_name in
  1370. let ctx = { ctx with type_params = t.t_types } in
  1371. let tt = load_complex_type ctx p d.d_data in
  1372. if t.t_type == follow tt then error "Recursive typedef is not allowed" p;
  1373. (match t.t_type with
  1374. | TMono r ->
  1375. (match !r with
  1376. | None -> r := Some tt;
  1377. | Some _ -> assert false);
  1378. | _ -> assert false);
  1379. ) tdecls;
  1380. (* PASS 3 : type checking, delayed until all modules and types are built *)
  1381. List.iter (delay ctx) (List.rev (!delays));
  1382. m
  1383. let resolve_module_file com m remap p =
  1384. let file = (match m with
  1385. | [] , name -> name
  1386. | x :: l , name ->
  1387. let x = (try
  1388. match PMap.find x com.package_rules with
  1389. | Forbidden -> raise (Error (Forbid_package (x,m),p));
  1390. | Directory d -> d
  1391. | Remap d -> remap := d :: l; d
  1392. with Not_found -> x
  1393. ) in
  1394. String.concat "/" (x :: l) ^ "/" ^ name
  1395. ) ^ ".hx" in
  1396. let file = Common.find_file com file in
  1397. match String.lowercase (snd m) with
  1398. | "con" | "aux" | "prn" | "nul" | "com1" | "com2" | "com3" | "lpt1" | "lpt2" | "lpt3" when Sys.os_type = "Win32" ->
  1399. (* these names are reserved by the OS - old DOS legacy, such files cannot be easily created but are reported as visible *)
  1400. if (try (Unix.stat file).Unix.st_size with _ -> 0) > 0 then file else raise Not_found
  1401. | _ -> file
  1402. let parse_module ctx m p =
  1403. let remap = ref (fst m) in
  1404. let file = resolve_module_file ctx.com m remap p in
  1405. let pack, decls = (!parse_hook) ctx.com file p in
  1406. if pack <> !remap then begin
  1407. let spack m = if m = [] then "<empty>" else String.concat "." m in
  1408. if p == Ast.null_pos then
  1409. display_error ctx ("Invalid commandline class : " ^ s_type_path m ^ " should be " ^ s_type_path (pack,snd m)) p
  1410. else
  1411. display_error ctx ("Invalid package : " ^ spack (fst m) ^ " should be " ^ spack pack) p
  1412. end;
  1413. file, if !remap <> fst m then
  1414. (* build typedefs to redirect to real package *)
  1415. List.rev (List.fold_left (fun acc (t,p) ->
  1416. let build f d =
  1417. let priv = List.mem f d.d_flags in
  1418. (ETypedef {
  1419. d_name = d.d_name;
  1420. d_doc = None;
  1421. d_meta = [];
  1422. d_params = d.d_params;
  1423. d_flags = if priv then [EPrivate] else [];
  1424. d_data = CTPath (if priv then { tpackage = []; tname = "Dynamic"; tparams = []; tsub = None; } else
  1425. {
  1426. tpackage = !remap;
  1427. tname = d.d_name;
  1428. tparams = List.map (fun (s,_) ->
  1429. TPType (CTPath { tpackage = []; tname = s; tparams = []; tsub = None; })
  1430. ) d.d_params;
  1431. tsub = None;
  1432. });
  1433. },p) :: acc
  1434. in
  1435. match t with
  1436. | EClass d -> build HPrivate d
  1437. | EEnum d -> build EPrivate d
  1438. | ETypedef d -> build EPrivate d
  1439. | EImport _ | EUsing _ -> acc
  1440. ) [(EImport { tpackage = !remap; tname = snd m; tparams = []; tsub = None; },null_pos)] decls)
  1441. else
  1442. decls
  1443. let load_module ctx m p =
  1444. let m2 = (try
  1445. Hashtbl.find ctx.g.modules m
  1446. with
  1447. Not_found ->
  1448. match !type_module_hook ctx m p with
  1449. | Some m -> m
  1450. | None ->
  1451. let file, decls = (try
  1452. parse_module ctx m p
  1453. with Not_found ->
  1454. let rec loop = function
  1455. | [] ->
  1456. raise (Error (Module_not_found m,p))
  1457. | load :: l ->
  1458. match load m p with
  1459. | None -> loop l
  1460. | Some (file,(_,a)) -> file, a
  1461. in
  1462. loop ctx.com.load_extern_type
  1463. ) in
  1464. type_module ctx m file decls p
  1465. ) in
  1466. add_dependency ctx.current m2;
  1467. m2