typeload.ml 119 KB

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