2
0

typeload.ml 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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 type_constant ctx c p =
  24. match c with
  25. | Int s ->
  26. (try
  27. mk (TConst (TInt (Int32.of_string s))) ctx.api.tint p
  28. with
  29. _ -> mk (TConst (TFloat s)) ctx.api.tfloat p)
  30. | Float f -> mk (TConst (TFloat f)) ctx.api.tfloat p
  31. | String s -> mk (TConst (TString s)) ctx.api.tstring p
  32. | Ident "true" -> mk (TConst (TBool true)) ctx.api.tbool p
  33. | Ident "false" -> mk (TConst (TBool false)) ctx.api.tbool p
  34. | Ident "null" -> mk (TConst TNull) (ctx.api.tnull (mk_mono())) p
  35. | _ -> assert false
  36. let type_function_param ctx t e opt p =
  37. match e with
  38. | None ->
  39. if opt then ctx.api.tnull t, Some (EConst (Ident "null"),p) else t, None
  40. | Some e ->
  41. t, Some e
  42. let exc_protect f =
  43. let rec r = ref (fun() ->
  44. try
  45. f r
  46. with
  47. | Error (Protect _,_) as e -> raise e
  48. | Error (m,p) -> raise (Error (Protect m,p))
  49. ) in
  50. r
  51. let type_static_var ctx t e p =
  52. ctx.in_static <- true;
  53. let e = type_expr ctx e true in
  54. unify ctx e.etype t p;
  55. e
  56. (** since load_type is used in PASS2 , it cannot access the structure of a type **)
  57. let load_type_def ctx p tpath =
  58. let no_pack = fst tpath = [] in
  59. try
  60. List.find (fun t ->
  61. let tp = t_path t in
  62. tp = tpath || (no_pack && snd tp = snd tpath)
  63. ) ctx.local_types
  64. with
  65. Not_found ->
  66. let tpath, m = (try
  67. if not no_pack then raise Exit;
  68. (match fst ctx.current.mpath with
  69. | [] -> raise Exit
  70. | x :: _ ->
  71. (* this can occur due to haxe remoting : a module can be
  72. already defined in the "js" package and is not allowed
  73. to access the js classes *)
  74. try
  75. (match PMap.find x ctx.com.package_rules with
  76. | Forbidden -> raise Exit
  77. | _ -> ())
  78. with Not_found -> ());
  79. let tpath2 = fst ctx.current.mpath , snd tpath in
  80. tpath2, ctx.api.load_module tpath2 p
  81. with
  82. | Error (Module_not_found _,p2) when p == p2 -> tpath, ctx.api.load_module tpath p
  83. | Exit -> tpath, ctx.api.load_module tpath p
  84. ) in
  85. try
  86. List.find (fun t -> not (t_private t) && t_path t = tpath) m.mtypes
  87. with
  88. Not_found -> error ("Module " ^ s_type_path tpath ^ " does not define type " ^ snd tpath) p
  89. let rec load_normal_type ctx t p allow_no_params =
  90. try
  91. if t.tpackage <> [] then raise Not_found;
  92. let pt = List.assoc t.tname ctx.type_params in
  93. if t.tparams <> [] then error ("Class type parameter " ^ t.tname ^ " can't have parameters") p;
  94. pt
  95. with Not_found ->
  96. let types , path , f = ctx.api.build_instance (load_type_def ctx p (t.tpackage,t.tname)) p in
  97. if allow_no_params && t.tparams = [] then
  98. f (List.map (fun (name,t) ->
  99. match follow t with
  100. | TInst (c,_) -> if c.cl_implements = [] then mk_mono() else error ("Type parameter " ^ name ^ " need constraint") p
  101. | _ -> assert false
  102. ) types)
  103. else if path = ([],"Dynamic") then
  104. match t.tparams with
  105. | [] -> t_dynamic
  106. | [TPType t] -> TDynamic (load_type ctx p t)
  107. | _ -> error "Too many parameters for Dynamic" p
  108. else begin
  109. if List.length types <> List.length t.tparams then error ("Invalid number of type parameters for " ^ s_type_path path) p;
  110. let tparams = List.map (fun t ->
  111. match t with
  112. | TPConst c ->
  113. let name, const = (match c with
  114. | String s -> "S" ^ s, TString s
  115. | Int i -> "I" ^ i, TInt (Int32.of_string i)
  116. | Float f -> "F" ^ f, TFloat f
  117. | _ -> assert false
  118. ) in
  119. let c = mk_class ([],name) p None false in
  120. c.cl_kind <- KConstant const;
  121. TInst (c,[])
  122. | TPType t -> load_type ctx p t
  123. ) t.tparams in
  124. let params = List.map2 (fun t (name,t2) ->
  125. let isconst = (match t with TInst ({ cl_kind = KConstant _ },_) -> true | _ -> false) in
  126. if isconst <> (name = "Const") && t != t_dynamic then error (if isconst then "Constant value unexpected here" else "Constant value excepted as type parameter") p;
  127. match follow t2 with
  128. | TInst ({ cl_implements = [] }, []) ->
  129. t
  130. | TInst (c,[]) ->
  131. let r = exc_protect (fun r ->
  132. r := (fun() -> t);
  133. List.iter (fun (i,params) ->
  134. unify ctx t (apply_params types tparams (TInst (i,params))) p
  135. ) c.cl_implements;
  136. t
  137. ) in
  138. ctx.delays := [(fun () -> ignore(!r()))] :: !(ctx.delays);
  139. TLazy r
  140. | _ -> assert false
  141. ) tparams types in
  142. f params
  143. end
  144. and load_type ctx p t =
  145. match t with
  146. | TPParent t -> load_type ctx p t
  147. | TPNormal t -> load_normal_type ctx t p false
  148. | TPExtend (t,l) ->
  149. (match load_type ctx p (TPAnonymous l) with
  150. | TAnon a ->
  151. let rec loop t =
  152. match follow t with
  153. | TInst (c,tl) ->
  154. let c2 = mk_class (fst c.cl_path,"+" ^ snd c.cl_path) p None true in
  155. PMap.iter (fun f _ ->
  156. try
  157. ignore(class_field c f);
  158. error ("Cannot redefine field " ^ f) p
  159. with
  160. Not_found -> ()
  161. ) a.a_fields;
  162. (* do NOT tag as extern - for protect *)
  163. c2.cl_kind <- KExtension (c,tl);
  164. c2.cl_super <- Some (c,tl);
  165. c2.cl_fields <- a.a_fields;
  166. TInst (c2,[])
  167. | TMono _ ->
  168. error "Please ensure correct initialization of cascading signatures" p
  169. | TAnon a2 ->
  170. PMap.iter (fun f _ ->
  171. if PMap.mem f a2.a_fields then error ("Cannot redefine field " ^ f) p
  172. ) a.a_fields;
  173. mk_anon (PMap.foldi PMap.add a.a_fields a2.a_fields)
  174. | _ -> error "Cannot only extend classes and anonymous" p
  175. in
  176. loop (load_normal_type ctx t p false)
  177. | _ -> assert false)
  178. | TPAnonymous l ->
  179. let rec loop acc (n,pub,f,p) =
  180. if PMap.mem n acc then error ("Duplicate field declaration : " ^ n) p;
  181. let t , get, set = (match f with
  182. | AFVar t ->
  183. load_type ctx p t, NormalAccess, NormalAccess
  184. | AFFun (tl,t) ->
  185. let t = load_type ctx p t in
  186. let args = List.map (fun (name,o,t) -> name , o, load_type ctx p t) tl in
  187. TFun (args,t), NormalAccess, MethodCantAccess
  188. | AFProp (t,i1,i2) ->
  189. let access m get =
  190. match m with
  191. | "null" -> NoAccess
  192. | "default" -> NormalAccess
  193. | "dynamic" -> MethodAccess ((if get then "get_" else "set_") ^ n)
  194. | _ -> MethodAccess m
  195. in
  196. load_type ctx p t, access i1 true, access i2 false
  197. ) in
  198. PMap.add n {
  199. cf_name = n;
  200. cf_type = t;
  201. cf_public = (match pub with None -> true | Some p -> p);
  202. cf_get = get;
  203. cf_set = set;
  204. cf_params = [];
  205. cf_expr = None;
  206. cf_doc = None;
  207. } acc
  208. in
  209. mk_anon (List.fold_left loop PMap.empty l)
  210. | TPFunction (args,r) ->
  211. match args with
  212. | [TPNormal { tpackage = []; tparams = []; tname = "Void" }] ->
  213. TFun ([],load_type ctx p r)
  214. | _ ->
  215. TFun (List.map (fun t -> "",false,load_type ctx p t) args,load_type ctx p r)
  216. let hide_types ctx =
  217. let old_locals = ctx.local_types in
  218. let old_type_params = ctx.type_params in
  219. ctx.local_types <- ctx.std.mtypes;
  220. ctx.type_params <- [];
  221. (fun() ->
  222. ctx.local_types <- old_locals;
  223. ctx.type_params <- old_type_params;
  224. )
  225. let load_core_type ctx name =
  226. let show = hide_types ctx in
  227. let t = load_normal_type ctx { tpackage = []; tname = name; tparams = [] } null_pos false in
  228. show();
  229. t
  230. let t_array_access ctx =
  231. let show = hide_types ctx in
  232. match load_type_def ctx null_pos ([],"ArrayAccess") with
  233. | TClassDecl c ->
  234. show();
  235. if List.length c.cl_types <> 1 then assert false;
  236. let pt = mk_mono() in
  237. TInst (c,[pt]) , pt
  238. | _ ->
  239. assert false
  240. let t_iterator ctx =
  241. let show = hide_types ctx in
  242. match load_type_def ctx null_pos ([],"Iterator") with
  243. | TTypeDecl t ->
  244. show();
  245. if List.length t.t_types <> 1 then assert false;
  246. let pt = mk_mono() in
  247. apply_params t.t_types [pt] t.t_type, pt
  248. | _ ->
  249. assert false
  250. let load_type_opt ?(opt=false) ctx p t =
  251. let t = (match t with None -> mk_mono() | Some t -> load_type ctx p t) in
  252. if opt then ctx.api.tnull t else t
  253. (* ---------------------------------------------------------------------- *)
  254. (* Structure check *)
  255. let valid_redefinition ctx f1 t1 f2 t2 =
  256. let valid t1 t2 =
  257. type_eq EqStrict t1 t2;
  258. if is_null t1 <> is_null t2 then raise (Unify_error [Cannot_unify (t1,t2)]);
  259. in
  260. let t1, t2 = (match f1.cf_params, f2.cf_params with
  261. | [], [] -> t1, t2
  262. | l1, l2 when List.length l1 = List.length l2 ->
  263. let monos = List.map (fun _ -> mk_mono()) l1 in
  264. apply_params l1 monos t1, apply_params l2 monos t2
  265. | _ -> t1, t2
  266. ) in
  267. match follow t1, follow t2 with
  268. | TFun (args1,r1) , TFun (args2,r2) when List.length args1 = List.length args2 ->
  269. List.iter2 (fun (n,o1,a1) (_,o2,a2) ->
  270. if o1 <> o2 then raise (Unify_error [Not_matching_optional n]);
  271. valid a1 a2;
  272. ) args1 args2;
  273. valid r1 r2;
  274. | _ , _ ->
  275. (* in case args differs, or if an interface var *)
  276. valid t1 t2
  277. let check_overriding ctx c p () =
  278. match c.cl_super with
  279. | None ->
  280. (match c.cl_overrides with
  281. | [] -> ()
  282. | i :: _ ->
  283. display_error ctx ("Field " ^ i ^ " is declared 'override' but doesn't override any field") p)
  284. | Some (csup,params) ->
  285. PMap.iter (fun i f ->
  286. try
  287. let t , f2 = raw_class_field (fun f -> f.cf_type) csup i in
  288. ignore(follow f.cf_type); (* force evaluation *)
  289. let p = (match f.cf_expr with None -> p | Some e -> e.epos) in
  290. if not (List.mem i c.cl_overrides) then
  291. display_error ctx ("Field " ^ i ^ " should be declared with 'override' since it is inherited from superclass") p
  292. else if f.cf_public <> f2.cf_public then
  293. display_error ctx ("Field " ^ i ^ " has different visibility (public/private) than superclass one") p
  294. else if f2.cf_get = InlineAccess then
  295. display_error ctx ("Field " ^ i ^ " is inlined and cannot be overridden") p
  296. else if f2.cf_get <> f.cf_get || f2.cf_set <> f.cf_set then
  297. display_error ctx ("Field " ^ i ^ " has different property access than in superclass") p
  298. else try
  299. let t = apply_params csup.cl_types params t in
  300. valid_redefinition ctx f f.cf_type f2 t
  301. with
  302. Unify_error l ->
  303. display_error ctx ("Field " ^ i ^ " overload parent class with different or incomplete type") p;
  304. display_error ctx (error_msg (Unify l)) p;
  305. with
  306. Not_found ->
  307. if List.mem i c.cl_overrides then display_error ctx ("Field " ^ i ^ " is declared 'override' but doesn't override any field") p
  308. ) c.cl_fields
  309. let class_field_no_interf c i =
  310. try
  311. let f = PMap.find i c.cl_fields in
  312. f.cf_type , f
  313. with Not_found ->
  314. match c.cl_super with
  315. | None ->
  316. raise Not_found
  317. | Some (c,tl) ->
  318. (* rec over class_field *)
  319. let t , f = raw_class_field (fun f -> f.cf_type) c i in
  320. apply_params c.cl_types tl t , f
  321. let rec check_interface ctx c p intf params =
  322. PMap.iter (fun i f ->
  323. try
  324. let t2, f2 = class_field_no_interf c i in
  325. ignore(follow f2.cf_type); (* force evaluation *)
  326. let p = (match f2.cf_expr with None -> p | Some e -> e.epos) in
  327. if f.cf_public && not f2.cf_public then
  328. display_error ctx ("Field " ^ i ^ " should be public as requested by " ^ s_type_path intf.cl_path) p
  329. else if f2.cf_get <> f.cf_get || f2.cf_set <> f.cf_set then
  330. display_error ctx ("Field " ^ i ^ " has different property access than in " ^ s_type_path intf.cl_path) p
  331. else try
  332. valid_redefinition ctx f2 t2 f (apply_params intf.cl_types params f.cf_type)
  333. with
  334. Unify_error l ->
  335. display_error ctx ("Field " ^ i ^ " has different type than in " ^ s_type_path intf.cl_path) p;
  336. display_error ctx (error_msg (Unify l)) p;
  337. with
  338. Not_found ->
  339. if not c.cl_interface then display_error ctx ("Field " ^ i ^ " needed by " ^ s_type_path intf.cl_path ^ " is missing") p
  340. ) intf.cl_fields;
  341. List.iter (fun (i2,p2) ->
  342. check_interface ctx c p i2 (List.map (apply_params intf.cl_types params) p2)
  343. ) intf.cl_implements
  344. let check_interfaces ctx c p () =
  345. match c.cl_path with
  346. | "Proxy" :: _ , _ -> ()
  347. | _ ->
  348. List.iter (fun (intf,params) -> check_interface ctx c p intf params) c.cl_implements
  349. let rec return_flow ctx e =
  350. let error() = display_error ctx "A return is missing here" e.epos; raise Exit in
  351. let return_flow = return_flow ctx in
  352. match e.eexpr with
  353. | TReturn _ | TThrow _ -> ()
  354. | TParenthesis e ->
  355. return_flow e
  356. | TBlock el ->
  357. let rec loop = function
  358. | [] -> error()
  359. | [e] -> return_flow e
  360. | { eexpr = TReturn _ } :: _ | { eexpr = TThrow _ } :: _ -> ()
  361. | _ :: l -> loop l
  362. in
  363. loop el
  364. | TIf (_,e1,Some e2) ->
  365. return_flow e1;
  366. return_flow e2;
  367. | TSwitch (v,cases,Some e) ->
  368. List.iter (fun (_,e) -> return_flow e) cases;
  369. return_flow e
  370. | TSwitch (e,cases,None) when (match follow e.etype with TEnum _ -> true | _ -> false) ->
  371. List.iter (fun (_,e) -> return_flow e) cases;
  372. | TMatch (_,_,cases,def) ->
  373. List.iter (fun (_,_,e) -> return_flow e) cases;
  374. (match def with None -> () | Some e -> return_flow e)
  375. | TTry (e,cases) ->
  376. return_flow e;
  377. List.iter (fun (_,_,e) -> return_flow e) cases;
  378. | _ ->
  379. error()
  380. (* ---------------------------------------------------------------------- *)
  381. (* PASS 1 & 2 : Module and Class Structure *)
  382. let set_heritance ctx c herits p =
  383. let rec loop = function
  384. | HPrivate | HExtern | HInterface ->
  385. ()
  386. | HExtends t ->
  387. if c.cl_super <> None then error "Cannot extend several classes" p;
  388. let t = load_normal_type ctx t p false in
  389. (match follow t with
  390. | TInst ({ cl_path = [],"Array" },_)
  391. | TInst ({ cl_path = [],"String" },_)
  392. | TInst ({ cl_path = [],"Date" },_)
  393. | TInst ({ cl_path = [],"Xml" },_) ->
  394. error "Cannot extend basic class" p;
  395. | TInst (cl,params) ->
  396. if is_parent c cl then error "Recursive class" p;
  397. if c.cl_interface then error "Cannot extend an interface" p;
  398. if cl.cl_interface then error "Cannot extend by using an interface" p;
  399. c.cl_super <- Some (cl,params)
  400. | _ -> error "Should extend by using a class" p)
  401. | HImplements t ->
  402. let t = load_normal_type ctx t p false in
  403. (match follow t with
  404. | TInst (cl,params) ->
  405. if is_parent c cl then error "Recursive class" p;
  406. c.cl_implements <- (cl, params) :: c.cl_implements
  407. | TDynamic t ->
  408. if c.cl_dynamic <> None then error "Cannot have several dynamics" p;
  409. c.cl_dynamic <- Some t
  410. | _ -> error "Should implement by using an interface or a class" p)
  411. in
  412. List.iter loop (List.filter ((!build_inheritance) ctx c p) herits)
  413. let type_type_params ctx path p (n,flags) =
  414. let c = mk_class (fst path @ [snd path],n) p None false in
  415. c.cl_kind <- KTypeParameter;
  416. let t = TInst (c,[]) in
  417. match flags with
  418. | [] -> n, t
  419. | _ ->
  420. let r = exc_protect (fun r ->
  421. r := (fun _ -> t);
  422. set_heritance ctx c (List.map (fun t -> HImplements t) flags) p;
  423. t
  424. ) in
  425. ctx.delays := [(fun () -> ignore(!r()))] :: !(ctx.delays);
  426. n, TLazy r
  427. let type_function ctx args ret static constr f p =
  428. let locals = save_locals ctx in
  429. let fargs = List.map (fun (n,c,t) ->
  430. let c = (match c with
  431. | None -> None
  432. | Some e ->
  433. let p = pos e in
  434. let e = type_expr ctx e true in
  435. unify ctx t e.etype p;
  436. match e.eexpr with
  437. | TConst c -> Some c
  438. | _ -> error "Parameter default value should be constant" p
  439. ) in
  440. let n = add_local ctx n t in
  441. n, c, t
  442. ) args in
  443. let old_ret = ctx.ret in
  444. let old_static = ctx.in_static in
  445. let old_constr = ctx.in_constructor in
  446. let old_opened = ctx.opened in
  447. ctx.in_static <- static;
  448. ctx.in_constructor <- constr;
  449. ctx.ret <- ret;
  450. ctx.opened <- [];
  451. let e = type_expr ctx f.f_expr false in
  452. let rec loop e =
  453. match e.eexpr with
  454. | TReturn (Some _) -> raise Exit
  455. | TFunction _ -> ()
  456. | _ -> Type.iter loop e
  457. in
  458. let have_ret = (try loop e; false with Exit -> true) in
  459. if have_ret then
  460. (try return_flow ctx e with Exit -> ())
  461. else
  462. unify ctx ret ctx.api.tvoid p;
  463. let rec loop e =
  464. match e.eexpr with
  465. | TCall ({ eexpr = TConst TSuper },_) -> raise Exit
  466. | TFunction _ -> ()
  467. | _ -> Type.iter loop e
  468. in
  469. if constr && (match ctx.curclass.cl_super with None -> false | Some (cl,_) -> cl.cl_constructor <> None) then
  470. (try
  471. loop e;
  472. error "Missing super constructor call" p
  473. with
  474. Exit -> ());
  475. locals();
  476. List.iter (fun r -> r := Closed) ctx.opened;
  477. ctx.ret <- old_ret;
  478. ctx.in_static <- old_static;
  479. ctx.in_constructor <- old_constr;
  480. ctx.opened <- old_opened;
  481. e , fargs
  482. let init_class ctx c p herits fields =
  483. ctx.type_params <- c.cl_types;
  484. c.cl_extern <- List.mem HExtern herits;
  485. c.cl_interface <- List.mem HInterface herits;
  486. set_heritance ctx c herits p;
  487. let tthis = TInst (c,List.map snd c.cl_types) in
  488. let rec extends_public c =
  489. List.exists (fun (c,_) -> c.cl_path = (["haxe"],"Public") || extends_public c) c.cl_implements ||
  490. match c.cl_super with
  491. | None -> false
  492. | Some (c,_) -> extends_public c
  493. in
  494. let extends_public = extends_public c in
  495. let is_public access parent =
  496. if List.mem APrivate access then
  497. false
  498. else if List.mem APublic access then
  499. true
  500. else match parent with
  501. | Some { cf_public = p } -> p
  502. | _ -> c.cl_extern || c.cl_interface || extends_public
  503. in
  504. let rec get_parent c name =
  505. match c.cl_super with
  506. | None -> None
  507. | Some (csup,_) ->
  508. try
  509. Some (PMap.find name csup.cl_fields)
  510. with
  511. Not_found -> get_parent csup name
  512. in
  513. let type_opt ctx p t =
  514. match t with
  515. | None when c.cl_extern || c.cl_interface ->
  516. display_error ctx "Type required for extern classes and interfaces" p;
  517. t_dynamic
  518. | _ ->
  519. load_type_opt ctx p t
  520. in
  521. let rec has_field f = function
  522. | None -> false
  523. | Some (c,_) ->
  524. PMap.exists f c.cl_fields || has_field f c.cl_super || List.exists (fun i -> has_field f (Some i)) c.cl_implements
  525. in
  526. let loop_cf f p =
  527. match f with
  528. | FVar (name,doc,access,t,e) ->
  529. let stat = List.mem AStatic access in
  530. let inline = List.mem AInline access in
  531. if not stat && has_field name c.cl_super then error ("Redefinition of variable " ^ name ^ " in subclass is not allowed") p;
  532. if inline && not stat then error "Inline variable must be static" p;
  533. if inline && e = None then error "Inline variable must be initialized" p;
  534. let t = (match t with
  535. | None ->
  536. if not stat then display_error ctx ("Type required for member variable " ^ name) p;
  537. mk_mono()
  538. | Some t ->
  539. let old = ctx.type_params in
  540. if stat then ctx.type_params <- [];
  541. let t = load_type ctx p t in
  542. if stat then ctx.type_params <- old;
  543. t
  544. ) in
  545. let cf = {
  546. cf_name = name;
  547. cf_doc = doc;
  548. cf_type = t;
  549. cf_get = if inline then InlineAccess else NormalAccess;
  550. cf_set = if inline then NeverAccess else NormalAccess;
  551. cf_expr = None;
  552. cf_public = is_public access None;
  553. cf_params = [];
  554. } in
  555. let delay = (match e with
  556. | None -> (fun() -> ())
  557. | Some e ->
  558. let ctx = { ctx with curclass = c; tthis = tthis } in
  559. let r = exc_protect (fun r ->
  560. r := (fun() -> t);
  561. if ctx.com.verbose then print_endline ("Typing " ^ s_type_path c.cl_path ^ "." ^ name);
  562. cf.cf_expr <- Some (type_static_var ctx t e p);
  563. t
  564. ) in
  565. cf.cf_type <- TLazy r;
  566. (fun () -> ignore(!r()))
  567. ) in
  568. access, false, cf, delay
  569. | FFun (name,doc,access,params,f) ->
  570. let params = List.map (fun (n,flags) ->
  571. match flags with
  572. | [] ->
  573. type_type_params ctx ([],name) p (n,[])
  574. | _ -> error "This notation is not allowed because it can't be checked" p
  575. ) params in
  576. let stat = List.mem AStatic access in
  577. let inline = List.mem AInline access in
  578. let parent = (if not stat then get_parent c name else None) in
  579. let dynamic = List.mem ADynamic access || (match parent with Some { cf_set = NormalAccess } -> true | _ -> false) in
  580. let ctx = { ctx with
  581. curclass = c;
  582. curmethod = name;
  583. tthis = tthis;
  584. type_params = if stat then params else params @ ctx.type_params;
  585. } in
  586. let ret = type_opt ctx p f.f_type in
  587. let args = List.map (fun (name,opt,t,c) ->
  588. let t, c = type_function_param ctx (type_opt ctx p t) c opt p in
  589. name, c, t
  590. ) f.f_args in
  591. let t = TFun (fun_args args,ret) in
  592. let constr = (name = "new") in
  593. if constr && c.cl_interface then error "An interface cannot have a constructor" p;
  594. if c.cl_interface && not stat && (match f.f_expr with EBlock [] , _ -> false | _ -> true) then error "An interface method cannot have a body" p;
  595. if constr then (match f.f_type with
  596. | None | Some (TPNormal { tpackage = []; tname = "Void" }) -> ()
  597. | _ -> error "A class constructor can't have a return value" p
  598. );
  599. let cf = {
  600. cf_name = name;
  601. cf_doc = doc;
  602. cf_type = t;
  603. cf_get = if inline then InlineAccess else NormalAccess;
  604. cf_set = (if inline then NeverAccess else if dynamic then NormalAccess else MethodCantAccess);
  605. cf_expr = None;
  606. cf_public = is_public access parent;
  607. cf_params = params;
  608. } in
  609. let r = exc_protect (fun r ->
  610. r := (fun() -> t);
  611. if ctx.com.verbose then print_endline ("Typing " ^ s_type_path c.cl_path ^ "." ^ name);
  612. let e , fargs = type_function ctx args ret stat constr f p in
  613. let f = {
  614. tf_args = fargs;
  615. tf_type = ret;
  616. tf_expr = e;
  617. } in
  618. if stat && name = "__init__" then c.cl_init <- Some e;
  619. cf.cf_expr <- Some (mk (TFunction f) t p);
  620. t
  621. ) in
  622. let delay = (
  623. if (c.cl_extern || c.cl_interface) && cf.cf_name <> "__init__" then
  624. (fun() -> ())
  625. else begin
  626. cf.cf_type <- TLazy r;
  627. (fun() -> ignore((!r)()))
  628. end
  629. ) in
  630. access, constr, cf, delay
  631. | FProp (name,doc,access,get,set,t) ->
  632. let ret = load_type ctx p t in
  633. let check_get = ref (fun() -> ()) in
  634. let check_set = ref (fun() -> ()) in
  635. let check_method m t () =
  636. try
  637. let t2 = (if List.mem AStatic access then (PMap.find m c.cl_statics).cf_type else fst (class_field c m)) in
  638. unify_raise ctx t2 t p;
  639. with
  640. | Error (Unify l,_) -> raise (Error (Stack (Custom ("In method " ^ m ^ " required by property " ^ name),Unify l),p))
  641. | Not_found -> if not c.cl_interface then error ("Method " ^ m ^ " required by property " ^ name ^ " is missing") p
  642. in
  643. let get = (match get with
  644. | "null" -> NoAccess
  645. | "dynamic" -> MethodAccess ("get_" ^ name)
  646. | "default" -> NormalAccess
  647. | _ ->
  648. check_get := check_method get (TFun ([],ret));
  649. MethodAccess get
  650. ) in
  651. let set = (match set with
  652. | "null" ->
  653. (* standard flash library read-only variables can't be accessed for writing, even in subclasses *)
  654. if c.cl_extern && (match c.cl_path with "flash" :: _ , _ -> true | _ -> false) && Common.defined ctx.com "flash9" then
  655. NeverAccess
  656. else
  657. NoAccess
  658. | "dynamic" -> MethodAccess ("set_" ^ name)
  659. | "default" -> NormalAccess
  660. | _ ->
  661. check_set := check_method set (TFun (["",false,ret],ret));
  662. MethodAccess set
  663. ) in
  664. if set = NormalAccess && (match get with MethodAccess _ -> true | _ -> false) then error "Unsupported property combination" p;
  665. let cf = {
  666. cf_name = name;
  667. cf_doc = doc;
  668. cf_get = get;
  669. cf_set = set;
  670. cf_expr = None;
  671. cf_type = ret;
  672. cf_public = is_public access None;
  673. cf_params = [];
  674. } in
  675. access, false, cf, (fun() -> (!check_get)(); (!check_set)())
  676. in
  677. let fl = List.map (fun (f,p) ->
  678. let access , constr, f , delayed = loop_cf f p in
  679. let is_static = List.mem AStatic access in
  680. if is_static && f.cf_name = "name" && Common.defined ctx.com "js" then error "This identifier cannot be used in Javascript for statics" p;
  681. if (is_static || constr) && c.cl_interface && f.cf_name <> "__init__" then error "You can't declare static fields in interfaces" p;
  682. if constr then begin
  683. if c.cl_constructor <> None then error "Duplicate constructor" p;
  684. c.cl_constructor <- Some f;
  685. end else if not is_static || f.cf_name <> "__init__" then begin
  686. 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;
  687. if is_static then begin
  688. c.cl_statics <- PMap.add f.cf_name f c.cl_statics;
  689. c.cl_ordered_statics <- f :: c.cl_ordered_statics;
  690. end else begin
  691. c.cl_fields <- PMap.add f.cf_name f c.cl_fields;
  692. c.cl_ordered_fields <- f :: c.cl_ordered_fields;
  693. if List.mem AOverride access then c.cl_overrides <- f.cf_name :: c.cl_overrides;
  694. end;
  695. end;
  696. delayed
  697. ) fields in
  698. c.cl_ordered_statics <- List.rev c.cl_ordered_statics;
  699. c.cl_ordered_fields <- List.rev c.cl_ordered_fields;
  700. (*
  701. define a default inherited constructor.
  702. This is actually pretty tricky since we can't assume that the constructor of the
  703. superclass has been defined yet because type structure is not stabilized wrt recursion.
  704. *)
  705. let rec define_constructor ctx c =
  706. try
  707. Some (Hashtbl.find ctx.constructs c.cl_path)
  708. with Not_found ->
  709. match c.cl_super with
  710. | None -> None
  711. | Some (csuper,_) ->
  712. match define_constructor ctx csuper with
  713. | None -> None
  714. | Some (acc,pl,f) as infos ->
  715. let p = c.cl_pos in
  716. let esuper = (ECall ((EConst (Ident "super"),p),List.map (fun (n,_,_,_) -> (EConst (Ident n),p)) f.f_args),p) in
  717. let acc = (if csuper.cl_extern && acc = [] then [APublic] else acc) in
  718. let fnew = { f with f_expr = esuper; f_args = List.map (fun (a,opt,t,def) ->
  719. (*
  720. we are removing the type and letting the type inference
  721. work because the current package is not the same as the superclass one
  722. or there might be private and/or imported types
  723. if we are an extern class then we need a type
  724. if the type is Dynamic also because it would not propagate
  725. if we have a package declaration, we are sure it's fully qualified
  726. *)
  727. let rec is_qualified = function
  728. | TPNormal t -> is_qual_name t
  729. | TPParent t -> is_qualified t
  730. | TPFunction (tl,t) -> List.for_all is_qualified tl && is_qualified t
  731. | TPAnonymous fl -> List.for_all (fun (_,_,f,_) -> is_qual_field f) fl
  732. | TPExtend (t,fl) -> is_qual_name t && List.for_all (fun (_,_,f,_) -> is_qual_field f) fl
  733. and is_qual_field = function
  734. | AFVar t -> is_qualified t
  735. | AFProp (t,_,_) -> is_qualified t
  736. | AFFun (pl,t) -> List.for_all (fun (_,_,t) -> is_qualified t) pl && is_qualified t
  737. and is_qual_name t =
  738. match t.tpackage with
  739. | [] -> t.tname = "Dynamic" && List.for_all is_qual_param t.tparams
  740. | _ :: _ -> true
  741. and is_qual_param = function
  742. | TPType t -> is_qualified t
  743. | TPConst _ -> false (* prevent multiple incompatible types *)
  744. in
  745. let t = (match t with
  746. | Some t when c.cl_extern || is_qualified t -> Some t
  747. | _ -> None
  748. ) in
  749. a,opt,t,def
  750. ) f.f_args } in
  751. let _, _, cf, delayed = loop_cf (FFun ("new",None,acc,pl,fnew)) p in
  752. c.cl_constructor <- Some cf;
  753. Hashtbl.add ctx.constructs c.cl_path (acc,pl,f);
  754. ctx.delays := [delayed] :: !(ctx.delays);
  755. infos
  756. in
  757. ignore(define_constructor ctx c);
  758. fl
  759. let type_module ctx m tdecls loadp =
  760. (* PASS 1 : build module structure - does not load any module or type - should be atomic ! *)
  761. let decls = ref [] in
  762. let decl_with_name name p priv =
  763. let tpath = if priv then (fst m @ ["_" ^ snd m], name) else (fst m, name) in
  764. if priv then begin
  765. if List.exists (fun t -> tpath = t_path t) (!decls) then error ("Type name " ^ name ^ " is alreday defined in this module") p;
  766. tpath
  767. end else try
  768. let m2 = Hashtbl.find ctx.types_module tpath in
  769. if m <> m2 && String.lowercase (s_type_path m2) = String.lowercase (s_type_path m) then error ("Module " ^ s_type_path m2 ^ " is loaded with a different case than " ^ s_type_path m) loadp;
  770. error ("Type name " ^ s_type_path tpath ^ " is redefined from module " ^ s_type_path m2) p
  771. with
  772. Not_found ->
  773. Hashtbl.add ctx.types_module (fst m,name) m;
  774. tpath
  775. in
  776. List.iter (fun (d,p) ->
  777. match d with
  778. | EImport _ -> ()
  779. | EClass d ->
  780. let priv = List.mem HPrivate d.d_flags in
  781. let path = decl_with_name d.d_name p priv in
  782. let c = mk_class path p d.d_doc priv in
  783. (* store the constructor for later usage *)
  784. List.iter (fun (cf,_) ->
  785. match cf with
  786. | FFun ("new",_,acc,pl,f) -> Hashtbl.add ctx.constructs path (acc,pl,f)
  787. | _ -> ()
  788. ) d.d_data;
  789. decls := TClassDecl c :: !decls
  790. | EEnum d ->
  791. let priv = List.mem EPrivate d.d_flags in
  792. let path = decl_with_name d.d_name p priv in
  793. let e = {
  794. e_path = path;
  795. e_pos = p;
  796. e_doc = d.d_doc;
  797. e_types = [];
  798. e_private = priv;
  799. e_extern = List.mem EExtern d.d_flags || d.d_data = [];
  800. e_constrs = PMap.empty;
  801. e_names = [];
  802. } in
  803. decls := TEnumDecl e :: !decls
  804. | ETypedef d ->
  805. let priv = List.mem EPrivate d.d_flags in
  806. let path = decl_with_name d.d_name p priv in
  807. let t = {
  808. t_path = path;
  809. t_pos = p;
  810. t_doc = d.d_doc;
  811. t_private = priv;
  812. t_types = [];
  813. t_type = mk_mono();
  814. } in
  815. decls := TTypeDecl t :: !decls
  816. ) tdecls;
  817. let m = {
  818. mpath = m;
  819. mtypes = List.rev !decls;
  820. mimports = [];
  821. } in
  822. Hashtbl.add ctx.modules m.mpath m;
  823. (* PASS 2 : build types structure - does not type any expression ! *)
  824. let ctx = {
  825. com = ctx.com;
  826. api = ctx.api;
  827. modules = ctx.modules;
  828. delays = ctx.delays;
  829. constructs = ctx.constructs;
  830. types_module = ctx.types_module;
  831. curclass = ctx.curclass;
  832. tthis = ctx.tthis;
  833. std = ctx.std;
  834. ret = ctx.ret;
  835. doinline = ctx.doinline;
  836. current = m;
  837. locals = PMap.empty;
  838. locals_map = PMap.empty;
  839. locals_map_inv = PMap.empty;
  840. local_types = ctx.std.mtypes @ m.mtypes;
  841. type_params = [];
  842. curmethod = "";
  843. super_call = false;
  844. in_constructor = false;
  845. in_static = false;
  846. in_display = false;
  847. in_loop = false;
  848. untyped = false;
  849. opened = [];
  850. param_type = None;
  851. } in
  852. let delays = ref [] in
  853. let get_class name =
  854. let c = List.find (fun d -> match d with TClassDecl { cl_path = _ , n } -> n = name | _ -> false) m.mtypes in
  855. match c with TClassDecl c -> c | _ -> assert false
  856. in
  857. let get_enum name =
  858. let e = List.find (fun d -> match d with TEnumDecl { e_path = _ , n } -> n = name | _ -> false) m.mtypes in
  859. match e with TEnumDecl e -> e | _ -> assert false
  860. in
  861. let get_tdef name =
  862. let s = List.find (fun d -> match d with TTypeDecl { t_path = _ , n } -> n = name | _ -> false) m.mtypes in
  863. match s with TTypeDecl s -> s | _ -> assert false
  864. in
  865. (* here is an additional PASS 1 phase, which handle the type parameters declaration, with lazy contraints *)
  866. List.iter (fun (d,p) ->
  867. match d with
  868. | EImport _ -> ()
  869. | EClass d ->
  870. let c = get_class d.d_name in
  871. c.cl_types <- List.map (type_type_params ctx c.cl_path p) d.d_params;
  872. | EEnum d ->
  873. let e = get_enum d.d_name in
  874. e.e_types <- List.map (type_type_params ctx e.e_path p) d.d_params;
  875. | ETypedef d ->
  876. let t = get_tdef d.d_name in
  877. t.t_types <- List.map (type_type_params ctx t.t_path p) d.d_params;
  878. ) tdecls;
  879. (* back to PASS2 *)
  880. List.iter (fun (d,p) ->
  881. match d with
  882. | EImport (pack,name,topt) ->
  883. let md = ctx.api.load_module (pack,name) p in
  884. let types = List.filter (fun t -> not (t_private t)) md.mtypes in
  885. (match topt with
  886. | None -> ctx.local_types <- ctx.local_types @ types
  887. | Some t ->
  888. try
  889. let t = List.find (fun tdecl -> snd (t_path tdecl) = t) types in
  890. ctx.local_types <- ctx.local_types @ [t]
  891. with
  892. Not_found -> error ("Module " ^ s_type_path (pack,name) ^ " does not define type " ^ t) p
  893. );
  894. m.mimports <- (md,topt) :: m.mimports;
  895. | EClass d ->
  896. let c = get_class d.d_name in
  897. delays := !delays @ check_overriding ctx c p :: check_interfaces ctx c p :: init_class ctx c p d.d_flags d.d_data
  898. | EEnum d ->
  899. let e = get_enum d.d_name in
  900. ctx.type_params <- e.e_types;
  901. let et = TEnum (e,List.map snd e.e_types) in
  902. let names = ref [] in
  903. let index = ref 0 in
  904. List.iter (fun (c,doc,t,p) ->
  905. if c = "name" && Common.defined ctx.com "js" then error "This identifier cannot be used in Javascript" p;
  906. let t = (match t with
  907. | [] -> et
  908. | l -> TFun (List.map (fun (s,opt,t) -> s, opt, load_type_opt ~opt ctx p (Some t)) l, et)
  909. ) in
  910. if PMap.mem c e.e_constrs then error ("Duplicate constructor " ^ c) p;
  911. e.e_constrs <- PMap.add c {
  912. ef_name = c;
  913. ef_type = t;
  914. ef_pos = p;
  915. ef_doc = doc;
  916. ef_index = !index;
  917. } e.e_constrs;
  918. incr index;
  919. names := c :: !names;
  920. ) d.d_data;
  921. e.e_names <- List.rev !names;
  922. | ETypedef d ->
  923. let t = get_tdef d.d_name in
  924. ctx.type_params <- t.t_types;
  925. let tt = load_type ctx p d.d_data in
  926. if t.t_type == follow tt then error "Recursive typedef is not allowed" p;
  927. (match t.t_type with
  928. | TMono r ->
  929. (match !r with
  930. | None -> r := Some tt;
  931. | Some _ -> assert false);
  932. | _ -> assert false);
  933. ) tdecls;
  934. (* PASS 3 : type checking, delayed until all modules and types are built *)
  935. ctx.delays := !delays :: !(ctx.delays);
  936. m.mimports <- List.rev m.mimports;
  937. m
  938. let parse_module ctx m p =
  939. let remap = ref (fst m) in
  940. let file = (match m with
  941. | [] , name -> name
  942. | x :: l , name ->
  943. let x = (try
  944. match PMap.find x ctx.com.package_rules with
  945. | Forbidden -> error ("You can't access the " ^ x ^ " package with current compilation flags (for " ^ s_type_path m ^ ")") p;
  946. | Directory d -> d
  947. | Remap d -> remap := d :: l; d
  948. with Not_found -> x
  949. ) in
  950. String.concat "/" (x :: l) ^ "/" ^ name
  951. ) ^ ".hx" in
  952. let file = (try Common.find_file ctx.com file with Not_found -> raise (Error (Module_not_found m,p))) in
  953. let ch = (try open_in_bin file with _ -> error ("Could not open " ^ file) p) in
  954. let t = Common.timer "parsing" in
  955. let pack , decls = (try Parser.parse ctx.com (Lexing.from_channel ch) file with e -> close_in ch; t(); raise e) in
  956. t();
  957. close_in ch;
  958. if ctx.com.verbose then print_endline ("Parsed " ^ file);
  959. if pack <> !remap then begin
  960. let spack m = if m = [] then "<empty>" else String.concat "." m in
  961. if p == Ast.null_pos then
  962. error ("Invalid commandline class : " ^ s_type_path m ^ " should be " ^ s_type_path (pack,snd m)) p
  963. else
  964. error ("Invalid package : " ^ spack (fst m) ^ " should be " ^ spack pack) p
  965. end;
  966. if !remap <> fst m then
  967. (* build typedefs to redirect to real package *)
  968. List.rev (List.fold_left (fun acc (t,p) ->
  969. let build f d =
  970. let priv = List.mem f d.d_flags in
  971. (ETypedef {
  972. d_name = d.d_name;
  973. d_doc = None;
  974. d_params = d.d_params;
  975. d_flags = if priv then [EPrivate] else [];
  976. d_data = TPNormal (if priv then { tpackage = []; tname = "Dynamic"; tparams = []; } else
  977. {
  978. tpackage = !remap;
  979. tname = d.d_name;
  980. tparams = List.map (fun (s,_) ->
  981. TPType (TPNormal { tpackage = []; tname = s; tparams = [] })
  982. ) d.d_params;
  983. });
  984. },p) :: acc
  985. in
  986. match t with
  987. | EClass d -> build HPrivate d
  988. | EEnum d -> build EPrivate d
  989. | ETypedef d -> build EPrivate d
  990. | EImport _ -> acc
  991. ) [(EImport (!remap, snd m, None),null_pos)] decls)
  992. else
  993. decls
  994. let load_module ctx m p =
  995. try
  996. Hashtbl.find ctx.modules m
  997. with
  998. Not_found ->
  999. let decls = parse_module ctx m p in
  1000. type_module ctx m decls p