typeload.ml 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814
  1. (*
  2. * Copyright (C)2005-2013 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. *)
  22. open Ast
  23. open Type
  24. open Common
  25. open Typecore
  26. (*
  27. Build module structure : should be atomic - no type loading is possible
  28. *)
  29. let make_module ctx mpath file tdecls loadp =
  30. let decls = ref [] in
  31. let make_path name priv =
  32. if List.exists (fun (t,_) -> snd (t_path t) = name) !decls then error ("Type name " ^ name ^ " is already defined in this module") loadp;
  33. if priv then (fst mpath @ ["_" ^ snd mpath], name) else (fst mpath, name)
  34. in
  35. let m = {
  36. m_id = alloc_mid();
  37. m_path = mpath;
  38. m_types = [];
  39. m_extra = module_extra (Common.unique_full_path file) (Common.get_signature ctx.com) (file_time file) (if ctx.in_macro then MMacro else MCode);
  40. } in
  41. let pt = ref None in
  42. let rec make_decl acc decl =
  43. let p = snd decl in
  44. let acc = (match fst decl with
  45. | EImport _ | EUsing _ ->
  46. (match !pt with
  47. | None -> acc
  48. | Some pt ->
  49. display_error ctx "import and using may not appear after a type declaration" p;
  50. error "Previous type declaration found here" pt)
  51. | EClass d ->
  52. pt := Some p;
  53. let priv = List.mem HPrivate d.d_flags in
  54. let path = make_path d.d_name priv in
  55. let c = mk_class m path p in
  56. c.cl_module <- m;
  57. c.cl_private <- priv;
  58. c.cl_doc <- d.d_doc;
  59. c.cl_meta <- d.d_meta;
  60. decls := (TClassDecl c, decl) :: !decls;
  61. acc
  62. | EEnum d ->
  63. pt := Some p;
  64. let priv = List.mem EPrivate d.d_flags in
  65. let path = make_path d.d_name priv in
  66. let e = {
  67. e_path = path;
  68. e_module = m;
  69. e_pos = p;
  70. e_doc = d.d_doc;
  71. e_meta = d.d_meta;
  72. e_types = [];
  73. e_private = priv;
  74. e_extern = List.mem EExtern d.d_flags;
  75. e_constrs = PMap.empty;
  76. e_names = [];
  77. e_type = {
  78. t_path = [], "Enum<" ^ (s_type_path path) ^ ">";
  79. t_module = m;
  80. t_doc = None;
  81. t_pos = p;
  82. t_type = mk_mono();
  83. t_private = true;
  84. t_types = [];
  85. t_meta = [];
  86. };
  87. } in
  88. decls := (TEnumDecl e, decl) :: !decls;
  89. acc
  90. | ETypedef d ->
  91. pt := Some p;
  92. let priv = List.mem EPrivate d.d_flags in
  93. let path = make_path d.d_name priv in
  94. let t = {
  95. t_path = path;
  96. t_module = m;
  97. t_pos = p;
  98. t_doc = d.d_doc;
  99. t_private = priv;
  100. t_types = [];
  101. t_type = mk_mono();
  102. t_meta = d.d_meta;
  103. } in
  104. decls := (TTypeDecl t, decl) :: !decls;
  105. acc
  106. | EAbstract d ->
  107. let priv = List.mem APrivAbstract d.d_flags in
  108. let path = make_path d.d_name priv in
  109. let a = {
  110. a_path = path;
  111. a_private = priv;
  112. a_module = m;
  113. a_pos = p;
  114. a_doc = d.d_doc;
  115. a_types = [];
  116. a_meta = d.d_meta;
  117. a_from = [];
  118. a_to = [];
  119. a_ops = [];
  120. a_unops = [];
  121. a_impl = None;
  122. a_array = [];
  123. a_this = mk_mono();
  124. } in
  125. decls := (TAbstractDecl a, decl) :: !decls;
  126. match d.d_data with
  127. | [] when Meta.has Meta.CoreType a.a_meta ->
  128. a.a_this <- t_dynamic;
  129. acc
  130. | fields ->
  131. let rec loop = function
  132. | [] ->
  133. let params = List.map (fun t -> TPType (CTPath { tname = t.tp_name; tparams = []; tsub = None; tpackage = [] })) d.d_params in
  134. CTPath { tpackage = []; tname = d.d_name; tparams = params; tsub = None }
  135. | AIsType t :: _ -> t
  136. | _ :: l -> loop l
  137. in
  138. let this_t = loop d.d_flags in
  139. let fields = List.map (fun f ->
  140. let stat = List.mem AStatic f.cff_access in
  141. let p = f.cff_pos in
  142. match f.cff_kind with
  143. | FProp (("get" | "never"),("set" | "never"),_,_) when not stat ->
  144. (* TODO: hack to avoid issues with abstract property generation on As3 *)
  145. if Common.defined ctx.com Define.As3 then f.cff_meta <- (Meta.Extern,[],p) :: f.cff_meta;
  146. { f with cff_access = AStatic :: f.cff_access; cff_meta = (Meta.Impl,[],p) :: f.cff_meta }
  147. | FProp _ when not stat ->
  148. display_error ctx "Member property accessors must be get/set or never" p;
  149. f
  150. | FFun fu when f.cff_name = "new" && not stat ->
  151. let init p = (EVars ["this",Some this_t,None],p) in
  152. let ret p = (EReturn (Some (EConst (Ident "this"),p)),p) in
  153. if Meta.has Meta.MultiType a.a_meta then begin
  154. if List.mem AInline f.cff_access then error "MultiType constructors cannot be inline" f.cff_pos;
  155. if fu.f_expr <> None then error "MultiType constructors cannot have a body" f.cff_pos;
  156. end;
  157. let has_call e =
  158. let rec loop e = match fst e with
  159. | ECall _ -> raise Exit
  160. | _ -> Ast.map_expr loop e
  161. in
  162. try ignore(loop e); false with Exit -> true
  163. in
  164. let fu = {
  165. fu with
  166. f_expr = (match fu.f_expr with
  167. | None -> if Meta.has Meta.MultiType a.a_meta then Some (EConst (Ident "null"),p) else None
  168. | Some (EBlock [EBinop (OpAssign,(EConst (Ident "this"),_),e),_],_ | EBinop (OpAssign,(EConst (Ident "this"),_),e),_) when not (has_call e) ->
  169. Some (EReturn (Some e), pos e)
  170. | Some (EBlock el,p) -> Some (EBlock (init p :: el @ [ret p]),p)
  171. | Some e -> Some (EBlock [init p;e;ret p],p)
  172. );
  173. f_type = Some this_t;
  174. } in
  175. { f with cff_name = "_new"; cff_access = AStatic :: f.cff_access; cff_kind = FFun fu; cff_meta = (Meta.Impl,[],p) :: f.cff_meta }
  176. | FFun fu when not stat ->
  177. if Meta.has Meta.From f.cff_meta then error "@:from cast functions must be static" f.cff_pos;
  178. let fu = { fu with f_args = (if List.mem AMacro f.cff_access then fu.f_args else ("this",false,Some this_t,None) :: fu.f_args) } in
  179. { f with cff_kind = FFun fu; cff_access = AStatic :: f.cff_access; cff_meta = (Meta.Impl,[],p) :: f.cff_meta }
  180. | _ ->
  181. f
  182. ) fields in
  183. let meta = ref [] in
  184. if has_meta Meta.Dce a.a_meta then meta := (Meta.Dce,[],p) :: !meta;
  185. let acc = make_decl acc (EClass { d_name = d.d_name ^ "_Impl_"; d_flags = [HPrivate]; d_data = fields; d_doc = None; d_params = []; d_meta = !meta },p) in
  186. (match !decls with
  187. | (TClassDecl c,_) :: _ ->
  188. List.iter (fun m -> match m with
  189. | ((Meta.Build | Meta.CoreApi | Meta.Allow | Meta.Access | Meta.Enum | Meta.Dce),_,_) ->
  190. c.cl_meta <- m :: c.cl_meta;
  191. | _ ->
  192. ()
  193. ) a.a_meta;
  194. a.a_impl <- Some c;
  195. c.cl_kind <- KAbstractImpl a
  196. | _ -> assert false);
  197. acc
  198. ) in
  199. decl :: acc
  200. in
  201. let tdecls = List.fold_left make_decl [] tdecls in
  202. let decls = List.rev !decls in
  203. m.m_types <- List.map fst decls;
  204. m, decls, List.rev tdecls
  205. let parse_file com file p =
  206. let ch = (try open_in_bin file with _ -> error ("Could not open " ^ file) p) in
  207. let t = Common.timer "parsing" in
  208. Lexer.init file true;
  209. incr stats.s_files_parsed;
  210. let data = (try Parser.parse com (Lexing.from_channel ch) with e -> close_in ch; t(); raise e) in
  211. close_in ch;
  212. t();
  213. Common.log com ("Parsed " ^ file);
  214. data
  215. let parse_hook = ref parse_file
  216. let type_module_hook = ref (fun _ _ _ -> None)
  217. let type_function_params_rec = ref (fun _ _ _ _ -> assert false)
  218. let return_partial_type = ref false
  219. let type_function_param ctx t e opt p =
  220. if opt then
  221. let e = (match e with None -> Some (EConst (Ident "null"),p) | _ -> e) in
  222. ctx.t.tnull t, e
  223. else
  224. let t = match e with Some (EConst (Ident "null"),p) -> ctx.t.tnull t | _ -> t in
  225. t, e
  226. let type_var_field ctx t e stat p =
  227. if stat then ctx.curfun <- FunStatic else ctx.curfun <- FunMember;
  228. let e = type_expr ctx e (WithType t) in
  229. unify ctx e.etype t p;
  230. match t with
  231. | TType ({ t_path = ([],"UInt") },[]) | TAbstract ({ a_path = ([],"UInt") },[]) when stat -> { e with etype = t }
  232. | _ -> e
  233. let apply_macro ctx mode path el p =
  234. let cpath, meth = (match List.rev (ExtString.String.nsplit path ".") with
  235. | meth :: name :: pack -> (List.rev pack,name), meth
  236. | _ -> error "Invalid macro path" p
  237. ) in
  238. ctx.g.do_macro ctx mode cpath meth el p
  239. (** since load_type_def and load_instance are used in PASS2, they should not access the structure of a type **)
  240. (*
  241. load a type or a subtype definition
  242. *)
  243. let rec load_type_def ctx p t =
  244. let no_pack = t.tpackage = [] in
  245. let tname = (match t.tsub with None -> t.tname | Some n -> n) in
  246. try
  247. if t.tsub <> None then raise Not_found;
  248. List.find (fun t2 ->
  249. let tp = t_path t2 in
  250. tp = (t.tpackage,tname) || (no_pack && snd tp = tname)
  251. ) (ctx.m.curmod.m_types @ ctx.m.module_types)
  252. with
  253. Not_found ->
  254. let next() =
  255. let t, m = (try
  256. t, ctx.g.do_load_module ctx (t.tpackage,t.tname) p
  257. with Error (Module_not_found _,p2) as e when p == p2 ->
  258. match t.tpackage with
  259. | "std" :: l ->
  260. let t = { t with tpackage = l } in
  261. t, ctx.g.do_load_module ctx (t.tpackage,t.tname) p
  262. | _ -> raise e
  263. ) in
  264. let tpath = (t.tpackage,tname) in
  265. try
  266. List.find (fun t -> not (t_infos t).mt_private && t_path t = tpath) m.m_types
  267. with
  268. Not_found -> raise (Error (Type_not_found (m.m_path,tname),p))
  269. in
  270. (* lookup in wildcard imported packages *)
  271. try
  272. if not no_pack then raise Exit;
  273. let rec loop = function
  274. | [] -> raise Exit
  275. | wp :: l ->
  276. try
  277. load_type_def ctx p { t with tpackage = wp }
  278. with
  279. | Error (Module_not_found _,p2)
  280. | Error (Type_not_found _,p2) when p == p2 -> loop l
  281. in
  282. loop ctx.m.wildcard_packages
  283. with Exit ->
  284. (* lookup in our own package - and its upper packages *)
  285. let rec loop = function
  286. | [] -> raise Exit
  287. | (_ :: lnext) as l ->
  288. try
  289. load_type_def ctx p { t with tpackage = List.rev l }
  290. with
  291. | Error (Module_not_found _,p2)
  292. | Error (Type_not_found _,p2) when p == p2 -> loop lnext
  293. in
  294. try
  295. if not no_pack then raise Exit;
  296. (match fst ctx.m.curmod.m_path with
  297. | [] -> raise Exit
  298. | x :: _ ->
  299. (* this can occur due to haxe remoting : a module can be
  300. already defined in the "js" package and is not allowed
  301. to access the js classes *)
  302. try
  303. (match PMap.find x ctx.com.package_rules with
  304. | Forbidden -> raise Exit
  305. | _ -> ())
  306. with Not_found -> ());
  307. loop (List.rev (fst ctx.m.curmod.m_path));
  308. with
  309. Exit -> next()
  310. let check_param_constraints ctx types t pl c p =
  311. match follow t with
  312. | TMono _ -> ()
  313. | _ ->
  314. let ctl = (match c.cl_kind with KTypeParameter l -> l | _ -> []) in
  315. List.iter (fun ti ->
  316. let ti = apply_params types pl ti in
  317. let ti = (match follow ti with
  318. | TInst ({ cl_kind = KGeneric } as c,pl) ->
  319. (* if we solve a generic contraint, let's substitute with the actual generic instance before unifying *)
  320. let _,_, f = ctx.g.do_build_instance ctx (TClassDecl c) p in
  321. f pl
  322. | _ -> ti
  323. ) in
  324. try
  325. unify_raise ctx t ti p
  326. with Error(Unify l,p) ->
  327. if not ctx.untyped then display_error ctx (error_msg (Unify (Constraint_failure (s_type_path c.cl_path) :: l))) p;
  328. ) ctl
  329. (* build an instance from a full type *)
  330. let rec load_instance ctx t p allow_no_params =
  331. try
  332. if t.tpackage <> [] || t.tsub <> None then raise Not_found;
  333. let pt = List.assoc t.tname ctx.type_params in
  334. if t.tparams <> [] then error ("Class type parameter " ^ t.tname ^ " can't have parameters") p;
  335. pt
  336. with Not_found ->
  337. let mt = load_type_def ctx p t in
  338. let is_generic,is_generic_build = match mt with
  339. | TClassDecl {cl_kind = KGeneric} -> true,false
  340. | TClassDecl {cl_kind = KGenericBuild _} -> false,true
  341. | _ -> false,false
  342. in
  343. let types , path , f = ctx.g.do_build_instance ctx mt p in
  344. if allow_no_params && t.tparams = [] && not (match types with ["Rest",_] -> true | _ -> false) then begin
  345. let pl = ref [] in
  346. pl := List.map (fun (name,t) ->
  347. match follow t with
  348. | TInst (c,_) ->
  349. let t = mk_mono() in
  350. if c.cl_kind <> KTypeParameter [] || is_generic then delay ctx PCheckConstraint (fun() -> check_param_constraints ctx types t (!pl) c p);
  351. t;
  352. | _ -> assert false
  353. ) types;
  354. f (!pl)
  355. end else if path = ([],"Dynamic") then
  356. match t.tparams with
  357. | [] -> t_dynamic
  358. | [TPType t] -> TDynamic (load_complex_type ctx p t)
  359. | _ -> error "Too many parameters for Dynamic" p
  360. else begin
  361. (* if List.length types <> List.length t.tparams then error ("Invalid number of type parameters for " ^ s_type_path path) p; *)
  362. let tparams = List.map (fun t ->
  363. match t with
  364. | TPExpr e ->
  365. let name = (match fst e with
  366. | EConst (String s) -> "S" ^ s
  367. | EConst (Int i) -> "I" ^ i
  368. | EConst (Float f) -> "F" ^ f
  369. | _ -> "Expr"
  370. ) in
  371. let c = mk_class null_module ([],name) p in
  372. c.cl_kind <- KExpr e;
  373. TInst (c,[])
  374. | TPType t -> load_complex_type ctx p t
  375. ) t.tparams in
  376. let rec loop tl1 tl2 is_rest = match tl1,tl2 with
  377. | t :: tl1,(name,t2) :: tl2 ->
  378. let isconst = (match t with TInst ({ cl_kind = KExpr _ },_) -> true | _ -> false) in
  379. if isconst <> (name = "Const") && t != t_dynamic && name <> "Rest" then error (if isconst then "Constant value unexpected here" else "Constant value excepted as type parameter") p;
  380. let is_rest = is_rest || name = "Rest" && is_generic_build in
  381. let t = match follow t2 with
  382. | TInst ({ cl_kind = KTypeParameter [] }, []) when not is_generic ->
  383. t
  384. | TInst (c,[]) ->
  385. let r = exc_protect ctx (fun r ->
  386. r := (fun() -> t);
  387. delay ctx PCheckConstraint (fun() -> check_param_constraints ctx types t tparams c p);
  388. t
  389. ) "constraint" in
  390. delay ctx PForce (fun () -> ignore(!r()));
  391. TLazy r
  392. | _ -> assert false
  393. in
  394. t :: loop tl1 tl2 is_rest
  395. | [],[] ->
  396. []
  397. | [],["Rest",_] when is_generic_build ->
  398. []
  399. | [],_ ->
  400. error ("Not enough type parameters for " ^ s_type_path path) p
  401. | t :: tl,[] ->
  402. if is_rest then
  403. t :: loop tl [] true
  404. else
  405. error ("Too many parameters for " ^ s_type_path path) p
  406. in
  407. let params = loop tparams types false in
  408. f params
  409. end
  410. (*
  411. build an instance from a complex type
  412. *)
  413. and load_complex_type ctx p t =
  414. match t with
  415. | CTParent t -> load_complex_type ctx p t
  416. | CTPath t -> load_instance ctx t p false
  417. | CTOptional _ -> error "Optional type not allowed here" p
  418. | CTExtend (tl,l) ->
  419. (match load_complex_type ctx p (CTAnonymous l) with
  420. | TAnon a as ta ->
  421. let is_redefined cf1 a2 =
  422. try
  423. let cf2 = PMap.find cf1.cf_name a2.a_fields in
  424. let st = s_type (print_context()) in
  425. if not (type_iseq cf1.cf_type cf2.cf_type) then begin
  426. display_error ctx ("Cannot redefine field " ^ cf1.cf_name ^ " with different type") p;
  427. display_error ctx ("First type was " ^ (st cf1.cf_type)) cf1.cf_pos;
  428. error ("Second type was " ^ (st cf2.cf_type)) cf2.cf_pos
  429. end else
  430. true
  431. with Not_found ->
  432. false
  433. in
  434. let mk_extension t =
  435. match follow t with
  436. | TInst ({cl_kind = KTypeParameter _},_) ->
  437. error "Cannot structurally extend type parameters" p
  438. | TInst (c,tl) ->
  439. ctx.com.warning "Structurally extending classes is deprecated and will be removed" p;
  440. let c2 = mk_class null_module (fst c.cl_path,"+" ^ snd c.cl_path) p in
  441. c2.cl_private <- true;
  442. PMap.iter (fun f _ ->
  443. try
  444. ignore(class_field c f);
  445. error ("Cannot redefine field " ^ f) p
  446. with
  447. Not_found -> ()
  448. ) a.a_fields;
  449. (* do NOT tag as extern - for protect *)
  450. c2.cl_kind <- KExtension (c,tl);
  451. c2.cl_super <- Some (c,tl);
  452. c2.cl_fields <- a.a_fields;
  453. TInst (c2,[])
  454. | TMono _ ->
  455. error "Loop found in cascading signatures definitions. Please change order/import" p
  456. | TAnon a2 ->
  457. PMap.iter (fun _ cf -> ignore(is_redefined cf a2)) a.a_fields;
  458. TAnon { a_fields = (PMap.foldi PMap.add a.a_fields a2.a_fields); a_status = ref (Extend [t]); }
  459. | _ -> error "Can only extend classes and structures" p
  460. in
  461. let loop t = match follow t with
  462. | TAnon a2 ->
  463. PMap.iter (fun f cf ->
  464. if not (is_redefined cf a) then
  465. a.a_fields <- PMap.add f cf a.a_fields
  466. ) a2.a_fields
  467. | _ ->
  468. error "Multiple structural extension is only allowed for structures" p
  469. in
  470. let il = List.map (fun t -> load_instance ctx t p false) tl in
  471. let tr = ref None in
  472. let t = TMono tr in
  473. let r = exc_protect ctx (fun r ->
  474. r := (fun _ -> t);
  475. tr := Some (match il with
  476. | [i] ->
  477. mk_extension i
  478. | _ ->
  479. List.iter loop il;
  480. a.a_status := Extend il;
  481. ta);
  482. t
  483. ) "constraint" in
  484. delay ctx PForce (fun () -> ignore(!r()));
  485. TLazy r
  486. | _ -> assert false)
  487. | CTAnonymous l ->
  488. let rec loop acc f =
  489. let n = f.cff_name in
  490. let p = f.cff_pos in
  491. if PMap.mem n acc then error ("Duplicate field declaration : " ^ n) p;
  492. let topt = function
  493. | None -> error ("Explicit type required for field " ^ n) p
  494. | Some t -> load_complex_type ctx p t
  495. in
  496. let no_expr = function
  497. | None -> ()
  498. | Some (_,p) -> error "Expression not allowed here" p
  499. in
  500. let pub = ref true in
  501. let dyn = ref false in
  502. let params = ref [] in
  503. List.iter (fun a ->
  504. match a with
  505. | APublic -> ()
  506. | APrivate -> pub := false;
  507. | ADynamic when (match f.cff_kind with FFun _ -> true | _ -> false) -> dyn := true
  508. | AStatic | AOverride | AInline | ADynamic | AMacro -> error ("Invalid access " ^ Ast.s_access a) p
  509. ) f.cff_access;
  510. let t , access = (match f.cff_kind with
  511. | FVar (Some (CTPath({tpackage=[];tname="Void"})), _) | FProp (_,_,Some (CTPath({tpackage=[];tname="Void"})),_) ->
  512. error "Fields of type Void are not allowed in structures" p
  513. | FVar (t, e) ->
  514. no_expr e;
  515. topt t, Var { v_read = AccNormal; v_write = AccNormal }
  516. | FFun fd ->
  517. params := (!type_function_params_rec) ctx fd f.cff_name p;
  518. no_expr fd.f_expr;
  519. let old = ctx.type_params in
  520. ctx.type_params <- !params @ old;
  521. let args = List.map (fun (name,o,t,e) -> no_expr e; name, o, topt t) fd.f_args in
  522. let t = TFun (args,topt fd.f_type), Method (if !dyn then MethDynamic else MethNormal) in
  523. ctx.type_params <- old;
  524. t
  525. | FProp (i1,i2,t,e) ->
  526. no_expr e;
  527. let access m get =
  528. match m with
  529. | "null" -> AccNo
  530. | "never" -> AccNever
  531. | "default" -> AccNormal
  532. | "dynamic" -> AccCall
  533. | "get" when get -> AccCall
  534. | "set" when not get -> AccCall
  535. | x when get && x = "get_" ^ n -> AccCall
  536. | x when not get && x = "set_" ^ n -> AccCall
  537. | _ ->
  538. error "Custom property access is no longer supported in Haxe 3" f.cff_pos;
  539. in
  540. let t = (match t with None -> error "Type required for structure property" p | Some t -> t) in
  541. load_complex_type ctx p t, Var { v_read = access i1 true; v_write = access i2 false }
  542. ) in
  543. let t = if Meta.has Meta.Optional f.cff_meta then ctx.t.tnull t else t in
  544. let cf = {
  545. cf_name = n;
  546. cf_type = t;
  547. cf_pos = p;
  548. cf_public = !pub;
  549. cf_kind = access;
  550. cf_params = !params;
  551. cf_expr = None;
  552. cf_doc = f.cff_doc;
  553. cf_meta = f.cff_meta;
  554. cf_overloads = [];
  555. } in
  556. init_meta_overloads ctx cf;
  557. PMap.add n cf acc
  558. in
  559. mk_anon (List.fold_left loop PMap.empty l)
  560. | CTFunction (args,r) ->
  561. match args with
  562. | [CTPath { tpackage = []; tparams = []; tname = "Void" }] ->
  563. TFun ([],load_complex_type ctx p r)
  564. | _ ->
  565. TFun (List.map (fun t ->
  566. let t, opt = (match t with CTOptional t -> t, true | _ -> t,false) in
  567. "",opt,load_complex_type ctx p t
  568. ) args,load_complex_type ctx p r)
  569. and init_meta_overloads ctx cf =
  570. let overloads = ref [] in
  571. cf.cf_meta <- List.filter (fun m ->
  572. match m with
  573. | (Meta.Overload,[(EFunction (fname,f),p)],_) ->
  574. if fname <> None then error "Function name must not be part of @:overload" p;
  575. (match f.f_expr with Some (EBlock [], _) -> () | _ -> error "Overload must only declare an empty method body {}" p);
  576. let old = ctx.type_params in
  577. (match cf.cf_params with
  578. | [] -> ()
  579. | l -> ctx.type_params <- List.filter (fun t -> not (List.mem t l)) ctx.type_params);
  580. let params = (!type_function_params_rec) ctx f cf.cf_name p in
  581. ctx.type_params <- params @ ctx.type_params;
  582. let topt = function None -> error "Explicit type required" p | Some t -> load_complex_type ctx p t in
  583. let args = List.map (fun (a,opt,t,_) -> a,opt,topt t) f.f_args in
  584. overloads := (args,topt f.f_type, params) :: !overloads;
  585. ctx.type_params <- old;
  586. false
  587. | (Meta.Overload,[],_) when ctx.com.config.pf_overload ->
  588. let topt (n,_,t) = match t with | TMono t when !t = None -> error ("Explicit type required for overload functions\nFor function argument '" ^ n ^ "'") cf.cf_pos | _ -> () in
  589. (match follow cf.cf_type with
  590. | TFun (args,_) -> List.iter topt args
  591. | _ -> () (* could be a variable *));
  592. true
  593. | (Meta.Overload,[],p) ->
  594. error "This platform does not support this kind of overload declaration. Try @:overload(function()... {}) instead" p
  595. | (Meta.Overload,_,p) ->
  596. error "Invalid @:overload metadata format" p
  597. | _ ->
  598. true
  599. ) cf.cf_meta;
  600. cf.cf_overloads <- List.map (fun (args,ret,params) -> { cf with cf_type = TFun (args,ret); cf_params = params }) (List.rev !overloads)
  601. let hide_types ctx =
  602. let old_m = ctx.m in
  603. let old_type_params = ctx.type_params in
  604. let old_deps = ctx.g.std.m_extra.m_deps in
  605. ctx.m <- {
  606. curmod = ctx.g.std;
  607. module_types = [];
  608. module_using = [];
  609. module_globals = PMap.empty;
  610. wildcard_packages = [];
  611. };
  612. ctx.type_params <- [];
  613. (fun() ->
  614. ctx.m <- old_m;
  615. ctx.type_params <- old_type_params;
  616. (* restore dependencies that might be have been wronly inserted *)
  617. ctx.g.std.m_extra.m_deps <- old_deps;
  618. )
  619. (*
  620. load a type while ignoring the current imports or local types
  621. *)
  622. let load_core_type ctx name =
  623. let show = hide_types ctx in
  624. let t = load_instance ctx { tpackage = []; tname = name; tparams = []; tsub = None; } null_pos false in
  625. show();
  626. add_dependency ctx.m.curmod (match t with
  627. | TInst (c,_) -> c.cl_module
  628. | TType (t,_) -> t.t_module
  629. | TAbstract (a,_) -> a.a_module
  630. | TEnum (e,_) -> e.e_module
  631. | _ -> assert false);
  632. t
  633. let t_iterator ctx =
  634. let show = hide_types ctx in
  635. match load_type_def ctx null_pos { tpackage = []; tname = "Iterator"; tparams = []; tsub = None } with
  636. | TTypeDecl t ->
  637. show();
  638. add_dependency ctx.m.curmod t.t_module;
  639. if List.length t.t_types <> 1 then assert false;
  640. let pt = mk_mono() in
  641. apply_params t.t_types [pt] t.t_type, pt
  642. | _ ->
  643. assert false
  644. (*
  645. load either a type t or Null<Unknown> if not defined
  646. *)
  647. let load_type_opt ?(opt=false) ctx p t =
  648. let t = (match t with None -> mk_mono() | Some t -> load_complex_type ctx p t) in
  649. if opt then ctx.t.tnull t else t
  650. (* ---------------------------------------------------------------------- *)
  651. (* Structure check *)
  652. let valid_redefinition ctx f1 t1 f2 t2 =
  653. let valid t1 t2 =
  654. Type.unify t1 t2;
  655. if is_null t1 <> is_null t2 then raise (Unify_error [Cannot_unify (t1,t2)]);
  656. in
  657. let t1, t2 = (match f1.cf_params, f2.cf_params with
  658. | [], [] -> t1, t2
  659. | l1, l2 when List.length l1 = List.length l2 ->
  660. let to_check = ref [] in
  661. let monos = List.map2 (fun (name,p1) (_,p2) ->
  662. (match follow p1, follow p2 with
  663. | TInst ({ cl_kind = KTypeParameter ct1 } as c1,pl1), TInst ({ cl_kind = KTypeParameter ct2 } as c2,pl2) ->
  664. (match ct1, ct2 with
  665. | [], [] -> ()
  666. | _, _ when List.length ct1 = List.length ct2 ->
  667. (* if same constraints, they are the same type *)
  668. let check monos =
  669. List.iter2 (fun t1 t2 ->
  670. try
  671. let t1 = apply_params l1 monos (apply_params c1.cl_types pl1 t1) in
  672. let t2 = apply_params l2 monos (apply_params c2.cl_types pl2 t2) in
  673. type_eq EqStrict t1 t2
  674. with Unify_error l ->
  675. raise (Unify_error (Unify_custom "Constraints differ" :: l))
  676. ) ct1 ct2
  677. in
  678. to_check := check :: !to_check;
  679. | _ ->
  680. raise (Unify_error [Unify_custom "Different number of constraints"]))
  681. | _ -> ());
  682. TInst (mk_class null_module ([],name) Ast.null_pos,[])
  683. ) l1 l2 in
  684. List.iter (fun f -> f monos) !to_check;
  685. apply_params l1 monos t1, apply_params l2 monos t2
  686. | _ ->
  687. (* ignore type params, will create other errors later *)
  688. t1, t2
  689. ) in
  690. match follow t1, follow t2 with
  691. | TFun (args1,r1) , TFun (args2,r2) when List.length args1 = List.length args2 -> (try
  692. List.iter2 (fun (n,o1,a1) (_,o2,a2) ->
  693. if o1 <> o2 then raise (Unify_error [Not_matching_optional n]);
  694. (try valid a2 a1 with Unify_error _ -> raise (Unify_error [Cannot_unify(a1,a2)]))
  695. ) args1 args2;
  696. valid r1 r2
  697. with Unify_error l ->
  698. raise (Unify_error (Cannot_unify (t1,t2) :: l)))
  699. | _ , _ ->
  700. (* in case args differs, or if an interface var *)
  701. type_eq EqStrict t1 t2;
  702. if is_null t1 <> is_null t2 then raise (Unify_error [Cannot_unify (t1,t2)])
  703. let copy_meta meta_src meta_target sl =
  704. let meta = ref meta_target in
  705. List.iter (fun (m,e,p) ->
  706. if List.mem m sl then meta := (m,e,p) :: !meta
  707. ) meta_src;
  708. !meta
  709. let same_overload_args t1 t2 f1 f2 =
  710. if List.length f1.cf_params <> List.length f2.cf_params then
  711. false
  712. else
  713. let rec follow_skip_null t = match t with
  714. | TMono r ->
  715. (match !r with
  716. | Some t -> follow_skip_null t
  717. | _ -> t)
  718. | TLazy f ->
  719. follow_skip_null (!f())
  720. | TType ({ t_path = [],"Null" } as t, [p]) ->
  721. TType(t,[follow p])
  722. | TType (t,tl) ->
  723. follow_skip_null (apply_params t.t_types tl t.t_type)
  724. | _ -> t
  725. in
  726. let same_arg t1 t2 =
  727. let t1 = follow_skip_null t1 in
  728. let t2 = follow_skip_null t2 in
  729. match follow_skip_null t1, follow_skip_null t2 with
  730. | TType _, TType _ -> type_iseq t1 t2
  731. | TType _, _
  732. | _, TType _ -> false
  733. | _ -> type_iseq t1 t2
  734. in
  735. match follow (apply_params f1.cf_params (List.map (fun (_,t) -> t) f2.cf_params) t1), follow t2 with
  736. | TFun(a1,_), TFun(a2,_) ->
  737. (try
  738. List.for_all2 (fun (_,_,t1) (_,_,t2) ->
  739. same_arg t1 t2) a1 a2
  740. with | Invalid_argument("List.for_all2") ->
  741. false)
  742. | _ -> assert false
  743. (** retrieves all overloads from class c and field i, as (Type.t * tclass_field) list *)
  744. let rec get_overloads c i =
  745. let ret = try
  746. let f = PMap.find i c.cl_fields in
  747. (f.cf_type, f) :: (List.map (fun f -> f.cf_type, f) f.cf_overloads)
  748. with | Not_found -> []
  749. in
  750. let rsup = match c.cl_super with
  751. | None when c.cl_interface ->
  752. let ifaces = List.concat (List.map (fun (c,tl) ->
  753. List.map (fun (t,f) -> apply_params c.cl_types tl t, f) (get_overloads c i)
  754. ) c.cl_implements) in
  755. ret @ ifaces
  756. | None -> ret
  757. | Some (c,tl) ->
  758. ret @ ( List.map (fun (t,f) -> apply_params c.cl_types tl t, f) (get_overloads c i) )
  759. in
  760. ret @ (List.filter (fun (t,f) -> not (List.exists (fun (t2,f2) -> same_overload_args t t2 f f2) ret)) rsup)
  761. let check_overloads ctx c =
  762. (* check if field with same signature was declared more than once *)
  763. List.iter (fun f ->
  764. if Meta.has Meta.Overload f.cf_meta then
  765. List.iter (fun f2 ->
  766. try
  767. ignore (List.find (fun f3 -> f3 != f2 && same_overload_args f2.cf_type f3.cf_type f2 f3) (f :: f.cf_overloads));
  768. display_error ctx ("Another overloaded field of same signature was already declared : " ^ f2.cf_name) f2.cf_pos
  769. with | Not_found -> ()
  770. ) (f :: f.cf_overloads)) (c.cl_ordered_fields @ c.cl_ordered_statics)
  771. let check_overriding ctx c =
  772. match c.cl_super with
  773. | None ->
  774. (match c.cl_overrides with
  775. | [] -> ()
  776. | i :: _ ->
  777. display_error ctx ("Field " ^ i.cf_name ^ " is declared 'override' but doesn't override any field") i.cf_pos)
  778. | Some (csup,params) ->
  779. PMap.iter (fun i f ->
  780. let p = f.cf_pos in
  781. let check_field f get_super_field is_overload = try
  782. (if is_overload && not (Meta.has Meta.Overload f.cf_meta) then
  783. display_error ctx ("Missing @:overload declaration for field " ^ i) p);
  784. let t, f2 = get_super_field csup i in
  785. (* allow to define fields that are not defined for this platform version in superclass *)
  786. (match f2.cf_kind with
  787. | Var { v_read = AccRequire _ } -> raise Not_found;
  788. | _ -> ());
  789. if ctx.com.config.pf_overload && (Meta.has Meta.Overload f2.cf_meta && not (Meta.has Meta.Overload f.cf_meta)) then
  790. display_error ctx ("Field " ^ i ^ " should be declared with @:overload since it was already declared as @:overload in superclass") p
  791. else if not (List.memq f c.cl_overrides) then
  792. display_error ctx ("Field " ^ i ^ " should be declared with 'override' since it is inherited from superclass") p
  793. else if not f.cf_public && f2.cf_public then
  794. display_error ctx ("Field " ^ i ^ " has less visibility (public/private) than superclass one") p
  795. else (match f.cf_kind, f2.cf_kind with
  796. | _, Method MethInline ->
  797. display_error ctx ("Field " ^ i ^ " is inlined and cannot be overridden") p
  798. | a, b when a = b -> ()
  799. | Method MethInline, Method MethNormal ->
  800. () (* allow to redefine a method as inlined *)
  801. | _ ->
  802. display_error ctx ("Field " ^ i ^ " has different property access than in superclass") p);
  803. try
  804. let t = apply_params csup.cl_types params t in
  805. valid_redefinition ctx f f.cf_type f2 t
  806. with
  807. Unify_error l ->
  808. display_error ctx ("Field " ^ i ^ " overloads parent class with different or incomplete type") p;
  809. display_error ctx (error_msg (Unify l)) p;
  810. with
  811. Not_found ->
  812. if List.memq f c.cl_overrides then
  813. let msg = if is_overload then
  814. ("Field " ^ i ^ " is declared 'override' but no compatible overload was found")
  815. else
  816. ("Field " ^ i ^ " is declared 'override' but doesn't override any field")
  817. in
  818. display_error ctx msg p
  819. in
  820. if ctx.com.config.pf_overload && Meta.has Meta.Overload f.cf_meta then begin
  821. let overloads = get_overloads csup i in
  822. List.iter (fun (t,f2) ->
  823. (* check if any super class fields are vars *)
  824. match f2.cf_kind with
  825. | Var _ ->
  826. display_error ctx ("A variable named '" ^ f2.cf_name ^ "' was already declared in a superclass") f.cf_pos
  827. | _ -> ()
  828. ) overloads;
  829. List.iter (fun f ->
  830. (* find the exact field being overridden *)
  831. check_field f (fun csup i ->
  832. List.find (fun (t,f2) ->
  833. same_overload_args f.cf_type (apply_params csup.cl_types params t) f f2
  834. ) overloads
  835. ) true
  836. ) f.cf_overloads
  837. end else
  838. check_field f (fun csup i ->
  839. let _, t, f2 = raw_class_field (fun f -> f.cf_type) csup i in
  840. t, f2) false
  841. ) c.cl_fields
  842. let class_field_no_interf c i =
  843. try
  844. let f = PMap.find i c.cl_fields in
  845. f.cf_type , f
  846. with Not_found ->
  847. match c.cl_super with
  848. | None ->
  849. raise Not_found
  850. | Some (c,tl) ->
  851. (* rec over class_field *)
  852. let _, t , f = raw_class_field (fun f -> f.cf_type) c i in
  853. apply_params c.cl_types tl t , f
  854. let rec check_interface ctx c intf params =
  855. let p = c.cl_pos in
  856. let rec check_field i f =
  857. (if ctx.com.config.pf_overload then
  858. List.iter (function
  859. | f2 when f != f2 ->
  860. check_field i f2
  861. | _ -> ()) f.cf_overloads);
  862. let is_overload = ref false in
  863. try
  864. let t2, f2 = class_field_no_interf c i in
  865. let t2, f2 =
  866. if ctx.com.config.pf_overload && (f2.cf_overloads <> [] || Meta.has Meta.Overload f2.cf_meta) then
  867. let overloads = get_overloads c i in
  868. is_overload := true;
  869. let t = (apply_params intf.cl_types params f.cf_type) in
  870. List.find (fun (t1,f1) -> same_overload_args t t1 f f1) overloads
  871. else
  872. t2, f2
  873. in
  874. ignore(follow f2.cf_type); (* force evaluation *)
  875. let p = (match f2.cf_expr with None -> p | Some e -> e.epos) in
  876. let mkind = function
  877. | MethNormal | MethInline -> 0
  878. | MethDynamic -> 1
  879. | MethMacro -> 2
  880. in
  881. if f.cf_public && not f2.cf_public then
  882. display_error ctx ("Field " ^ i ^ " should be public as requested by " ^ s_type_path intf.cl_path) p
  883. else if not (unify_kind f2.cf_kind f.cf_kind) || not (match f.cf_kind, f2.cf_kind with Var _ , Var _ -> true | Method m1, Method m2 -> mkind m1 = mkind m2 | _ -> false) then
  884. display_error ctx ("Field " ^ i ^ " has different property access than in " ^ s_type_path intf.cl_path ^ " (" ^ s_kind f2.cf_kind ^ " should be " ^ s_kind f.cf_kind ^ ")") p
  885. else try
  886. valid_redefinition ctx f2 t2 f (apply_params intf.cl_types params f.cf_type)
  887. with
  888. Unify_error l ->
  889. if not (Meta.has Meta.CsNative c.cl_meta && c.cl_extern) then begin
  890. display_error ctx ("Field " ^ i ^ " has different type than in " ^ s_type_path intf.cl_path) p;
  891. display_error ctx (error_msg (Unify l)) p;
  892. end
  893. with
  894. | Not_found when not c.cl_interface ->
  895. let msg = if !is_overload then
  896. let ctx = print_context() in
  897. let args = match follow f.cf_type with | TFun(args,_) -> String.concat ", " (List.map (fun (n,o,t) -> (if o then "?" else "") ^ n ^ " : " ^ (s_type ctx t)) args) | _ -> assert false in
  898. "No suitable overload for " ^ i ^ "( " ^ args ^ " ), as needed by " ^ s_type_path intf.cl_path ^ " was found"
  899. else
  900. ("Field " ^ i ^ " needed by " ^ s_type_path intf.cl_path ^ " is missing")
  901. in
  902. display_error ctx msg p
  903. | Not_found -> ()
  904. in
  905. PMap.iter check_field intf.cl_fields;
  906. List.iter (fun (i2,p2) ->
  907. check_interface ctx c i2 (List.map (apply_params intf.cl_types params) p2)
  908. ) intf.cl_implements
  909. let check_interfaces ctx c =
  910. match c.cl_path with
  911. | "Proxy" :: _ , _ -> ()
  912. | _ ->
  913. List.iter (fun (intf,params) -> check_interface ctx c intf params) c.cl_implements
  914. let rec return_flow ctx e =
  915. let error() = display_error ctx "A return is missing here" e.epos; raise Exit in
  916. let return_flow = return_flow ctx in
  917. match e.eexpr with
  918. | TReturn _ | TThrow _ -> ()
  919. | TParenthesis e | TMeta(_,e) ->
  920. return_flow e
  921. | TBlock el ->
  922. let rec loop = function
  923. | [] -> error()
  924. | [e] -> return_flow e
  925. | { eexpr = TReturn _ } :: _ | { eexpr = TThrow _ } :: _ -> ()
  926. | _ :: l -> loop l
  927. in
  928. loop el
  929. | TIf (_,e1,Some e2) ->
  930. return_flow e1;
  931. return_flow e2;
  932. | TSwitch (v,cases,Some e) ->
  933. List.iter (fun (_,e) -> return_flow e) cases;
  934. return_flow e
  935. | TSwitch ({eexpr = TMeta((Meta.Exhaustive,_,_),_)},cases,None) ->
  936. List.iter (fun (_,e) -> return_flow e) cases;
  937. | TPatMatch dt ->
  938. let rec loop d = match d with
  939. | DTExpr e -> return_flow e
  940. | DTGuard(_,dt1,dt2) ->
  941. loop dt1;
  942. (match dt2 with None -> () | Some dt -> loop dt)
  943. | DTBind (_,d) -> loop d
  944. | DTSwitch (_,cl,dto) ->
  945. List.iter (fun (_,dt) -> loop dt) cl;
  946. (match dto with None -> () | Some dt -> loop dt)
  947. | DTGoto i -> loop (dt.dt_dt_lookup.(i))
  948. in
  949. loop (dt.dt_dt_lookup.(dt.dt_first))
  950. | TTry (e,cases) ->
  951. return_flow e;
  952. List.iter (fun (_,e) -> return_flow e) cases;
  953. | TWhile({eexpr = (TConst (TBool true))},e,_) ->
  954. (* a special case for "inifite" while loops that have no break *)
  955. let rec loop e = match e.eexpr with
  956. (* ignore nested loops to not accidentally get one of its breaks *)
  957. | TWhile _ | TFor _ -> ()
  958. | TBreak -> error()
  959. | _ -> Type.iter loop e
  960. in
  961. loop e
  962. | _ ->
  963. error()
  964. (* ---------------------------------------------------------------------- *)
  965. (* PASS 1 & 2 : Module and Class Structure *)
  966. let is_generic_parameter ctx c =
  967. (* first check field parameters, then class parameters *)
  968. try
  969. ignore (List.assoc (snd c.cl_path) ctx.curfield.cf_params);
  970. Meta.has Meta.Generic ctx.curfield.cf_meta
  971. with Not_found -> try
  972. ignore(List.assoc (snd c.cl_path) ctx.type_params);
  973. (match ctx.curclass.cl_kind with | KGeneric -> true | _ -> false);
  974. with Not_found ->
  975. false
  976. let check_extends ctx c t p = match follow t with
  977. | TInst ({ cl_path = [],"Array" },_)
  978. | TInst ({ cl_path = [],"String" },_)
  979. | TInst ({ cl_path = [],"Date" },_)
  980. | TInst ({ cl_path = [],"Xml" },_) when ((not (platform ctx.com Cpp)) && (match c.cl_path with ("mt" | "flash") :: _ , _ -> false | _ -> true)) ->
  981. error "Cannot extend basic class" p;
  982. | TInst (csup,params) ->
  983. if is_parent c csup then error "Recursive class" p;
  984. begin match csup.cl_kind with
  985. | KTypeParameter _ when not (is_generic_parameter ctx csup) -> error "Cannot extend non-generic type parameters" p
  986. | _ -> csup,params
  987. end
  988. | _ -> error "Should extend by using a class" p
  989. let rec add_constructor ctx c force_constructor p =
  990. match c.cl_constructor, c.cl_super with
  991. | None, Some ({ cl_constructor = Some cfsup } as csup,cparams) when not c.cl_extern ->
  992. let cf = {
  993. cfsup with
  994. cf_pos = p;
  995. cf_meta = [];
  996. cf_doc = None;
  997. cf_expr = None;
  998. } in
  999. let r = exc_protect ctx (fun r ->
  1000. let t = mk_mono() in
  1001. r := (fun() -> t);
  1002. let ctx = { ctx with
  1003. curfield = cf;
  1004. pass = PTypeField;
  1005. } in
  1006. ignore (follow cfsup.cf_type); (* make sure it's typed *)
  1007. (if ctx.com.config.pf_overload then List.iter (fun cf -> ignore (follow cf.cf_type)) cf.cf_overloads);
  1008. let args = (match cfsup.cf_expr with
  1009. | Some { eexpr = TFunction f } ->
  1010. List.map (fun (v,def) ->
  1011. (*
  1012. let's optimize a bit the output by not always copying the default value
  1013. into the inherited constructor when it's not necessary for the platform
  1014. *)
  1015. match ctx.com.platform, def with
  1016. | _, Some _ when not ctx.com.config.pf_static -> v, (Some TNull)
  1017. | Flash, Some (TString _) -> v, (Some TNull)
  1018. | Cpp, Some (TString _) -> v, def
  1019. | Cpp, Some _ -> { v with v_type = ctx.t.tnull v.v_type }, (Some TNull)
  1020. | _ -> v, def
  1021. ) f.tf_args
  1022. | _ ->
  1023. match follow cfsup.cf_type with
  1024. | TFun (args,_) -> List.map (fun (n,o,t) -> alloc_var n (if o then ctx.t.tnull t else t), if o then Some TNull else None) args
  1025. | _ -> assert false
  1026. ) in
  1027. let p = c.cl_pos in
  1028. let vars = List.map (fun (v,def) -> alloc_var v.v_name (apply_params csup.cl_types cparams v.v_type), def) args in
  1029. let super_call = mk (TCall (mk (TConst TSuper) (TInst (csup,cparams)) p,List.map (fun (v,_) -> mk (TLocal v) v.v_type p) vars)) ctx.t.tvoid p in
  1030. let constr = mk (TFunction {
  1031. tf_args = vars;
  1032. tf_type = ctx.t.tvoid;
  1033. tf_expr = super_call;
  1034. }) (TFun (List.map (fun (v,c) -> v.v_name, c <> None, v.v_type) vars,ctx.t.tvoid)) p in
  1035. cf.cf_expr <- Some constr;
  1036. cf.cf_type <- t;
  1037. unify ctx t constr.etype p;
  1038. t
  1039. ) "add_constructor" in
  1040. cf.cf_type <- TLazy r;
  1041. c.cl_constructor <- Some cf;
  1042. delay ctx PForce (fun() -> ignore((!r)()));
  1043. | None,_ when force_constructor ->
  1044. let constr = mk (TFunction {
  1045. tf_args = [];
  1046. tf_type = ctx.t.tvoid;
  1047. tf_expr = mk (TBlock []) ctx.t.tvoid p;
  1048. }) (tfun [] ctx.t.tvoid) p in
  1049. let cf = mk_field "new" constr.etype p in
  1050. cf.cf_expr <- Some constr;
  1051. cf.cf_type <- constr.etype;
  1052. cf.cf_meta <- [Meta.CompilerGenerated,[],p];
  1053. cf.cf_kind <- Method MethNormal;
  1054. c.cl_constructor <- Some cf;
  1055. | _ ->
  1056. (* nothing to do *)
  1057. ()
  1058. let set_heritance ctx c herits p =
  1059. let ctx = { ctx with curclass = c; type_params = c.cl_types; } in
  1060. let process_meta csup =
  1061. List.iter (fun m ->
  1062. match m with
  1063. | Meta.Final, _, _ -> if not (Meta.has Meta.Hack c.cl_meta || (match c.cl_kind with KTypeParameter _ -> true | _ -> false)) then error "Cannot extend a final class" p;
  1064. | Meta.AutoBuild, el, p -> c.cl_meta <- (Meta.Build,el,p) :: m :: c.cl_meta
  1065. | _ -> ()
  1066. ) csup.cl_meta
  1067. in
  1068. let has_interf = ref false in
  1069. let rec loop = function
  1070. | HPrivate | HExtern | HInterface ->
  1071. ()
  1072. | HExtends t ->
  1073. if c.cl_super <> None then error "Cannot extend several classes" p;
  1074. let t = load_instance ctx t p false in
  1075. let csup,params = check_extends ctx c t p in
  1076. csup.cl_build();
  1077. process_meta csup;
  1078. if c.cl_interface then begin
  1079. if not csup.cl_interface then error "Cannot extend by using a class" p;
  1080. c.cl_implements <- (csup,params) :: c.cl_implements;
  1081. if not !has_interf then begin
  1082. delay ctx PForce (fun() -> check_interfaces ctx c);
  1083. has_interf := true;
  1084. end
  1085. end else begin
  1086. if csup.cl_interface then error "Cannot extend by using an interface" p;
  1087. c.cl_super <- Some (csup,params)
  1088. end
  1089. | HImplements t ->
  1090. let t = load_instance ctx t p false in
  1091. (match follow t with
  1092. | TInst ({ cl_path = [],"ArrayAccess"; cl_extern = true; },[t]) ->
  1093. if c.cl_array_access <> None then error "Duplicate array access" p;
  1094. c.cl_array_access <- Some t
  1095. | TInst (intf,params) ->
  1096. intf.cl_build();
  1097. if is_parent c intf then error "Recursive class" p;
  1098. if c.cl_interface then error "Interfaces cannot implement another interface (use extends instead)" p;
  1099. if not intf.cl_interface then error "You can only implement an interface" p;
  1100. process_meta intf;
  1101. c.cl_implements <- (intf, params) :: c.cl_implements;
  1102. if not !has_interf then begin
  1103. delay ctx PForce (fun() -> check_interfaces ctx c);
  1104. has_interf := true;
  1105. end
  1106. | TDynamic t ->
  1107. if c.cl_dynamic <> None then error "Cannot have several dynamics" p;
  1108. c.cl_dynamic <- Some t
  1109. | _ -> error "Should implement by using an interface" p)
  1110. in
  1111. (*
  1112. resolve imports before calling build_inheritance, since it requires full paths.
  1113. that means that typedefs are not working, but that's a fair limitation
  1114. *)
  1115. let rec resolve_imports t =
  1116. match t.tpackage with
  1117. | _ :: _ -> t
  1118. | [] ->
  1119. try
  1120. let find = List.find (fun lt -> snd (t_path lt) = t.tname) in
  1121. let lt = try find ctx.m.curmod.m_types with Not_found -> find ctx.m.module_types in
  1122. { t with tpackage = fst (t_path lt) }
  1123. with
  1124. Not_found -> t
  1125. in
  1126. let herits = List.map (function
  1127. | HExtends t -> HExtends (resolve_imports t)
  1128. | HImplements t -> HImplements (resolve_imports t)
  1129. | h -> h
  1130. ) herits in
  1131. List.iter loop (List.filter (ctx.g.do_inherit ctx c p) herits)
  1132. let rec type_type_params ?(enum_constructor=false) ctx path get_params p tp =
  1133. let n = tp.tp_name in
  1134. let c = mk_class ctx.m.curmod (fst path @ [snd path],n) p in
  1135. c.cl_types <- List.map (type_type_params ctx c.cl_path get_params p) tp.tp_params;
  1136. c.cl_kind <- KTypeParameter [];
  1137. if enum_constructor then c.cl_meta <- (Meta.EnumConstructorParam,[],c.cl_pos) :: c.cl_meta;
  1138. let t = TInst (c,List.map snd c.cl_types) in
  1139. match tp.tp_constraints with
  1140. | [] ->
  1141. n, t
  1142. | _ ->
  1143. let r = exc_protect ctx (fun r ->
  1144. r := (fun _ -> t);
  1145. let ctx = { ctx with type_params = ctx.type_params @ get_params() } in
  1146. let constr = List.map (load_complex_type ctx p) tp.tp_constraints in
  1147. (* check against direct recursion *)
  1148. let rec loop t =
  1149. match follow t with
  1150. | TInst (c2,_) when c == c2 -> error "Recursive constraint parameter is not allowed" p
  1151. | TInst ({ cl_kind = KTypeParameter cl },_) ->
  1152. List.iter loop cl
  1153. | _ ->
  1154. ()
  1155. in
  1156. List.iter loop constr;
  1157. c.cl_kind <- KTypeParameter constr;
  1158. t
  1159. ) "constraint" in
  1160. delay ctx PForce (fun () -> ignore(!r()));
  1161. n, TLazy r
  1162. let type_function_params ctx fd fname p =
  1163. let params = ref [] in
  1164. params := List.map (fun tp ->
  1165. type_type_params ctx ([],fname) (fun() -> !params) p tp
  1166. ) fd.f_params;
  1167. !params
  1168. let find_enclosing com e =
  1169. let display_pos = ref (!Parser.resume_display) in
  1170. let encloses_display_pos p =
  1171. if p.pmin <= !display_pos.pmin && p.pmax >= !display_pos.pmax then begin
  1172. let p = !display_pos in
  1173. display_pos := { pfile = ""; pmin = -2; pmax = -2 };
  1174. Some p
  1175. end else
  1176. None
  1177. in
  1178. let rec loop e = match fst e with
  1179. | EBlock el ->
  1180. let p = pos e in
  1181. (* We want to find the innermost block which contains the display position. *)
  1182. let el = List.map loop el in
  1183. let el = match encloses_display_pos p with
  1184. | None ->
  1185. el
  1186. | Some p2 ->
  1187. let b,el = List.fold_left (fun (b,el) e ->
  1188. let p = pos e in
  1189. if b || p.pmax <= p2.pmin then begin
  1190. (b,e :: el)
  1191. end else begin
  1192. let e_d = (EDisplay(e,false)),p in
  1193. (true,e_d :: el)
  1194. end
  1195. ) (false,[]) el in
  1196. let el = if b then
  1197. el
  1198. else begin
  1199. (EDisplay(((EConst(Ident "null")),p),false),p) :: el
  1200. end in
  1201. List.rev el
  1202. in
  1203. (EBlock el),(pos e)
  1204. | _ ->
  1205. Ast.map_expr loop e
  1206. in
  1207. loop e
  1208. let find_before_pos com e =
  1209. let display_pos = ref (!Parser.resume_display) in
  1210. let is_annotated p =
  1211. if p.pmax = !display_pos.pmin - 1 then begin
  1212. display_pos := { pfile = ""; pmin = -2; pmax = -2 };
  1213. true
  1214. end else
  1215. false
  1216. in
  1217. let rec loop e =
  1218. if is_annotated (pos e) then
  1219. (EDisplay(e,false),(pos e))
  1220. else
  1221. e
  1222. in
  1223. let rec map e =
  1224. loop (Ast.map_expr map e)
  1225. in
  1226. map e
  1227. let type_function ctx args ret fmode f do_display p =
  1228. let locals = save_locals ctx in
  1229. let fargs = List.map (fun (n,c,t) ->
  1230. if n.[0] = '$' then error "Function argument names starting with a dollar are not allowed" p;
  1231. let c = (match c with
  1232. | None -> None
  1233. | Some e ->
  1234. let p = pos e in
  1235. let e = ctx.g.do_optimize ctx (type_expr ctx e (WithType t)) in
  1236. unify ctx e.etype t p;
  1237. let rec loop e = match e.eexpr with
  1238. | TConst c -> Some c
  1239. | TCast(e,None) -> loop e
  1240. | _ -> display_error ctx "Parameter default value should be constant" p; None
  1241. in
  1242. loop e
  1243. ) in
  1244. let v,c = add_local ctx n t, c in
  1245. if n = "this" then v.v_meta <- (Meta.This,[],p) :: v.v_meta;
  1246. v,c
  1247. ) args in
  1248. let old_ret = ctx.ret in
  1249. let old_fun = ctx.curfun in
  1250. let old_opened = ctx.opened in
  1251. ctx.curfun <- fmode;
  1252. ctx.ret <- ret;
  1253. ctx.opened <- [];
  1254. let e = match f.f_expr with None -> error "Function body required" p | Some e -> e in
  1255. let e = if not do_display then
  1256. type_expr ctx e NoValue
  1257. else begin
  1258. let e = match ctx.com.display with
  1259. | DMToplevel -> find_enclosing ctx.com e
  1260. | DMPosition | DMUsage -> find_before_pos ctx.com e
  1261. | _ -> e
  1262. in
  1263. try
  1264. if Common.defined ctx.com Define.NoCOpt then raise Exit;
  1265. type_expr ctx (Optimizer.optimize_completion_expr e) NoValue
  1266. with
  1267. | Parser.TypePath (_,None) | Exit ->
  1268. type_expr ctx e NoValue
  1269. | DisplayTypes [t] when (match follow t with TMono _ -> true | _ -> false) ->
  1270. type_expr ctx (if ctx.com.display = DMToplevel then find_enclosing ctx.com e else e) NoValue
  1271. end in
  1272. let e = match e.eexpr with
  1273. | TMeta((Meta.MergeBlock,_,_), ({eexpr = TBlock el} as e1)) -> e1
  1274. | _ -> e
  1275. in
  1276. let rec loop e =
  1277. match e.eexpr with
  1278. | TReturn (Some e) -> (match follow e.etype with TAbstract({a_path = [],"Void"},[]) -> () | _ -> raise Exit)
  1279. | TFunction _ -> ()
  1280. | _ -> Type.iter loop e
  1281. in
  1282. let have_ret = (try loop e; false with Exit -> true) in
  1283. if have_ret then
  1284. (try return_flow ctx e with Exit -> ())
  1285. else (try type_eq EqStrict ret ctx.t.tvoid with Unify_error _ ->
  1286. match e.eexpr with
  1287. (* accept final throw (issue #1923) *)
  1288. | TThrow _ -> ()
  1289. | TBlock el when (match List.rev el with ({eexpr = TThrow _} :: _) -> true | _ -> false) -> ()
  1290. | _ -> display_error ctx ("Missing return " ^ (s_type (print_context()) ret)) p);
  1291. let rec loop e =
  1292. match e.eexpr with
  1293. | TCall ({ eexpr = TConst TSuper },_) -> raise Exit
  1294. | TFunction _ -> ()
  1295. | _ -> Type.iter loop e
  1296. in
  1297. let has_super_constr() =
  1298. match ctx.curclass.cl_super with
  1299. | None ->
  1300. None
  1301. | Some (csup,tl) ->
  1302. try
  1303. let _,cf = get_constructor (fun f->f.cf_type) csup in
  1304. Some (Meta.has Meta.CompilerGenerated cf.cf_meta,TInst(csup,tl))
  1305. with Not_found ->
  1306. None
  1307. in
  1308. let e = if fmode <> FunConstructor then
  1309. e
  1310. else match has_super_constr() with
  1311. | Some (was_forced,t_super) ->
  1312. (try
  1313. loop e;
  1314. if was_forced then
  1315. let e_super = mk (TConst TSuper) t_super e.epos in
  1316. let e_super_call = mk (TCall(e_super,[])) ctx.t.tvoid e.epos in
  1317. concat e_super_call e
  1318. else begin
  1319. display_error ctx "Missing super constructor call" p;
  1320. e
  1321. end
  1322. with
  1323. Exit -> e);
  1324. | None ->
  1325. e
  1326. in
  1327. locals();
  1328. let e = match ctx.curfun, ctx.vthis with
  1329. | (FunMember|FunConstructor), Some v ->
  1330. let ev = mk (TVar (v,Some (mk (TConst TThis) ctx.tthis p))) ctx.t.tvoid p in
  1331. (match e.eexpr with
  1332. | TBlock l -> { e with eexpr = TBlock (ev::l) }
  1333. | _ -> mk (TBlock [ev;e]) e.etype p)
  1334. | _ -> e
  1335. in
  1336. List.iter (fun r -> r := Closed) ctx.opened;
  1337. ctx.ret <- old_ret;
  1338. ctx.curfun <- old_fun;
  1339. ctx.opened <- old_opened;
  1340. e , fargs
  1341. let load_core_class ctx c =
  1342. let ctx2 = (match ctx.g.core_api with
  1343. | None ->
  1344. let com2 = Common.clone ctx.com in
  1345. com2.defines <- PMap.empty;
  1346. Common.define com2 Define.CoreApi;
  1347. Common.define com2 Define.Sys;
  1348. if ctx.in_macro then Common.define com2 Define.Macro;
  1349. com2.class_path <- ctx.com.std_path;
  1350. let ctx2 = ctx.g.do_create com2 in
  1351. ctx.g.core_api <- Some ctx2;
  1352. ctx2
  1353. | Some c ->
  1354. c
  1355. ) in
  1356. let tpath = match c.cl_kind with
  1357. | KAbstractImpl a -> { tpackage = fst a.a_path; tname = snd a.a_path; tparams = []; tsub = None; }
  1358. | _ -> { tpackage = fst c.cl_path; tname = snd c.cl_path; tparams = []; tsub = None; }
  1359. in
  1360. let t = load_instance ctx2 tpath c.cl_pos true in
  1361. flush_pass ctx2 PFinal "core_final";
  1362. match t with
  1363. | TInst (ccore,_) | TAbstract({a_impl = Some ccore}, _) ->
  1364. ccore
  1365. | _ ->
  1366. assert false
  1367. let init_core_api ctx c =
  1368. let ccore = load_core_class ctx c in
  1369. begin try
  1370. List.iter2 (fun (n1,t1) (n2,t2) -> match follow t1, follow t2 with
  1371. | TInst({cl_kind = KTypeParameter l1},_),TInst({cl_kind = KTypeParameter l2},_) ->
  1372. begin try
  1373. List.iter2 (fun t1 t2 -> type_eq EqCoreType t2 t1) l1 l2
  1374. with
  1375. | Invalid_argument _ ->
  1376. error "Type parameters must have the same number of constraints as core type" c.cl_pos
  1377. | Unify_error l ->
  1378. display_error ctx ("Type parameter " ^ n2 ^ " has different constraint than in core type") c.cl_pos;
  1379. display_error ctx (error_msg (Unify l)) c.cl_pos
  1380. end
  1381. | t1,t2 ->
  1382. Printf.printf "%s %s" (s_type (print_context()) t1) (s_type (print_context()) t2);
  1383. assert false
  1384. ) ccore.cl_types c.cl_types;
  1385. with Invalid_argument _ ->
  1386. error "Class must have the same number of type parameters as core type" c.cl_pos
  1387. end;
  1388. (match c.cl_doc with
  1389. | None -> c.cl_doc <- ccore.cl_doc
  1390. | Some _ -> ());
  1391. let compare_fields f f2 =
  1392. let p = (match f2.cf_expr with None -> c.cl_pos | Some e -> e.epos) in
  1393. (try
  1394. type_eq EqCoreType (apply_params ccore.cl_types (List.map snd c.cl_types) f.cf_type) f2.cf_type
  1395. with Unify_error l ->
  1396. display_error ctx ("Field " ^ f.cf_name ^ " has different type than in core type") p;
  1397. display_error ctx (error_msg (Unify l)) p);
  1398. if f2.cf_public <> f.cf_public then error ("Field " ^ f.cf_name ^ " has different visibility than core type") p;
  1399. (match f2.cf_doc with
  1400. | None -> f2.cf_doc <- f.cf_doc
  1401. | Some _ -> ());
  1402. if f2.cf_kind <> f.cf_kind then begin
  1403. match f2.cf_kind, f.cf_kind with
  1404. | Method MethInline, Method MethNormal -> () (* allow to add 'inline' *)
  1405. | Method MethNormal, Method MethInline -> () (* allow to disable 'inline' *)
  1406. | _ ->
  1407. error ("Field " ^ f.cf_name ^ " has different property access than core type") p;
  1408. end;
  1409. (match follow f.cf_type, follow f2.cf_type with
  1410. | TFun (pl1,_), TFun (pl2,_) ->
  1411. if List.length pl1 != List.length pl2 then error "Argument count mismatch" p;
  1412. List.iter2 (fun (n1,_,_) (n2,_,_) ->
  1413. if n1 <> n2 then error ("Method parameter name '" ^ n2 ^ "' should be '" ^ n1 ^ "'") p;
  1414. ) pl1 pl2;
  1415. | _ -> ());
  1416. in
  1417. let check_fields fcore fl =
  1418. PMap.iter (fun i f ->
  1419. if not f.cf_public then () else
  1420. let f2 = try PMap.find f.cf_name fl with Not_found -> error ("Missing field " ^ i ^ " required by core type") c.cl_pos in
  1421. compare_fields f f2;
  1422. ) fcore;
  1423. PMap.iter (fun i f ->
  1424. let p = (match f.cf_expr with None -> c.cl_pos | Some e -> e.epos) in
  1425. if f.cf_public && not (Meta.has Meta.Hack f.cf_meta) && not (PMap.mem f.cf_name fcore) && not (List.memq f c.cl_overrides) then error ("Public field " ^ i ^ " is not part of core type") p;
  1426. ) fl;
  1427. in
  1428. check_fields ccore.cl_fields c.cl_fields;
  1429. check_fields ccore.cl_statics c.cl_statics;
  1430. (match ccore.cl_constructor, c.cl_constructor with
  1431. | None, None -> ()
  1432. | Some { cf_public = false }, _ -> ()
  1433. | Some f, Some f2 -> compare_fields f f2
  1434. | None, Some { cf_public = false } -> ()
  1435. | _ -> error "Constructor differs from core type" c.cl_pos)
  1436. let patch_class ctx c fields =
  1437. let h = (try Some (Hashtbl.find ctx.g.type_patches c.cl_path) with Not_found -> None) in
  1438. match h with
  1439. | None -> fields
  1440. | Some (h,hcl) ->
  1441. c.cl_meta <- c.cl_meta @ hcl.tp_meta;
  1442. let rec loop acc = function
  1443. | [] -> acc
  1444. | f :: l ->
  1445. (* patch arguments types *)
  1446. (match f.cff_kind with
  1447. | FFun ff ->
  1448. let param ((n,opt,t,e) as p) =
  1449. try
  1450. let t2 = (try Hashtbl.find h (("$" ^ f.cff_name ^ "__" ^ n),false) with Not_found -> Hashtbl.find h (("$" ^ n),false)) in
  1451. n, opt, t2.tp_type, e
  1452. with Not_found ->
  1453. p
  1454. in
  1455. f.cff_kind <- FFun { ff with f_args = List.map param ff.f_args }
  1456. | _ -> ());
  1457. (* other patches *)
  1458. match (try Some (Hashtbl.find h (f.cff_name,List.mem AStatic f.cff_access)) with Not_found -> None) with
  1459. | None -> loop (f :: acc) l
  1460. | Some { tp_remove = true } -> loop acc l
  1461. | Some p ->
  1462. f.cff_meta <- f.cff_meta @ p.tp_meta;
  1463. (match p.tp_type with
  1464. | None -> ()
  1465. | Some t ->
  1466. f.cff_kind <- match f.cff_kind with
  1467. | FVar (_,e) -> FVar (Some t,e)
  1468. | FProp (get,set,_,eo) -> FProp (get,set,Some t,eo)
  1469. | FFun f -> FFun { f with f_type = Some t });
  1470. loop (f :: acc) l
  1471. in
  1472. List.rev (loop [] fields)
  1473. let rec string_list_of_expr_path (e,p) =
  1474. match e with
  1475. | EConst (Ident i) -> [i]
  1476. | EField (e,f) -> f :: string_list_of_expr_path e
  1477. | _ -> error "Invalid path" p
  1478. let build_enum_abstract ctx c a fields p =
  1479. List.iter (fun field ->
  1480. match field.cff_kind with
  1481. | FVar(ct,eo) when not (List.mem AStatic field.cff_access) ->
  1482. begin match ct with
  1483. | Some _ -> error "Type hints on enum abstract fields are not allowed" field.cff_pos
  1484. | None -> ()
  1485. end;
  1486. field.cff_access <- [AStatic;APublic;AInline];
  1487. field.cff_meta <- (Meta.Enum,[],field.cff_pos) :: (Meta.Impl,[],field.cff_pos) :: field.cff_meta;
  1488. let e = match eo with
  1489. | None -> error "Value required" field.cff_pos
  1490. | Some e -> (ECast(e,None),field.cff_pos)
  1491. in
  1492. field.cff_kind <- FVar(ct,Some e)
  1493. | _ ->
  1494. ()
  1495. ) fields;
  1496. EVars ["",Some (CTAnonymous fields),None],p
  1497. let build_module_def ctx mt meta fvars context_init fbuild =
  1498. let rec loop = function
  1499. | (Meta.Build,args,p) :: l ->
  1500. let epath, el = (match args with
  1501. | [ECall (epath,el),p] -> epath, el
  1502. | _ -> error "Invalid build parameters" p
  1503. ) in
  1504. let s = try String.concat "." (List.rev (string_list_of_expr_path epath)) with Error (_,p) -> error "Build call parameter must be a class path" p in
  1505. if ctx.in_macro then error "You cannot use @:build inside a macro : make sure that your enum is not used in macro" p;
  1506. let old = ctx.g.get_build_infos in
  1507. ctx.g.get_build_infos <- (fun() -> Some (mt, List.map snd (t_infos mt).mt_types, fvars()));
  1508. context_init();
  1509. let r = try apply_macro ctx MBuild s el p with e -> ctx.g.get_build_infos <- old; raise e in
  1510. ctx.g.get_build_infos <- old;
  1511. (match r with
  1512. | None -> error "Build failure" p
  1513. | Some e -> fbuild e; loop l)
  1514. | (Meta.Enum,_,p) :: l ->
  1515. begin match mt with
  1516. | TClassDecl ({cl_kind = KAbstractImpl a} as c) ->
  1517. context_init();
  1518. let e = build_enum_abstract ctx c a (fvars()) p in
  1519. fbuild e;
  1520. loop l
  1521. | _ ->
  1522. loop l
  1523. end
  1524. | _ :: l -> loop l
  1525. | [] -> ()
  1526. in
  1527. (* let errors go through to prevent resume if build fails *)
  1528. loop meta
  1529. let init_class ctx c p context_init herits fields =
  1530. let ctx = {
  1531. ctx with
  1532. curclass = c;
  1533. type_params = c.cl_types;
  1534. pass = PBuildClass;
  1535. tthis = (match c.cl_kind with
  1536. | KAbstractImpl a ->
  1537. (match a.a_this with
  1538. | TMono r when !r = None -> TAbstract (a,List.map snd c.cl_types)
  1539. | t -> t)
  1540. | _ -> TInst (c,List.map snd c.cl_types));
  1541. on_error = (fun ctx msg ep ->
  1542. ctx.com.error msg ep;
  1543. (* macros expressions might reference other code, let's recall which class we are actually compiling *)
  1544. if ep.pfile <> c.cl_pos.pfile then ctx.com.error "Defined in this class" c.cl_pos
  1545. );
  1546. } in
  1547. incr stats.s_classes_built;
  1548. let fields = patch_class ctx c fields in
  1549. let fields = ref fields in
  1550. let get_fields() = !fields in
  1551. build_module_def ctx (TClassDecl c) c.cl_meta get_fields context_init (fun (e,p) ->
  1552. match e with
  1553. | EVars [_,Some (CTAnonymous f),None] ->
  1554. List.iter (fun f ->
  1555. if List.mem AMacro f.cff_access then
  1556. (match ctx.g.macros with
  1557. | Some (_,mctx) when Hashtbl.mem mctx.g.types_module c.cl_path ->
  1558. (* assume that if we had already a macro with the same name, it has not been changed during the @:build operation *)
  1559. if not (List.exists (fun f2 -> f2.cff_name = f.cff_name && List.mem AMacro f2.cff_access) (!fields)) then
  1560. error "Class build macro cannot return a macro function when the class has already been compiled into the macro context" p
  1561. | _ -> ())
  1562. ) f;
  1563. fields := f
  1564. | _ -> error "Class build macro must return a single variable with anonymous fields" p
  1565. );
  1566. let fields = !fields in
  1567. let core_api = Meta.has Meta.CoreApi c.cl_meta in
  1568. let is_class_macro = Meta.has Meta.Macro c.cl_meta in
  1569. if is_class_macro then display_error ctx "Macro classes are no longer allowed in haxe 3" p;
  1570. let fields, herits = if is_class_macro && not ctx.in_macro then begin
  1571. c.cl_extern <- true;
  1572. List.filter (fun f -> List.mem AStatic f.cff_access) fields, []
  1573. end else fields, herits in
  1574. if core_api && ctx.com.display = DMNone then delay ctx PForce (fun() -> init_core_api ctx c);
  1575. let rec extends_public c =
  1576. Meta.has Meta.PublicFields c.cl_meta ||
  1577. match c.cl_super with
  1578. | None -> false
  1579. | Some (c,_) -> extends_public c
  1580. in
  1581. let extends_public = extends_public c in
  1582. let is_public access parent =
  1583. if List.mem APrivate access then
  1584. false
  1585. else if List.mem APublic access then
  1586. true
  1587. else match parent with
  1588. | Some { cf_public = p } -> p
  1589. | _ -> c.cl_extern || c.cl_interface || extends_public
  1590. in
  1591. let rec get_parent c name =
  1592. match c.cl_super with
  1593. | None -> None
  1594. | Some (csup,_) ->
  1595. try
  1596. Some (PMap.find name csup.cl_fields)
  1597. with
  1598. Not_found -> get_parent csup name
  1599. in
  1600. let type_opt ctx p t =
  1601. match t with
  1602. | None when c.cl_extern || c.cl_interface ->
  1603. display_error ctx "Type required for extern classes and interfaces" p;
  1604. t_dynamic
  1605. | None when core_api ->
  1606. display_error ctx "Type required for core api classes" p;
  1607. t_dynamic
  1608. | _ ->
  1609. load_type_opt ctx p t
  1610. in
  1611. let rec has_field f = function
  1612. | None -> false
  1613. | Some (c,_) ->
  1614. PMap.exists f c.cl_fields || has_field f c.cl_super || List.exists (fun i -> has_field f (Some i)) c.cl_implements
  1615. in
  1616. (match c.cl_super with None -> () | Some _ -> delay ctx PForce (fun() -> check_overriding ctx c));
  1617. if ctx.com.config.pf_overload then delay ctx PForce (fun() -> check_overloads ctx c);
  1618. (* ----------------------- COMPLETION ----------------------------- *)
  1619. let display_file = if ctx.com.display <> DMNone then Common.unique_full_path p.pfile = (!Parser.resume_display).pfile else false in
  1620. let cp = !Parser.resume_display in
  1621. let delayed_expr = ref [] in
  1622. let rec is_full_type t =
  1623. match t with
  1624. | TFun (args,ret) -> is_full_type ret && List.for_all (fun (_,_,t) -> is_full_type t) args
  1625. | TMono r -> (match !r with None -> false | Some t -> is_full_type t)
  1626. | TAbstract _ | TInst _ | TEnum _ | TLazy _ | TDynamic _ | TAnon _ | TType _ -> true
  1627. in
  1628. let bind_type ctx cf r p macro =
  1629. if ctx.com.display <> DMNone then begin
  1630. let cp = !Parser.resume_display in
  1631. if display_file && (cp.pmin = 0 || (p.pmin <= cp.pmin && p.pmax >= cp.pmax)) then begin
  1632. if macro && not ctx.in_macro then
  1633. (* force macro system loading of this class in order to get completion *)
  1634. delay ctx PTypeField (fun() -> ignore(ctx.g.do_macro ctx MExpr c.cl_path cf.cf_name [] p))
  1635. else begin
  1636. cf.cf_type <- TLazy r;
  1637. delayed_expr := (ctx,Some r) :: !delayed_expr;
  1638. end
  1639. end else begin
  1640. if not (is_full_type cf.cf_type) then begin
  1641. delayed_expr := (ctx, None) :: !delayed_expr;
  1642. cf.cf_type <- TLazy r;
  1643. end;
  1644. end
  1645. end else if macro && not ctx.in_macro then
  1646. ()
  1647. else begin
  1648. cf.cf_type <- TLazy r;
  1649. delayed_expr := (ctx,Some r) :: !delayed_expr;
  1650. end
  1651. in
  1652. let force_constructor = ref false in
  1653. let bind_var ctx cf e stat inline =
  1654. let p = cf.cf_pos in
  1655. if not stat && has_field cf.cf_name c.cl_super then error ("Redefinition of variable " ^ cf.cf_name ^ " in subclass is not allowed") p;
  1656. let t = cf.cf_type in
  1657. match e with
  1658. | None -> ()
  1659. | Some e ->
  1660. let check_cast e =
  1661. (* insert cast to keep explicit field type (issue #1901) *)
  1662. let st = s_type (print_context()) in
  1663. if e.epos.pfile = "src/Main.hx" then Printf.printf "%s %s\n" (st e.etype) (st cf.cf_type);
  1664. if type_iseq e.etype cf.cf_type then
  1665. e
  1666. else begin match e.eexpr,follow cf.cf_type with
  1667. | TConst (TInt i),TAbstract({a_path=[],"Float"},_) ->
  1668. (* turn int constant to float constant if expected type is float *)
  1669. {e with eexpr = TConst (TFloat (Int32.to_string i))}
  1670. | _ ->
  1671. let e' = (!check_abstract_cast_ref) ctx cf.cf_type e e.epos in
  1672. if e' == e then
  1673. mk (TCast(e,None)) cf.cf_type e.epos
  1674. else
  1675. e'
  1676. end
  1677. in
  1678. let r = exc_protect ctx (fun r ->
  1679. (* type constant init fields (issue #1956) *)
  1680. if not !return_partial_type || (match fst e with EConst _ -> true | _ -> false) then begin
  1681. r := (fun() -> t);
  1682. context_init();
  1683. if ctx.com.verbose then Common.log ctx.com ("Typing " ^ (if ctx.in_macro then "macro " else "") ^ s_type_path c.cl_path ^ "." ^ cf.cf_name);
  1684. let e = type_var_field ctx t e stat p in
  1685. let require_constant_expression e msg = match Optimizer.make_constant_expression ctx e with
  1686. | Some e -> e
  1687. | None -> display_error ctx msg p; e
  1688. in
  1689. let e = (match cf.cf_kind with
  1690. | Var v when c.cl_extern || Meta.has Meta.Extern cf.cf_meta ->
  1691. if not stat then begin
  1692. display_error ctx "Extern non-static variables may not be initialized" p;
  1693. e
  1694. end else if v.v_read <> AccInline then begin
  1695. display_error ctx "Extern non-inline variables may not be initialized" p;
  1696. e
  1697. end else require_constant_expression e "Extern variable initialization must be a constant value"
  1698. | Var v when is_extern_field cf ->
  1699. (* disallow initialization of non-physical fields (issue #1958) *)
  1700. display_error ctx "This field cannot be initialized because it is not a real variable" p; e
  1701. | Var v when not stat ->
  1702. let e = match Optimizer.make_constant_expression ctx e with
  1703. | Some e -> e
  1704. | None ->
  1705. let rec has_this e = match e.eexpr with
  1706. | TConst TThis ->
  1707. display_error ctx "Cannot access this or other member field in variable initialization" e.epos;
  1708. | _ ->
  1709. Type.iter has_this e
  1710. in
  1711. has_this e;
  1712. e
  1713. in
  1714. e
  1715. | Var v when v.v_read = AccInline ->
  1716. let e = require_constant_expression e "Inline variable initialization must be a constant value" in
  1717. begin match c.cl_kind with
  1718. | KAbstractImpl a when Meta.has Meta.Enum cf.cf_meta && Meta.has Meta.Enum a.a_meta ->
  1719. unify ctx (TAbstract(a,(List.map (fun _ -> mk_mono()) a.a_types))) t p;
  1720. begin match e.eexpr with
  1721. | TCast(e1,None) -> unify ctx e1.etype a.a_this e1.epos
  1722. | _ -> assert false
  1723. end
  1724. | _ ->
  1725. ()
  1726. end;
  1727. e
  1728. | _ ->
  1729. e
  1730. ) in
  1731. let e = check_cast e in
  1732. cf.cf_expr <- Some e;
  1733. cf.cf_type <- t;
  1734. end;
  1735. t
  1736. ) "bind_var" in
  1737. if not stat then force_constructor := true;
  1738. bind_type ctx cf r (snd e) false
  1739. in
  1740. (* ----------------------- FIELD INIT ----------------------------- *)
  1741. let loop_cf f =
  1742. let name = f.cff_name in
  1743. let p = f.cff_pos in
  1744. if name.[0] = '$' && ctx.com.display = DMNone then error "Field names starting with a dollar are not allowed" p;
  1745. let stat = List.mem AStatic f.cff_access in
  1746. let extern = Meta.has Meta.Extern f.cff_meta || c.cl_extern in
  1747. let is_abstract,allow_inline =
  1748. match c.cl_kind, f.cff_kind with
  1749. | KAbstractImpl _, _ -> true,true
  1750. |_, FFun _ -> false,ctx.g.doinline || extern
  1751. | _ -> false,true
  1752. in
  1753. let inline = List.mem AInline f.cff_access && allow_inline in
  1754. let override = List.mem AOverride f.cff_access in
  1755. let is_macro = Meta.has Meta.Macro f.cff_meta in
  1756. if is_macro then ctx.com.warning "@:macro should now be 'macro' accessor" p;
  1757. let is_macro = is_macro || List.mem AMacro f.cff_access in
  1758. List.iter (fun acc ->
  1759. match (acc, f.cff_kind) with
  1760. | APublic, _ | APrivate, _ | AStatic, _ -> ()
  1761. | ADynamic, FFun _ | AOverride, FFun _ | AMacro, FFun _ | AInline, FFun _ | AInline, FVar _ -> ()
  1762. | _, FVar _ -> error ("Invalid accessor '" ^ Ast.s_access acc ^ "' for variable " ^ name) p
  1763. | _, FProp _ -> error ("Invalid accessor '" ^ Ast.s_access acc ^ "' for property " ^ name) p
  1764. ) f.cff_access;
  1765. if override then (match c.cl_super with None -> error ("Invalid override on field '" ^ f.cff_name ^ "': class has no super class") p | _ -> ());
  1766. (* build the per-field context *)
  1767. let ctx = {
  1768. ctx with
  1769. pass = PBuildClass; (* will be set later to PTypeExpr *)
  1770. } in
  1771. match f.cff_kind with
  1772. | FVar (t,e) ->
  1773. if not stat && is_abstract then error (f.cff_name ^ ": Cannot declare member variable in abstract") p;
  1774. if inline && not stat then error (f.cff_name ^ ": Inline variable must be static") p;
  1775. if inline && e = None then error (f.cff_name ^ ": Inline variable must be initialized") p;
  1776. let t = (match t with
  1777. | None when not stat && e = None ->
  1778. error ("Type required for member variable " ^ name) p;
  1779. | None ->
  1780. mk_mono()
  1781. | Some t ->
  1782. let old = ctx.type_params in
  1783. if stat then ctx.type_params <- [];
  1784. let t = load_complex_type ctx p t in
  1785. if stat then ctx.type_params <- old;
  1786. t
  1787. ) in
  1788. let cf = {
  1789. cf_name = name;
  1790. cf_doc = f.cff_doc;
  1791. cf_meta = f.cff_meta;
  1792. cf_type = t;
  1793. cf_pos = f.cff_pos;
  1794. cf_kind = Var (if inline then { v_read = AccInline ; v_write = AccNever } else { v_read = AccNormal; v_write = AccNormal });
  1795. cf_expr = None;
  1796. cf_public = is_public f.cff_access None;
  1797. cf_params = [];
  1798. cf_overloads = [];
  1799. } in
  1800. ctx.curfield <- cf;
  1801. bind_var ctx cf e stat inline;
  1802. f, false, cf, true
  1803. | FFun fd ->
  1804. let params = type_function_params ctx fd f.cff_name p in
  1805. if inline && c.cl_interface then error (f.cff_name ^ ": You can't declare inline methods in interfaces") p;
  1806. if Meta.has Meta.Generic f.cff_meta then begin
  1807. if params = [] then error (f.cff_name ^ ": Generic functions must have type parameters") p;
  1808. end;
  1809. let is_macro = is_macro || (is_class_macro && stat) in
  1810. let f, stat, fd = if not is_macro || stat then
  1811. f, stat, fd
  1812. else if ctx.in_macro then
  1813. (* non-static macros methods are turned into static when we are running the macro *)
  1814. { f with cff_access = AStatic :: f.cff_access }, true, fd
  1815. else
  1816. (* remove display of first argument which will contain the "this" expression *)
  1817. f, stat, { fd with f_args = match fd.f_args with [] -> [] | _ :: l -> l }
  1818. in
  1819. let fd = if not is_macro then
  1820. fd
  1821. else begin
  1822. if ctx.in_macro then begin
  1823. (* a class with a macro cannot be extern in macro context (issue #2015) *)
  1824. c.cl_extern <- false;
  1825. let texpr = CTPath { tpackage = ["haxe";"macro"]; tname = "Expr"; tparams = []; tsub = None } in
  1826. (* ExprOf type parameter might contain platform-specific type, let's replace it by Expr *)
  1827. let no_expr_of = function
  1828. | CTPath { tpackage = ["haxe";"macro"]; tname = "Expr"; tsub = Some ("ExprOf"); tparams = [TPType _] }
  1829. | CTPath { tpackage = []; tname = ("ExprOf"); tsub = None; tparams = [TPType _] } -> Some texpr
  1830. | t -> Some t
  1831. in
  1832. {
  1833. f_params = fd.f_params;
  1834. f_type = (match fd.f_type with None -> Some texpr | Some t -> no_expr_of t);
  1835. f_args = List.map (fun (a,o,t,e) -> a,o,(match t with None -> Some texpr | Some t -> no_expr_of t),e) fd.f_args;
  1836. f_expr = fd.f_expr;
  1837. }
  1838. end else
  1839. let tdyn = Some (CTPath { tpackage = []; tname = "Dynamic"; tparams = []; tsub = None }) in
  1840. let to_dyn = function
  1841. | { tpackage = ["haxe";"macro"]; tname = "Expr"; tsub = Some ("ExprOf"); tparams = [TPType t] } -> Some t
  1842. | { tpackage = []; tname = ("ExprOf"); tsub = None; tparams = [TPType t] } -> Some t
  1843. | { tpackage = ["haxe"]; tname = ("PosInfos"); tsub = None; tparams = [] } -> error "haxe.PosInfos is not allowed on macro functions, use Context.currentPos() instead" p
  1844. | _ -> tdyn
  1845. in
  1846. {
  1847. f_params = fd.f_params;
  1848. f_type = (match fd.f_type with Some (CTPath t) -> to_dyn t | _ -> tdyn);
  1849. f_args = List.map (fun (a,o,t,_) -> a,o,(match t with Some (CTPath t) -> to_dyn t | _ -> tdyn),None) fd.f_args;
  1850. f_expr = None;
  1851. }
  1852. end in
  1853. let parent = (if not stat then get_parent c name else None) in
  1854. let dynamic = List.mem ADynamic f.cff_access || (match parent with Some { cf_kind = Method MethDynamic } -> true | _ -> false) in
  1855. if inline && dynamic then error (f.cff_name ^ ": You can't have both 'inline' and 'dynamic'") p;
  1856. ctx.type_params <- (match c.cl_kind with
  1857. | KAbstractImpl a when Meta.has Meta.Impl f.cff_meta || Meta.has Meta.From f.cff_meta || Meta.has Meta.MultiType a.a_meta && Meta.has Meta.To f.cff_meta ->
  1858. params @ a.a_types
  1859. | _ ->
  1860. if stat then params else params @ ctx.type_params);
  1861. let constr = (name = "new") in
  1862. let ret = if constr then ctx.t.tvoid else type_opt ctx p fd.f_type in
  1863. let args = List.map (fun (name,opt,t,c) ->
  1864. let t, c = type_function_param ctx (type_opt ctx p t) c opt p in
  1865. name, c, t
  1866. ) fd.f_args in
  1867. let t = TFun (fun_args args,ret) in
  1868. if c.cl_interface && not stat && fd.f_expr <> None then error (f.cff_name ^ ": An interface method cannot have a body") p;
  1869. if constr then begin
  1870. if c.cl_interface then error "An interface cannot have a constructor" p;
  1871. if stat then error "A constructor must not be static" p;
  1872. match fd.f_type with
  1873. | None | Some (CTPath { tpackage = []; tname = "Void" }) -> ()
  1874. | _ -> error "A class constructor can't have a return value" p
  1875. end;
  1876. let cf = {
  1877. cf_name = name;
  1878. cf_doc = f.cff_doc;
  1879. cf_meta = f.cff_meta;
  1880. cf_type = t;
  1881. cf_pos = f.cff_pos;
  1882. cf_kind = Method (if is_macro then MethMacro else if inline then MethInline else if dynamic then MethDynamic else MethNormal);
  1883. cf_expr = None;
  1884. cf_public = is_public f.cff_access parent;
  1885. cf_params = params;
  1886. cf_overloads = [];
  1887. } in
  1888. let do_bind = ref (((not c.cl_extern || inline) && not c.cl_interface) || cf.cf_name = "__init__") in
  1889. let do_add = ref true in
  1890. (match c.cl_kind with
  1891. | KAbstractImpl a ->
  1892. let m = mk_mono() in
  1893. let ta = TAbstract(a, List.map (fun _ -> mk_mono()) a.a_types) in
  1894. let tthis = if Meta.has Meta.Impl f.cff_meta || Meta.has Meta.To f.cff_meta then monomorphs a.a_types a.a_this else a.a_this in
  1895. let check_bind () =
  1896. if fd.f_expr = None then begin
  1897. if inline then error (f.cff_name ^ ": Inline functions must have an expression") f.cff_pos;
  1898. begin match fd.f_type with
  1899. | None -> error (f.cff_name ^ ": Functions without expressions must have an explicit return type") f.cff_pos
  1900. | Some _ -> ()
  1901. end;
  1902. do_add := false;
  1903. do_bind := false;
  1904. end
  1905. in
  1906. let rec loop ml = match ml with
  1907. | (Meta.From,_,_) :: _ ->
  1908. if is_macro then error (f.cff_name ^ ": Macro cast functions are not supported") p;
  1909. let r = fun () ->
  1910. (* the return type of a from-function must be the abstract, not the underlying type *)
  1911. (try type_eq EqStrict ret ta with Unify_error l -> error (error_msg (Unify l)) p);
  1912. match t with
  1913. | TFun([_,_,t],_) -> t
  1914. | _ -> error (f.cff_name ^ ": @:from cast functions must accept exactly one argument") p
  1915. in
  1916. a.a_from <- (TLazy (ref r),Some cf) :: a.a_from;
  1917. | (Meta.To,_,_) :: _ ->
  1918. if is_macro then error (f.cff_name ^ ": Macro cast functions are not supported") p;
  1919. if not (Meta.has Meta.Impl cf.cf_meta) then cf.cf_meta <- (Meta.Impl,[],cf.cf_pos) :: cf.cf_meta;
  1920. let resolve_m args =
  1921. (try unify_raise ctx t (tfun (tthis :: args) m) f.cff_pos with Error (Unify l,p) -> error (error_msg (Unify l)) p);
  1922. match follow m with
  1923. | TMono _ when (match cf.cf_type with TFun(_,r) -> r == t_dynamic | _ -> false) -> t_dynamic
  1924. | m -> m
  1925. in
  1926. let r = if Meta.has Meta.MultiType a.a_meta then begin
  1927. let ctor = try
  1928. PMap.find "_new" c.cl_statics
  1929. with Not_found ->
  1930. error "Constructor of multi-type abstract must be defined before the individual @:to-functions are" cf.cf_pos
  1931. in
  1932. (fun () ->
  1933. delay ctx PFinal (fun () -> unify ctx m tthis f.cff_pos);
  1934. let args = match follow (monomorphs a.a_types ctor.cf_type) with
  1935. | TFun(args,_) -> List.map (fun (_,_,t) -> t) args
  1936. | _ -> assert false
  1937. in
  1938. resolve_m args
  1939. )
  1940. end else (fun () ->
  1941. resolve_m []
  1942. ) in
  1943. a.a_to <- (TLazy (ref r), Some cf) :: a.a_to
  1944. | (Meta.ArrayAccess,_,_) :: _ ->
  1945. if is_macro then error (f.cff_name ^ ": Macro array-access functions are not supported") p;
  1946. a.a_array <- cf :: a.a_array;
  1947. if Meta.has Meta.CoreType a.a_meta then check_bind();
  1948. | (Meta.Op,[EBinop(op,_,_),_],_) :: _ ->
  1949. if is_macro then error (f.cff_name ^ ": Macro operator functions are not supported") p;
  1950. let targ = if Meta.has Meta.Impl f.cff_meta then tthis else ta in
  1951. let left_eq,right_eq = match follow t with
  1952. | TFun([(_,_,t1);(_,_,t2)],_) ->
  1953. type_iseq targ t1,type_iseq targ t2
  1954. | _ ->
  1955. if Meta.has Meta.Impl cf.cf_meta then
  1956. error (f.cff_name ^ ": Member @:op functions must accept exactly one argument") cf.cf_pos
  1957. else
  1958. error (f.cff_name ^ ": Static @:op functions must accept exactly two arguments") cf.cf_pos
  1959. in
  1960. if not (left_eq || right_eq) then error (f.cff_name ^ ": The left or right argument type must be " ^ (s_type (print_context()) targ)) f.cff_pos;
  1961. if right_eq && Meta.has Meta.Commutative f.cff_meta then error (f.cff_name ^ ": @:commutative is only allowed if the right argument is not " ^ (s_type (print_context()) targ)) f.cff_pos;
  1962. a.a_ops <- (op,cf) :: a.a_ops;
  1963. check_bind();
  1964. | (Meta.Op,[EUnop(op,flag,_),_],_) :: _ ->
  1965. if is_macro then error (f.cff_name ^ ": Macro operator functions are not supported") p;
  1966. let targ = if Meta.has Meta.Impl f.cff_meta then tthis else ta in
  1967. (try type_eq EqStrict t (tfun [targ] (mk_mono())) with Unify_error l -> raise (Error ((Unify l),f.cff_pos)));
  1968. a.a_unops <- (op,flag,cf) :: a.a_unops;
  1969. check_bind();
  1970. | _ :: ml ->
  1971. loop ml
  1972. | [] ->
  1973. ()
  1974. in
  1975. loop f.cff_meta;
  1976. if f.cff_name = "_new" && Meta.has Meta.MultiType a.a_meta then do_bind := false;
  1977. | _ ->
  1978. ());
  1979. init_meta_overloads ctx cf;
  1980. ctx.curfield <- cf;
  1981. let r = exc_protect ctx (fun r ->
  1982. if not !return_partial_type then begin
  1983. r := (fun() -> t);
  1984. context_init();
  1985. incr stats.s_methods_typed;
  1986. if ctx.com.verbose then Common.log ctx.com ("Typing " ^ (if ctx.in_macro then "macro " else "") ^ s_type_path c.cl_path ^ "." ^ name);
  1987. let fmode = (match c.cl_kind with
  1988. | KAbstractImpl _ ->
  1989. (match args with
  1990. | ("this",_,_) :: _ -> FunMemberAbstract
  1991. | _ when name = "_new" -> FunMemberAbstract
  1992. | _ -> FunStatic)
  1993. | _ ->
  1994. if constr then FunConstructor else if stat then FunStatic else FunMember
  1995. ) in
  1996. let display_field = display_file && (f.cff_pos.pmin <= cp.pmin && f.cff_pos.pmax >= cp.pmax) in
  1997. let e , fargs = type_function ctx args ret fmode fd display_field p in
  1998. let f = {
  1999. tf_args = fargs;
  2000. tf_type = ret;
  2001. tf_expr = e;
  2002. } in
  2003. if stat && name = "__init__" then
  2004. (match e.eexpr with
  2005. | TBlock [] | TBlock [{ eexpr = TConst _ }] | TConst _ | TObjectDecl [] -> ()
  2006. | _ -> c.cl_init <- Some e);
  2007. cf.cf_expr <- Some (mk (TFunction f) t p);
  2008. cf.cf_type <- t;
  2009. end;
  2010. t
  2011. ) "type_fun" in
  2012. if !do_bind then bind_type ctx cf r (match fd.f_expr with Some e -> snd e | None -> f.cff_pos) is_macro;
  2013. f, constr, cf, !do_add
  2014. | FProp (get,set,t,eo) ->
  2015. (match c.cl_kind with
  2016. | KAbstractImpl a when Meta.has Meta.Impl f.cff_meta ->
  2017. ctx.type_params <- a.a_types;
  2018. | _ -> ());
  2019. let ret = (match t, eo with
  2020. | None, None -> error (f.cff_name ^ ": Property must either define a type or a default value") p;
  2021. | None, _ -> mk_mono()
  2022. | Some t, _ -> load_complex_type ctx p t
  2023. ) in
  2024. let t_get,t_set = match c.cl_kind with
  2025. | KAbstractImpl a when Meta.has Meta.Impl f.cff_meta ->
  2026. if Meta.has Meta.IsVar f.cff_meta then error (f.cff_name ^ ": Abstract properties cannot be real variables") f.cff_pos;
  2027. let ta = apply_params a.a_types (List.map snd a.a_types) a.a_this in
  2028. tfun [ta] ret, tfun [ta;ret] ret
  2029. | _ -> tfun [] ret, tfun [ret] ret
  2030. in
  2031. let check_method m t req_name =
  2032. if ctx.com.display <> DMNone then () else
  2033. try
  2034. let _, t2, f = (if stat then let f = PMap.find m c.cl_statics in Some c, f.cf_type, f else class_field c m) in
  2035. (* accessors must be public on As3 (issue #1872) *)
  2036. if Common.defined ctx.com Define.As3 then f.cf_meta <- (Meta.Public,[],p) :: f.cf_meta;
  2037. (match f.cf_kind with
  2038. | Method MethMacro ->
  2039. display_error ctx (f.cf_name ^ ": Macro methods cannot be used as property accessor") p;
  2040. display_error ctx (f.cf_name ^ ": Accessor method is here") f.cf_pos;
  2041. | _ -> ());
  2042. unify_raise ctx t2 t f.cf_pos;
  2043. (match req_name with None -> () | Some n -> display_error ctx ("Please use " ^ n ^ " to name your property access method") f.cf_pos);
  2044. with
  2045. | Error (Unify l,p) -> raise (Error (Stack (Custom ("In method " ^ m ^ " required by property " ^ name),Unify l),p))
  2046. | Not_found ->
  2047. if req_name <> None then display_error ctx (f.cff_name ^ ": Custom property accessor is no longer supported, please use get/set") p else
  2048. if not (c.cl_interface || c.cl_extern) then display_error ctx ("Method " ^ m ^ " required by property " ^ name ^ " is missing") p
  2049. in
  2050. let get = (match get with
  2051. | "null" -> AccNo
  2052. | "dynamic" -> AccCall
  2053. | "never" -> AccNever
  2054. | "default" -> AccNormal
  2055. | _ ->
  2056. let get = if get = "get" then "get_" ^ name else get in
  2057. delay ctx PForce (fun() -> check_method get t_get (if get <> "get" && get <> "get_" ^ name then Some ("get_" ^ name) else None));
  2058. AccCall
  2059. ) in
  2060. let set = (match set with
  2061. | "null" ->
  2062. (* standard flash library read-only variables can't be accessed for writing, even in subclasses *)
  2063. if c.cl_extern && (match c.cl_path with "flash" :: _ , _ -> true | _ -> false) && ctx.com.platform = Flash then
  2064. AccNever
  2065. else
  2066. AccNo
  2067. | "never" -> AccNever
  2068. | "dynamic" -> AccCall
  2069. | "default" -> AccNormal
  2070. | _ ->
  2071. let set = if set = "set" then "set_" ^ name else set in
  2072. delay ctx PForce (fun() -> check_method set t_set (if set <> "set" && set <> "set_" ^ name then Some ("set_" ^ name) else None));
  2073. AccCall
  2074. ) in
  2075. if set = AccNormal && (match get with AccCall -> true | _ -> false) then error (f.cff_name ^ ": Unsupported property combination") p;
  2076. let cf = {
  2077. cf_name = name;
  2078. cf_doc = f.cff_doc;
  2079. cf_meta = f.cff_meta;
  2080. cf_pos = f.cff_pos;
  2081. cf_kind = Var { v_read = get; v_write = set };
  2082. cf_expr = None;
  2083. cf_type = ret;
  2084. cf_public = is_public f.cff_access None;
  2085. cf_params = [];
  2086. cf_overloads = [];
  2087. } in
  2088. ctx.curfield <- cf;
  2089. bind_var ctx cf eo stat inline;
  2090. f, false, cf, true
  2091. in
  2092. let rec check_require = function
  2093. | [] -> None
  2094. | (Meta.Require,conds,_) :: l ->
  2095. let rec loop = function
  2096. | [] -> check_require l
  2097. | e :: l ->
  2098. let sc = match fst e with
  2099. | EConst (Ident s) -> s
  2100. | EBinop ((OpEq|OpNotEq|OpGt|OpGte|OpLt|OpLte) as op,(EConst (Ident s),_),(EConst ((Int _ | Float _ | String _) as c),_)) -> s ^ s_binop op ^ s_constant c
  2101. | _ -> ""
  2102. in
  2103. if not (Parser.is_true (Parser.eval ctx.com e)) then
  2104. Some (sc,(match List.rev l with (EConst (String msg),_) :: _ -> Some msg | _ -> None))
  2105. else
  2106. loop l
  2107. in
  2108. loop conds
  2109. | _ :: l ->
  2110. check_require l
  2111. in
  2112. let cl_req = check_require c.cl_meta in
  2113. List.iter (fun f ->
  2114. let p = f.cff_pos in
  2115. try
  2116. let fd , constr, f, do_add = loop_cf f in
  2117. let is_static = List.mem AStatic fd.cff_access in
  2118. if (is_static || constr) && c.cl_interface && f.cf_name <> "__init__" then error "You can't declare static fields in interfaces" p;
  2119. begin try
  2120. let _,args,_ = Meta.get Meta.IfFeature f.cf_meta in
  2121. List.iter (fun e -> match fst e with
  2122. | EConst(String s) ->
  2123. ctx.m.curmod.m_extra.m_features <- (s,(c,f,is_static)) :: ctx.m.curmod.m_extra.m_features;
  2124. | _ ->
  2125. error "String expected" (pos e)
  2126. ) args
  2127. with Not_found -> () end;
  2128. let req = check_require fd.cff_meta in
  2129. let req = (match req with None -> if is_static || constr then cl_req else None | _ -> req) in
  2130. (match req with
  2131. | None -> ()
  2132. | Some r -> f.cf_kind <- Var { v_read = AccRequire (fst r, snd r); v_write = AccRequire (fst r, snd r) });
  2133. if constr then begin
  2134. match c.cl_constructor with
  2135. | None ->
  2136. c.cl_constructor <- Some f
  2137. | Some ctor when ctx.com.config.pf_overload ->
  2138. if Meta.has Meta.Overload f.cf_meta && Meta.has Meta.Overload ctor.cf_meta then
  2139. ctor.cf_overloads <- f :: ctor.cf_overloads
  2140. else if Meta.has Meta.Overload f.cf_meta <> Meta.has Meta.Overload ctor.cf_meta then
  2141. display_error ctx ("If using overloaded constructors, all constructors must be declared with @:overload") (if Meta.has Meta.Overload f.cf_meta then ctor.cf_pos else f.cf_pos)
  2142. | Some ctor ->
  2143. display_error ctx "Duplicate constructor" p
  2144. end else if not is_static || f.cf_name <> "__init__" then begin
  2145. let dup = if is_static then PMap.exists f.cf_name c.cl_fields || has_field f.cf_name c.cl_super else PMap.exists f.cf_name c.cl_statics in
  2146. if dup then error ("Same field name can't be use for both static and instance : " ^ f.cf_name) p;
  2147. if List.mem AOverride fd.cff_access then c.cl_overrides <- f :: c.cl_overrides;
  2148. let is_var f = match f.cf_kind with | Var _ -> true | _ -> false in
  2149. if PMap.mem f.cf_name (if is_static then c.cl_statics else c.cl_fields) then
  2150. if ctx.com.config.pf_overload && Meta.has Meta.Overload f.cf_meta && not (is_var f) then
  2151. let mainf = PMap.find f.cf_name (if is_static then c.cl_statics else c.cl_fields) in
  2152. if is_var mainf then display_error ctx "Cannot declare a variable with same name as a method" mainf.cf_pos;
  2153. (if not (Meta.has Meta.Overload mainf.cf_meta) then display_error ctx ("Overloaded methods must have @:overload metadata") mainf.cf_pos);
  2154. mainf.cf_overloads <- f :: mainf.cf_overloads
  2155. else
  2156. display_error ctx ("Duplicate class field declaration : " ^ f.cf_name) p
  2157. else
  2158. if not do_add then
  2159. ()
  2160. else if is_static then begin
  2161. c.cl_statics <- PMap.add f.cf_name f c.cl_statics;
  2162. c.cl_ordered_statics <- f :: c.cl_ordered_statics;
  2163. end else begin
  2164. c.cl_fields <- PMap.add f.cf_name f c.cl_fields;
  2165. c.cl_ordered_fields <- f :: c.cl_ordered_fields;
  2166. end;
  2167. end
  2168. with Error (Custom str,p2) when p = p2 ->
  2169. display_error ctx str p
  2170. ) fields;
  2171. (match c.cl_kind with
  2172. | KAbstractImpl a ->
  2173. a.a_to <- List.rev a.a_to;
  2174. a.a_from <- List.rev a.a_from;
  2175. a.a_ops <- List.rev a.a_ops;
  2176. a.a_unops <- List.rev a.a_unops;
  2177. | _ -> ());
  2178. c.cl_ordered_statics <- List.rev c.cl_ordered_statics;
  2179. c.cl_ordered_fields <- List.rev c.cl_ordered_fields;
  2180. (*
  2181. make sure a default contructor with same access as super one will be added to the class structure at some point.
  2182. *)
  2183. (* add_constructor does not deal with overloads correctly *)
  2184. if not ctx.com.config.pf_overload then add_constructor ctx c !force_constructor p;
  2185. (* check overloaded constructors *)
  2186. (if ctx.com.config.pf_overload then match c.cl_constructor with
  2187. | Some ctor ->
  2188. List.iter (fun f ->
  2189. try
  2190. (* TODO: consider making a broader check, and treat some types, like TAnon and type parameters as Dynamic *)
  2191. ignore(List.find (fun f2 -> f != f2 && same_overload_args f.cf_type f2.cf_type f f2) (ctor :: ctor.cf_overloads));
  2192. display_error ctx ("Another overloaded field of same signature was already declared : " ^ f.cf_name) f.cf_pos;
  2193. with Not_found -> ()
  2194. ) (ctor :: ctor.cf_overloads)
  2195. | _ -> ());
  2196. (* push delays in reverse order so they will be run in correct order *)
  2197. List.iter (fun (ctx,r) ->
  2198. ctx.pass <- PTypeField;
  2199. (match r with
  2200. | None -> ()
  2201. | Some r -> delay ctx PTypeField (fun() -> ignore((!r)())))
  2202. ) !delayed_expr
  2203. let resolve_typedef t =
  2204. match t with
  2205. | TClassDecl _ | TEnumDecl _ | TAbstractDecl _ -> t
  2206. | TTypeDecl td ->
  2207. match follow td.t_type with
  2208. | TEnum (e,_) -> TEnumDecl e
  2209. | TInst (c,_) -> TClassDecl c
  2210. | TAbstract (a,_) -> TAbstractDecl a
  2211. | _ -> t
  2212. let add_module ctx m p =
  2213. let decl_type t =
  2214. let t = t_infos t in
  2215. try
  2216. let m2 = Hashtbl.find ctx.g.types_module t.mt_path in
  2217. if m.m_path <> m2 && String.lowercase (s_type_path m2) = String.lowercase (s_type_path m.m_path) then error ("Module " ^ s_type_path m2 ^ " is loaded with a different case than " ^ s_type_path m.m_path) p;
  2218. error ("Type name " ^ s_type_path t.mt_path ^ " is redefined from module " ^ s_type_path m2) p
  2219. with
  2220. Not_found ->
  2221. Hashtbl.add ctx.g.types_module t.mt_path m.m_path
  2222. in
  2223. List.iter decl_type m.m_types;
  2224. Hashtbl.add ctx.g.modules m.m_path m
  2225. (*
  2226. In this pass, we can access load and access other modules types, but we cannot follow them or access their structure
  2227. since they have not been setup. We also build a context_init list that will be evaluated the first time we evaluate
  2228. an expression into the context
  2229. *)
  2230. let rec init_module_type ctx context_init do_init (decl,p) =
  2231. let get_type name =
  2232. try List.find (fun t -> snd (t_infos t).mt_path = name) ctx.m.curmod.m_types with Not_found -> assert false
  2233. in
  2234. match decl with
  2235. | EImport (path,mode) ->
  2236. let rec loop acc = function
  2237. | x :: l when is_lower_ident (fst x) -> loop (x::acc) l
  2238. | rest -> List.rev acc, rest
  2239. in
  2240. let pack, rest = loop [] path in
  2241. (match rest with
  2242. | [] ->
  2243. (match mode with
  2244. | IAll ->
  2245. ctx.m.wildcard_packages <- List.map fst pack :: ctx.m.wildcard_packages
  2246. | _ ->
  2247. (match List.rev path with
  2248. | [] -> assert false
  2249. | (_,p) :: _ -> error "Module name must start with an uppercase letter" p))
  2250. | (tname,p2) :: rest ->
  2251. let p1 = (match pack with [] -> p2 | (_,p1) :: _ -> p1) in
  2252. let p = punion p1 p2 in
  2253. let md = ctx.g.do_load_module ctx (List.map fst pack,tname) p in
  2254. let types = md.m_types in
  2255. let no_private t = not (t_infos t).mt_private in
  2256. let chk_private t p = if (t_infos t).mt_private then error "You can't import a private type" p in
  2257. let has_name name t = snd (t_infos t).mt_path = name in
  2258. let get_type tname =
  2259. let t = (try List.find (has_name tname) types with Not_found -> error (string_error tname (List.map (fun mt -> snd (t_infos mt).mt_path) types) ("Module " ^ s_type_path md.m_path ^ " does not define type " ^ tname)) p) in
  2260. chk_private t p;
  2261. t
  2262. in
  2263. let rebind t name =
  2264. let _, _, f = ctx.g.do_build_instance ctx t p in
  2265. (* create a temp private typedef, does not register it in module *)
  2266. TTypeDecl {
  2267. t_path = (fst md.m_path @ ["_" ^ snd md.m_path],name);
  2268. t_module = md;
  2269. t_pos = p;
  2270. t_private = true;
  2271. t_doc = None;
  2272. t_meta = [];
  2273. t_types = (t_infos t).mt_types;
  2274. t_type = f (List.map snd (t_infos t).mt_types);
  2275. }
  2276. in
  2277. let add_static_init t name s =
  2278. let name = (match name with None -> s | Some n -> n) in
  2279. match resolve_typedef t with
  2280. | TClassDecl c ->
  2281. c.cl_build();
  2282. ignore(PMap.find s c.cl_statics);
  2283. ctx.m.module_globals <- PMap.add name (TClassDecl c,s) ctx.m.module_globals
  2284. | TEnumDecl e ->
  2285. ignore(PMap.find s e.e_constrs);
  2286. ctx.m.module_globals <- PMap.add name (TEnumDecl e,s) ctx.m.module_globals
  2287. | _ ->
  2288. raise Not_found
  2289. in
  2290. (match mode with
  2291. | INormal | IAsName _ ->
  2292. let name = (match mode with IAsName n -> Some n | _ -> None) in
  2293. (match rest with
  2294. | [] ->
  2295. (match name with
  2296. | None ->
  2297. ctx.m.module_types <- List.filter no_private types @ ctx.m.module_types
  2298. | Some newname ->
  2299. ctx.m.module_types <- rebind (get_type tname) newname :: ctx.m.module_types);
  2300. | [tsub,p2] ->
  2301. let p = punion p1 p2 in
  2302. (try
  2303. let tsub = List.find (has_name tsub) types in
  2304. chk_private tsub p;
  2305. ctx.m.module_types <- (match name with None -> tsub | Some n -> rebind tsub n) :: ctx.m.module_types
  2306. with Not_found ->
  2307. (* this might be a static property, wait later to check *)
  2308. let tmain = get_type tname in
  2309. context_init := (fun() ->
  2310. try
  2311. add_static_init tmain name tsub
  2312. with Not_found ->
  2313. error (s_type_path (t_infos tmain).mt_path ^ " has no field or subtype " ^ tsub) p
  2314. ) :: !context_init)
  2315. | (tsub,p2) :: (fname,p3) :: rest ->
  2316. (match rest with
  2317. | [] -> ()
  2318. | (n,p) :: _ -> error ("Unexpected " ^ n) p);
  2319. let tsub = get_type tsub in
  2320. context_init := (fun() ->
  2321. try
  2322. add_static_init tsub name fname
  2323. with Not_found ->
  2324. error (s_type_path (t_infos tsub).mt_path ^ " has no field " ^ fname) (punion p p3)
  2325. ) :: !context_init;
  2326. )
  2327. | IAll ->
  2328. let t = (match rest with
  2329. | [] -> get_type tname
  2330. | [tsub,_] -> get_type tsub
  2331. | _ :: (n,p) :: _ -> error ("Unexpected " ^ n) p
  2332. ) in
  2333. context_init := (fun() ->
  2334. match resolve_typedef t with
  2335. | TClassDecl c
  2336. | TAbstractDecl {a_impl = Some c} ->
  2337. c.cl_build();
  2338. PMap.iter (fun _ cf -> if not (has_meta Meta.NoImportGlobal cf.cf_meta) then ctx.m.module_globals <- PMap.add cf.cf_name (TClassDecl c,cf.cf_name) ctx.m.module_globals) c.cl_statics
  2339. | TEnumDecl e ->
  2340. PMap.iter (fun _ c -> if not (has_meta Meta.NoImportGlobal c.ef_meta) then ctx.m.module_globals <- PMap.add c.ef_name (TEnumDecl e,c.ef_name) ctx.m.module_globals) e.e_constrs
  2341. | _ ->
  2342. error "No statics to import from this type" p
  2343. ) :: !context_init
  2344. ))
  2345. | EUsing t ->
  2346. (* do the import first *)
  2347. let types = (match t.tsub with
  2348. | None ->
  2349. let md = ctx.g.do_load_module ctx (t.tpackage,t.tname) p in
  2350. let types = List.filter (fun t -> not (t_infos t).mt_private) md.m_types in
  2351. ctx.m.module_types <- types @ ctx.m.module_types;
  2352. types
  2353. | Some _ ->
  2354. let t = load_type_def ctx p t in
  2355. ctx.m.module_types <- t :: ctx.m.module_types;
  2356. [t]
  2357. ) in
  2358. (* delay the using since we need to resolve typedefs *)
  2359. let filter_classes types =
  2360. let rec loop acc types = match types with
  2361. | td :: l ->
  2362. (match resolve_typedef td with
  2363. | TClassDecl c | TAbstractDecl({a_impl = Some c}) ->
  2364. loop (c :: acc) l
  2365. | td ->
  2366. loop acc l)
  2367. | [] ->
  2368. acc
  2369. in
  2370. loop [] types
  2371. in
  2372. context_init := (fun() -> ctx.m.module_using <- filter_classes types @ ctx.m.module_using) :: !context_init
  2373. | EClass d ->
  2374. let c = (match get_type d.d_name with TClassDecl c -> c | _ -> assert false) in
  2375. let herits = d.d_flags in
  2376. if Meta.has Meta.Generic c.cl_meta && c.cl_types <> [] then c.cl_kind <- KGeneric;
  2377. if Meta.has Meta.GenericBuild c.cl_meta then c.cl_kind <- KGenericBuild d.d_data;
  2378. if c.cl_path = (["haxe";"macro"],"MacroType") then c.cl_kind <- KMacroType;
  2379. c.cl_extern <- List.mem HExtern herits;
  2380. c.cl_interface <- List.mem HInterface herits;
  2381. let build() =
  2382. c.cl_build <- (fun()->());
  2383. set_heritance ctx c herits p;
  2384. init_class ctx c p do_init d.d_flags d.d_data
  2385. in
  2386. ctx.pass <- PBuildClass;
  2387. ctx.curclass <- c;
  2388. c.cl_build <- make_pass ctx build;
  2389. ctx.pass <- PBuildModule;
  2390. ctx.curclass <- null_class;
  2391. delay ctx PBuildClass (fun() -> c.cl_build());
  2392. | EEnum d ->
  2393. let e = (match get_type d.d_name with TEnumDecl e -> e | _ -> assert false) in
  2394. let ctx = { ctx with type_params = e.e_types } in
  2395. let h = (try Some (Hashtbl.find ctx.g.type_patches e.e_path) with Not_found -> None) in
  2396. (match h with
  2397. | None -> ()
  2398. | Some (h,hcl) ->
  2399. Hashtbl.iter (fun _ _ -> error "Field type patch not supported for enums" e.e_pos) h;
  2400. e.e_meta <- e.e_meta @ hcl.tp_meta);
  2401. let constructs = ref d.d_data in
  2402. let get_constructs() =
  2403. List.map (fun c ->
  2404. {
  2405. cff_name = c.ec_name;
  2406. cff_doc = c.ec_doc;
  2407. cff_meta = c.ec_meta;
  2408. cff_pos = c.ec_pos;
  2409. cff_access = [];
  2410. cff_kind = (match c.ec_args, c.ec_params with
  2411. | [], [] -> FVar (c.ec_type,None)
  2412. | _ -> FFun { f_params = c.ec_params; f_type = c.ec_type; f_expr = None; f_args = List.map (fun (n,o,t) -> n,o,Some t,None) c.ec_args });
  2413. }
  2414. ) (!constructs)
  2415. in
  2416. let init () = List.iter (fun f -> f()) !context_init in
  2417. build_module_def ctx (TEnumDecl e) e.e_meta get_constructs init (fun (e,p) ->
  2418. match e with
  2419. | EVars [_,Some (CTAnonymous fields),None] ->
  2420. constructs := List.map (fun f ->
  2421. let args, params, t = (match f.cff_kind with
  2422. | FVar (t,None) -> [], [], t
  2423. | FFun { f_params = pl; f_type = t; f_expr = (None|Some (EBlock [],_)); f_args = al } ->
  2424. let al = List.map (fun (n,o,t,_) -> match t with None -> error "Missing function parameter type" f.cff_pos | Some t -> n,o,t) al in
  2425. al, pl, t
  2426. | _ ->
  2427. error "Invalid enum constructor in @:build result" p
  2428. ) in
  2429. {
  2430. ec_name = f.cff_name;
  2431. ec_doc = f.cff_doc;
  2432. ec_meta = f.cff_meta;
  2433. ec_pos = f.cff_pos;
  2434. ec_args = args;
  2435. ec_params = params;
  2436. ec_type = t;
  2437. }
  2438. ) fields
  2439. | _ -> error "Enum build macro must return a single variable with anonymous object fields" p
  2440. );
  2441. let et = TEnum (e,List.map snd e.e_types) in
  2442. let names = ref [] in
  2443. let index = ref 0 in
  2444. let is_flat = ref true in
  2445. let fields = ref PMap.empty in
  2446. List.iter (fun c ->
  2447. let p = c.ec_pos in
  2448. let params = ref [] in
  2449. params := List.map (fun tp -> type_type_params ~enum_constructor:true ctx ([],c.ec_name) (fun() -> !params) c.ec_pos tp) c.ec_params;
  2450. let params = !params in
  2451. let ctx = { ctx with type_params = params @ ctx.type_params } in
  2452. let rt = (match c.ec_type with
  2453. | None -> et
  2454. | Some t ->
  2455. let t = load_complex_type ctx p t in
  2456. (match follow t with
  2457. | TEnum (te,_) when te == e ->
  2458. ()
  2459. | _ ->
  2460. error "Explicit enum type must be of the same enum type" p);
  2461. t
  2462. ) in
  2463. let t = (match c.ec_args with
  2464. | [] -> rt
  2465. | l ->
  2466. is_flat := false;
  2467. let pnames = ref PMap.empty in
  2468. TFun (List.map (fun (s,opt,t) ->
  2469. (match t with CTPath({tpackage=[];tname="Void"}) -> error "Arguments of type Void are not allowed in enum constructors" c.ec_pos | _ -> ());
  2470. if PMap.mem s (!pnames) then error ("Duplicate parameter '" ^ s ^ "' in enum constructor " ^ c.ec_name) p;
  2471. pnames := PMap.add s () (!pnames);
  2472. s, opt, load_type_opt ~opt ctx p (Some t)
  2473. ) l, rt)
  2474. ) in
  2475. if PMap.mem c.ec_name e.e_constrs then error ("Duplicate constructor " ^ c.ec_name) p;
  2476. let f = {
  2477. ef_name = c.ec_name;
  2478. ef_type = t;
  2479. ef_pos = p;
  2480. ef_doc = c.ec_doc;
  2481. ef_index = !index;
  2482. ef_params = params;
  2483. ef_meta = c.ec_meta;
  2484. } in
  2485. let cf = {
  2486. cf_name = f.ef_name;
  2487. cf_public = true;
  2488. cf_type = f.ef_type;
  2489. cf_kind = (match follow f.ef_type with
  2490. | TFun _ -> Method MethNormal
  2491. | _ -> Var { v_read = AccNormal; v_write = AccNo }
  2492. );
  2493. cf_pos = e.e_pos;
  2494. cf_doc = None;
  2495. cf_meta = no_meta;
  2496. cf_expr = None;
  2497. cf_params = f.ef_params;
  2498. cf_overloads = [];
  2499. } in
  2500. e.e_constrs <- PMap.add f.ef_name f e.e_constrs;
  2501. fields := PMap.add cf.cf_name cf !fields;
  2502. incr index;
  2503. names := c.ec_name :: !names;
  2504. ) (!constructs);
  2505. e.e_names <- List.rev !names;
  2506. e.e_extern <- e.e_extern;
  2507. e.e_type.t_types <- e.e_types;
  2508. e.e_type.t_type <- TAnon {
  2509. a_fields = !fields;
  2510. a_status = ref (EnumStatics e);
  2511. };
  2512. if !is_flat then e.e_meta <- (Meta.FlatEnum,[],e.e_pos) :: e.e_meta;
  2513. | ETypedef d ->
  2514. let t = (match get_type d.d_name with TTypeDecl t -> t | _ -> assert false) in
  2515. let ctx = { ctx with type_params = t.t_types } in
  2516. let tt = load_complex_type ctx p d.d_data in
  2517. (*
  2518. we exceptionnaly allow follow here because we don't care the type we get as long as it's not our own
  2519. *)
  2520. (match d.d_data with
  2521. | CTExtend _ -> ()
  2522. | _ ->
  2523. if t.t_type == follow tt then error "Recursive typedef is not allowed" p);
  2524. (match t.t_type with
  2525. | TMono r ->
  2526. (match !r with
  2527. | None -> r := Some tt;
  2528. | Some _ -> assert false);
  2529. | _ -> assert false);
  2530. | EAbstract d ->
  2531. let a = (match get_type d.d_name with TAbstractDecl a -> a | _ -> assert false) in
  2532. let ctx = { ctx with type_params = a.a_types } in
  2533. let is_type = ref false in
  2534. let load_type t from =
  2535. let t = load_complex_type ctx p t in
  2536. if not (Meta.has Meta.CoreType a.a_meta) then begin
  2537. if !is_type then begin
  2538. delay ctx PFinal (fun () ->
  2539. let at = monomorphs a.a_types a.a_this in
  2540. (try (if from then Type.unify t at else Type.unify at t) with Unify_error _ -> error "You can only declare from/to with compatible types" p)
  2541. );
  2542. end else
  2543. error "Missing underlying type declaration or @:coreType declaration" p;
  2544. end;
  2545. t
  2546. in
  2547. List.iter (function
  2548. | AFromType t -> a.a_from <- (load_type t true, None) :: a.a_from
  2549. | AToType t -> a.a_to <- (load_type t false, None) :: a.a_to
  2550. | AIsType t ->
  2551. if a.a_impl = None then error "Abstracts with underlying type must have an implementation" a.a_pos;
  2552. if Meta.has Meta.CoreType a.a_meta then error "@:coreType abstracts cannot have an underlying type" p;
  2553. let at = load_complex_type ctx p t in
  2554. (match at with TAbstract(a2,_) when a == a2 -> error "Abstract underlying type cannot be recursive" a.a_pos | _ -> ());
  2555. a.a_this <- at;
  2556. is_type := true;
  2557. | APrivAbstract -> ()
  2558. ) d.d_flags;
  2559. if not !is_type then begin
  2560. if Meta.has Meta.CoreType a.a_meta then
  2561. a.a_this <- TAbstract(a,List.map snd a.a_types)
  2562. else
  2563. error "Abstract is missing underlying type declaration" a.a_pos
  2564. end
  2565. let type_module ctx m file tdecls p =
  2566. let m, decls, tdecls = make_module ctx m file tdecls p in
  2567. add_module ctx m p;
  2568. (* define the per-module context for the next pass *)
  2569. let ctx = {
  2570. com = ctx.com;
  2571. g = ctx.g;
  2572. t = ctx.t;
  2573. m = {
  2574. curmod = m;
  2575. module_types = ctx.g.std.m_types;
  2576. module_using = [];
  2577. module_globals = PMap.empty;
  2578. wildcard_packages = [];
  2579. };
  2580. meta = [];
  2581. this_stack = [];
  2582. with_type_stack = [];
  2583. constructor_argument_stack = [];
  2584. pass = PBuildModule;
  2585. on_error = (fun ctx msg p -> ctx.com.error msg p);
  2586. macro_depth = ctx.macro_depth;
  2587. curclass = null_class;
  2588. curfield = null_field;
  2589. tthis = ctx.tthis;
  2590. ret = ctx.ret;
  2591. locals = PMap.empty;
  2592. type_params = [];
  2593. curfun = FunStatic;
  2594. untyped = false;
  2595. in_super_call = false;
  2596. in_macro = ctx.in_macro;
  2597. in_display = false;
  2598. in_loop = false;
  2599. opened = [];
  2600. vthis = None;
  2601. } in
  2602. if ctx.g.std != null_module then begin
  2603. add_dependency m ctx.g.std;
  2604. (* this will ensure both String and (indirectly) Array which are basic types which might be referenced *)
  2605. ignore(load_core_type ctx "String");
  2606. end;
  2607. (* here is an additional PASS 1 phase, which define the type parameters for all module types.
  2608. Constraints are handled lazily (no other type is loaded) because they might be recursive anyway *)
  2609. List.iter (fun d ->
  2610. match d with
  2611. | (TClassDecl c, (EClass d, p)) ->
  2612. c.cl_types <- List.map (type_type_params ctx c.cl_path (fun() -> c.cl_types) p) d.d_params;
  2613. | (TEnumDecl e, (EEnum d, p)) ->
  2614. e.e_types <- List.map (type_type_params ctx e.e_path (fun() -> e.e_types) p) d.d_params;
  2615. | (TTypeDecl t, (ETypedef d, p)) ->
  2616. t.t_types <- List.map (type_type_params ctx t.t_path (fun() -> t.t_types) p) d.d_params;
  2617. | (TAbstractDecl a, (EAbstract d, p)) ->
  2618. a.a_types <- List.map (type_type_params ctx a.a_path (fun() -> a.a_types) p) d.d_params;
  2619. | _ ->
  2620. assert false
  2621. ) decls;
  2622. (* setup module types *)
  2623. let context_init = ref [] in
  2624. let do_init() =
  2625. match !context_init with
  2626. | [] -> ()
  2627. | l -> context_init := []; List.iter (fun f -> f()) (List.rev l)
  2628. in
  2629. List.iter (init_module_type ctx context_init do_init) tdecls;
  2630. m
  2631. let resolve_module_file com m remap p =
  2632. let forbid = ref false in
  2633. let file = (match m with
  2634. | [] , name -> name
  2635. | x :: l , name ->
  2636. let x = (try
  2637. match PMap.find x com.package_rules with
  2638. | Forbidden -> forbid := true; x
  2639. | Directory d -> d
  2640. | Remap d -> remap := d :: l; d
  2641. with Not_found -> x
  2642. ) in
  2643. String.concat "/" (x :: l) ^ "/" ^ name
  2644. ) ^ ".hx" in
  2645. let file = Common.find_file com file in
  2646. let file = (match String.lowercase (snd m) with
  2647. | "con" | "aux" | "prn" | "nul" | "com1" | "com2" | "com3" | "lpt1" | "lpt2" | "lpt3" when Sys.os_type = "Win32" ->
  2648. (* these names are reserved by the OS - old DOS legacy, such files cannot be easily created but are reported as visible *)
  2649. if (try (Unix.stat file).Unix.st_size with _ -> 0) > 0 then file else raise Not_found
  2650. | _ -> file
  2651. ) in
  2652. (* if we try to load a std.xxxx class and resolve a real std file, the package name is not valid, ignore *)
  2653. (match fst m with
  2654. | "std" :: _ ->
  2655. let file = Common.unique_full_path file in
  2656. if List.exists (fun path -> ExtString.String.starts_with file (try Common.unique_full_path path with _ -> path)) com.std_path then raise Not_found;
  2657. | _ -> ());
  2658. if !forbid then begin
  2659. let _, decls = (!parse_hook) com file p in
  2660. let meta = (match decls with
  2661. | (EClass d,_) :: _ -> d.d_meta
  2662. | (EEnum d,_) :: _ -> d.d_meta
  2663. | (EAbstract d,_) :: _ -> d.d_meta
  2664. | (ETypedef d,_) :: _ -> d.d_meta
  2665. | _ -> []
  2666. ) in
  2667. if not (Meta.has Meta.NoPackageRestrict meta) then begin
  2668. let x = (match fst m with [] -> assert false | x :: _ -> x) in
  2669. raise (Forbid_package ((x,m,p),[],if Common.defined com Define.Macro then "macro" else platform_name com.platform));
  2670. end;
  2671. end;
  2672. file
  2673. let parse_module ctx m p =
  2674. let remap = ref (fst m) in
  2675. let file = resolve_module_file ctx.com m remap p in
  2676. let pack, decls = (!parse_hook) ctx.com file p in
  2677. if pack <> !remap then begin
  2678. let spack m = if m = [] then "<empty>" else String.concat "." m in
  2679. if p == Ast.null_pos then
  2680. display_error ctx ("Invalid commandline class : " ^ s_type_path m ^ " should be " ^ s_type_path (pack,snd m)) p
  2681. else
  2682. display_error ctx ("Invalid package : " ^ spack (fst m) ^ " should be " ^ spack pack) p
  2683. end;
  2684. file, if !remap <> fst m then
  2685. (* build typedefs to redirect to real package *)
  2686. List.rev (List.fold_left (fun acc (t,p) ->
  2687. let build f d =
  2688. let priv = List.mem f d.d_flags in
  2689. (ETypedef {
  2690. d_name = d.d_name;
  2691. d_doc = None;
  2692. d_meta = [];
  2693. d_params = d.d_params;
  2694. d_flags = if priv then [EPrivate] else [];
  2695. d_data = CTPath (if priv then { tpackage = []; tname = "Dynamic"; tparams = []; tsub = None; } else
  2696. {
  2697. tpackage = !remap;
  2698. tname = d.d_name;
  2699. tparams = List.map (fun tp ->
  2700. TPType (CTPath { tpackage = []; tname = tp.tp_name; tparams = []; tsub = None; })
  2701. ) d.d_params;
  2702. tsub = None;
  2703. });
  2704. },p) :: acc
  2705. in
  2706. match t with
  2707. | EClass d -> build HPrivate d
  2708. | EEnum d -> build EPrivate d
  2709. | ETypedef d -> build EPrivate d
  2710. | EAbstract d -> build APrivAbstract d
  2711. | EImport _ | EUsing _ -> acc
  2712. ) [(EImport (List.map (fun s -> s,null_pos) (!remap @ [snd m]),INormal),null_pos)] decls)
  2713. else
  2714. decls
  2715. let load_module ctx m p =
  2716. let m2 = (try
  2717. Hashtbl.find ctx.g.modules m
  2718. with
  2719. Not_found ->
  2720. match !type_module_hook ctx m p with
  2721. | Some m -> m
  2722. | None ->
  2723. let file, decls = (try
  2724. parse_module ctx m p
  2725. with Not_found ->
  2726. let rec loop = function
  2727. | [] ->
  2728. raise (Error (Module_not_found m,p))
  2729. | load :: l ->
  2730. match load m p with
  2731. | None -> loop l
  2732. | Some (file,(_,a)) -> file, a
  2733. in
  2734. loop ctx.com.load_extern_type
  2735. ) in
  2736. try
  2737. type_module ctx m file decls p
  2738. with Forbid_package (inf,pl,pf) when p <> Ast.null_pos ->
  2739. raise (Forbid_package (inf,p::pl,pf))
  2740. ) in
  2741. add_dependency ctx.m.curmod m2;
  2742. if ctx.pass = PTypeField then flush_pass ctx PBuildClass "load_module";
  2743. m2
  2744. ;;
  2745. type_function_params_rec := type_function_params