typeload.ml 121 KB

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