typeload.ml 34 KB

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