typeload.ml 121 KB

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