typeload.ml 119 KB

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