typeload.ml 121 KB

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