typeload.ml 34 KB

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