typeload.ml 35 KB

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