typeload.ml 120 KB

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