typeload.ml 36 KB

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