genjava.ml 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630
  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 JData
  23. open Unix
  24. open Ast
  25. open Common
  26. open Type
  27. open Gencommon
  28. open Gencommon.SourceWriter
  29. open Printf
  30. open Option
  31. open ExtString
  32. module SS = Set.Make(String)
  33. let is_boxed_type t = match follow t with
  34. | TInst ({ cl_path = (["java";"lang"], "Boolean") }, [])
  35. | TInst ({ cl_path = (["java";"lang"], "Double") }, [])
  36. | TInst ({ cl_path = (["java";"lang"], "Integer") }, [])
  37. | TInst ({ cl_path = (["java";"lang"], "Byte") }, [])
  38. | TInst ({ cl_path = (["java";"lang"], "Short") }, [])
  39. | TInst ({ cl_path = (["java";"lang"], "Character") }, [])
  40. | TInst ({ cl_path = (["java";"lang"], "Float") }, []) -> true
  41. | TAbstract ({ a_path = (["java";"lang"], "Boolean") }, [])
  42. | TAbstract ({ a_path = (["java";"lang"], "Double") }, [])
  43. | TAbstract ({ a_path = (["java";"lang"], "Integer") }, [])
  44. | TAbstract ({ a_path = (["java";"lang"], "Byte") }, [])
  45. | TAbstract ({ a_path = (["java";"lang"], "Short") }, [])
  46. | TAbstract ({ a_path = (["java";"lang"], "Character") }, [])
  47. | TAbstract ({ a_path = (["java";"lang"], "Float") }, []) -> true
  48. | _ -> false
  49. let unboxed_type gen t tbyte tshort tchar tfloat = match follow t with
  50. | TInst ({ cl_path = (["java";"lang"], "Boolean") }, []) -> gen.gcon.basic.tbool
  51. | TInst ({ cl_path = (["java";"lang"], "Double") }, []) -> gen.gcon.basic.tfloat
  52. | TInst ({ cl_path = (["java";"lang"], "Integer") }, []) -> gen.gcon.basic.tint
  53. | TInst ({ cl_path = (["java";"lang"], "Byte") }, []) -> tbyte
  54. | TInst ({ cl_path = (["java";"lang"], "Short") }, []) -> tshort
  55. | TInst ({ cl_path = (["java";"lang"], "Character") }, []) -> tchar
  56. | TInst ({ cl_path = (["java";"lang"], "Float") }, []) -> tfloat
  57. | TAbstract ({ a_path = (["java";"lang"], "Boolean") }, []) -> gen.gcon.basic.tbool
  58. | TAbstract ({ a_path = (["java";"lang"], "Double") }, []) -> gen.gcon.basic.tfloat
  59. | TAbstract ({ a_path = (["java";"lang"], "Integer") }, []) -> gen.gcon.basic.tint
  60. | TAbstract ({ a_path = (["java";"lang"], "Byte") }, []) -> tbyte
  61. | TAbstract ({ a_path = (["java";"lang"], "Short") }, []) -> tshort
  62. | TAbstract ({ a_path = (["java";"lang"], "Character") }, []) -> tchar
  63. | TAbstract ({ a_path = (["java";"lang"], "Float") }, []) -> tfloat
  64. | _ -> assert false
  65. let rec t_has_type_param t = match follow t with
  66. | TInst({ cl_kind = KTypeParameter _ }, []) -> true
  67. | TEnum(_, params)
  68. | TAbstract(_, params)
  69. | TInst(_, params) -> List.exists t_has_type_param params
  70. | TFun(f,ret) -> t_has_type_param ret || List.exists (fun (_,_,t) -> t_has_type_param t) f
  71. | _ -> false
  72. let is_type_param t = match follow t with
  73. | TInst({ cl_kind = KTypeParameter _ }, _) -> true
  74. | _ -> false
  75. let rec t_has_type_param_shallow last t = match follow t with
  76. | TInst({ cl_kind = KTypeParameter _ }, []) -> true
  77. | TEnum(_, params)
  78. | TAbstract(_, params)
  79. | TInst(_, params) when not last -> List.exists (t_has_type_param_shallow true) params
  80. | TFun(f,ret) when not last -> t_has_type_param_shallow true ret || List.exists (fun (_,_,t) -> t_has_type_param_shallow true t) f
  81. | _ -> false
  82. let rec replace_type_param t = match follow t with
  83. | TInst({ cl_kind = KTypeParameter _ }, []) -> t_dynamic
  84. | TEnum(e, params) -> TEnum(e, List.map replace_type_param params)
  85. | TAbstract(a, params) -> TAbstract(a, List.map replace_type_param params)
  86. | TInst(cl, params) -> TInst(cl, List.map replace_type_param params)
  87. | _ -> t
  88. let is_java_basic_type t =
  89. match follow t with
  90. | TInst( { cl_path = (["haxe"], "Int32") }, [] )
  91. | TInst( { cl_path = (["haxe"], "Int64") }, [] )
  92. | TAbstract( { a_path = ([], "Single") }, [] )
  93. | TAbstract( { a_path = (["java"], ("Int8" | "Int16" | "Char16" | "Int64")) }, [] )
  94. | TAbstract( { a_path = ([], "Int") }, [] )
  95. | TAbstract( { a_path = ([], "Float") }, [] )
  96. | TAbstract( { a_path = ([], "Bool") }, [] ) ->
  97. true
  98. | _ -> false
  99. let is_bool t =
  100. match follow t with
  101. | TAbstract ({ a_path = ([], "Bool") },[]) ->
  102. true
  103. | _ -> false
  104. let like_bool t =
  105. match follow t with
  106. | TAbstract ({ a_path = ([], "Bool") },[])
  107. | TAbstract ({ a_path = (["java";"lang"],"Boolean") },[])
  108. | TInst ({ cl_path = (["java";"lang"],"Boolean") },[]) ->
  109. true
  110. | _ -> false
  111. let is_int_float gen t =
  112. match follow (gen.greal_type t) with
  113. | TInst( { cl_path = (["haxe"], "Int32") }, [] )
  114. | TAbstract( { a_path = ([], "Int") }, [] )
  115. | TAbstract( { a_path = ([], "Float") }, [] ) ->
  116. true
  117. | (TAbstract _ as t) when like_float t && not (like_i64 t)-> true
  118. | _ -> false
  119. let parse_explicit_iface =
  120. let regex = Str.regexp "\\." in
  121. let parse_explicit_iface str =
  122. let split = Str.split regex str in
  123. let rec get_iface split pack =
  124. match split with
  125. | clname :: fn_name :: [] -> fn_name, (List.rev pack, clname)
  126. | pack_piece :: tl -> get_iface tl (pack_piece :: pack)
  127. | _ -> assert false
  128. in
  129. get_iface split []
  130. in parse_explicit_iface
  131. let is_string t =
  132. match follow t with
  133. | TInst( { cl_path = ([], "String") }, [] ) -> true
  134. | _ -> false
  135. let is_cl t = match follow t with
  136. | TInst({ cl_path = ["java";"lang"],"Class" },_)
  137. | TAbstract({ a_path = [], ("Class"|"Enum") },_) -> true
  138. | TAnon(a) when is_some (anon_class t) -> true
  139. | _ -> false
  140. (* ******************************************* *)
  141. (* JavaSpecificESynf *)
  142. (* ******************************************* *)
  143. (*
  144. Some Java-specific syntax filters that must run before ExpressionUnwrap
  145. dependencies:
  146. It must run before ExprUnwrap, as it may not return valid Expr/Statement expressions
  147. It must run before ClassInstance, as it will detect expressions that need unchanged TTypeExpr
  148. It must run after CastDetect, as it changes casts
  149. It must run after TryCatchWrapper, to change Std.is() calls inside there
  150. *)
  151. module JavaSpecificESynf =
  152. struct
  153. let name = "java_specific_e"
  154. let priority = solve_deps name [ DBefore ExpressionUnwrap.priority; DBefore ClassInstance.priority; DAfter CastDetect.priority; DAfter TryCatchWrapper.priority ]
  155. let get_cl_from_t t =
  156. match follow t with
  157. | TInst(cl,_) -> cl
  158. | _ -> assert false
  159. let traverse gen runtime_cl =
  160. let basic = gen.gcon.basic in
  161. let float_cl = get_cl ( get_type gen (["java";"lang"], "Double")) in
  162. let i8_md = ( get_type gen (["java";"lang"], "Byte")) in
  163. let i16_md = ( get_type gen (["java";"lang"], "Short")) in
  164. let i64_md = ( get_type gen (["java";"lang"], "Long")) in
  165. let c16_md = ( get_type gen (["java";"lang"], "Character")) in
  166. let f_md = ( get_type gen (["java";"lang"], "Float")) in
  167. let bool_md = get_type gen (["java";"lang"], "Boolean") in
  168. let is_var = alloc_var "__is__" t_dynamic in
  169. let rec run e =
  170. match e.eexpr with
  171. (* Math changes *)
  172. | TField( _, FStatic({ cl_path = (["java";"lang"], "Math") }, { cf_name = "NaN" }) ) ->
  173. mk_static_field_access_infer float_cl "NaN" e.epos []
  174. | TField( _, FStatic({ cl_path = (["java";"lang"], "Math") }, { cf_name = "NEGATIVE_INFINITY" }) ) ->
  175. mk_static_field_access_infer float_cl "NEGATIVE_INFINITY" e.epos []
  176. | TField( _, FStatic({ cl_path = (["java";"lang"], "Math") }, { cf_name = "POSITIVE_INFINITY" }) ) ->
  177. mk_static_field_access_infer float_cl "POSITIVE_INFINITY" e.epos []
  178. | TField( _, FStatic({ cl_path = (["java";"lang"], "Math") }, { cf_name = "isNaN"}) ) ->
  179. mk_static_field_access_infer float_cl "isNaN" e.epos []
  180. | TCall( ({ eexpr = TField( (_ as ef), FStatic({ cl_path = (["java";"lang"], "Math") }, { cf_name = ("ffloor" as f) }) ) } as fe), p)
  181. | TCall( ({ eexpr = TField( (_ as ef), FStatic({ cl_path = (["java";"lang"], "Math") }, { cf_name = ("fceil" as f) }) ) } as fe), p) ->
  182. Type.map_expr run { e with eexpr = TCall({ fe with eexpr = TField(ef, FDynamic (String.sub f 1 (String.length f - 1))) }, p) }
  183. | TCall( ({ eexpr = TField( (_ as ef), FStatic({ cl_path = (["java";"lang"], "Math") }, { cf_name = ("fround") }) ) } as fe), p) ->
  184. Type.map_expr run { e with eexpr = TCall({ fe with eexpr = TField(ef, FDynamic "rint") }, p) }
  185. | TCall( { eexpr = TField( _, FStatic({ cl_path = (["java";"lang"], "Math") }, { cf_name = "floor" }) ) }, _)
  186. | TCall( { eexpr = TField( _, FStatic({ cl_path = (["java";"lang"], "Math") }, { cf_name = "round" }) ) }, _)
  187. | TCall( { eexpr = TField( _, FStatic({ cl_path = (["java";"lang"], "Math") }, { cf_name = "ceil" }) ) }, _) ->
  188. mk_cast basic.tint (Type.map_expr run { e with etype = basic.tfloat })
  189. | TCall( ( { eexpr = TField( _, FStatic({ cl_path = (["java";"lang"], "Math") }, { cf_name = "isFinite" }) ) } as efield ), [v]) ->
  190. { e with eexpr = TCall( mk_static_field_access_infer runtime_cl "isFinite" efield.epos [], [run v] ) }
  191. (* end of math changes *)
  192. (* Std.is() *)
  193. | TCall(
  194. { eexpr = TField( _, FStatic({ cl_path = ([], "Std") }, { cf_name = "is" })) },
  195. [ obj; { eexpr = TTypeExpr(md) } ]
  196. ) ->
  197. let mk_is is_basic obj md =
  198. let obj = if is_basic then mk_cast t_dynamic obj else obj in
  199. { e with eexpr = TCall( { eexpr = TLocal is_var; etype = t_dynamic; epos = e.epos }, [
  200. run obj;
  201. { eexpr = TTypeExpr md; etype = t_dynamic (* this is after all a syntax filter *); epos = e.epos }
  202. ] ) }
  203. in
  204. (match follow_module follow md with
  205. | TAbstractDecl({ a_path = ([], "Float") }) ->
  206. {
  207. eexpr = TCall(
  208. mk_static_field_access_infer runtime_cl "isDouble" e.epos [],
  209. [ run obj ]
  210. );
  211. etype = basic.tbool;
  212. epos = e.epos
  213. }
  214. | TAbstractDecl{ a_path = ([], "Int") } ->
  215. {
  216. eexpr = TCall(
  217. mk_static_field_access_infer runtime_cl "isInt" e.epos [],
  218. [ run obj ]
  219. );
  220. etype = basic.tbool;
  221. epos = e.epos
  222. }
  223. | TAbstractDecl{ a_path = ([], "Bool") } ->
  224. mk_is true obj bool_md
  225. | TAbstractDecl{ a_path = ([], "Single") } ->
  226. mk_is true obj f_md
  227. | TAbstractDecl{ a_path = (["java"], "Int8") } ->
  228. mk_is true obj i8_md
  229. | TAbstractDecl{ a_path = (["java"], "Int16") } ->
  230. mk_is true obj i16_md
  231. | TAbstractDecl{ a_path = (["java"], "Char16") } ->
  232. mk_is true obj c16_md
  233. | TAbstractDecl{ a_path = (["java"], "Int64") } ->
  234. mk_is true obj i64_md
  235. | TClassDecl{ cl_path = (["haxe"], "Int64") } ->
  236. mk_is true obj i64_md
  237. | TAbstractDecl{ a_path = ([], "Dynamic") }
  238. | TClassDecl{ cl_path = ([], "Dynamic") } ->
  239. (match obj.eexpr with
  240. | TLocal _ | TConst _ -> { e with eexpr = TConst(TBool true) }
  241. | _ -> { e with eexpr = TBlock([run obj; { e with eexpr = TConst(TBool true) }]) }
  242. )
  243. | _ ->
  244. mk_is false obj md
  245. )
  246. (* end Std.is() *)
  247. | _ -> Type.map_expr run e
  248. in
  249. run
  250. let configure gen (mapping_func:texpr->texpr) =
  251. let map e = Some(mapping_func e) in
  252. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  253. end;;
  254. (* ******************************************* *)
  255. (* JavaSpecificSynf *)
  256. (* ******************************************* *)
  257. (*
  258. Some Java-specific syntax filters that can run after ExprUnwrap
  259. dependencies:
  260. Runs after ExprUnwarp
  261. *)
  262. module JavaSpecificSynf =
  263. struct
  264. let name = "java_specific"
  265. let priority = solve_deps name [ DAfter ExpressionUnwrap.priority; DAfter ObjectDeclMap.priority; DAfter ArrayDeclSynf.priority; DBefore IntDivisionSynf.priority ]
  266. let java_hash s =
  267. let h = ref Int32.zero in
  268. let thirtyone = Int32.of_int 31 in
  269. for i = 0 to String.length s - 1 do
  270. h := Int32.add (Int32.mul thirtyone !h) (Int32.of_int (int_of_char (String.unsafe_get s i)));
  271. done;
  272. !h
  273. let rec is_final_return_expr is_switch e =
  274. let is_final_return_expr = is_final_return_expr is_switch in
  275. match e.eexpr with
  276. | TReturn _
  277. | TThrow _ -> true
  278. (* this is hack to not use 'break' on switch cases *)
  279. | TLocal { v_name = "__fallback__" } when is_switch -> true
  280. | TCall( { eexpr = TLocal { v_name = "__goto__" } }, _ ) -> true
  281. | TParenthesis p | TMeta (_,p) -> is_final_return_expr p
  282. | TBlock bl -> is_final_return_block is_switch bl
  283. | TSwitch (_, el_e_l, edef) ->
  284. List.for_all (fun (_,e) -> is_final_return_expr e) el_e_l && Option.map_default is_final_return_expr false edef
  285. (* | TMatch (_, _, il_vl_e_l, edef) ->
  286. List.for_all (fun (_,_,e) -> is_final_return_expr e)il_vl_e_l && Option.map_default is_final_return_expr false edef *)
  287. | TIf (_,eif, Some eelse) ->
  288. is_final_return_expr eif && is_final_return_expr eelse
  289. | TFor (_,_,e) ->
  290. is_final_return_expr e
  291. | TWhile (_,e,_) ->
  292. is_final_return_expr e
  293. | TFunction tf ->
  294. is_final_return_expr tf.tf_expr
  295. | TTry (e, ve_l) ->
  296. is_final_return_expr e && List.for_all (fun (_,e) -> is_final_return_expr e) ve_l
  297. | _ -> false
  298. and is_final_return_block is_switch el =
  299. match el with
  300. | [] -> false
  301. | final :: [] -> is_final_return_expr is_switch final
  302. | hd :: tl -> is_final_return_block is_switch tl
  303. let is_null e = match e.eexpr with | TConst(TNull) -> true | _ -> false
  304. let rec is_equatable gen t =
  305. match follow t with
  306. | TInst(cl,_) ->
  307. if cl.cl_path = (["haxe";"lang"], "IEquatable") then
  308. true
  309. else
  310. List.exists (fun (cl,p) -> is_equatable gen (TInst(cl,p))) cl.cl_implements
  311. || (match cl.cl_super with | Some(cl,p) -> is_equatable gen (TInst(cl,p)) | None -> false)
  312. | _ -> false
  313. (*
  314. Changing string switch
  315. will take an expression like
  316. switch(str)
  317. {
  318. case "a":
  319. case "b":
  320. }
  321. and modify it to:
  322. {
  323. var execute_def = true;
  324. switch(str.hashCode())
  325. {
  326. case (hashcode of a):
  327. if (str == "a")
  328. {
  329. execute_def = false;
  330. ..code here
  331. } //else if (str == otherVariableWithSameHashCode) {
  332. ...
  333. }
  334. ...
  335. }
  336. if (execute_def)
  337. {
  338. ..default code
  339. }
  340. }
  341. this might actually be slower in some cases than a if/else approach, but it scales well and as a bonus,
  342. hashCode in java are cached, so we only have the performance hit once to cache it.
  343. *)
  344. let change_string_switch gen eswitch e1 ecases edefault =
  345. let basic = gen.gcon.basic in
  346. let is_final_ret = is_final_return_expr false eswitch in
  347. let has_default = is_some edefault in
  348. let block = ref [] in
  349. let local = match e1.eexpr with
  350. | TLocal _ -> e1
  351. | _ ->
  352. let var = mk_temp gen "svar" e1.etype in
  353. let added = { e1 with eexpr = TVar(var, Some(e1)); etype = basic.tvoid } in
  354. let local = mk_local var e1.epos in
  355. block := added :: !block;
  356. local
  357. in
  358. let execute_def_var = mk_temp gen "executeDef" gen.gcon.basic.tbool in
  359. let execute_def = mk_local execute_def_var e1.epos in
  360. let execute_def_set = { eexpr = TBinop(Ast.OpAssign, execute_def, { eexpr = TConst(TBool false); etype = basic.tbool; epos = e1.epos }); etype = basic.tbool; epos = e1.epos } in
  361. let hash_cache = ref None in
  362. let local_hashcode = ref { local with
  363. eexpr = TCall({ local with
  364. eexpr = TField(local, FDynamic "hashCode");
  365. etype = TFun([], basic.tint);
  366. }, []);
  367. etype = basic.tint
  368. } in
  369. let get_hash_cache () =
  370. match !hash_cache with
  371. | Some c -> c
  372. | None ->
  373. let var = mk_temp gen "hash" basic.tint in
  374. let cond = !local_hashcode in
  375. block := { eexpr = TVar(var, Some cond); etype = basic.tvoid; epos = local.epos } :: !block;
  376. let local = mk_local var local.epos in
  377. local_hashcode := local;
  378. hash_cache := Some local;
  379. local
  380. in
  381. let has_case = ref false in
  382. (* first we need to reorder all cases so all collisions are close to each other *)
  383. let get_str e = match e.eexpr with | TConst(TString s) -> s | _ -> assert false in
  384. let has_conflict = ref false in
  385. let rec reorder_cases unordered ordered =
  386. match unordered with
  387. | [] -> ordered
  388. | (el, e) :: tl ->
  389. let current = Hashtbl.create 1 in
  390. List.iter (fun e ->
  391. let str = get_str e in
  392. let hash = java_hash str in
  393. Hashtbl.add current hash true
  394. ) el;
  395. let rec extract_fields cases found_cases ret_cases =
  396. match cases with
  397. | [] -> found_cases, ret_cases
  398. | (el, e) :: tl ->
  399. if List.exists (fun e -> Hashtbl.mem current (java_hash (get_str e)) ) el then begin
  400. has_conflict := true;
  401. List.iter (fun e -> Hashtbl.add current (java_hash (get_str e)) true) el;
  402. extract_fields tl ( (el, e) :: found_cases ) ret_cases
  403. end else
  404. extract_fields tl found_cases ( (el, e) :: ret_cases )
  405. in
  406. let found, remaining = extract_fields tl [] [] in
  407. let ret = if found <> [] then
  408. let ret = List.sort (fun (e1,_) (e2,_) -> compare (List.length e2) (List.length e1) ) ( (el, e) :: found ) in
  409. let rec loop ret acc =
  410. match ret with
  411. | (el, e) :: ( (_,_) :: _ as tl ) -> loop tl ( (true, el, e) :: acc )
  412. | (el, e) :: [] -> ( (false, el, e) :: acc )
  413. | _ -> assert false
  414. in
  415. List.rev (loop ret [])
  416. else
  417. (false, el, e) :: []
  418. in
  419. reorder_cases remaining (ordered @ ret)
  420. in
  421. let already_in_cases = Hashtbl.create 0 in
  422. let change_case (has_fallback, el, e) =
  423. let conds, el = List.fold_left (fun (conds,el) e ->
  424. has_case := true;
  425. match e.eexpr with
  426. | TConst(TString s) ->
  427. let hashed = java_hash s in
  428. let equals_test = {
  429. eexpr = TCall({ e with eexpr = TField(local, FDynamic "equals"); etype = TFun(["obj",false,t_dynamic],basic.tbool) }, [ e ]);
  430. etype = basic.tbool;
  431. epos = e.epos
  432. } in
  433. let hashed_expr = { eexpr = TConst(TInt hashed); etype = basic.tint; epos = e.epos } in
  434. let hashed_exprs = if !has_conflict then begin
  435. if Hashtbl.mem already_in_cases hashed then
  436. el
  437. else begin
  438. Hashtbl.add already_in_cases hashed true;
  439. hashed_expr :: el
  440. end
  441. end else hashed_expr :: el in
  442. let conds = match conds with
  443. | None -> equals_test
  444. | Some c ->
  445. (*
  446. if there is more than one case, we should test first if hash equals to the one specified.
  447. This way we can save a heavier string compare
  448. *)
  449. let equals_test = mk_paren {
  450. eexpr = TBinop(Ast.OpBoolAnd, { eexpr = TBinop(Ast.OpEq, get_hash_cache(), hashed_expr); etype = basic.tbool; epos = e.epos }, equals_test);
  451. etype = basic.tbool;
  452. epos = e.epos;
  453. } in
  454. { eexpr = TBinop(Ast.OpBoolOr, equals_test, c); etype = basic.tbool; epos = e1.epos }
  455. in
  456. Some conds, hashed_exprs
  457. | _ -> assert false
  458. ) (None,[]) el in
  459. let e = if has_default then Type.concat execute_def_set e else e in
  460. let e = if !has_conflict then Type.concat e { e with eexpr = TBreak; etype = basic.tvoid } else e in
  461. let e = {
  462. eexpr = TIf(get conds, e, None);
  463. etype = basic.tvoid;
  464. epos = e.epos
  465. } in
  466. let e = if has_fallback then { e with eexpr = TBlock([ e; mk_local (alloc_var "__fallback__" t_dynamic) e.epos]) } else e in
  467. (el, e)
  468. in
  469. let switch = { eswitch with
  470. eexpr = TSwitch(!local_hashcode, List.map change_case (reorder_cases ecases []), None);
  471. } in
  472. (if !has_case then begin
  473. (if has_default then block := { e1 with eexpr = TVar(execute_def_var, Some({ e1 with eexpr = TConst(TBool true); etype = basic.tbool })); etype = basic.tvoid } :: !block);
  474. block := switch :: !block
  475. end);
  476. (match edefault with
  477. | None -> ()
  478. | Some edef when not !has_case ->
  479. block := edef :: !block
  480. | Some edef ->
  481. let eelse = if is_final_ret then Some { eexpr = TThrow { eexpr = TConst(TNull); etype = t_dynamic; epos = edef.epos }; etype = basic.tvoid; epos = edef.epos } else None in
  482. block := { edef with eexpr = TIf(execute_def, edef, eelse); etype = basic.tvoid } :: !block
  483. );
  484. { eswitch with eexpr = TBlock(List.rev !block) }
  485. let get_cl_from_t t =
  486. match follow t with
  487. | TInst(cl,_) -> cl
  488. | _ -> assert false
  489. let traverse gen runtime_cl =
  490. let basic = gen.gcon.basic in
  491. (* let tchar = mt_to_t_dyn ( get_type gen (["java"], "Char16") ) in *)
  492. (* let tbyte = mt_to_t_dyn ( get_type gen (["java"], "Int8") ) in *)
  493. (* let tshort = mt_to_t_dyn ( get_type gen (["java"], "Int16") ) in *)
  494. (* let tsingle = mt_to_t_dyn ( get_type gen ([], "Single") ) in *)
  495. let string_ext = get_cl ( get_type gen (["haxe";"lang"], "StringExt")) in
  496. let is_string t = match follow t with | TInst({ cl_path = ([], "String") }, []) -> true | _ -> false in
  497. let rec run e =
  498. match e.eexpr with
  499. (* for new NativeArray<T> issues *)
  500. | TNew(({ cl_path = (["java"], "NativeArray") } as cl), [t], el) when is_type_param t ->
  501. mk_cast (TInst(cl,[t])) (mk_cast t_dynamic ({ e with eexpr = TNew(cl, [t_empty], List.map run el) }))
  502. (* Std.int() *)
  503. | TCall(
  504. { eexpr = TField( _, FStatic({ cl_path = ([], "Std") }, { cf_name = "int" })) },
  505. [obj]
  506. ) ->
  507. run (mk_cast basic.tint obj)
  508. (* end Std.int() *)
  509. | TField( ef, FInstance({ cl_path = ([], "String") }, _, { cf_name = "length" }) ) ->
  510. { e with eexpr = TCall(Type.map_expr run e, []) }
  511. | TField( ef, field ) when field_name field = "length" && is_string ef.etype ->
  512. { e with eexpr = TCall(Type.map_expr run e, []) }
  513. | TCall( ( { eexpr = TField(ef, field) } as efield ), args ) when is_string ef.etype && String.get (field_name field) 0 = '_' ->
  514. let field = field_name field in
  515. { e with eexpr = TCall({ efield with eexpr = TField(run ef, FDynamic (String.sub field 1 ( (String.length field) - 1)) )}, List.map run args) }
  516. | TCall( ( { eexpr = TField(ef, FInstance({ cl_path = [], "String" }, _, field )) } as efield ), args ) ->
  517. let field = field.cf_name in
  518. (match field with
  519. | "charAt" | "charCodeAt" | "split" | "indexOf"
  520. | "lastIndexOf" | "substring" | "substr" ->
  521. { e with eexpr = TCall(mk_static_field_access_infer string_ext field e.epos [], [run ef] @ (List.map run args)) }
  522. | _ ->
  523. { e with eexpr = TCall(run efield, List.map run args) }
  524. )
  525. (* | TCall( { eexpr = TField(ef, FInstance({ cl_path = [], "String" }, { cf_name = ("toString") })) }, [] ) ->
  526. run ef *)
  527. (* | TCast(expr, m) when is_boxed_type e.etype -> *)
  528. (* (* let unboxed_type gen t tbyte tshort tchar tfloat = match follow t with *) *)
  529. (* run { e with etype = unboxed_type gen e.etype tbyte tshort tchar tsingle } *)
  530. | TCast(expr, _) when is_bool e.etype ->
  531. {
  532. eexpr = TCall(
  533. mk_static_field_access_infer runtime_cl "toBool" expr.epos [],
  534. [ run expr ]
  535. );
  536. etype = basic.tbool;
  537. epos = e.epos
  538. }
  539. | TCast(expr, _) when is_int_float gen e.etype && not (is_int_float gen expr.etype) ->
  540. let needs_cast = match gen.gfollow#run_f e.etype with
  541. | TInst _ -> false
  542. | _ -> true
  543. in
  544. let fun_name = if like_int e.etype then "toInt" else "toDouble" in
  545. let ret = {
  546. eexpr = TCall(
  547. mk_static_field_access_infer runtime_cl fun_name expr.epos [],
  548. [ run expr ]
  549. );
  550. etype = if fun_name = "toDouble" then basic.tfloat else basic.tint;
  551. epos = expr.epos
  552. } in
  553. if needs_cast then mk_cast e.etype ret else ret
  554. (*| TCast(expr, c) when is_int_float gen e.etype ->
  555. (* cases when float x = (float) (java.lang.Double val); *)
  556. (* FIXME: this fix is broken since it will fail on cases where float x = (float) (java.lang.Float val) or similar. FIX THIS *)
  557. let need_second_cast = match gen.gfollow#run_f e.etype with
  558. | TInst _ -> false
  559. | _ -> true
  560. in
  561. if need_second_cast then { e with eexpr = TCast(mk_cast (follow e.etype) (run expr), c) } else Type.map_expr run e*)
  562. | TBinop( (Ast.OpAssignOp OpAdd as op), e1, e2)
  563. | TBinop( (Ast.OpAdd as op), e1, e2) when is_string e.etype || is_string e1.etype || is_string e2.etype ->
  564. let is_assign = match op with Ast.OpAssignOp _ -> true | _ -> false in
  565. let mk_to_string e = { e with eexpr = TCall( mk_static_field_access_infer runtime_cl "toString" e.epos [], [run e] ); etype = gen.gcon.basic.tstring } in
  566. let check_cast e = match gen.greal_type e.etype with
  567. | TDynamic _
  568. | TAbstract({ a_path = ([], "Float") }, [])
  569. | TAbstract({ a_path = ([], "Single") }, []) ->
  570. mk_to_string e
  571. | _ -> run e
  572. in
  573. { e with eexpr = TBinop(op, (if is_assign then run e1 else check_cast e1), check_cast e2) }
  574. | TCast(expr, _) when is_string e.etype ->
  575. { e with eexpr = TCall( mk_static_field_access_infer runtime_cl "toString" expr.epos [], [run expr] ) }
  576. | TSwitch(cond, ecases, edefault) when is_string cond.etype ->
  577. (*let change_string_switch gen eswitch e1 ecases edefault =*)
  578. change_string_switch gen e (run cond) (List.map (fun (el,e) -> (el, run e)) ecases) (Option.map run edefault)
  579. | TBinop( (Ast.OpNotEq as op), e1, e2)
  580. | TBinop( (Ast.OpEq as op), e1, e2) when not (is_null e2 || is_null e1) && (is_string e1.etype || is_string e2.etype || is_equatable gen e1.etype || is_equatable gen e2.etype) ->
  581. let static = mk_static_field_access_infer (runtime_cl) "valEq" e1.epos [] in
  582. let eret = { eexpr = TCall(static, [run e1; run e2]); etype = gen.gcon.basic.tbool; epos=e.epos } in
  583. if op = Ast.OpNotEq then { eret with eexpr = TUnop(Ast.Not, Ast.Prefix, eret) } else eret
  584. | TBinop( (Ast.OpNotEq | Ast.OpEq as op), e1, e2) when is_cl e1.etype && is_cl e2.etype ->
  585. { e with eexpr = TBinop(op, mk_cast t_empty (run e1), mk_cast t_empty (run e2)) }
  586. | _ -> Type.map_expr run e
  587. in
  588. run
  589. let configure gen (mapping_func:texpr->texpr) =
  590. (if java_hash "Testing string hashCode implementation from haXe" <> (Int32.of_int 545883604) then assert false);
  591. let map e = Some(mapping_func e) in
  592. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  593. end;;
  594. (* ******************************************* *)
  595. (* handle @:throws *)
  596. (* ******************************************* *)
  597. let rec is_checked_exc cl =
  598. match cl.cl_path with
  599. | ["java";"lang"],"RuntimeException" ->
  600. false
  601. | ["java";"lang"],"Throwable" ->
  602. true
  603. | _ -> match cl.cl_super with
  604. | None -> false
  605. | Some(c,_) -> is_checked_exc c
  606. let rec cls_any_super cl supers =
  607. PMap.mem cl.cl_path supers || match cl.cl_super with
  608. | None -> false
  609. | Some(c,_) -> cls_any_super c supers
  610. let rec handle_throws gen cf =
  611. List.iter (handle_throws gen) cf.cf_overloads;
  612. match cf.cf_expr with
  613. | Some ({ eexpr = TFunction(tf) } as e) ->
  614. let rec collect_throws acc = function
  615. | (Meta.Throws, [Ast.EConst (Ast.String path), _],_) :: meta -> (try
  616. collect_throws (get_cl ( get_type gen (parse_path path)) :: acc) meta
  617. with | Not_found | TypeNotFound _ ->
  618. collect_throws acc meta)
  619. | [] ->
  620. acc
  621. | _ :: meta ->
  622. collect_throws acc meta
  623. in
  624. let cf_throws = collect_throws [] cf.cf_meta in
  625. let throws = ref (List.fold_left (fun map cl ->
  626. PMap.add cl.cl_path cl map
  627. ) PMap.empty cf_throws) in
  628. let rec iter e = match e.eexpr with
  629. | TTry(etry,ecatches) ->
  630. let old = !throws in
  631. let needs_check_block = ref true in
  632. List.iter (fun (v,e) ->
  633. Type.iter iter e;
  634. match follow (run_follow gen v.v_type) with
  635. | TInst({ cl_path = ["java";"lang"],"Throwable" },_)
  636. | TDynamic _ ->
  637. needs_check_block := false
  638. | TInst(c,_) when is_checked_exc c ->
  639. throws := PMap.add c.cl_path c !throws
  640. | _ ->()
  641. ) ecatches;
  642. if !needs_check_block then Type.iter iter etry;
  643. throws := old
  644. | TField(e, (FInstance(_,_,f) | FStatic(_,f) | FClosure(_,f))) ->
  645. let tdefs = collect_throws [] f.cf_meta in
  646. if tdefs <> [] && not (List.for_all (fun c -> cls_any_super c !throws) tdefs) then
  647. raise Exit;
  648. Type.iter iter e
  649. | TThrow e -> (match follow (run_follow gen e.etype) with
  650. | TInst(c,_) when is_checked_exc c && not (cls_any_super c !throws) ->
  651. raise Exit
  652. | _ -> iter e)
  653. | _ -> Type.iter iter e
  654. in
  655. (try
  656. Type.iter iter e
  657. with | Exit -> (* needs typed exception to be caught *)
  658. let throwable = get_cl (get_type gen (["java";"lang"],"Throwable")) in
  659. let catch_var = alloc_var "typedException" (TInst(throwable,[])) in
  660. let rethrow = mk_local catch_var e.epos in
  661. let hx_exception = get_cl (get_type gen (["haxe";"lang"], "HaxeException")) in
  662. let wrap_static = mk_static_field_access (hx_exception) "wrap" (TFun([("obj",false,t_dynamic)], t_dynamic)) rethrow.epos in
  663. let wrapped = { rethrow with eexpr = TThrow { rethrow with eexpr = TCall(wrap_static, [rethrow]) }; } in
  664. let map_throws cl =
  665. let var = alloc_var "typedException" (TInst(cl,List.map (fun _ -> t_dynamic) cl.cl_params)) in
  666. var, { tf.tf_expr with eexpr = TThrow (mk_local var e.epos) }
  667. in
  668. cf.cf_expr <- Some { e with
  669. eexpr = TFunction({ tf with
  670. tf_expr = mk_block { tf.tf_expr with eexpr = TTry(tf.tf_expr, List.map (map_throws) cf_throws @ [catch_var, wrapped]) }
  671. })
  672. })
  673. | _ -> ()
  674. let connecting_string = "?" (* ? see list here http://www.fileformat.info/info/unicode/category/index.htm and here for C# http://msdn.microsoft.com/en-us/library/aa664670.aspx *)
  675. let default_package = "java"
  676. let strict_mode = ref false (* strict mode is so we can check for unexpected information *)
  677. (* reserved java words *)
  678. let reserved = let res = Hashtbl.create 120 in
  679. List.iter (fun lst -> Hashtbl.add res lst ("_" ^ lst)) ["abstract"; "assert"; "boolean"; "break"; "byte"; "case"; "catch"; "char"; "class";
  680. "const"; "continue"; "default"; "do"; "double"; "else"; "enum"; "extends"; "final";
  681. "false"; "finally"; "float"; "for"; "goto"; "if"; "implements"; "import"; "instanceof"; "int";
  682. "interface"; "long"; "native"; "new"; "null"; "package"; "private"; "protected"; "public"; "return"; "short";
  683. "static"; "strictfp"; "super"; "switch"; "synchronized"; "this"; "throw"; "throws"; "transient"; "true"; "try";
  684. "void"; "volatile"; "while"; ];
  685. res
  686. let dynamic_anon = TAnon( { a_fields = PMap.empty; a_status = ref Closed } )
  687. let rec get_class_modifiers meta cl_type cl_access cl_modifiers =
  688. match meta with
  689. | [] -> cl_type,cl_access,cl_modifiers
  690. (*| (Meta.Struct,[],_) :: meta -> get_class_modifiers meta "struct" cl_access cl_modifiers*)
  691. | (Meta.Protected,[],_) :: meta -> get_class_modifiers meta cl_type "protected" cl_modifiers
  692. | (Meta.Internal,[],_) :: meta -> get_class_modifiers meta cl_type "" cl_modifiers
  693. (* no abstract for now | (":abstract",[],_) :: meta -> get_class_modifiers meta cl_type cl_access ("abstract" :: cl_modifiers)
  694. | (Meta.Static,[],_) :: meta -> get_class_modifiers meta cl_type cl_access ("static" :: cl_modifiers) TODO: support those types *)
  695. | (Meta.Final,[],_) :: meta -> get_class_modifiers meta cl_type cl_access ("final" :: cl_modifiers)
  696. | _ :: meta -> get_class_modifiers meta cl_type cl_access cl_modifiers
  697. let rec get_fun_modifiers meta access modifiers =
  698. match meta with
  699. | [] -> access,modifiers
  700. | (Meta.Protected,[],_) :: meta -> get_fun_modifiers meta "protected" modifiers
  701. | (Meta.Internal,[],_) :: meta -> get_fun_modifiers meta "" modifiers
  702. | (Meta.ReadOnly,[],_) :: meta -> get_fun_modifiers meta access ("final" :: modifiers)
  703. (*| (Meta.Unsafe,[],_) :: meta -> get_fun_modifiers meta access ("unsafe" :: modifiers)*)
  704. | (Meta.Volatile,[],_) :: meta -> get_fun_modifiers meta access ("volatile" :: modifiers)
  705. | (Meta.Transient,[],_) :: meta -> get_fun_modifiers meta access ("transient" :: modifiers)
  706. | (Meta.Native,[],_) :: meta -> get_fun_modifiers meta access ("native" :: modifiers)
  707. | _ :: meta -> get_fun_modifiers meta access modifiers
  708. (* this was the way I found to pass the generator context to be accessible across all functions here *)
  709. (* so 'configure' is almost 'top-level' and will have all functions needed to make this work *)
  710. let configure gen =
  711. let native_arr_cl = get_cl ( get_type gen (["java"], "NativeArray") ) in
  712. gen.gclasses.nativearray <- (fun t -> TInst(native_arr_cl,[t]));
  713. gen.gclasses.nativearray_type <- (function TInst(_,[t]) -> t | _ -> assert false);
  714. gen.gclasses.nativearray_len <- (fun e p -> mk_field_access gen e "length" p);
  715. let basic = gen.gcon.basic in
  716. let fn_cl = get_cl (get_type gen (["haxe";"lang"],"Function")) in
  717. let runtime_cl = get_cl (get_type gen (["haxe";"lang"],"Runtime")) in
  718. let nulltdef = get_tdef (get_type gen ([],"Null")) in
  719. (*let string_ref = get_cl ( get_type gen (["haxe";"lang"], "StringRefl")) in*)
  720. let ti64 = match ( get_type gen (["java"], "Int64") ) with | TAbstractDecl a -> TAbstract(a,[]) | _ -> assert false in
  721. let has_tdynamic params =
  722. List.exists (fun e -> match run_follow gen e with | TDynamic _ -> true | _ -> false) params
  723. in
  724. (*
  725. The type parameters always need to be changed to their boxed counterparts
  726. *)
  727. let change_param_type md params =
  728. match md with
  729. | TClassDecl( { cl_path = (["java"], "NativeArray") } ) -> params
  730. | TAbstractDecl { a_path=[],("Class" | "Enum") } | TClassDecl { cl_path = (["java";"lang"],("Class"|"Enum")) } ->
  731. List.map (fun _ -> t_dynamic) params
  732. | _ ->
  733. match params with
  734. | [] -> []
  735. | _ ->
  736. if has_tdynamic params then List.map (fun _ -> t_dynamic) params else
  737. List.map (fun t ->
  738. let f_t = gen.gfollow#run_f t in
  739. match f_t with
  740. | TAbstract ({ a_path = ([], "Bool") },[])
  741. | TAbstract ({ a_path = ([],"Float") },[])
  742. | TInst ({ cl_path = ["haxe"],"Int32" },[])
  743. | TInst ({ cl_path = ["haxe"],"Int64" },[])
  744. | TAbstract ({ a_path = ([],"Int") },[])
  745. | TType ({ t_path = ["java"], "Int64" },[])
  746. | TAbstract ({ a_path = ["java"], "Int64" },[])
  747. | TType ({ t_path = ["java"],"Int8" },[])
  748. | TAbstract ({ a_path = ["java"],"Int8" },[])
  749. | TType ({ t_path = ["java"],"Int16" },[])
  750. | TAbstract ({ a_path = ["java"],"Int16" },[])
  751. | TType ({ t_path = ["java"],"Char16" },[])
  752. | TAbstract ({ a_path = ["java"],"Char16" },[])
  753. | TType ({ t_path = [],"Single" },[])
  754. | TAbstract ({ a_path = [],"Single" },[]) ->
  755. TType(nulltdef, [f_t])
  756. (*| TType ({ t_path = [], "Null"*)
  757. | TInst (cl, ((_ :: _) as p)) when cl.cl_path <> (["java"],"NativeArray") ->
  758. TInst(cl, List.map (fun _ -> t_dynamic) p)
  759. | TEnum (e, ((_ :: _) as p)) ->
  760. TEnum(e, List.map (fun _ -> t_dynamic) p)
  761. | _ -> t
  762. ) params
  763. in
  764. let change_clname name =
  765. String.map (function | '$' -> '.' | c -> c) name
  766. in
  767. let change_id name = try Hashtbl.find reserved name with | Not_found -> name in
  768. let rec change_ns ns = match ns with
  769. | [] -> ["haxe"; "root"]
  770. | _ -> List.map change_id ns
  771. in
  772. let change_field = change_id in
  773. let write_id w name = write w (change_id name) in
  774. let write_field w name = write w (change_field name) in
  775. gen.gfollow#add ~name:"follow_basic" (fun t -> match t with
  776. | TAbstract ({ a_path = ([], "Bool") },[])
  777. | TAbstract ({ a_path = ([], "Void") },[])
  778. | TAbstract ({ a_path = ([],"Float") },[])
  779. | TAbstract ({ a_path = ([],"Int") },[])
  780. | TInst( { cl_path = (["haxe"], "Int32") }, [] )
  781. | TInst( { cl_path = (["haxe"], "Int64") }, [] )
  782. | TType ({ t_path = ["java"], "Int64" },[])
  783. | TAbstract ({ a_path = ["java"], "Int64" },[])
  784. | TType ({ t_path = ["java"],"Int8" },[])
  785. | TAbstract ({ a_path = ["java"],"Int8" },[])
  786. | TType ({ t_path = ["java"],"Int16" },[])
  787. | TAbstract ({ a_path = ["java"],"Int16" },[])
  788. | TType ({ t_path = ["java"],"Char16" },[])
  789. | TAbstract ({ a_path = ["java"],"Char16" },[])
  790. | TType ({ t_path = [],"Single" },[])
  791. | TAbstract ({ a_path = [],"Single" },[]) ->
  792. Some t
  793. | TType (({ t_path = [],"Null" } as tdef),[t2]) ->
  794. Some (TType(tdef,[gen.gfollow#run_f t2]))
  795. | TAbstract (a, pl) when not (Meta.has Meta.CoreType a.a_meta) ->
  796. Some (gen.gfollow#run_f ( Abstract.get_underlying_type a pl) )
  797. | TAbstract( { a_path = ([], "EnumValue") }, _ )
  798. | TInst( { cl_path = ([], "EnumValue") }, _ ) -> Some t_dynamic
  799. | _ -> None);
  800. let change_path path = (change_ns (fst path), change_clname (snd path)) in
  801. let path_s path meta = try
  802. match Meta.get Meta.JavaCanonical meta with
  803. | (Meta.JavaCanonical, [EConst(String pack), _; EConst(String name), _], _) ->
  804. if pack = "" then
  805. name
  806. else
  807. pack ^ "." ^ name
  808. | _ -> raise Not_found
  809. with Not_found -> match path with
  810. | (ns,clname) -> path_s (change_ns ns, change_clname clname)
  811. in
  812. let cl_cl = get_cl (get_type gen (["java";"lang"],"Class")) in
  813. let rec real_type t =
  814. let t = gen.gfollow#run_f t in
  815. match t with
  816. | TAbstract (a, pl) when not (Meta.has Meta.CoreType a.a_meta) ->
  817. real_type (Abstract.get_underlying_type a pl)
  818. | TInst( { cl_path = (["haxe"], "Int32") }, [] ) -> gen.gcon.basic.tint
  819. | TInst( { cl_path = (["haxe"], "Int64") }, [] ) -> ti64
  820. | TAbstract( { a_path = ([], "Class") }, p )
  821. | TAbstract( { a_path = ([], "Enum") }, p )
  822. | TInst( { cl_path = ([], "Class") }, p )
  823. | TInst( { cl_path = ([], "Enum") }, p ) -> TInst(cl_cl,[t_dynamic])
  824. | TEnum(e,params) -> TEnum(e, List.map (fun _ -> t_dynamic) params)
  825. | TInst(c,params) when Meta.has Meta.Enum c.cl_meta ->
  826. TInst(c, List.map (fun _ -> t_dynamic) params)
  827. | TInst _ -> t
  828. | TType({ t_path = ([], "Null") }, [t]) when is_java_basic_type (gen.gfollow#run_f t) -> t_dynamic
  829. | TType({ t_path = ([], "Null") }, [t]) ->
  830. (match follow t with
  831. | TInst( { cl_kind = KTypeParameter _ }, []) ->
  832. t_dynamic
  833. (* real_type t *)
  834. | _ -> real_type t
  835. )
  836. | TType _ | TAbstract _ -> t
  837. | TAnon (anon) -> (match !(anon.a_status) with
  838. | Statics _ | EnumStatics _ | AbstractStatics _ -> t
  839. | _ -> t_dynamic)
  840. | TFun _ -> TInst(fn_cl,[])
  841. | _ -> t_dynamic
  842. in
  843. let scope = ref PMap.empty in
  844. let imports = ref [] in
  845. let clear_scope () =
  846. scope := PMap.empty;
  847. imports := [];
  848. in
  849. let add_scope name =
  850. scope := PMap.add name () !scope
  851. in
  852. let add_import pos path meta =
  853. let name = snd path in
  854. let rec loop = function
  855. | (pack, n) :: _ when name = n ->
  856. if path <> (pack,n) then
  857. gen.gcon.error ("This expression cannot be generated because " ^ path_s path meta ^ " is shadowed by the current scope and ") pos
  858. | _ :: tl ->
  859. loop tl
  860. | [] ->
  861. (* add import *)
  862. imports := path :: !imports
  863. in
  864. loop !imports
  865. in
  866. let path_s_import pos path meta = match path with
  867. | [], name when PMap.mem name !scope ->
  868. gen.gcon.error ("This expression cannot be generated because " ^ name ^ " is shadowed by the current scope") pos;
  869. name
  870. | pack1 :: _, name when PMap.mem pack1 !scope -> (* exists in scope *)
  871. add_import pos path meta;
  872. (* check if name exists in scope *)
  873. if PMap.mem name !scope then
  874. gen.gcon.error ("This expression cannot be generated because " ^ pack1 ^ " and " ^ name ^ " are both shadowed by the current scope") pos;
  875. name
  876. | _ -> path_s path meta
  877. in
  878. let is_dynamic t = match real_type t with
  879. | TMono _ | TDynamic _
  880. | TInst({ cl_kind = KTypeParameter _ }, _) -> true
  881. | TAnon anon ->
  882. (match !(anon.a_status) with
  883. | EnumStatics _ | Statics _ | AbstractStatics _ -> false
  884. | _ -> true
  885. )
  886. | _ -> false
  887. in
  888. let rec t_s pos t =
  889. match real_type t with
  890. (* basic types *)
  891. | TAbstract ({ a_path = ([], "Bool") },[]) -> "boolean"
  892. | TAbstract ({ a_path = ([], "Void") },[]) ->
  893. path_s_import pos (["java";"lang"], "Object") []
  894. | TAbstract ({ a_path = ([],"Float") },[]) -> "double"
  895. | TAbstract ({ a_path = ([],"Int") },[]) -> "int"
  896. | TType ({ t_path = ["java"], "Int64" },[])
  897. | TAbstract ({ a_path = ["java"], "Int64" },[]) -> "long"
  898. | TType ({ t_path = ["java"],"Int8" },[])
  899. | TAbstract ({ a_path = ["java"],"Int8" },[]) -> "byte"
  900. | TType ({ t_path = ["java"],"Int16" },[])
  901. | TAbstract ({ a_path = ["java"],"Int16" },[]) -> "short"
  902. | TType ({ t_path = ["java"],"Char16" },[])
  903. | TAbstract ({ a_path = ["java"],"Char16" },[]) -> "char"
  904. | TType ({ t_path = [],"Single" },[])
  905. | TAbstract ({ a_path = [],"Single" },[]) -> "float"
  906. | TInst ({ cl_path = ["haxe"],"Int32" },[])
  907. | TAbstract ({ a_path = ["haxe"],"Int32" },[]) -> "int"
  908. | TInst ({ cl_path = ["haxe"],"Int64" },[])
  909. | TAbstract ({ a_path = ["haxe"],"Int64" },[]) -> "long"
  910. | TInst({ cl_path = (["java"], "NativeArray") }, [param]) ->
  911. let rec check_t_s t =
  912. match real_type t with
  913. | TInst({ cl_path = (["java"], "NativeArray") }, [param]) ->
  914. (check_t_s param) ^ "[]"
  915. | _ -> t_s pos (run_follow gen t)
  916. in
  917. (check_t_s param) ^ "[]"
  918. (* end of basic types *)
  919. | TInst ({ cl_kind = KTypeParameter _; cl_path=p }, []) -> snd p
  920. | TAbstract ({ a_path = [], "Dynamic" },[]) ->
  921. path_s_import pos (["java";"lang"], "Object") []
  922. | TMono r -> (match !r with | None -> "java.lang.Object" | Some t -> t_s pos (run_follow gen t))
  923. | TInst ({ cl_path = [], "String" }, []) ->
  924. path_s_import pos (["java";"lang"], "String") []
  925. | TAbstract ({ a_path = [], "Class" }, [p]) | TAbstract ({ a_path = [], "Enum" }, [p])
  926. | TInst ({ cl_path = [], "Class" }, [p]) | TInst ({ cl_path = [], "Enum" }, [p]) ->
  927. path_param_s pos (TClassDecl cl_cl) (["java";"lang"], "Class") [p] []
  928. | TAbstract ({ a_path = [], "Class" }, _) | TAbstract ({ a_path = [], "Enum" }, _)
  929. | TInst ({ cl_path = [], "Class" }, _) | TInst ({ cl_path = [], "Enum" }, _) ->
  930. path_s_import pos (["java";"lang"], "Class") []
  931. | TEnum ({e_path = p; e_meta = meta}, _) ->
  932. path_s_import pos p meta
  933. | TInst (({cl_path = p; cl_meta = meta} as cl), _) when Meta.has Meta.Enum cl.cl_meta ->
  934. path_s_import pos p meta
  935. | TInst (({cl_path = p; cl_meta = meta} as cl), params) -> (path_param_s pos (TClassDecl cl) p params meta)
  936. | TType (({t_path = p; t_meta = meta} as t), params) -> (path_param_s pos (TTypeDecl t) p params meta)
  937. | TAnon (anon) ->
  938. (match !(anon.a_status) with
  939. | Statics _ | EnumStatics _ | AbstractStatics _ ->
  940. path_s_import pos (["java";"lang"], "Class") []
  941. | _ ->
  942. path_s_import pos (["java";"lang"], "Object") [])
  943. | TDynamic _ ->
  944. path_s_import pos (["java";"lang"], "Object") []
  945. (* No Lazy type nor Function type made. That's because function types will be at this point be converted into other types *)
  946. | _ -> if !strict_mode then begin trace ("[ !TypeError " ^ (Type.s_type (Type.print_context()) t) ^ " ]"); assert false end else "[ !TypeError " ^ (Type.s_type (Type.print_context()) t) ^ " ]"
  947. and param_t_s pos t =
  948. match run_follow gen t with
  949. | TAbstract ({ a_path = ([], "Bool") },[]) ->
  950. path_s_import pos (["java";"lang"], "Boolean") []
  951. | TAbstract ({ a_path = ([],"Float") },[]) ->
  952. path_s_import pos (["java";"lang"], "Double") []
  953. | TAbstract ({ a_path = ([],"Int") },[]) ->
  954. path_s_import pos (["java";"lang"], "Integer") []
  955. | TType ({ t_path = ["java"], "Int64" },[])
  956. | TAbstract ({ a_path = ["java"], "Int64" },[]) ->
  957. path_s_import pos (["java";"lang"], "Long") []
  958. | TInst ({ cl_path = ["haxe"],"Int64" },[])
  959. | TAbstract ({ a_path = ["haxe"],"Int64" },[]) ->
  960. path_s_import pos (["java";"lang"], "Long") []
  961. | TInst ({ cl_path = ["haxe"],"Int32" },[])
  962. | TAbstract ({ a_path = ["haxe"],"Int32" },[]) ->
  963. path_s_import pos (["java";"lang"], "Integer") []
  964. | TType ({ t_path = ["java"],"Int8" },[])
  965. | TAbstract ({ a_path = ["java"],"Int8" },[]) ->
  966. path_s_import pos (["java";"lang"], "Byte") []
  967. | TType ({ t_path = ["java"],"Int16" },[])
  968. | TAbstract ({ a_path = ["java"],"Int16" },[]) ->
  969. path_s_import pos (["java";"lang"], "Short") []
  970. | TType ({ t_path = ["java"],"Char16" },[])
  971. | TAbstract ({ a_path = ["java"],"Char16" },[]) ->
  972. path_s_import pos (["java";"lang"], "Character") []
  973. | TType ({ t_path = [],"Single" },[])
  974. | TAbstract ({ a_path = [],"Single" },[]) ->
  975. path_s_import pos (["java";"lang"], "Float") []
  976. | TDynamic _ -> "?"
  977. | TInst (cl, params) -> t_s pos (TInst(cl, change_param_type (TClassDecl cl) params))
  978. | TType (cl, params) -> t_s pos (TType(cl, change_param_type (TTypeDecl cl) params))
  979. | TEnum (e, params) -> t_s pos (TEnum(e, change_param_type (TEnumDecl e) params))
  980. | _ -> t_s pos t
  981. and path_param_s pos md path params meta =
  982. match params with
  983. | [] -> path_s_import pos path meta
  984. | _ when has_tdynamic (change_param_type md params) -> path_s_import pos path meta
  985. | _ -> sprintf "%s<%s>" (path_s_import pos path meta) (String.concat ", " (List.map (fun t -> param_t_s pos t) (change_param_type md params)))
  986. in
  987. let rett_s pos t =
  988. match t with
  989. | TAbstract ({ a_path = ([], "Void") },[]) -> "void"
  990. | _ -> t_s pos t
  991. in
  992. let high_surrogate c = (c lsr 10) + 0xD7C0 in
  993. let low_surrogate c = (c land 0x3FF) lor 0xDC00 in
  994. let escape ichar b =
  995. match ichar with
  996. | 92 (* \ *) -> Buffer.add_string b "\\\\"
  997. | 39 (* ' *) -> Buffer.add_string b "\\\'"
  998. | 34 -> Buffer.add_string b "\\\""
  999. | 13 (* \r *) -> Buffer.add_string b "\\r"
  1000. | 10 (* \n *) -> Buffer.add_string b "\\n"
  1001. | 9 (* \t *) -> Buffer.add_string b "\\t"
  1002. | c when c < 32 || (c >= 127 && c <= 0xFFFF) -> Buffer.add_string b (Printf.sprintf "\\u%.4x" c)
  1003. | c when c > 0xFFFF -> Buffer.add_string b (Printf.sprintf "\\u%.4x\\u%.4x" (high_surrogate c) (low_surrogate c))
  1004. | c -> Buffer.add_char b (Char.chr c)
  1005. in
  1006. let escape s =
  1007. let b = Buffer.create 0 in
  1008. (try
  1009. UTF8.validate s;
  1010. UTF8.iter (fun c -> escape (UChar.code c) b) s
  1011. with
  1012. UTF8.Malformed_code ->
  1013. String.iter (fun c -> escape (Char.code c) b) s
  1014. );
  1015. Buffer.contents b
  1016. in
  1017. let has_semicolon e =
  1018. match e.eexpr with
  1019. | TLocal { v_name = "__fallback__" }
  1020. | TCall ({ eexpr = TLocal( { v_name = "__label__" } ) }, [ { eexpr = TConst(TInt _) } ] ) -> false
  1021. | TCall ({ eexpr = TLocal( { v_name = "__lock__" } ) }, _ ) -> false
  1022. | TBlock _ | TFor _ | TSwitch _ | TTry _ | TIf _ -> false
  1023. | TWhile (_,_,flag) when flag = Ast.NormalWhile -> false
  1024. | _ -> true
  1025. in
  1026. let in_value = ref false in
  1027. let rec md_s pos md =
  1028. let md = follow_module (gen.gfollow#run_f) md in
  1029. match md with
  1030. | TClassDecl (cl) ->
  1031. t_s pos (TInst(cl,[]))
  1032. | TEnumDecl (e) ->
  1033. t_s pos (TEnum(e,[]))
  1034. | TTypeDecl t ->
  1035. t_s pos (TType(t, []))
  1036. | TAbstractDecl a ->
  1037. t_s pos (TAbstract(a, []))
  1038. in
  1039. (*
  1040. it seems that Java doesn't like when you create a new array with the type parameter defined
  1041. so we'll just ignore all type parameters, and hope for the best!
  1042. *)
  1043. let rec transform_nativearray_t t = match real_type t with
  1044. | TInst( ({ cl_path = (["java"], "NativeArray") } as narr), [t]) ->
  1045. TInst(narr, [transform_nativearray_t t])
  1046. | TInst(cl, params) -> TInst(cl, List.map (fun _ -> t_dynamic) params)
  1047. | TEnum(e, params) -> TEnum(e, List.map (fun _ -> t_dynamic) params)
  1048. | TType(t, params) -> TType(t, List.map (fun _ -> t_dynamic) params)
  1049. | _ -> t
  1050. in
  1051. let rec extract_tparams params el =
  1052. match el with
  1053. | ({ eexpr = TLocal({ v_name = "$type_param" }) } as tp) :: tl ->
  1054. extract_tparams (tp.etype :: params) tl
  1055. | _ -> (params, el)
  1056. in
  1057. let line_directive =
  1058. if Common.defined gen.gcon Define.RealPosition then
  1059. fun w p -> ()
  1060. else fun w p ->
  1061. let cur_line = Lexer.get_error_line p in
  1062. let file = Common.get_full_path p.pfile in
  1063. print w "//line %d \"%s\"" cur_line (Ast.s_escape file); newline w
  1064. in
  1065. let extract_statements expr =
  1066. let ret = ref [] in
  1067. let rec loop expr = match expr.eexpr with
  1068. | TCall ({ eexpr = TLocal {
  1069. v_name = "__is__" | "__typeof__" | "__array__"
  1070. } }, el) ->
  1071. List.iter loop el
  1072. | TNew ({ cl_path = (["java"], "NativeArray") }, params, [ size ]) ->
  1073. ()
  1074. | TUnop (Ast.Increment, _, _)
  1075. | TUnop (Ast.Decrement, _, _)
  1076. | TBinop (Ast.OpAssign, _, _)
  1077. | TBinop (Ast.OpAssignOp _, _, _)
  1078. | TLocal { v_name = "__fallback__" }
  1079. | TLocal { v_name = "__sbreak__" } ->
  1080. ret := expr :: !ret
  1081. | TConst _
  1082. | TLocal _
  1083. | TArray _
  1084. | TBinop _
  1085. | TField _
  1086. | TEnumParameter _
  1087. | TTypeExpr _
  1088. | TObjectDecl _
  1089. | TArrayDecl _
  1090. | TCast _
  1091. | TMeta _
  1092. | TParenthesis _
  1093. | TUnop _ ->
  1094. Type.iter loop expr
  1095. | TFunction _ -> () (* do not extract parameters from inside of it *)
  1096. | _ ->
  1097. ret := expr :: !ret
  1098. in
  1099. loop expr;
  1100. (* [expr] *)
  1101. List.rev !ret
  1102. in
  1103. let expr_s w e =
  1104. in_value := false;
  1105. let rec expr_s w e =
  1106. let was_in_value = !in_value in
  1107. in_value := true;
  1108. match e.eexpr with
  1109. | TConst c ->
  1110. (match c with
  1111. | TInt i32 ->
  1112. print w "%ld" i32;
  1113. (match real_type e.etype with
  1114. | TType( { t_path = (["java"], "Int64") }, [] ) -> write w "L";
  1115. | _ -> ()
  1116. )
  1117. | TFloat s ->
  1118. write w s;
  1119. (* fix for Int notation, which only fit in a Float *)
  1120. (if not (String.contains s '.' || String.contains s 'e' || String.contains s 'E') then write w ".0");
  1121. (match real_type e.etype with
  1122. | TType( { t_path = ([], "Single") }, [] ) -> write w "f"
  1123. | _ -> ()
  1124. )
  1125. | TString s -> print w "\"%s\"" (escape s)
  1126. | TBool b -> write w (if b then "true" else "false")
  1127. | TNull ->
  1128. (match real_type e.etype with
  1129. | TAbstract( { a_path = (["java"], "Int64") }, [] )
  1130. | TInst( { cl_path = (["haxe"], "Int64") }, [] ) -> write w "0L"
  1131. | TInst( { cl_path = (["haxe"], "Int32") }, [] )
  1132. | TAbstract ({ a_path = ([], "Int") },[]) -> expr_s w ({ e with eexpr = TConst(TInt Int32.zero) })
  1133. | TAbstract ({ a_path = ([], "Float") },[]) -> expr_s w ({ e with eexpr = TConst(TFloat "0.0") })
  1134. | TAbstract ({ a_path = ([], "Bool") },[]) -> write w "false"
  1135. | TAbstract _ when like_int e.etype ->
  1136. expr_s w (mk_cast e.etype { e with eexpr = TConst(TInt Int32.zero) })
  1137. | TAbstract _ when like_float e.etype ->
  1138. expr_s w (mk_cast e.etype { e with eexpr = TConst(TFloat "0.0") } )
  1139. | t -> write w ("null") )
  1140. | TThis -> write w "this"
  1141. | TSuper -> write w "super")
  1142. | TLocal { v_name = "__fallback__" } -> ()
  1143. | TLocal { v_name = "__sbreak__" } -> write w "break"
  1144. | TLocal { v_name = "__undefined__" } ->
  1145. write w (t_s e.epos (TInst(runtime_cl, List.map (fun _ -> t_dynamic) runtime_cl.cl_params)));
  1146. write w ".undefined";
  1147. | TLocal var ->
  1148. write_id w var.v_name
  1149. | TField(_, FEnum(en,ef)) ->
  1150. let s = ef.ef_name in
  1151. print w "%s." (path_s_import e.epos en.e_path en.e_meta); write_field w s
  1152. | TArray (e1, e2) ->
  1153. expr_s w e1; write w "["; expr_s w e2; write w "]"
  1154. | TBinop ((Ast.OpAssign as op), e1, e2)
  1155. | TBinop ((Ast.OpAssignOp _ as op), e1, e2) ->
  1156. expr_s w e1; write w ( " " ^ (Ast.s_binop op) ^ " " ); expr_s w e2
  1157. | TBinop (op, e1, e2) ->
  1158. write w "( ";
  1159. expr_s w e1; write w ( " " ^ (Ast.s_binop op) ^ " " ); expr_s w e2;
  1160. write w " )"
  1161. | TField (e, FStatic(_, cf)) when Meta.has Meta.Native cf.cf_meta ->
  1162. let rec loop meta = match meta with
  1163. | (Meta.Native, [EConst (String s), _],_) :: _ ->
  1164. expr_s w e; write w "."; write_field w s
  1165. | _ :: tl -> loop tl
  1166. | [] -> expr_s w e; write w "."; write_field w (cf.cf_name)
  1167. in
  1168. loop cf.cf_meta
  1169. | TField (e, s) ->
  1170. expr_s w e; write w "."; write_field w (field_name s)
  1171. | TTypeExpr (TClassDecl { cl_path = (["haxe"], "Int32") }) ->
  1172. write w (path_s_import e.epos (["haxe"], "Int32") [])
  1173. | TTypeExpr (TClassDecl { cl_path = (["haxe"], "Int64") }) ->
  1174. write w (path_s_import e.epos (["haxe"], "Int64") [])
  1175. | TTypeExpr mt -> write w (md_s e.epos mt)
  1176. | TParenthesis e ->
  1177. write w "("; expr_s w e; write w ")"
  1178. | TMeta (_,e) ->
  1179. expr_s w e
  1180. | TCall ({ eexpr = TLocal { v_name = "__array__" } }, el)
  1181. | TCall ({ eexpr = TField(_, FStatic({ cl_path = (["java"],"NativeArray") }, { cf_name = "make" })) }, el)
  1182. | TArrayDecl el when t_has_type_param e.etype ->
  1183. let _, el = extract_tparams [] el in
  1184. print w "( (%s) (new %s " (t_s e.epos e.etype) (t_s e.epos (replace_type_param e.etype));
  1185. write w "{";
  1186. ignore (List.fold_left (fun acc e ->
  1187. (if acc <> 0 then write w ", ");
  1188. expr_s w e;
  1189. acc + 1
  1190. ) 0 el);
  1191. write w "}) )"
  1192. | TCall ({ eexpr = TLocal { v_name = "__array__" } }, el)
  1193. | TCall ({ eexpr = TField(_, FStatic({ cl_path = (["java"],"NativeArray") }, { cf_name = "make" })) }, el)
  1194. | TArrayDecl el ->
  1195. let _, el = extract_tparams [] el in
  1196. print w "new %s" (param_t_s e.epos (transform_nativearray_t e.etype));
  1197. let is_double = match follow e.etype with
  1198. | TInst(_,[ t ]) -> if like_float t && not (like_int t) then Some t else None
  1199. | _ -> None
  1200. in
  1201. write w "{";
  1202. ignore (List.fold_left (fun acc e ->
  1203. (if acc <> 0 then write w ", ");
  1204. (* this is a hack so we are able to convert ints to boxed Double / Float when needed *)
  1205. let e = if is_some is_double then mk_cast (get is_double) e else e in
  1206. expr_s w e;
  1207. acc + 1
  1208. ) 0 el);
  1209. write w "}"
  1210. | TCall( ( { eexpr = TField(_, FStatic({ cl_path = ([], "String") }, { cf_name = "fromCharCode" })) } ), [cc] ) ->
  1211. write w "Character.toString((char) ";
  1212. expr_s w cc;
  1213. write w ")"
  1214. | TCall ({ eexpr = TLocal( { v_name = "__is__" } ) }, [ expr; { eexpr = TTypeExpr(md) } ] ) ->
  1215. write w "( ";
  1216. expr_s w expr;
  1217. write w " instanceof ";
  1218. write w (md_s e.epos md);
  1219. write w " )"
  1220. | TCall ({ eexpr = TLocal( { v_name = "__java__" } ) }, [ { eexpr = TConst(TString(s)) } ] ) ->
  1221. write w s
  1222. | TCall ({ eexpr = TLocal( { v_name = "__java__" } ) }, { eexpr = TConst(TString(s)) } :: tl ) ->
  1223. Codegen.interpolate_code gen.gcon s tl (write w) (expr_s w) e.epos
  1224. | TCall ({ eexpr = TLocal( { v_name = "__lock__" } ) }, [ eobj; eblock ] ) ->
  1225. write w "synchronized(";
  1226. let rec loop eobj = match eobj.eexpr with
  1227. | TTypeExpr md ->
  1228. expr_s w eobj;
  1229. write w ".class"
  1230. | TMeta(_,e) | TParenthesis(e) ->
  1231. loop e
  1232. | _ ->
  1233. expr_s w eobj
  1234. in
  1235. loop eobj;
  1236. write w ")";
  1237. (match eblock.eexpr with
  1238. | TBlock(_ :: _) ->
  1239. expr_s w eblock
  1240. | _ ->
  1241. begin_block w;
  1242. expr_s w eblock;
  1243. if has_semicolon eblock then write w ";";
  1244. end_block w;
  1245. )
  1246. | TCall ({ eexpr = TLocal( { v_name = "__goto__" } ) }, [ { eexpr = TConst(TInt v) } ] ) ->
  1247. print w "break label%ld" v
  1248. | TCall ({ eexpr = TLocal( { v_name = "__label__" } ) }, [ { eexpr = TConst(TInt v) } ] ) ->
  1249. print w "label%ld:" v
  1250. | TCall ({ eexpr = TLocal( { v_name = "__typeof__" } ) }, [ { eexpr = TTypeExpr md } as expr ] ) ->
  1251. expr_s w expr;
  1252. write w ".class"
  1253. | TCall (e, el) ->
  1254. let params, el = extract_tparams [] el in
  1255. expr_s w e;
  1256. (*(match params with
  1257. | [] -> ()
  1258. | params ->
  1259. let md = match e.eexpr with
  1260. | TField(ef, _) -> t_to_md (run_follow gen ef.etype)
  1261. | _ -> assert false
  1262. in
  1263. write w "<";
  1264. ignore (List.fold_left (fun acc t ->
  1265. (if acc <> 0 then write w ", ");
  1266. write w (param_t_s (change_param_type md t));
  1267. acc + 1
  1268. ) 0 params);
  1269. write w ">"
  1270. );*)
  1271. write w "(";
  1272. ignore (List.fold_left (fun acc e ->
  1273. (if acc <> 0 then write w ", ");
  1274. expr_s w e;
  1275. acc + 1
  1276. ) 0 el);
  1277. write w ")"
  1278. | TNew (({ cl_path = (["java"], "NativeArray") } as cl), params, [ size ]) ->
  1279. let rec check_t_s t times =
  1280. match real_type t with
  1281. | TInst({ cl_path = (["java"], "NativeArray") }, [param]) ->
  1282. (check_t_s param (times+1))
  1283. | _ ->
  1284. print w "new %s[" (t_s e.epos (transform_nativearray_t t));
  1285. expr_s w size;
  1286. print w "]";
  1287. let rec loop i =
  1288. if i <= 0 then () else (write w "[]"; loop (i-1))
  1289. in
  1290. loop (times - 1)
  1291. in
  1292. check_t_s (TInst(cl, params)) 0
  1293. | TNew ({ cl_path = ([], "String") } as cl, [], el) ->
  1294. write w "new ";
  1295. write w (t_s e.epos (TInst(cl, [])));
  1296. write w "(";
  1297. ignore (List.fold_left (fun acc e ->
  1298. (if acc <> 0 then write w ", ");
  1299. expr_s w e;
  1300. acc + 1
  1301. ) 0 el);
  1302. write w ")"
  1303. | TNew ({ cl_kind = KTypeParameter _ } as cl, params, el) ->
  1304. print w "null /* This code should never be reached. It was produced by the use of @:generic on a new type parameter instance: %s */" (path_param_s e.epos (TClassDecl cl) cl.cl_path params cl.cl_meta)
  1305. | TNew (cl, params, el) ->
  1306. write w "new ";
  1307. write w (path_param_s e.epos (TClassDecl cl) cl.cl_path params cl.cl_meta);
  1308. write w "(";
  1309. ignore (List.fold_left (fun acc e ->
  1310. (if acc <> 0 then write w ", ");
  1311. expr_s w e;
  1312. acc + 1
  1313. ) 0 el);
  1314. write w ")"
  1315. | TUnop ((Ast.Increment as op), flag, e)
  1316. | TUnop ((Ast.Decrement as op), flag, e) ->
  1317. (match flag with
  1318. | Ast.Prefix -> write w ( " " ^ (Ast.s_unop op) ^ " " ); expr_s w e
  1319. | Ast.Postfix -> expr_s w e; write w (Ast.s_unop op))
  1320. | TUnop (op, flag, e) ->
  1321. (match flag with
  1322. | Ast.Prefix -> write w ( " " ^ (Ast.s_unop op) ^ " (" ); expr_s w e; write w ") "
  1323. | Ast.Postfix -> write w "("; expr_s w e; write w (") " ^ Ast.s_unop op))
  1324. | TVar (var, eopt) ->
  1325. print w "%s " (t_s e.epos var.v_type);
  1326. write_id w var.v_name;
  1327. (match eopt with
  1328. | None ->
  1329. write w " = ";
  1330. expr_s w (null var.v_type e.epos)
  1331. | Some e ->
  1332. write w " = ";
  1333. expr_s w e
  1334. )
  1335. | TBlock [e] when was_in_value ->
  1336. expr_s w e
  1337. | TBlock el ->
  1338. begin_block w;
  1339. List.iter (fun e ->
  1340. List.iter (fun e ->
  1341. in_value := false;
  1342. line_directive w e.epos;
  1343. expr_s w e;
  1344. if has_semicolon e then write w ";";
  1345. newline w;
  1346. ) (extract_statements e)
  1347. ) el;
  1348. end_block w
  1349. | TIf (econd, e1, Some(eelse)) when was_in_value ->
  1350. write w "( ";
  1351. expr_s w (mk_paren econd);
  1352. write w " ? ";
  1353. expr_s w (mk_paren e1);
  1354. write w " : ";
  1355. expr_s w (mk_paren eelse);
  1356. write w " )";
  1357. | TIf (econd, e1, eelse) ->
  1358. write w "if ";
  1359. expr_s w (mk_paren econd);
  1360. write w " ";
  1361. in_value := false;
  1362. expr_s w (mk_block e1);
  1363. (match eelse with
  1364. | None -> ()
  1365. | Some e ->
  1366. write w "else";
  1367. in_value := false;
  1368. expr_s w (mk_block e)
  1369. )
  1370. | TWhile (econd, eblock, flag) ->
  1371. (match flag with
  1372. | Ast.NormalWhile ->
  1373. write w "while ";
  1374. expr_s w (mk_paren econd);
  1375. write w "";
  1376. in_value := false;
  1377. expr_s w (mk_block eblock)
  1378. | Ast.DoWhile ->
  1379. write w "do ";
  1380. in_value := false;
  1381. expr_s w (mk_block eblock);
  1382. write w "while ";
  1383. in_value := true;
  1384. expr_s w (mk_paren econd);
  1385. )
  1386. | TSwitch (econd, ele_l, default) ->
  1387. write w "switch ";
  1388. expr_s w (mk_paren econd);
  1389. begin_block w;
  1390. List.iter (fun (el, e) ->
  1391. List.iter (fun e ->
  1392. write w "case ";
  1393. in_value := true;
  1394. (match e.eexpr with
  1395. | TField(_,FEnum(e,ef)) ->
  1396. write w ef.ef_name
  1397. | _ ->
  1398. expr_s w e);
  1399. write w ":";
  1400. newline w;
  1401. ) el;
  1402. in_value := false;
  1403. expr_s w (mk_block e);
  1404. newline w;
  1405. newline w
  1406. ) ele_l;
  1407. if is_some default then begin
  1408. write w "default:";
  1409. newline w;
  1410. in_value := false;
  1411. expr_s w (get default);
  1412. newline w;
  1413. end;
  1414. end_block w
  1415. | TTry (tryexpr, ve_l) ->
  1416. write w "try ";
  1417. in_value := false;
  1418. expr_s w (mk_block tryexpr);
  1419. let pos = e.epos in
  1420. List.iter (fun (var, e) ->
  1421. print w "catch (%s %s)" (t_s pos var.v_type) (var.v_name);
  1422. in_value := false;
  1423. expr_s w (mk_block e);
  1424. newline w
  1425. ) ve_l
  1426. | TReturn eopt ->
  1427. write w "return ";
  1428. if is_some eopt then expr_s w (get eopt)
  1429. | TBreak -> write w "break"
  1430. | TContinue -> write w "continue"
  1431. | TThrow e ->
  1432. write w "throw ";
  1433. expr_s w e
  1434. | TCast (e1,md_t) ->
  1435. ((*match gen.gfollow#run_f e.etype with
  1436. | TType({ t_path = ([], "UInt") }, []) ->
  1437. write w "( unchecked ((uint) ";
  1438. expr_s w e1;
  1439. write w ") )"
  1440. | _ ->*)
  1441. (* FIXME I'm ignoring module type *)
  1442. print w "((%s) (" (t_s e.epos e.etype);
  1443. expr_s w e1;
  1444. write w ") )"
  1445. )
  1446. | TFor (_,_,content) ->
  1447. write w "[ for not supported ";
  1448. expr_s w content;
  1449. write w " ]";
  1450. if !strict_mode then assert false
  1451. | TObjectDecl _ -> write w "[ obj decl not supported ]"; if !strict_mode then assert false
  1452. | TFunction _ -> write w "[ func decl not supported ]"; if !strict_mode then assert false
  1453. | TEnumParameter _ -> write w "[ enum parameter not supported ]"; if !strict_mode then assert false
  1454. in
  1455. expr_s w e
  1456. in
  1457. let rec gen_fpart_attrib w = function
  1458. | EConst( Ident i ), _ ->
  1459. write w i
  1460. | EField( ef, f ), _ ->
  1461. gen_fpart_attrib w ef;
  1462. write w ".";
  1463. write w f
  1464. | _, p ->
  1465. gen.gcon.error "Invalid expression inside @:meta metadata" p
  1466. in
  1467. let rec gen_spart w = function
  1468. | EConst c, p -> (match c with
  1469. | Int s | Float s | Ident s ->
  1470. write w s
  1471. | String s ->
  1472. write w "\"";
  1473. write w (escape s);
  1474. write w "\""
  1475. | _ -> gen.gcon.error "Invalid expression inside @:meta metadata" p)
  1476. | EField( ef, f ), _ ->
  1477. gen_spart w ef;
  1478. write w ".";
  1479. write w f
  1480. | EBinop( Ast.OpAssign, (EConst (Ident s), _), e2 ), _ ->
  1481. write w s;
  1482. write w " = ";
  1483. gen_spart w e2
  1484. | EArrayDecl( el ), _ ->
  1485. write w "{";
  1486. let fst = ref true in
  1487. List.iter (fun e ->
  1488. if !fst then fst := false else write w ", ";
  1489. gen_spart w e
  1490. ) el;
  1491. write w "}"
  1492. | ECall(fpart,args), _ ->
  1493. gen_fpart_attrib w fpart;
  1494. write w "(";
  1495. let fst = ref true in
  1496. List.iter (fun e ->
  1497. if !fst then fst := false else write w ", ";
  1498. gen_spart w e
  1499. ) args;
  1500. write w ")"
  1501. | _, p ->
  1502. gen.gcon.error "Invalid expression inside @:meta metadata" p
  1503. in
  1504. let gen_annotations w ?(add_newline=true) metadata =
  1505. List.iter (function
  1506. | Meta.Meta, [meta], _ ->
  1507. write w "@";
  1508. gen_spart w meta;
  1509. if add_newline then newline w else write w " ";
  1510. | _ -> ()
  1511. ) metadata
  1512. in
  1513. let argt_s p t =
  1514. let w = new_source_writer () in
  1515. let rec run t =
  1516. match t with
  1517. | TType (tdef,p) ->
  1518. gen_annotations w ~add_newline:false tdef.t_meta;
  1519. run (follow_once t)
  1520. | TMono r ->
  1521. (match !r with
  1522. | Some t -> run t
  1523. | _ -> () (* avoid infinite loop / should be the same in this context *))
  1524. | TLazy f ->
  1525. run (!f())
  1526. | _ -> ()
  1527. in
  1528. run t;
  1529. let ret = t_s p t in
  1530. let c = contents w in
  1531. if c <> "" then
  1532. c ^ " " ^ ret
  1533. else
  1534. ret
  1535. in
  1536. let get_string_params cl_params =
  1537. match cl_params with
  1538. | [] ->
  1539. ("","")
  1540. | _ ->
  1541. let params = sprintf "<%s>" (String.concat ", " (List.map (fun (_, tcl) -> match follow tcl with | TInst(cl, _) -> snd cl.cl_path | _ -> assert false) cl_params)) in
  1542. let params_extends = List.fold_left (fun acc (name, t) ->
  1543. match run_follow gen t with
  1544. | TInst (cl, p) ->
  1545. (match cl.cl_implements with
  1546. | [] -> acc
  1547. | _ -> acc) (* TODO
  1548. | _ -> (sprintf " where %s : %s" name (String.concat ", " (List.map (fun (cl,p) -> path_param_s (TClassDecl cl) cl.cl_path p) cl.cl_implements))) :: acc ) *)
  1549. | _ -> trace (t_s Ast.null_pos t); assert false (* FIXME it seems that a cl_params will never be anything other than cl.cl_params. I'll take the risk and fail if not, just to see if that confirms *)
  1550. ) [] cl_params in
  1551. (params, String.concat " " params_extends)
  1552. in
  1553. let write_parts w parts =
  1554. let parts = List.filter (fun s -> s <> "") parts in
  1555. write w (String.concat " " parts)
  1556. in
  1557. let rec gen_class_field w ?(is_overload=false) is_static cl is_final cf =
  1558. let is_interface = cl.cl_interface in
  1559. let name, is_new, is_explicit_iface = match cf.cf_name with
  1560. | "new" -> snd cl.cl_path, true, false
  1561. | name when String.contains name '.' ->
  1562. let fn_name, path = parse_explicit_iface name in
  1563. (path_s path cl.cl_meta) ^ "." ^ fn_name, false, true
  1564. | name -> name, false, false
  1565. in
  1566. (match cf.cf_kind with
  1567. | Var _
  1568. | Method (MethDynamic) when not (Type.is_extern_field cf) ->
  1569. (if is_overload || List.exists (fun cf -> cf.cf_expr <> None) cf.cf_overloads then
  1570. gen.gcon.error "Only normal (non-dynamic) methods can be overloaded" cf.cf_pos);
  1571. if not is_interface then begin
  1572. let access, modifiers = get_fun_modifiers cf.cf_meta "public" [] in
  1573. write_parts w (access :: (if is_static then "static" else "") :: modifiers @ [(t_s cf.cf_pos (run_follow gen cf.cf_type)); (change_field name)]);
  1574. (match cf.cf_expr with
  1575. | Some e ->
  1576. write w " = ";
  1577. expr_s w e;
  1578. write w ";"
  1579. | None -> write w ";"
  1580. )
  1581. end (* TODO see how (get,set) variable handle when they are interfaces *)
  1582. | Method _ when Type.is_extern_field cf || (match cl.cl_kind, cf.cf_expr with | KAbstractImpl _, None -> true | _ -> false) ->
  1583. List.iter (fun cf -> if cl.cl_interface || cf.cf_expr <> None then
  1584. gen_class_field w ~is_overload:true is_static cl (Meta.has Meta.Final cf.cf_meta) cf
  1585. ) cf.cf_overloads
  1586. | Var _ | Method MethDynamic -> ()
  1587. | Method mkind ->
  1588. List.iter (fun cf ->
  1589. if cl.cl_interface || cf.cf_expr <> None then
  1590. gen_class_field w ~is_overload:true is_static cl (Meta.has Meta.Final cf.cf_meta) cf
  1591. ) cf.cf_overloads;
  1592. let is_virtual = is_new || (not is_final && match mkind with | MethInline -> false | _ when not is_new -> true | _ -> false) in
  1593. let is_override = match cf.cf_name with
  1594. | "equals" when not is_static ->
  1595. (match cf.cf_type with
  1596. | TFun([_,_,t], ret) ->
  1597. (match (real_type t, real_type ret) with
  1598. | TDynamic _, TAbstract ({ a_path = ([], "Bool") },[])
  1599. | TAnon _, TAbstract ({ a_path = ([], "Bool") },[]) -> true
  1600. | _ -> List.memq cf cl.cl_overrides
  1601. )
  1602. | _ -> List.memq cf cl.cl_overrides)
  1603. | "toString" when not is_static ->
  1604. (match cf.cf_type with
  1605. | TFun([], ret) ->
  1606. (match real_type ret with
  1607. | TInst( { cl_path = ([], "String") }, []) -> true
  1608. | _ -> gen.gcon.error "A toString() function should return a String!" cf.cf_pos; false
  1609. )
  1610. | _ -> List.memq cf cl.cl_overrides
  1611. )
  1612. | "hashCode" when not is_static ->
  1613. (match cf.cf_type with
  1614. | TFun([], ret) ->
  1615. (match real_type ret with
  1616. | TAbstract ({ a_path = ([], "Int") },[]) ->
  1617. true
  1618. | _ -> gen.gcon.error "A hashCode() function should return an Int!" cf.cf_pos; false
  1619. )
  1620. | _ -> List.memq cf cl.cl_overrides
  1621. )
  1622. | _ -> List.memq cf cl.cl_overrides
  1623. in
  1624. let visibility = if is_interface then "" else "public" in
  1625. let visibility, modifiers = get_fun_modifiers cf.cf_meta visibility [] in
  1626. let visibility, is_virtual = if is_explicit_iface then "",false else visibility, is_virtual in
  1627. let v_n = if is_static then "static" else if is_override && not is_interface then "" else if not is_virtual then "final" else "" in
  1628. let cf_type = if is_override && not is_overload && not (Meta.has Meta.Overload cf.cf_meta) then match field_access gen (TInst(cl, List.map snd cl.cl_params)) cf.cf_name with | FClassField(_,_,_,_,_,actual_t,_) -> actual_t | _ -> assert false else cf.cf_type in
  1629. let params = List.map snd cl.cl_params in
  1630. let ret_type, args = match follow cf_type, follow cf.cf_type with
  1631. | TFun (strbtl, t), TFun(rargs, _) ->
  1632. (apply_params cl.cl_params params (real_type t), List.map2 (fun(_,_,t) (n,o,_) -> (n,o,apply_params cl.cl_params params (real_type t))) strbtl rargs)
  1633. | _ -> assert false
  1634. in
  1635. (if is_override && not is_interface then write w "@Override ");
  1636. gen_annotations w cf.cf_meta;
  1637. (* public static void funcName *)
  1638. let params, _ = get_string_params cf.cf_params in
  1639. write_parts w (visibility :: v_n :: modifiers @ [params; (if is_new then "" else rett_s cf.cf_pos (run_follow gen ret_type)); (change_field name)]);
  1640. (* <T>(string arg1, object arg2) with T : object *)
  1641. (match cf.cf_expr with
  1642. | Some { eexpr = TFunction tf } ->
  1643. print w "(%s)" (String.concat ", " (List.map2 (fun (var,_) (_,_,t) -> sprintf "%s %s" (argt_s cf.cf_pos (run_follow gen t)) (change_id var.v_name)) tf.tf_args args))
  1644. | _ ->
  1645. print w "(%s)" (String.concat ", " (List.map (fun (name, _, t) -> sprintf "%s %s" (argt_s cf.cf_pos (run_follow gen t)) (change_id name)) args))
  1646. );
  1647. if is_interface || List.mem "native" modifiers then
  1648. write w ";"
  1649. else begin
  1650. let rec loop meta =
  1651. match meta with
  1652. | [] ->
  1653. let expr = match cf.cf_expr with
  1654. | None -> mk (TBlock([])) t_dynamic Ast.null_pos
  1655. | Some s ->
  1656. match s.eexpr with
  1657. | TFunction tf ->
  1658. mk_block (tf.tf_expr)
  1659. | _ -> assert false (* FIXME *)
  1660. in
  1661. (if is_new then begin
  1662. (*let rec get_super_call el =
  1663. match el with
  1664. | ( { eexpr = TCall( { eexpr = TConst(TSuper) }, _) } as call) :: rest ->
  1665. Some call, rest
  1666. | ( { eexpr = TBlock(bl) } as block ) :: rest ->
  1667. let ret, mapped = get_super_call bl in
  1668. ret, ( { block with eexpr = TBlock(mapped) } :: rest )
  1669. | _ ->
  1670. None, el
  1671. in*)
  1672. expr_s w expr
  1673. end else begin
  1674. expr_s w expr;
  1675. end)
  1676. | (Meta.Throws, [Ast.EConst (Ast.String t), _], _) :: tl ->
  1677. print w " throws %s" t;
  1678. loop tl
  1679. | (Meta.FunctionCode, [Ast.EConst (Ast.String contents),_],_) :: tl ->
  1680. begin_block w;
  1681. write w contents;
  1682. end_block w
  1683. | _ :: tl -> loop tl
  1684. in
  1685. loop cf.cf_meta
  1686. end);
  1687. newline w;
  1688. newline w
  1689. in
  1690. let gen_class w cl =
  1691. let cf_filters = [ handle_throws ] in
  1692. List.iter (fun f -> List.iter (f gen) cl.cl_ordered_fields) cf_filters;
  1693. List.iter (fun f -> List.iter (f gen) cl.cl_ordered_statics) cf_filters;
  1694. let should_close = match change_ns (fst cl.cl_path) with
  1695. | [] -> false
  1696. | ns ->
  1697. print w "package %s;" (String.concat "." (change_ns ns));
  1698. newline w;
  1699. newline w;
  1700. false
  1701. in
  1702. let rec loop_meta meta acc =
  1703. match meta with
  1704. | (Meta.SuppressWarnings, [Ast.EConst (Ast.String w),_],_) :: meta -> loop_meta meta (w :: acc)
  1705. | _ :: meta -> loop_meta meta acc
  1706. | _ -> acc
  1707. in
  1708. let suppress_warnings = loop_meta cl.cl_meta [ "rawtypes"; "unchecked" ] in
  1709. write w "import haxe.root.*;";
  1710. newline w;
  1711. let w_header = w in
  1712. let w = new_source_writer () in
  1713. clear_scope();
  1714. (* add all haxe.root.* to imports *)
  1715. List.iter (function
  1716. | TClassDecl { cl_path = ([],c) } ->
  1717. imports := ([],c) :: !imports
  1718. | TEnumDecl { e_path = ([],c) } ->
  1719. imports := ([],c) :: !imports
  1720. | TAbstractDecl { a_path = ([],c) } ->
  1721. imports := ([],c) :: !imports
  1722. | _ -> ()
  1723. ) gen.gcon.types;
  1724. newline w;
  1725. write w "@SuppressWarnings(value={";
  1726. let first = ref true in
  1727. List.iter (fun s ->
  1728. (if !first then first := false else write w ", ");
  1729. print w "\"%s\"" (escape s)
  1730. ) suppress_warnings;
  1731. write w "})";
  1732. newline w;
  1733. gen_annotations w cl.cl_meta;
  1734. let clt, access, modifiers = get_class_modifiers cl.cl_meta (if cl.cl_interface then "interface" else "class") "public" [] in
  1735. let is_final = Meta.has Meta.Final cl.cl_meta in
  1736. write_parts w (access :: modifiers @ [clt; (change_clname (snd cl.cl_path))]);
  1737. (* type parameters *)
  1738. let params, _ = get_string_params cl.cl_params in
  1739. let cl_p_to_string (c,p) =
  1740. let p = List.map (fun t -> match follow t with
  1741. | TMono _ | TDynamic _ -> t_empty
  1742. | _ -> t) p
  1743. in
  1744. path_param_s cl.cl_pos (TClassDecl c) c.cl_path p c.cl_meta
  1745. in
  1746. print w "%s" params;
  1747. (if is_some cl.cl_super then print w " extends %s" (cl_p_to_string (get cl.cl_super)));
  1748. (match cl.cl_implements with
  1749. | [] -> ()
  1750. | _ -> print w " %s %s" (if cl.cl_interface then "extends" else "implements") (String.concat ", " (List.map cl_p_to_string cl.cl_implements))
  1751. );
  1752. (* class head ok: *)
  1753. (* public class Test<A> : X, Y, Z where A : Y *)
  1754. begin_block w;
  1755. (* our constructor is expected to be a normal "new" function *
  1756. if !strict_mode && is_some cl.cl_constructor then assert false;*)
  1757. let rec loop cl =
  1758. List.iter (fun cf -> add_scope cf.cf_name) cl.cl_ordered_fields;
  1759. List.iter (fun cf -> add_scope cf.cf_name) cl.cl_ordered_statics;
  1760. match cl.cl_super with
  1761. | Some(c,_) -> loop c
  1762. | None -> ()
  1763. in
  1764. loop cl;
  1765. let rec loop meta =
  1766. match meta with
  1767. | [] -> ()
  1768. | (Meta.ClassCode, [Ast.EConst (Ast.String contents),_],_) :: tl ->
  1769. write w contents
  1770. | _ :: tl -> loop tl
  1771. in
  1772. loop cl.cl_meta;
  1773. (match gen.gcon.main_class with
  1774. | Some path when path = cl.cl_path ->
  1775. write w "public static void main(String[] args)";
  1776. begin_block w;
  1777. (try
  1778. let t = Hashtbl.find gen.gtypes ([], "Sys") in
  1779. match t with
  1780. | TClassDecl(cl) when PMap.mem "_args" cl.cl_statics ->
  1781. write w "Sys._args = args;"; newline w
  1782. | _ -> ()
  1783. with | Not_found -> ()
  1784. );
  1785. write w "main();";
  1786. end_block w;
  1787. newline w
  1788. | _ -> ()
  1789. );
  1790. (match cl.cl_init with
  1791. | None -> ()
  1792. | Some init ->
  1793. write w "static";
  1794. expr_s w (mk_block init);
  1795. newline w
  1796. );
  1797. (if is_some cl.cl_constructor then gen_class_field w false cl is_final (get cl.cl_constructor));
  1798. (if not cl.cl_interface then List.iter (gen_class_field w true cl is_final) cl.cl_ordered_statics);
  1799. List.iter (gen_class_field w false cl is_final) cl.cl_ordered_fields;
  1800. end_block w;
  1801. if should_close then end_block w;
  1802. (* add imports *)
  1803. List.iter (function
  1804. | ["haxe";"root"], _ | [], _ -> ()
  1805. | path ->
  1806. write w_header "import ";
  1807. write w_header (path_s path []);
  1808. write w_header ";\n"
  1809. ) !imports;
  1810. add_writer w w_header
  1811. in
  1812. let gen_enum w e =
  1813. let should_close = match change_ns (fst e.e_path) with
  1814. | [] -> false
  1815. | ns ->
  1816. print w "package %s;" (String.concat "." (change_ns ns));
  1817. newline w;
  1818. newline w;
  1819. false
  1820. in
  1821. gen_annotations w e.e_meta;
  1822. print w "public enum %s" (change_clname (snd e.e_path));
  1823. begin_block w;
  1824. write w (String.concat ", " (List.map (change_id) e.e_names));
  1825. end_block w;
  1826. if should_close then end_block w
  1827. in
  1828. let module_type_gen w md_tp =
  1829. match md_tp with
  1830. | TClassDecl cl ->
  1831. if not cl.cl_extern then begin
  1832. gen_class w cl;
  1833. newline w;
  1834. newline w
  1835. end;
  1836. (not cl.cl_extern)
  1837. | TEnumDecl e ->
  1838. if not e.e_extern then begin
  1839. gen_enum w e;
  1840. newline w;
  1841. newline w
  1842. end;
  1843. (not e.e_extern)
  1844. | TTypeDecl e ->
  1845. false
  1846. | TAbstractDecl a ->
  1847. false
  1848. in
  1849. let module_gen w md =
  1850. module_type_gen w md
  1851. in
  1852. (* generate source code *)
  1853. init_ctx gen;
  1854. Hashtbl.add gen.gspecial_vars "__label__" true;
  1855. Hashtbl.add gen.gspecial_vars "__goto__" true;
  1856. Hashtbl.add gen.gspecial_vars "__is__" true;
  1857. Hashtbl.add gen.gspecial_vars "__typeof__" true;
  1858. Hashtbl.add gen.gspecial_vars "__java__" true;
  1859. Hashtbl.add gen.gspecial_vars "__lock__" true;
  1860. Hashtbl.add gen.gspecial_vars "__array__" true;
  1861. gen.greal_type <- real_type;
  1862. gen.greal_type_param <- change_param_type;
  1863. SetHXGen.run_filter gen SetHXGen.default_hxgen_func;
  1864. (* before running the filters, follow all possible types *)
  1865. (* this is needed so our module transformations don't break some core features *)
  1866. (* like multitype selection *)
  1867. let run_follow_gen = run_follow gen in
  1868. let rec type_map e = Type.map_expr_type (fun e->type_map e) (run_follow_gen) (fun tvar-> tvar.v_type <- (run_follow_gen tvar.v_type); tvar) e in
  1869. let super_map (cl,tl) = (cl, List.map run_follow_gen tl) in
  1870. List.iter (function
  1871. | TClassDecl cl ->
  1872. let all_fields = (Option.map_default (fun cf -> [cf]) [] cl.cl_constructor) @ cl.cl_ordered_fields @ cl.cl_ordered_statics in
  1873. List.iter (fun cf ->
  1874. cf.cf_type <- run_follow_gen cf.cf_type;
  1875. cf.cf_expr <- Option.map type_map cf.cf_expr
  1876. ) all_fields;
  1877. cl.cl_dynamic <- Option.map run_follow_gen cl.cl_dynamic;
  1878. cl.cl_array_access <- Option.map run_follow_gen cl.cl_array_access;
  1879. cl.cl_init <- Option.map type_map cl.cl_init;
  1880. cl.cl_super <- Option.map super_map cl.cl_super;
  1881. cl.cl_implements <- List.map super_map cl.cl_implements
  1882. | _ -> ()
  1883. ) gen.gcon.types;
  1884. let closure_t = ClosuresToClass.DoubleAndDynamicClosureImpl.get_ctx gen 6 in
  1885. (*let closure_t = ClosuresToClass.create gen 10 float_cl
  1886. (fun l -> l)
  1887. (fun l -> l)
  1888. (fun args -> args)
  1889. (fun args -> [])
  1890. in
  1891. ClosuresToClass.configure gen (ClosuresToClass.default_implementation closure_t (fun e _ _ -> e));
  1892. StubClosureImpl.configure gen (StubClosureImpl.default_implementation gen float_cl 10 (fun e _ _ -> e));*)
  1893. FixOverrides.configure gen;
  1894. Normalize.configure gen ~metas:(Hashtbl.create 0);
  1895. AbstractImplementationFix.configure gen;
  1896. IteratorsInterface.configure gen (fun e -> e);
  1897. ClosuresToClass.configure gen (ClosuresToClass.default_implementation closure_t (get_cl (get_type gen (["haxe";"lang"],"Function")) ));
  1898. let enum_base = (get_cl (get_type gen (["haxe";"lang"],"Enum")) ) in
  1899. let param_enum_base = (get_cl (get_type gen (["haxe";"lang"],"ParamEnum")) ) in
  1900. EnumToClass.configure gen (None) false true enum_base param_enum_base false false;
  1901. InterfaceVarsDeleteModf.configure gen;
  1902. let dynamic_object = (get_cl (get_type gen (["haxe";"lang"],"DynamicObject")) ) in
  1903. let object_iface = get_cl (get_type gen (["haxe";"lang"],"IHxObject")) in
  1904. (*fixme: THIS IS A HACK. take this off *)
  1905. let empty_e = match (get_type gen (["haxe";"lang"], "EmptyObject")) with | TEnumDecl e -> e | _ -> assert false in
  1906. (*OverloadingCtor.set_new_create_empty gen ({eexpr=TEnumField(empty_e, "EMPTY"); etype=TEnum(empty_e,[]); epos=null_pos;});*)
  1907. let empty_expr = { eexpr = (TTypeExpr (TEnumDecl empty_e)); etype = (TAnon { a_fields = PMap.empty; a_status = ref (EnumStatics empty_e) }); epos = null_pos } in
  1908. let empty_ef =
  1909. try
  1910. PMap.find "EMPTY" empty_e.e_constrs
  1911. with Not_found -> gen.gcon.error "Required enum field EMPTY was not found" empty_e.e_pos; assert false
  1912. in
  1913. OverloadingConstructor.configure ~empty_ctor_type:(TEnum(empty_e, [])) ~empty_ctor_expr:({ eexpr=TField(empty_expr, FEnum(empty_e, empty_ef)); etype=TEnum(empty_e,[]); epos=null_pos; }) ~supports_ctor_inheritance:false gen;
  1914. let rcf_static_find = mk_static_field_access_infer (get_cl (get_type gen (["haxe";"lang"], "FieldLookup"))) "findHash" Ast.null_pos [] in
  1915. (*let rcf_static_lookup = mk_static_field_access_infer (get_cl (get_type gen (["haxe";"lang"], "FieldLookup"))) "lookupHash" Ast.null_pos [] in*)
  1916. let get_specialized_postfix t = match t with
  1917. | TAbstract({a_path = [],"Float"}, _) -> "Float"
  1918. | TInst({cl_path = [],"String"},_) -> "String"
  1919. | TAnon _ | TDynamic _ -> "Dynamic"
  1920. | _ -> print_endline (debug_type t); assert false
  1921. in
  1922. let rcf_static_insert t = mk_static_field_access_infer (get_cl (get_type gen (["haxe";"lang"], "FieldLookup"))) ("insert" ^ get_specialized_postfix t) Ast.null_pos [] in
  1923. let rcf_static_remove t = mk_static_field_access_infer (get_cl (get_type gen (["haxe";"lang"], "FieldLookup"))) ("remove" ^ get_specialized_postfix t) Ast.null_pos [] in
  1924. let can_be_float t = like_float (real_type t) in
  1925. let rcf_on_getset_field main_expr field_expr field may_hash may_set is_unsafe =
  1926. let is_float = can_be_float (if is_none may_set then main_expr.etype else (get may_set).etype) in
  1927. let fn_name = if is_some may_set then "setField" else "getField" in
  1928. let fn_name = if is_float then fn_name ^ "_f" else fn_name in
  1929. let pos = field_expr.epos in
  1930. let is_unsafe = { eexpr = TConst(TBool is_unsafe); etype = basic.tbool; epos = pos } in
  1931. let should_cast = match main_expr.etype with | TAbstract({ a_path = ([], "Float") }, []) -> false | _ -> true in
  1932. let infer = mk_static_field_access_infer runtime_cl fn_name field_expr.epos [] in
  1933. let first_args =
  1934. [ field_expr; { eexpr = TConst(TString field); etype = basic.tstring; epos = pos } ]
  1935. @ if is_some may_hash then [ { eexpr = TConst(TInt (get may_hash)); etype = basic.tint; epos = pos } ] else []
  1936. in
  1937. let args = first_args @ match is_float, may_set with
  1938. | true, Some(set) ->
  1939. [ if should_cast then mk_cast basic.tfloat set else set ]
  1940. | false, Some(set) ->
  1941. [ set ]
  1942. | _ ->
  1943. [ is_unsafe ]
  1944. in
  1945. let call = { main_expr with eexpr = TCall(infer,args) } in
  1946. let call = if is_float && should_cast then mk_cast main_expr.etype call else call in
  1947. call
  1948. in
  1949. let rcf_on_call_field ecall field_expr field may_hash args =
  1950. let infer = mk_static_field_access_infer runtime_cl "callField" field_expr.epos [] in
  1951. let hash_arg = match may_hash with
  1952. | None -> []
  1953. | Some h -> [ { eexpr = TConst(TInt h); etype = basic.tint; epos = field_expr.epos } ]
  1954. in
  1955. let arr_call = if args <> [] then
  1956. { eexpr = TArrayDecl args; etype = basic.tarray t_dynamic; epos = ecall.epos }
  1957. else
  1958. null (basic.tarray t_dynamic) ecall.epos
  1959. in
  1960. let call_args =
  1961. [field_expr; { field_expr with eexpr = TConst(TString field); etype = basic.tstring } ]
  1962. @ hash_arg
  1963. @ [ arr_call ]
  1964. in
  1965. mk_cast ecall.etype { ecall with eexpr = TCall(infer, call_args); etype = t_dynamic }
  1966. in
  1967. let rcf_ctx =
  1968. ReflectionCFs.new_ctx
  1969. gen
  1970. closure_t
  1971. object_iface
  1972. false
  1973. rcf_on_getset_field
  1974. rcf_on_call_field
  1975. (fun hash hash_array length -> { hash with eexpr = TCall(rcf_static_find, [hash; hash_array; length]); etype=basic.tint })
  1976. (fun hash -> hash)
  1977. (fun hash_array length pos value ->
  1978. { hash_array with
  1979. eexpr = TBinop(OpAssign,
  1980. hash_array,
  1981. mk (TCall(rcf_static_insert value.etype, [hash_array; length; pos; value])) hash_array.etype hash_array.epos)
  1982. })
  1983. (fun hash_array length pos ->
  1984. let t = gen.gclasses.nativearray_type hash_array.etype in
  1985. { hash_array with eexpr = TCall(rcf_static_remove t, [hash_array; length; pos]); etype = gen.gcon.basic.tvoid }
  1986. )
  1987. false
  1988. in
  1989. ReflectionCFs.UniversalBaseClass.default_config gen (get_cl (get_type gen (["haxe";"lang"],"HxObject")) ) object_iface dynamic_object;
  1990. ReflectionCFs.configure_dynamic_field_access rcf_ctx false;
  1991. (* let closure_func = ReflectionCFs.implement_closure_cl rcf_ctx ( get_cl (get_type gen (["haxe";"lang"],"Closure")) ) in *)
  1992. let closure_cl = get_cl (get_type gen (["haxe";"lang"],"Closure")) in
  1993. let closure_func = ReflectionCFs.get_closure_func rcf_ctx closure_cl in
  1994. ReflectionCFs.implement_varargs_cl rcf_ctx ( get_cl (get_type gen (["haxe";"lang"], "VarArgsBase")) );
  1995. let slow_invoke = mk_static_field_access_infer (runtime_cl) "slowCallField" Ast.null_pos [] in
  1996. ReflectionCFs.configure rcf_ctx ~slow_invoke:(fun ethis efield eargs -> {
  1997. eexpr = TCall(slow_invoke, [ethis; efield; eargs]);
  1998. etype = t_dynamic;
  1999. epos = ethis.epos;
  2000. } ) object_iface;
  2001. let objdecl_fn = ReflectionCFs.implement_dynamic_object_ctor rcf_ctx dynamic_object in
  2002. ObjectDeclMap.configure gen (ObjectDeclMap.traverse gen objdecl_fn);
  2003. InitFunction.configure gen true true;
  2004. TArrayTransform.configure gen (TArrayTransform.default_implementation gen (
  2005. fun e _ ->
  2006. match e.eexpr with
  2007. | TArray ({ eexpr = TLocal { v_extra = Some( _ :: _, _) } }, _) -> (* captured transformation *)
  2008. false
  2009. | TArray(e1, e2) ->
  2010. ( match run_follow gen (follow e1.etype) with
  2011. | TInst({ cl_path = (["java"], "NativeArray") }, _) -> false
  2012. | _ -> true )
  2013. | _ -> assert false
  2014. ) "__get" "__set" );
  2015. let field_is_dynamic t field =
  2016. match field_access_esp gen (gen.greal_type t) field with
  2017. | FClassField (cl,p,_,_,_,t,_) ->
  2018. let p = change_param_type (TClassDecl cl) p in
  2019. is_dynamic (apply_params cl.cl_params p t)
  2020. | FEnumField _ -> false
  2021. | _ -> true
  2022. in
  2023. let is_type_param e = match follow e with
  2024. | TInst( { cl_kind = KTypeParameter _ },[]) -> true
  2025. | _ -> false
  2026. in
  2027. let is_dynamic_expr e =
  2028. is_dynamic e.etype || match e.eexpr with
  2029. | TField(tf, f) ->
  2030. field_is_dynamic tf.etype f
  2031. | _ ->
  2032. false
  2033. in
  2034. let may_nullable t = match gen.gfollow#run_f t with
  2035. | TType({ t_path = ([], "Null") }, [t]) ->
  2036. (match follow t with
  2037. | TInst({ cl_path = ([], "String") }, [])
  2038. | TAbstract ({ a_path = ([], "Float") },[])
  2039. | TInst({ cl_path = (["haxe"], "Int32")}, [] )
  2040. | TInst({ cl_path = (["haxe"], "Int64")}, [] )
  2041. | TAbstract ({ a_path = ([], "Int") },[])
  2042. | TAbstract ({ a_path = ([], "Bool") },[]) -> Some t
  2043. | t when is_java_basic_type t -> Some t
  2044. | _ -> None )
  2045. | _ -> None
  2046. in
  2047. let is_double t = like_float t && not (like_int t) in
  2048. let is_int t = like_int t in
  2049. DynamicOperators.configure gen
  2050. (DynamicOperators.abstract_implementation gen (fun e -> match e.eexpr with
  2051. | TBinop (Ast.OpEq, e1, e2) ->
  2052. is_dynamic e1.etype || is_dynamic e2.etype || is_type_param e1.etype || is_type_param e2.etype
  2053. | TBinop (Ast.OpAdd, e1, e2)
  2054. | TBinop (Ast.OpNotEq, e1, e2) -> is_dynamic e1.etype || is_dynamic e2.etype || is_type_param e1.etype || is_type_param e2.etype
  2055. | TBinop (Ast.OpLt, e1, e2)
  2056. | TBinop (Ast.OpLte, e1, e2)
  2057. | TBinop (Ast.OpGte, e1, e2)
  2058. | TBinop (Ast.OpGt, e1, e2) -> is_dynamic e.etype || is_dynamic_expr e1 || is_dynamic_expr e2 || is_string e1.etype || is_string e2.etype
  2059. | TBinop (_, e1, e2) -> is_dynamic e.etype || is_dynamic_expr e1 || is_dynamic_expr e2
  2060. | TUnop (_, _, e1) ->
  2061. is_dynamic_expr e1
  2062. | _ -> false)
  2063. (fun e1 e2 ->
  2064. let is_null e = match e.eexpr with | TConst(TNull) | TLocal({ v_name = "__undefined__" }) -> true | _ -> false in
  2065. match e1.eexpr, e2.eexpr with
  2066. | TConst c1, TConst c2 when is_null e1 || is_null e2 ->
  2067. { e1 with eexpr = TConst(TBool (c1 = c2)); etype = basic.tbool }
  2068. | _ when is_null e1 || is_null e2 && not (is_java_basic_type e1.etype || is_java_basic_type e2.etype) ->
  2069. { e1 with eexpr = TBinop(Ast.OpEq, e1, e2); etype = basic.tbool }
  2070. | _ ->
  2071. let is_ref = match follow e1.etype, follow e2.etype with
  2072. | TDynamic _, _
  2073. | _, TDynamic _
  2074. | TAbstract ({ a_path = ([], "Float") },[]) , _
  2075. | TInst( { cl_path = (["haxe"], "Int32") }, [] ), _
  2076. | TInst( { cl_path = (["haxe"], "Int64") }, [] ), _
  2077. | TAbstract ({ a_path = ([], "Int") },[]) , _
  2078. | TAbstract ({ a_path = ([], "Bool") },[]) , _
  2079. | _, TAbstract ({ a_path = ([], "Float") },[])
  2080. | _, TAbstract ({ a_path = ([], "Int") },[])
  2081. | _, TInst( { cl_path = (["haxe"], "Int32") }, [] )
  2082. | _, TInst( { cl_path = (["haxe"], "Int64") }, [] )
  2083. | _, TAbstract ({ a_path = ([], "Bool") },[])
  2084. | TInst( { cl_kind = KTypeParameter _ }, [] ), _
  2085. | _, TInst( { cl_kind = KTypeParameter _ }, [] ) -> false
  2086. | _, _ -> true
  2087. in
  2088. let static = mk_static_field_access_infer (runtime_cl) (if is_ref then "refEq" else "eq") e1.epos [] in
  2089. { eexpr = TCall(static, [e1; e2]); etype = gen.gcon.basic.tbool; epos=e1.epos }
  2090. )
  2091. (fun e e1 e2 ->
  2092. match may_nullable e1.etype, may_nullable e2.etype with
  2093. | Some t1, Some t2 ->
  2094. let t1, t2 = if is_string t1 || is_string t2 then
  2095. basic.tstring, basic.tstring
  2096. else if is_double t1 || is_double t2 then
  2097. basic.tfloat, basic.tfloat
  2098. else if is_int t1 || is_int t2 then
  2099. basic.tint, basic.tint
  2100. else t1, t2 in
  2101. { eexpr = TBinop(Ast.OpAdd, mk_cast t1 e1, mk_cast t2 e2); etype = e.etype; epos = e1.epos }
  2102. | _ ->
  2103. let static = mk_static_field_access_infer (runtime_cl) "plus" e1.epos [] in
  2104. mk_cast e.etype { eexpr = TCall(static, [e1; e2]); etype = t_dynamic; epos=e1.epos })
  2105. (fun e1 e2 ->
  2106. if is_string e1.etype then begin
  2107. { e1 with eexpr = TCall(mk_field_access gen e1 "compareTo" e1.epos, [ e2 ]); etype = gen.gcon.basic.tint }
  2108. end else begin
  2109. let static = mk_static_field_access_infer (runtime_cl) "compare" e1.epos [] in
  2110. { eexpr = TCall(static, [e1; e2]); etype = gen.gcon.basic.tint; epos=e1.epos }
  2111. end));
  2112. FilterClosures.configure gen (FilterClosures.traverse gen (fun e1 s -> true) closure_func);
  2113. let base_exception = get_cl (get_type gen (["java"; "lang"], "Throwable")) in
  2114. let base_exception_t = TInst(base_exception, []) in
  2115. let hx_exception = get_cl (get_type gen (["haxe";"lang"], "HaxeException")) in
  2116. let hx_exception_t = TInst(hx_exception, []) in
  2117. let rec is_exception t =
  2118. match follow t with
  2119. | TInst(cl,_) ->
  2120. if cl == base_exception then
  2121. true
  2122. else
  2123. (match cl.cl_super with | None -> false | Some (cl,arg) -> is_exception (TInst(cl,arg)))
  2124. | _ -> false
  2125. in
  2126. TryCatchWrapper.configure gen
  2127. (
  2128. TryCatchWrapper.traverse gen
  2129. (fun t -> not (is_exception (real_type t)))
  2130. (fun throwexpr expr ->
  2131. let wrap_static = mk_static_field_access (hx_exception) "wrap" (TFun([("obj",false,t_dynamic)], hx_exception_t)) expr.epos in
  2132. { throwexpr with eexpr = TThrow { expr with eexpr = TCall(wrap_static, [expr]); etype = hx_exception_t }; etype = gen.gcon.basic.tvoid }
  2133. )
  2134. (fun v_to_unwrap pos ->
  2135. let local = mk_cast hx_exception_t { eexpr = TLocal(v_to_unwrap); etype = v_to_unwrap.v_type; epos = pos } in
  2136. mk_field_access gen local "obj" pos
  2137. )
  2138. (fun rethrow ->
  2139. let wrap_static = mk_static_field_access (hx_exception) "wrap" (TFun([("obj",false,t_dynamic)], hx_exception_t)) rethrow.epos in
  2140. { rethrow with eexpr = TThrow { rethrow with eexpr = TCall(wrap_static, [rethrow]); etype = hx_exception_t }; }
  2141. )
  2142. (base_exception_t)
  2143. (hx_exception_t)
  2144. (fun v e ->
  2145. let exc_cl = get_cl (get_type gen (["haxe";"lang"],"Exceptions")) in
  2146. let exc_field = mk_static_field_access_infer exc_cl "setException" e.epos [] in
  2147. let esetstack = { eexpr = TCall(exc_field,[mk_local v e.epos]); etype = gen.gcon.basic.tvoid; epos = e.epos } in
  2148. Type.concat esetstack e;
  2149. )
  2150. );
  2151. let get_typeof e =
  2152. { e with eexpr = TCall( { eexpr = TLocal( alloc_var "__typeof__" t_dynamic ); etype = t_dynamic; epos = e.epos }, [e] ) }
  2153. in
  2154. ClassInstance.configure gen (ClassInstance.traverse gen (fun e mt -> get_typeof e));
  2155. (*let v = alloc_var "$type_param" t_dynamic in*)
  2156. TypeParams.configure gen (fun ecall efield params elist ->
  2157. { ecall with eexpr = TCall(efield, elist) }
  2158. );
  2159. CastDetect.configure gen (CastDetect.default_implementation gen ~native_string_cast:false (Some (TEnum(empty_e, []))) false);
  2160. (*FollowAll.configure gen;*)
  2161. SwitchToIf.configure gen (SwitchToIf.traverse gen (fun e ->
  2162. match e.eexpr with
  2163. | TSwitch(cond, cases, def) ->
  2164. (match gen.gfollow#run_f cond.etype with
  2165. | TInst( { cl_path = (["haxe"], "Int32") }, [] )
  2166. | TAbstract ({ a_path = ([], "Int") },[])
  2167. | TInst({ cl_path = ([], "String") },[]) ->
  2168. (List.exists (fun (c,_) ->
  2169. List.exists (fun expr -> match expr.eexpr with | TConst _ -> false | _ -> true ) c
  2170. ) cases)
  2171. | _ -> true
  2172. )
  2173. | _ -> assert false
  2174. ) true );
  2175. ExpressionUnwrap.configure gen (ExpressionUnwrap.traverse gen (fun e -> Some { eexpr = TVar(mk_temp gen "expr" e.etype, Some e); etype = gen.gcon.basic.tvoid; epos = e.epos }));
  2176. UnnecessaryCastsRemoval.configure gen;
  2177. IntDivisionSynf.configure gen (IntDivisionSynf.default_implementation gen true);
  2178. UnreachableCodeEliminationSynf.configure gen (UnreachableCodeEliminationSynf.traverse gen false true true true);
  2179. ArrayDeclSynf.configure gen (ArrayDeclSynf.default_implementation gen native_arr_cl);
  2180. let goto_special = alloc_var "__goto__" t_dynamic in
  2181. let label_special = alloc_var "__label__" t_dynamic in
  2182. SwitchBreakSynf.configure gen (SwitchBreakSynf.traverse gen
  2183. (fun e_loop n api ->
  2184. { e_loop with eexpr = TBlock( { eexpr = TCall( mk_local label_special e_loop.epos, [ mk_int gen n e_loop.epos ] ); etype = t_dynamic; epos = e_loop.epos } :: [e_loop] ) };
  2185. )
  2186. (fun e_break n api ->
  2187. { eexpr = TCall( mk_local goto_special e_break.epos, [ mk_int gen n e_break.epos ] ); etype = t_dynamic; epos = e_break.epos }
  2188. )
  2189. );
  2190. DefaultArguments.configure gen (DefaultArguments.traverse gen);
  2191. InterfaceMetas.configure gen;
  2192. JavaSpecificSynf.configure gen (JavaSpecificSynf.traverse gen runtime_cl);
  2193. JavaSpecificESynf.configure gen (JavaSpecificESynf.traverse gen runtime_cl);
  2194. (* add native String as a String superclass *)
  2195. let str_cl = match gen.gcon.basic.tstring with | TInst(cl,_) -> cl | _ -> assert false in
  2196. str_cl.cl_super <- Some (get_cl (get_type gen (["haxe";"lang"], "NativeString")), []);
  2197. let mkdir dir = if not (Sys.file_exists dir) then Unix.mkdir dir 0o755 in
  2198. mkdir gen.gcon.file;
  2199. mkdir (gen.gcon.file ^ "/src");
  2200. let out_files = ref [] in
  2201. (* add resources array *)
  2202. let res = ref [] in
  2203. Hashtbl.iter (fun name v ->
  2204. res := { eexpr = TConst(TString name); etype = gen.gcon.basic.tstring; epos = Ast.null_pos } :: !res;
  2205. let name = Codegen.escape_res_name name true in
  2206. let full_path = gen.gcon.file ^ "/src/" ^ name in
  2207. mkdir_from_path full_path;
  2208. let f = open_out_bin full_path in
  2209. output_string f v;
  2210. close_out f;
  2211. out_files := (unique_full_path full_path) :: !out_files
  2212. ) gen.gcon.resources;
  2213. (try
  2214. let c = get_cl (Hashtbl.find gen.gtypes (["haxe"], "Resource")) in
  2215. let cf = PMap.find "content" c.cl_statics in
  2216. cf.cf_expr <- Some ({ eexpr = TArrayDecl(!res); etype = gen.gcon.basic.tarray gen.gcon.basic.tstring; epos = Ast.null_pos })
  2217. with | Not_found -> ());
  2218. run_filters gen;
  2219. TypeParams.RenameTypeParameters.run gen;
  2220. let t = Common.timer "code generation" in
  2221. let parts = Str.split_delim (Str.regexp "[\\/]+") gen.gcon.file in
  2222. mkdir_recursive "" parts;
  2223. generate_modules_t gen "java" "src" change_path module_gen out_files;
  2224. if not (Common.defined gen.gcon Define.KeepOldOutput) then
  2225. clean_files (gen.gcon.file ^ "/src") !out_files gen.gcon.verbose;
  2226. let path_s_desc path = path_s path [] in
  2227. dump_descriptor gen ("hxjava_build.txt") path_s_desc (fun md -> path_s_desc (t_infos md).mt_path);
  2228. if ( not (Common.defined gen.gcon Define.NoCompilation) ) then begin
  2229. let old_dir = Sys.getcwd() in
  2230. Sys.chdir gen.gcon.file;
  2231. let cmd = "haxelib run hxjava hxjava_build.txt --haxe-version " ^ (string_of_int gen.gcon.version) ^ " --feature-level 1" in
  2232. print_endline cmd;
  2233. if gen.gcon.run_command cmd <> 0 then failwith "Build failed";
  2234. Sys.chdir old_dir;
  2235. end;
  2236. t()
  2237. (* end of configure function *)
  2238. let before_generate con =
  2239. let java_ver = try
  2240. int_of_string (PMap.find "java_ver" con.defines)
  2241. with | Not_found ->
  2242. Common.define_value con Define.JavaVer "7";
  2243. 7
  2244. in
  2245. if java_ver < 5 then failwith ("Java version is defined to target Java " ^ string_of_int java_ver ^ ", but the compiler can only output code to versions equal or superior to Java 5");
  2246. let rec loop i =
  2247. Common.raw_define con ("java" ^ (string_of_int i));
  2248. if i > 0 then loop (i - 1)
  2249. in
  2250. loop java_ver;
  2251. ()
  2252. let generate con =
  2253. let exists = ref false in
  2254. con.java_libs <- List.map (fun (file,std,close,la,gr) ->
  2255. if String.ends_with file "hxjava-std.jar" then begin
  2256. exists := true;
  2257. (file,true,close,la,gr)
  2258. end else
  2259. (file,std,close,la,gr)) con.java_libs;
  2260. if not !exists then
  2261. failwith "Your version of hxjava is outdated. Please update it by running: `haxelib update hxjava`";
  2262. let gen = new_ctx con in
  2263. gen.gallow_tp_dynamic_conversion <- true;
  2264. let basic = con.basic in
  2265. (* make the basic functions in java *)
  2266. let basic_fns =
  2267. [
  2268. mk_class_field "equals" (TFun(["obj",false,t_dynamic], basic.tbool)) true Ast.null_pos (Method MethNormal) [];
  2269. mk_class_field "toString" (TFun([], basic.tstring)) true Ast.null_pos (Method MethNormal) [];
  2270. mk_class_field "hashCode" (TFun([], basic.tint)) true Ast.null_pos (Method MethNormal) [];
  2271. mk_class_field "wait" (TFun([], basic.tvoid)) true Ast.null_pos (Method MethNormal) [];
  2272. mk_class_field "notify" (TFun([], basic.tvoid)) true Ast.null_pos (Method MethNormal) [];
  2273. mk_class_field "notifyAll" (TFun([], basic.tvoid)) true Ast.null_pos (Method MethNormal) [];
  2274. ] in
  2275. List.iter (fun cf -> gen.gbase_class_fields <- PMap.add cf.cf_name cf gen.gbase_class_fields) basic_fns;
  2276. (try
  2277. configure gen
  2278. with | TypeNotFound path -> con.error ("Error. Module '" ^ (path_s path) ^ "' is required and was not included in build.") Ast.null_pos);
  2279. debug_mode := false
  2280. (** Java lib *)
  2281. open JData
  2282. type java_lib_ctx = {
  2283. jcom : Common.context;
  2284. (* current tparams context *)
  2285. mutable jtparams : jtypes list;
  2286. }
  2287. exception ConversionError of string * pos
  2288. let error s p = raise (ConversionError (s, p))
  2289. let is_haxe_keyword = function
  2290. | "callback" | "cast" | "extern" | "function" | "in" | "typedef" | "using" | "var" | "untyped" | "inline" -> true
  2291. | _ -> false
  2292. let jname_to_hx name =
  2293. let name =
  2294. if name <> "" && (String.get name 0 < 'A' || String.get name 0 > 'Z') then
  2295. Char.escaped (Char.uppercase (String.get name 0)) ^ String.sub name 1 (String.length name - 1)
  2296. else
  2297. name
  2298. in
  2299. let name = String.concat "__" (String.nsplit name "_") in
  2300. String.map (function | '$' -> '_' | c -> c) name
  2301. let normalize_pack pack =
  2302. List.map (function
  2303. | "" -> ""
  2304. | str when String.get str 0 >= 'A' && String.get str 0 <= 'Z' ->
  2305. String.lowercase str
  2306. | str -> str
  2307. ) pack
  2308. let jpath_to_hx (pack,name) = match pack, name with
  2309. | ["haxe";"root"], name -> [], name
  2310. | "com" :: ("oracle" | "sun") :: _, _
  2311. | "javax" :: _, _
  2312. | "org" :: ("ietf" | "jcp" | "omg" | "w3c" | "xml") :: _, _
  2313. | "sun" :: _, _
  2314. | "sunw" :: _, _ -> "java" :: normalize_pack pack, jname_to_hx name
  2315. | pack, name -> normalize_pack pack, jname_to_hx name
  2316. let real_java_path ctx (pack,name) =
  2317. path_s (pack, name)
  2318. let lookup_jclass com path =
  2319. let path = jpath_to_hx path in
  2320. List.fold_right (fun (_,_,_,_,get_raw_class) acc ->
  2321. match acc with
  2322. | None -> get_raw_class path
  2323. | Some p -> Some p
  2324. ) com.java_libs None
  2325. let mk_type_path ctx path params =
  2326. let name, sub = try
  2327. let p, _ = String.split (snd path) "$" in
  2328. jname_to_hx p, Some (jname_to_hx (snd path))
  2329. with | Invalid_string ->
  2330. jname_to_hx (snd path), None
  2331. in
  2332. let pack = fst (jpath_to_hx path) in
  2333. let pack, sub, name = match path with
  2334. | [], ("Float" as c)
  2335. | [], ("Int" as c)
  2336. | [], ("Single" as c)
  2337. | [], ("Bool" as c)
  2338. | [], ("Dynamic" as c)
  2339. | [], ("Iterator" as c)
  2340. | [], ("ArrayAccess" as c)
  2341. | [], ("Iterable" as c) ->
  2342. [], Some c, "StdTypes"
  2343. | [], ("String" as c) ->
  2344. ["std"], None, c
  2345. | _ ->
  2346. pack, sub, name
  2347. in
  2348. CTPath {
  2349. tpackage = pack;
  2350. tname = name;
  2351. tparams = params;
  2352. tsub = sub;
  2353. }
  2354. let has_tparam name params = List.exists(fun (n,_,_) -> n = name) params
  2355. let rec convert_arg ctx p arg =
  2356. match arg with
  2357. | TAny | TType (WSuper, _) -> TPType (mk_type_path ctx ([], "Dynamic") [])
  2358. | TType (_, jsig) -> TPType (convert_signature ctx p jsig)
  2359. and convert_signature ctx p jsig =
  2360. match jsig with
  2361. | TByte -> mk_type_path ctx (["java"; "types"], "Int8") []
  2362. | TChar -> mk_type_path ctx (["java"; "types"], "Char16") []
  2363. | TDouble -> mk_type_path ctx ([], "Float") []
  2364. | TFloat -> mk_type_path ctx ([], "Single") []
  2365. | TInt -> mk_type_path ctx ([], "Int") []
  2366. | TLong -> mk_type_path ctx (["haxe"], "Int64") []
  2367. | TShort -> mk_type_path ctx (["java"; "types"], "Int16") []
  2368. | TBool -> mk_type_path ctx ([], "Bool") []
  2369. | TObject ( (["haxe";"root"], name), args ) -> mk_type_path ctx ([], name) (List.map (convert_arg ctx p) args)
  2370. (** nullable types *)
  2371. (* replaced from Null<Type> to the actual abstract type to fix #2738 *)
  2372. (* | TObject ( (["java";"lang"], "Integer"), [] ) -> mk_type_path ctx ([], "Null") [ TPType (mk_type_path ctx ([], "Int") []) ] *)
  2373. (* | TObject ( (["java";"lang"], "Double"), [] ) -> mk_type_path ctx ([], "Null") [ TPType (mk_type_path ctx ([], "Float") []) ] *)
  2374. (* | TObject ( (["java";"lang"], "Float"), [] ) -> mk_type_path ctx ([], "Null") [ TPType (mk_type_path ctx ([], "Single") []) ] *)
  2375. (* | TObject ( (["java";"lang"], "Boolean"), [] ) -> mk_type_path ctx ([], "Null") [ TPType (mk_type_path ctx ([], "Bool") []) ] *)
  2376. (* | TObject ( (["java";"lang"], "Byte"), [] ) -> mk_type_path ctx ([], "Null") [ TPType (mk_type_path ctx (["java";"types"], "Int8") []) ] *)
  2377. (* | TObject ( (["java";"lang"], "Character"), [] ) -> mk_type_path ctx ([], "Null") [ TPType (mk_type_path ctx (["java";"types"], "Char16") []) ] *)
  2378. (* | TObject ( (["java";"lang"], "Short"), [] ) -> mk_type_path ctx ([], "Null") [ TPType (mk_type_path ctx (["java";"types"], "Int16") []) ] *)
  2379. (* | TObject ( (["java";"lang"], "Long"), [] ) -> mk_type_path ctx ([], "Null") [ TPType (mk_type_path ctx (["haxe"], "Int64") []) ] *)
  2380. (** other std types *)
  2381. | TObject ( (["java";"lang"], "Object"), [] ) -> mk_type_path ctx ([], "Dynamic") []
  2382. | TObject ( (["java";"lang"], "String"), [] ) -> mk_type_path ctx ([], "String") []
  2383. | TObject ( (["java";"lang"], "Enum"), [_] ) -> mk_type_path ctx ([], "EnumValue") []
  2384. (** other types *)
  2385. | TObject ( path, [] ) ->
  2386. (match lookup_jclass ctx.jcom path with
  2387. | Some (jcl, _, _) -> mk_type_path ctx path (List.map (fun _ -> convert_arg ctx p TAny) jcl.ctypes)
  2388. | None -> mk_type_path ctx path [])
  2389. | TObject ( path, args ) -> mk_type_path ctx path (List.map (convert_arg ctx p) args)
  2390. | TObjectInner (pack, (name, params) :: inners) ->
  2391. let actual_param = match List.rev inners with
  2392. | (_, p) :: _ -> p
  2393. | _ -> assert false in
  2394. mk_type_path ctx (pack, name ^ "$" ^ String.concat "$" (List.map fst inners)) (List.map (fun param -> convert_arg ctx p param) actual_param)
  2395. | TObjectInner (pack, inners) -> assert false
  2396. | TArray (jsig, _) -> mk_type_path ctx (["java"], "NativeArray") [ TPType (convert_signature ctx p jsig) ]
  2397. | TMethod _ -> JReader.error "TMethod cannot be converted directly into Complex Type"
  2398. | TTypeParameter s -> (match ctx.jtparams with
  2399. | cur :: others ->
  2400. if has_tparam s cur then
  2401. mk_type_path ctx ([], s) []
  2402. else begin
  2403. if ctx.jcom.verbose && not(List.exists (has_tparam s) others) then print_endline ("Type parameter " ^ s ^ " was not found while building type!");
  2404. mk_type_path ctx ([], "Dynamic") []
  2405. end
  2406. | _ ->
  2407. if ctx.jcom.verbose then print_endline ("Empty type parameter stack!");
  2408. mk_type_path ctx ([], "Dynamic") [])
  2409. let convert_constant ctx p const =
  2410. Option.map_default (function
  2411. | ConstString s -> Some (EConst (String s), p)
  2412. | ConstInt i -> Some (EConst (Int (Printf.sprintf "%ld" i)), p)
  2413. | ConstFloat f | ConstDouble f -> Some (EConst (Float (Printf.sprintf "%E" f)), p)
  2414. | _ -> None) None const
  2415. let rec same_sig parent jsig =
  2416. match jsig with
  2417. | TObject (p,targs) -> parent = p || List.exists (function | TType (_,s) -> same_sig parent s | _ -> false) targs
  2418. | TObjectInner(p, ntargs) ->
  2419. parent = (p, String.concat "$" (List.map fst ntargs)) ||
  2420. List.exists (fun (_,targs) -> List.exists (function | TType(_,s) -> same_sig parent s | _ -> false) targs) ntargs
  2421. | TArray(s,_) -> same_sig parent s
  2422. | _ -> false
  2423. let convert_param ctx p parent param =
  2424. let name, constraints = match param with
  2425. | (name, Some extends_sig, implem_sig) ->
  2426. name, extends_sig :: implem_sig
  2427. | (name, None, implemem_sig) ->
  2428. name, implemem_sig
  2429. in
  2430. let constraints = List.map (fun s -> if same_sig parent s then (TObject( (["java";"lang"], "Object"), [])) else s) constraints in
  2431. {
  2432. tp_name = name;
  2433. tp_params = [];
  2434. tp_constraints = List.map (convert_signature ctx p) constraints;
  2435. }
  2436. let get_type_path ctx ct = match ct with | CTPath p -> p | _ -> assert false
  2437. let is_override field =
  2438. List.exists (function | AttrVisibleAnnotations [{ ann_type = TObject( (["java";"lang"], "Override"), _ ) }] -> true | _ -> false) field.jf_attributes
  2439. let mk_override field =
  2440. { field with jf_attributes = ((AttrVisibleAnnotations [{ ann_type = TObject( (["java";"lang"], "Override"), [] ); ann_elements = [] }]) :: field.jf_attributes) }
  2441. let del_override field =
  2442. { field with jf_attributes = List.filter (fun a -> not (is_override_attrib a)) field.jf_attributes }
  2443. let get_canonical ctx p pack name =
  2444. (Meta.JavaCanonical, [EConst (String (String.concat "." pack)), p; EConst (String name), p], p)
  2445. let convert_java_enum ctx p pe =
  2446. let meta = ref (get_canonical ctx p (fst pe.cpath) (snd pe.cpath) :: [Meta.Native, [EConst (String (real_java_path ctx pe.cpath) ), p], p ]) in
  2447. let data = ref [] in
  2448. List.iter (fun f ->
  2449. (* if List.mem JEnum f.jf_flags then *)
  2450. match f.jf_vmsignature with
  2451. | TObject( path, [] ) when path = pe.cpath && List.mem JStatic f.jf_flags && List.mem JFinal f.jf_flags ->
  2452. data := { ec_name = f.jf_name; ec_doc = None; ec_meta = []; ec_args = []; ec_pos = p; ec_params = []; ec_type = None; } :: !data;
  2453. | _ -> ()
  2454. ) pe.cfields;
  2455. EEnum {
  2456. d_name = jname_to_hx (snd pe.cpath);
  2457. d_doc = None;
  2458. d_params = []; (* enums never have type parameters *)
  2459. d_meta = !meta;
  2460. d_flags = [EExtern];
  2461. d_data = List.rev !data;
  2462. }
  2463. let convert_java_field ctx p jc field =
  2464. let p = { p with pfile = p.pfile ^" (" ^field.jf_name ^")" } in
  2465. let cff_doc = None in
  2466. let cff_pos = p in
  2467. let cff_meta = ref [] in
  2468. let cff_access = ref [] in
  2469. let cff_name = match field.jf_name with
  2470. | "<init>" -> "new"
  2471. | "<clinit>"-> raise Exit (* __init__ field *)
  2472. | name when String.length name > 5 ->
  2473. (match String.sub name 0 5 with
  2474. | "__hx_" | "this$" -> raise Exit
  2475. | _ -> name)
  2476. | name -> name
  2477. in
  2478. let jf_constant = ref field.jf_constant in
  2479. let readonly = ref false in
  2480. List.iter (function
  2481. | JPublic -> cff_access := APublic :: !cff_access
  2482. | JPrivate -> raise Exit (* private instances aren't useful on externs *)
  2483. | JProtected -> cff_access := APrivate :: !cff_access
  2484. | JStatic -> cff_access := AStatic :: !cff_access
  2485. | JFinal ->
  2486. cff_meta := (Meta.Final, [], p) :: !cff_meta;
  2487. (match field.jf_kind, field.jf_vmsignature, field.jf_constant with
  2488. | JKField, TObject _, _ ->
  2489. jf_constant := None
  2490. | JKField, _, Some _ ->
  2491. readonly := true;
  2492. jf_constant := None;
  2493. | _ -> jf_constant := None)
  2494. (* | JSynchronized -> cff_meta := (Meta.Synchronized, [], p) :: !cff_meta *)
  2495. | JVolatile -> cff_meta := (Meta.Volatile, [], p) :: !cff_meta
  2496. | JTransient -> cff_meta := (Meta.Transient, [], p) :: !cff_meta
  2497. (* | JVarArgs -> cff_meta := (Meta.VarArgs, [], p) :: !cff_meta *)
  2498. | _ -> ()
  2499. ) field.jf_flags;
  2500. List.iter (function
  2501. | AttrDeprecated when jc.cpath <> (["java";"util"],"Date") -> cff_meta := (Meta.Deprecated, [], p) :: !cff_meta
  2502. (* TODO: pass anotations as @:meta *)
  2503. | AttrVisibleAnnotations ann ->
  2504. List.iter (function
  2505. | { ann_type = TObject( (["java";"lang"], "Override"), [] ) } ->
  2506. cff_access := AOverride :: !cff_access
  2507. | _ -> ()
  2508. ) ann
  2509. | _ -> ()
  2510. ) field.jf_attributes;
  2511. List.iter (fun jsig ->
  2512. match convert_signature ctx p jsig with
  2513. | CTPath path ->
  2514. cff_meta := (Meta.Throws, [Ast.EConst (Ast.String (path_s (path.tpackage,path.tname))), p],p) :: !cff_meta
  2515. | _ -> ()
  2516. ) field.jf_throws;
  2517. let kind = match field.jf_kind with
  2518. | JKField when !readonly ->
  2519. FProp ("default", "null", Some (convert_signature ctx p field.jf_signature), None)
  2520. | JKField ->
  2521. FVar (Some (convert_signature ctx p field.jf_signature), None)
  2522. | JKMethod ->
  2523. match field.jf_signature with
  2524. | TMethod (args, ret) ->
  2525. let old_types = ctx.jtparams in
  2526. (match ctx.jtparams with
  2527. | c :: others -> ctx.jtparams <- (c @ field.jf_types) :: others
  2528. | [] -> ctx.jtparams <- field.jf_types :: []);
  2529. let i = ref 0 in
  2530. let args = List.map (fun s ->
  2531. incr i;
  2532. "param" ^ string_of_int !i, false, Some(convert_signature ctx p s), None
  2533. ) args in
  2534. let t = Option.map_default (convert_signature ctx p) (mk_type_path ctx ([], "Void") []) ret in
  2535. cff_meta := (Meta.Overload, [], p) :: !cff_meta;
  2536. let types = List.map (function
  2537. | (name, Some ext, impl) ->
  2538. {
  2539. tp_name = name;
  2540. tp_params = [];
  2541. tp_constraints = List.map (convert_signature ctx p) (ext :: impl);
  2542. }
  2543. | (name, None, impl) ->
  2544. {
  2545. tp_name = name;
  2546. tp_params = [];
  2547. tp_constraints = List.map (convert_signature ctx p) (impl);
  2548. }
  2549. ) field.jf_types in
  2550. ctx.jtparams <- old_types;
  2551. FFun ({
  2552. f_params = types;
  2553. f_args = args;
  2554. f_type = Some t;
  2555. f_expr = None
  2556. })
  2557. | _ -> error "Method signature was expected" p
  2558. in
  2559. let cff_name, cff_meta =
  2560. match String.get cff_name 0 with
  2561. | '%' ->
  2562. let name = (String.sub cff_name 1 (String.length cff_name - 1)) in
  2563. if not (is_haxe_keyword name) then
  2564. cff_meta := (Meta.Deprecated, [EConst(String(
  2565. "This static field `_" ^ name ^ "` is deprecated and will be removed in later versions. Please use `" ^ name ^ "` instead")
  2566. ),p], p) :: !cff_meta;
  2567. "_" ^ name,
  2568. (Meta.Native, [EConst (String (name) ), cff_pos], cff_pos) :: !cff_meta
  2569. | _ ->
  2570. match String.nsplit cff_name "$" with
  2571. | [ no_dollar ] ->
  2572. cff_name, !cff_meta
  2573. | parts ->
  2574. String.concat "_" parts,
  2575. (Meta.Native, [EConst (String (cff_name) ), cff_pos], cff_pos) :: !cff_meta
  2576. in
  2577. if PMap.mem "java_loader_debug" ctx.jcom.defines then
  2578. Printf.printf "\t%s%sfield %s : %s\n" (if List.mem AStatic !cff_access then "static " else "") (if List.mem AOverride !cff_access then "override " else "") cff_name (s_sig field.jf_signature);
  2579. {
  2580. cff_name = cff_name;
  2581. cff_doc = cff_doc;
  2582. cff_pos = cff_pos;
  2583. cff_meta = cff_meta;
  2584. cff_access = !cff_access;
  2585. cff_kind = kind
  2586. }
  2587. let rec japply_params params jsig = match params with
  2588. | [] -> jsig
  2589. | _ -> match jsig with
  2590. | TTypeParameter s -> (try
  2591. List.assoc s params
  2592. with | Not_found -> jsig)
  2593. | TObject(p,tl) ->
  2594. TObject(p, args params tl)
  2595. | TObjectInner(sl, stll) ->
  2596. TObjectInner(sl, List.map (fun (s,tl) -> (s, args params tl)) stll)
  2597. | TArray(s,io) ->
  2598. TArray(japply_params params s, io)
  2599. | TMethod(sl, sopt) ->
  2600. TMethod(List.map (japply_params params) sl, Option.map (japply_params params) sopt)
  2601. | _ -> jsig
  2602. and args params tl = match params with
  2603. | [] -> tl
  2604. | _ -> List.map (function
  2605. | TAny -> TAny
  2606. | TType(w,s) -> TType(w,japply_params params s)) tl
  2607. let mk_params jtypes = List.map (fun (s,_,_) -> (s,TTypeParameter s)) jtypes
  2608. let convert_java_class ctx p jc =
  2609. match List.mem JEnum jc.cflags with
  2610. | true -> (* is enum *)
  2611. [convert_java_enum ctx p jc]
  2612. | false ->
  2613. let flags = ref [HExtern] in
  2614. if PMap.mem "java_loader_debug" ctx.jcom.defines then begin
  2615. let sup = jc.csuper :: jc.cinterfaces in
  2616. print_endline ("converting " ^ (if List.mem JAbstract jc.cflags then "abstract " else "") ^ JData.path_s jc.cpath ^ " : " ^ (String.concat ", " (List.map s_sig sup)));
  2617. end;
  2618. (* todo: instead of JavaNative, use more specific definitions *)
  2619. let meta = ref [Meta.JavaNative, [], p; Meta.Native, [EConst (String (real_java_path ctx jc.cpath) ), p], p; get_canonical ctx p (fst jc.cpath) (snd jc.cpath)] in
  2620. let force_check = Common.defined ctx.jcom Define.ForceLibCheck in
  2621. if not force_check then
  2622. meta := (Meta.LibType,[],p) :: !meta;
  2623. let is_interface = ref false in
  2624. List.iter (fun f -> match f with
  2625. | JFinal -> meta := (Meta.Final, [], p) :: !meta
  2626. | JInterface ->
  2627. is_interface := true;
  2628. flags := HInterface :: !flags
  2629. | JAbstract -> meta := (Meta.Abstract, [], p) :: !meta
  2630. | JAnnotation -> meta := (Meta.Annotation, [], p) :: !meta
  2631. | _ -> ()
  2632. ) jc.cflags;
  2633. (match jc.csuper with
  2634. | TObject( (["java";"lang"], "Object"), _ ) -> ()
  2635. | TObject( (["haxe";"lang"], "HxObject"), _ ) -> meta := (Meta.HxGen,[],p) :: !meta
  2636. | _ -> flags := HExtends (get_type_path ctx (convert_signature ctx p jc.csuper)) :: !flags
  2637. );
  2638. List.iter (fun i ->
  2639. match i with
  2640. | TObject ( (["haxe";"lang"], "IHxObject"), _ ) -> meta := (Meta.HxGen,[],p) :: !meta
  2641. | _ -> flags :=
  2642. if !is_interface then
  2643. HExtends (get_type_path ctx (convert_signature ctx p i)) :: !flags
  2644. else
  2645. HImplements (get_type_path ctx (convert_signature ctx p i)) :: !flags
  2646. ) jc.cinterfaces;
  2647. let fields = ref [] in
  2648. let jfields = ref [] in
  2649. if jc.cpath <> (["java";"lang"], "CharSequence") then
  2650. List.iter (fun f ->
  2651. try
  2652. if !is_interface && List.mem JStatic f.jf_flags then
  2653. ()
  2654. else begin
  2655. fields := convert_java_field ctx p jc f :: !fields;
  2656. jfields := f :: !jfields
  2657. end
  2658. with
  2659. | Exit -> ()
  2660. ) (jc.cfields @ jc.cmethods);
  2661. (* make sure the throws types are imported correctly *)
  2662. let imports = List.concat (List.map (fun f ->
  2663. List.map (fun jsig ->
  2664. match convert_signature ctx p jsig with
  2665. | CTPath path ->
  2666. let pos = { p with pfile = p.pfile ^ " (" ^ f.jf_name ^" @:throws)" } in
  2667. EImport( List.map (fun s -> s,pos) (path.tpackage @ [path.tname]), INormal )
  2668. | _ -> assert false
  2669. ) f.jf_throws
  2670. ) jc.cmethods) in
  2671. (EClass {
  2672. d_name = jname_to_hx (snd jc.cpath);
  2673. d_doc = None;
  2674. d_params = List.map (convert_param ctx p jc.cpath) jc.ctypes;
  2675. d_meta = !meta;
  2676. d_flags = !flags;
  2677. d_data = !fields;
  2678. }) :: imports
  2679. let create_ctx com =
  2680. {
  2681. jcom = com;
  2682. jtparams = [];
  2683. }
  2684. let rec has_type_param = function
  2685. | TTypeParameter _ -> true
  2686. | TMethod (lst, opt) -> List.exists has_type_param lst || Option.map_default has_type_param false opt
  2687. | TArray (s,_) -> has_type_param s
  2688. | TObjectInner (_, stpl) -> List.exists (fun (_,sigs) -> List.exists has_type_param_arg sigs) stpl
  2689. | TObject(_, pl) -> List.exists has_type_param_arg pl
  2690. | _ -> false
  2691. and has_type_param_arg = function | TType(_,s) -> has_type_param s | _ -> false
  2692. let rec japply_params jparams jsig = match jparams with
  2693. | [] -> jsig
  2694. | _ ->
  2695. match jsig with
  2696. | TObject(path,p) ->
  2697. TObject(path, List.map (japply_params_tp jparams ) p)
  2698. | TObjectInner(sl,stargl) ->
  2699. TObjectInner(sl,List.map (fun (s,targ) -> (s, List.map (japply_params_tp jparams) targ)) stargl)
  2700. | TArray(jsig,io) ->
  2701. TArray(japply_params jparams jsig,io)
  2702. | TMethod(args,ret) ->
  2703. TMethod(List.map (japply_params jparams ) args, Option.map (japply_params jparams ) ret)
  2704. | TTypeParameter s -> (try
  2705. List.assoc s jparams
  2706. with | Not_found -> jsig)
  2707. | _ -> jsig
  2708. and japply_params_tp jparams jtype_argument = match jtype_argument with
  2709. | TAny -> TAny
  2710. | TType(w,jsig) -> TType(w,japply_params jparams jsig)
  2711. let mk_jparams jtypes params = match jtypes, params with
  2712. | [], [] -> []
  2713. | _, [] -> List.map (fun (s,_,_) -> s, TObject( (["java";"lang"], "Object"), [] ) ) jtypes
  2714. | _ -> List.map2 (fun (s,_,_) jt -> match jt with
  2715. | TAny -> s, TObject((["java";"lang"],"Object"),[])
  2716. | TType(_,jsig) -> s, jsig) jtypes params
  2717. let rec compatible_signature_arg ?arg_test f1 f2 =
  2718. let arg_test = match arg_test with
  2719. | None -> (fun _ _ -> true)
  2720. | Some a -> a
  2721. in
  2722. if f1 = f2 then
  2723. true
  2724. else match f1, f2 with
  2725. | TObject(p,a), TObject(p2,a2) -> p = p2 && arg_test a a2
  2726. | TObjectInner(sl, stal), TObjectInner(sl2, stal2) -> sl = sl2 && List.map fst stal = List.map fst stal2
  2727. | TArray(s,_) , TArray(s2,_) -> compatible_signature_arg s s2
  2728. | TTypeParameter t1 , TTypeParameter t2 -> t1 = t2
  2729. | _ -> false
  2730. let rec compatible_param p1 p2 = match p1, p2 with
  2731. | TType (_,s1), TType(_,s2) -> compatible_signature_arg ~arg_test:compatible_tparams s1 s2
  2732. | TAny, TType(_, TObject( (["java";"lang"],"Object"), _ )) -> true
  2733. | TType(_, TObject( (["java";"lang"],"Object"), _ )), TAny -> true
  2734. | _ -> false
  2735. and compatible_tparams p1 p2 = try match p1, p2 with
  2736. | [], [] -> true
  2737. | _, [] ->
  2738. let p2 = List.map (fun _ -> TAny) p1 in
  2739. List.for_all2 compatible_param p1 p2
  2740. | [], _ ->
  2741. let p1 = List.map (fun _ -> TAny) p2 in
  2742. List.for_all2 compatible_param p1 p2
  2743. | _, _ ->
  2744. List.for_all2 compatible_param p1 p2
  2745. with | Invalid_argument("List.for_all2") -> false
  2746. let get_adapted_sig f f2 = match f.jf_types with
  2747. | [] ->
  2748. f.jf_signature
  2749. | _ ->
  2750. let jparams = mk_jparams f.jf_types (List.map (fun (s,_,_) -> TType(WNone, TTypeParameter s)) f2.jf_types) in
  2751. japply_params jparams f.jf_signature
  2752. let compatible_methods f1 f2 =
  2753. if List.length f1.jf_types <> List.length f2.jf_types then
  2754. false
  2755. else match (get_adapted_sig f1 f2), f2.jf_signature with
  2756. | TMethod(a1,_), TMethod(a2,_) when List.length a1 = List.length a2 ->
  2757. List.for_all2 compatible_signature_arg a1 a2
  2758. | _ -> false
  2759. let jcl_from_jsig com jsig =
  2760. let path, params = match jsig with
  2761. | TObject(path, params) ->
  2762. path,params
  2763. | TObjectInner(sl, stll) ->
  2764. let last_params = ref [] in
  2765. let real_path = sl, String.concat "$" (List.map (fun (s,p) -> last_params := p; s) stll) in
  2766. real_path, !last_params
  2767. | _ -> raise Not_found
  2768. in
  2769. match lookup_jclass com path with
  2770. | None -> raise Not_found
  2771. | Some(c,_,_) -> c,params
  2772. let jclass_with_params com cls params = try
  2773. match cls.ctypes with
  2774. | [] -> cls
  2775. | _ ->
  2776. let jparams = mk_jparams cls.ctypes params in
  2777. { cls with
  2778. cfields = List.map (fun f -> { f with jf_signature = japply_params jparams f.jf_signature }) cls.cfields;
  2779. cmethods = List.map (fun f -> { f with jf_signature = japply_params jparams f.jf_signature }) cls.cmethods;
  2780. csuper = japply_params jparams cls.csuper;
  2781. cinterfaces = List.map (japply_params jparams) cls.cinterfaces;
  2782. }
  2783. with Invalid_argument("List.map2") ->
  2784. if com.verbose then prerr_endline ("Differing parameters for class: " ^ path_s cls.cpath);
  2785. cls
  2786. let is_object = function | TObject( (["java";"lang"], "Object"), [] ) -> true | _ -> false
  2787. let is_tobject = function | TObject _ | TObjectInner _ -> true | _ -> false
  2788. let simplify_args args =
  2789. if List.for_all (function | TAny -> true | _ -> false) args then [] else args
  2790. let compare_type com s1 s2 =
  2791. if s1 = s2 then
  2792. 0
  2793. else if not (is_tobject s1) then
  2794. if is_tobject s2 then (* Dynamic *)
  2795. 1
  2796. else if compatible_signature_arg s1 s2 then
  2797. 0
  2798. else
  2799. raise Exit
  2800. else if not (is_tobject s2) then
  2801. -1
  2802. else begin
  2803. let rec loop ?(first_error=true) s1 s2 : bool =
  2804. if is_object s1 then
  2805. s1 = s2
  2806. else if compatible_signature_arg s1 s2 then begin
  2807. let p1, p2 = match s1, s2 with
  2808. | TObject(_, p1), TObject(_,p2) ->
  2809. p1, p2
  2810. | TObjectInner(_, npl1), TObjectInner(_, npl2) ->
  2811. snd (List.hd (List.rev npl1)), snd (List.hd (List.rev npl2))
  2812. | _ -> assert false (* not tobject *)
  2813. in
  2814. let p1, p2 = simplify_args p1, simplify_args p2 in
  2815. let lp1 = List.length p1 in
  2816. let lp2 = List.length p2 in
  2817. if lp1 > lp2 then
  2818. true
  2819. else if lp2 > lp1 then
  2820. false
  2821. else begin
  2822. (* if compatible tparams, it's fine *)
  2823. if not (compatible_tparams p1 p2) then
  2824. raise Exit; (* meaning: found, but incompatible type parameters *)
  2825. true
  2826. end
  2827. end else try
  2828. let c, p = jcl_from_jsig com s1 in
  2829. let jparams = mk_jparams c.ctypes p in
  2830. let super = japply_params jparams c.csuper in
  2831. let implements = List.map (japply_params jparams) c.cinterfaces in
  2832. loop ~first_error:first_error super s2 || List.exists (fun super -> loop ~first_error:first_error super s2) implements
  2833. with | Not_found ->
  2834. prerr_endline ("-java-lib: The type " ^ (s_sig s1) ^ " is referred but was not found. Compilation may not occur correctly.");
  2835. prerr_endline "Did you forget to include a needed lib?";
  2836. if first_error then
  2837. not (loop ~first_error:false s2 s1)
  2838. else
  2839. false
  2840. in
  2841. if loop s1 s2 then
  2842. if loop s2 s1 then
  2843. 0
  2844. else
  2845. 1
  2846. else
  2847. if loop s2 s1 then
  2848. -1
  2849. else
  2850. -2
  2851. end
  2852. (* given a list of same overload functions, choose the best (or none) *)
  2853. let select_best com flist =
  2854. let rec loop cur_best = function
  2855. | [] ->
  2856. Some cur_best
  2857. | f :: flist -> match get_adapted_sig f cur_best, cur_best.jf_signature with
  2858. | TMethod(_,Some r), TMethod(_, Some r2) -> (try
  2859. match compare_type com r r2 with
  2860. | 0 -> (* same type - select any of them *)
  2861. loop cur_best flist
  2862. | 1 ->
  2863. loop f flist
  2864. | -1 ->
  2865. loop cur_best flist
  2866. | -2 -> (* error - no type is compatible *)
  2867. if com.verbose then prerr_endline (f.jf_name ^ ": The types " ^ (s_sig r) ^ " and " ^ (s_sig r2) ^ " are incompatible");
  2868. (* bet that the current best has "beaten" other types *)
  2869. loop cur_best flist
  2870. | _ -> assert false
  2871. with | Exit -> (* incompatible type parameters *)
  2872. (* error mode *)
  2873. if com.verbose then prerr_endline (f.jf_name ^ ": Incompatible argument return signatures: " ^ (s_sig r) ^ " and " ^ (s_sig r2));
  2874. None)
  2875. | TMethod _, _ -> (* select the method *)
  2876. loop f flist
  2877. | _ ->
  2878. loop cur_best flist
  2879. in
  2880. match loop (List.hd flist) (List.tl flist) with
  2881. | Some f ->
  2882. Some f
  2883. | None -> match List.filter (fun f -> not (is_override f)) flist with
  2884. (* error mode; take off all override methods *)
  2885. | [] -> None
  2886. | f :: [] -> Some f
  2887. | f :: flist -> Some f (* pick one *)
  2888. (**** begin normalize_jclass helpers ****)
  2889. let fix_overrides_jclass com cls =
  2890. let force_check = Common.defined com Define.ForceLibCheck in
  2891. let methods = if force_check then List.map (fun f -> del_override f) cls.cmethods else cls.cmethods in
  2892. let cmethods = methods in
  2893. let super_fields = [] in
  2894. let super_methods = [] in
  2895. let nonstatics = List.filter (fun f -> not (List.mem JStatic f.jf_flags)) (cls.cfields @ cls.cmethods) in
  2896. let is_pub = fun f -> List.exists (function | JPublic | JProtected -> true | _ -> false) f.jf_flags in
  2897. let cmethods, super_fields = if not (List.mem JInterface cls.cflags) then
  2898. List.filter is_pub cmethods,
  2899. List.filter is_pub super_fields
  2900. else
  2901. cmethods,super_fields
  2902. in
  2903. let rec loop cls super_methods super_fields cmethods nonstatics = try
  2904. match cls.csuper with
  2905. | TObject((["java";"lang"],"Object"),_) ->
  2906. super_methods,super_fields,cmethods,nonstatics
  2907. | _ ->
  2908. let cls, params = jcl_from_jsig com cls.csuper in
  2909. let cls = jclass_with_params com cls params in
  2910. let nonstatics = (List.filter (fun f -> (List.mem JStatic f.jf_flags)) (cls.cfields @ cls.cmethods)) @ nonstatics in
  2911. let super_methods = cls.cmethods @ super_methods in
  2912. let super_fields = cls.cfields @ super_fields in
  2913. let cmethods = if force_check then begin
  2914. let overriden = ref [] in
  2915. let cmethods = List.map (fun jm ->
  2916. (* TODO rewrite/standardize empty spaces *)
  2917. if not (is_override jm) && not (List.mem JStatic jm.jf_flags) && List.exists (fun msup ->
  2918. let ret = msup.jf_name = jm.jf_name && not(List.mem JStatic msup.jf_flags) && compatible_methods msup jm in
  2919. if ret then begin
  2920. let f = mk_override msup in
  2921. overriden := { f with jf_flags = jm.jf_flags } :: !overriden
  2922. end;
  2923. ret
  2924. ) cls.cmethods then
  2925. mk_override jm
  2926. else
  2927. jm
  2928. ) cmethods in
  2929. !overriden @ cmethods
  2930. end else
  2931. cmethods
  2932. in
  2933. loop cls super_methods super_fields cmethods nonstatics
  2934. with | Not_found ->
  2935. super_methods,super_fields,cmethods,nonstatics
  2936. in
  2937. loop cls super_methods super_fields cmethods nonstatics
  2938. let normalize_jclass com cls =
  2939. (* after adding the noCheck metadata, this option will annotate what changes were needed *)
  2940. (* and that are now deprecated *)
  2941. let force_check = Common.defined com Define.ForceLibCheck in
  2942. (* fix overrides *)
  2943. let super_methods, super_fields, cmethods, nonstatics = fix_overrides_jclass com cls in
  2944. let all_methods = cmethods @ super_methods in
  2945. (* look for interfaces and add missing implementations (may happen on abstracts or by vmsig differences *)
  2946. (* (libType): even with libType enabled, we need to add these missing fields - otherwise we won't be able to use them from Haxe *)
  2947. let added_interface_fields = ref [] in
  2948. let rec loop_interface abstract cls iface = try
  2949. match iface with
  2950. | TObject ((["java";"lang"],"Object"), _) -> ()
  2951. | TObject (path,_) when path = cls.cpath -> ()
  2952. | _ ->
  2953. let cif, params = jcl_from_jsig com iface in
  2954. let cif = jclass_with_params com cif params in
  2955. List.iter (fun jf ->
  2956. if not(List.mem JStatic jf.jf_flags) && not (List.exists (fun jf2 -> jf.jf_name = jf2.jf_name && not (List.mem JStatic jf2.jf_flags) && jf.jf_signature = jf2.jf_signature) all_methods) then begin
  2957. let jf = if abstract && force_check then del_override jf else jf in
  2958. let jf = { jf with jf_flags = JPublic :: jf.jf_flags } in (* interfaces implementations are always public *)
  2959. added_interface_fields := jf :: !added_interface_fields;
  2960. end
  2961. ) cif.cmethods;
  2962. (* we don't need to loop again in the interface unless we are in an abstract class, since these interfaces are already normalized *)
  2963. if abstract then List.iter (loop_interface abstract cif) cif.cinterfaces;
  2964. with Not_found -> ()
  2965. in
  2966. List.iter (loop_interface (List.mem JAbstract cls.cflags) cls) cls.cinterfaces;
  2967. let nonstatics = !added_interface_fields @ nonstatics in
  2968. let cmethods = !added_interface_fields @ cmethods in
  2969. (* for each added field in the interface, lookup in super_methods possible methods to include *)
  2970. (* so we can choose the better method still *)
  2971. let cmethods = if not force_check then
  2972. cmethods
  2973. else
  2974. List.fold_left (fun cmethods im ->
  2975. (* see if any of the added_interface_fields need to be declared as override *)
  2976. let f = List.find_all (fun jf -> jf.jf_name = im.jf_name && compatible_methods jf im) super_methods in
  2977. let f = List.map mk_override f in
  2978. f @ cmethods
  2979. ) cmethods !added_interface_fields;
  2980. in
  2981. (* take off equals, hashCode and toString from interface *)
  2982. let cmethods = if List.mem JInterface cls.cflags then List.filter (fun jf -> match jf.jf_name, jf.jf_vmsignature with
  2983. | "equals", TMethod([TObject( (["java";"lang"],"Object"), _)],_)
  2984. | "hashCode", TMethod([], _)
  2985. | "toString", TMethod([], _) -> false
  2986. | _ -> true
  2987. ) cmethods
  2988. else
  2989. cmethods
  2990. in
  2991. (* change field name to not collide with haxe keywords and with static/non-static members *)
  2992. let fold_field acc f =
  2993. let change, both = match f.jf_name with
  2994. | _ when List.mem JStatic f.jf_flags && List.exists (fun f2 -> f.jf_name = f2.jf_name) nonstatics -> true, true
  2995. | _ -> is_haxe_keyword f.jf_name, false
  2996. in
  2997. let f2 = if change then
  2998. { f with jf_name = "%" ^ f.jf_name }
  2999. else
  3000. f
  3001. in
  3002. if both then f :: f2 :: acc else f2 :: acc
  3003. in
  3004. (* change static fields that have the same name as methods *)
  3005. let cfields = List.fold_left fold_field [] cls.cfields in
  3006. let cmethods = List.fold_left fold_field [] cmethods in
  3007. (* take off variable fields that have the same name as methods *)
  3008. (* and take off variables that already have been declared *)
  3009. let filter_field f f2 = f != f2 && (List.mem JStatic f.jf_flags = List.mem JStatic f2.jf_flags) && f.jf_name = f2.jf_name && f2.jf_kind <> f.jf_kind in
  3010. let cfields = List.filter (fun f ->
  3011. if List.mem JStatic f.jf_flags then
  3012. not (List.exists (filter_field f) cmethods)
  3013. else
  3014. not (List.exists (filter_field f) nonstatics) && not (List.exists (fun f2 -> f != f2 && f.jf_name = f2.jf_name && not (List.mem JStatic f2.jf_flags)) super_fields) ) cfields
  3015. in
  3016. (* now filter any method that clashes with a field - on a superclass *)
  3017. let cmethods = if force_check then List.filter (fun f ->
  3018. if List.mem JStatic f.jf_flags then
  3019. true
  3020. else
  3021. not (List.exists (filter_field f) super_fields) ) cmethods
  3022. else
  3023. cmethods
  3024. in
  3025. (* removing duplicate fields. They are there because of return type covariance in Java *)
  3026. (* Also, if a method overrides a previous definition, and changes a type parameters' variance, *)
  3027. (* we will take it off *)
  3028. (* this means that some rare codes will never compile on Haxe, but unless Haxe adds variance support *)
  3029. (* I can't see how this can be any different *)
  3030. let rec loop acc = function
  3031. | [] -> acc
  3032. | f :: cmeths ->
  3033. match List.partition (fun f2 -> f.jf_name = f2.jf_name && compatible_methods f f2) cmeths with
  3034. | [], cmeths ->
  3035. loop (f :: acc) cmeths
  3036. | flist, cmeths -> match select_best com (f :: flist) with
  3037. | None ->
  3038. loop acc cmeths
  3039. | Some f ->
  3040. loop (f :: acc) cmeths
  3041. in
  3042. (* last pass: take off all cfields that are internal / private (they won't be accessible anyway) *)
  3043. let cfields = List.filter(fun f -> List.exists (fun f -> f = JPublic || f = JProtected) f.jf_flags) cfields in
  3044. let cmethods = loop [] cmethods in
  3045. { cls with cfields = cfields; cmethods = cmethods }
  3046. (**** end normalize_jclass helpers ****)
  3047. let get_classes_zip zip =
  3048. let ret = ref [] in
  3049. List.iter (function
  3050. | { Zip.is_directory = false; Zip.filename = f } when (String.sub (String.uncapitalize f) (String.length f - 6) 6) = ".class" ->
  3051. (match List.rev (String.nsplit f "/") with
  3052. | clsname :: pack ->
  3053. if not (String.contains clsname '$') then begin
  3054. let path = jpath_to_hx (List.rev pack, String.sub clsname 0 (String.length clsname - 6)) in
  3055. ret := path :: !ret
  3056. end
  3057. | _ ->
  3058. ret := ([], jname_to_hx f) :: !ret)
  3059. | _ -> ()
  3060. ) (Zip.entries zip);
  3061. !ret
  3062. let add_java_lib com file std =
  3063. let file = if Sys.file_exists file then
  3064. file
  3065. else try Common.find_file com file with
  3066. | Not_found -> try Common.find_file com (file ^ ".jar") with
  3067. | Not_found ->
  3068. failwith ("Java lib " ^ file ^ " not found")
  3069. in
  3070. let hxpack_to_jpack = Hashtbl.create 16 in
  3071. let get_raw_class, close, list_all_files =
  3072. (* check if it is a directory or jar file *)
  3073. match (Unix.stat file).st_kind with
  3074. | S_DIR -> (* open classes directly from directory *)
  3075. let all = ref [] in
  3076. let rec iter_files pack dir path = try
  3077. let file = Unix.readdir dir in
  3078. let filepath = path ^ "/" ^ file in
  3079. (if String.ends_with file ".class" then
  3080. let file = String.sub file 0 (String.length file - 6) in
  3081. let path = jpath_to_hx (pack,file) in
  3082. all := path :: !all;
  3083. Hashtbl.add hxpack_to_jpack path (pack,file)
  3084. else if (Unix.stat filepath).st_kind = S_DIR && file <> "." && file <> ".." then
  3085. let pack = pack @ [file] in
  3086. iter_files (pack) (Unix.opendir filepath) filepath);
  3087. iter_files pack dir path
  3088. with | End_of_file | Unix.Unix_error _ ->
  3089. Unix.closedir dir
  3090. in
  3091. iter_files [] (Unix.opendir file) file;
  3092. let all = !all in
  3093. (fun (pack, name) ->
  3094. let real_path = file ^ "/" ^ (String.concat "/" pack) ^ "/" ^ (name ^ ".class") in
  3095. try
  3096. let data = Std.input_file ~bin:true real_path in
  3097. Some(JReader.parse_class (IO.input_string data), real_path, real_path)
  3098. with
  3099. | _ -> None), (fun () -> ()), (fun () -> all)
  3100. | _ -> (* open zip file *)
  3101. let closed = ref false in
  3102. let zip = ref (Zip.open_in file) in
  3103. let check_open () =
  3104. if !closed then begin
  3105. prerr_endline ("JAR file " ^ file ^ " already closed"); (* if this happens, find when *)
  3106. zip := Zip.open_in file;
  3107. closed := false
  3108. end
  3109. in
  3110. List.iter (function
  3111. | { Zip.is_directory = false; Zip.filename = filename } when String.ends_with filename ".class" ->
  3112. let pack = String.nsplit filename "/" in
  3113. (match List.rev pack with
  3114. | [] -> ()
  3115. | name :: pack ->
  3116. let name = String.sub name 0 (String.length name - 6) in
  3117. let pack = List.rev pack in
  3118. Hashtbl.add hxpack_to_jpack (jpath_to_hx (pack,name)) (pack,name))
  3119. | _ -> ()
  3120. ) (Zip.entries !zip);
  3121. (fun (pack, name) ->
  3122. check_open();
  3123. try
  3124. let location = (String.concat "/" (pack @ [name]) ^ ".class") in
  3125. let entry = Zip.find_entry !zip location in
  3126. let data = Zip.read_entry !zip entry in
  3127. Some(JReader.parse_class (IO.input_string data), file, file ^ "@" ^ location)
  3128. with
  3129. | Not_found ->
  3130. None),
  3131. (fun () -> if not !closed then begin closed := true; Zip.close_in !zip end),
  3132. (fun () -> check_open(); get_classes_zip !zip)
  3133. in
  3134. let cached_types = Hashtbl.create 12 in
  3135. let get_raw_class path =
  3136. try
  3137. Hashtbl.find cached_types path
  3138. with | Not_found -> try
  3139. let pack, name = Hashtbl.find hxpack_to_jpack path in
  3140. let try_file (pack,name) =
  3141. match get_raw_class (pack,name) with
  3142. | None ->
  3143. Hashtbl.add cached_types path None;
  3144. None
  3145. | Some (i, p1, p2) ->
  3146. Hashtbl.add cached_types path (Some(i,p1,p2)); (* type loop normalization *)
  3147. let ret = Some (normalize_jclass com i, p1, p2) in
  3148. Hashtbl.replace cached_types path ret;
  3149. ret
  3150. in
  3151. try_file (pack,name)
  3152. with Not_found ->
  3153. None
  3154. in
  3155. let replace_canonical_name p pack name_original name_replace decl =
  3156. let mk_meta name = (Meta.JavaCanonical, [EConst (String (String.concat "." pack)), p; EConst(String name), p], p) in
  3157. let add_meta name metas =
  3158. if Meta.has Meta.JavaCanonical metas then
  3159. List.map (function
  3160. | (Meta.JavaCanonical,[EConst (String cpack), _; EConst(String cname), _],_) ->
  3161. let did_replace,name = String.replace cname name_original name_replace in
  3162. if not did_replace then print_endline (cname ^ " -> " ^ name_original ^ " -> " ^ name_replace);
  3163. mk_meta name
  3164. | m -> m
  3165. ) metas
  3166. else
  3167. mk_meta name :: metas
  3168. in
  3169. match decl with
  3170. | EClass c ->
  3171. EClass { c with d_meta = add_meta c.d_name c.d_meta }
  3172. | EEnum e ->
  3173. EEnum { e with d_meta = add_meta e.d_name e.d_meta }
  3174. | EAbstract a ->
  3175. EAbstract { a with d_meta = add_meta a.d_name a.d_meta }
  3176. | d -> d
  3177. in
  3178. let rec build ctx path p types =
  3179. try
  3180. if List.mem path !types then
  3181. None
  3182. else begin
  3183. types := path :: !types;
  3184. match get_raw_class path, path with
  3185. | None, ([], c) -> build ctx (["haxe";"root"], c) p types
  3186. | None, _ -> None
  3187. | Some (cls, real_path, pos_path), _ ->
  3188. if com.verbose then print_endline ("Parsed Java class " ^ (path_s cls.cpath));
  3189. let old_types = ctx.jtparams in
  3190. ctx.jtparams <- cls.ctypes :: ctx.jtparams;
  3191. let pos = { pfile = pos_path; pmin = 0; pmax = 0; } in
  3192. let pack = match fst path with | ["haxe";"root"] -> [] | p -> p in
  3193. let ppath = Hashtbl.find hxpack_to_jpack path in
  3194. let inner = List.fold_left (fun acc (path,out,_,_) ->
  3195. let path = jpath_to_hx path in
  3196. (if out <> Some ppath then
  3197. acc
  3198. else match build ctx path p types with
  3199. | Some(_,(_, classes)) ->
  3200. let base = snd ppath ^ "$" in
  3201. (List.map (fun (def,p) ->
  3202. replace_canonical_name p (fst ppath) base (snd ppath ^ ".") def, p) classes) @ acc
  3203. | _ -> acc);
  3204. ) [] cls.cinner_types in
  3205. (* add _Statics class *)
  3206. let inner = try
  3207. if not (List.mem JInterface cls.cflags) then raise Not_found;
  3208. let smethods = List.filter (fun f -> List.mem JStatic f.jf_flags) cls.cmethods in
  3209. let sfields = List.filter (fun f -> List.mem JStatic f.jf_flags) cls.cfields in
  3210. if not (smethods <> [] || sfields <> []) then raise Not_found;
  3211. let obj = TObject( (["java";"lang"],"Object"), []) in
  3212. let ncls = convert_java_class ctx pos { cls with cmethods = smethods; cfields = sfields; cflags = []; csuper = obj; cinterfaces = []; cinner_types = []; ctypes = [] } in
  3213. match ncls with
  3214. | EClass c :: imports ->
  3215. (EClass { c with d_name = c.d_name ^ "_Statics" }, pos) :: inner @ List.map (fun i -> i,pos) imports
  3216. | _ -> assert false
  3217. with | Not_found ->
  3218. inner
  3219. in
  3220. let inner_alias = ref SS.empty in
  3221. List.iter (fun x ->
  3222. match fst x with
  3223. | EClass c ->
  3224. inner_alias := SS.add c.d_name !inner_alias;
  3225. | _ -> ()
  3226. ) inner;
  3227. let alias_list = ref [] in
  3228. List.iter (fun x ->
  3229. match x with
  3230. | (EClass c, pos) -> begin
  3231. let parts = String.nsplit c.d_name "_24" in
  3232. match parts with
  3233. | _ :: _ ->
  3234. let alias_name = String.concat "_" parts in
  3235. if (not (SS.mem alias_name !inner_alias)) && (not (String.exists (snd path) "_24")) then begin
  3236. let alias_def = ETypedef {
  3237. d_name = alias_name;
  3238. d_doc = None;
  3239. d_params = c.d_params;
  3240. d_meta = [];
  3241. d_flags = [];
  3242. d_data = CTPath {
  3243. tpackage = pack;
  3244. tname = snd path;
  3245. tparams = List.map (fun tp ->
  3246. TPType (CTPath {
  3247. tpackage = [];
  3248. tname = tp.tp_name;
  3249. tparams = [];
  3250. tsub = None;
  3251. })
  3252. ) c.d_params;
  3253. tsub = Some(c.d_name);
  3254. };
  3255. } in
  3256. inner_alias := SS.add alias_name !inner_alias;
  3257. alias_list := (alias_def, pos) :: !alias_list;
  3258. end
  3259. | _ -> ()
  3260. end
  3261. | _ -> ()
  3262. ) inner;
  3263. let inner = List.concat [!alias_list ; inner] in
  3264. let classes = List.map (fun t -> t,pos) (convert_java_class ctx pos cls) in
  3265. let imports, defs = List.partition (function | (EImport(_),_) -> true | _ -> false) (classes @ inner) in
  3266. let ret = Some ( real_path, (pack, imports @ defs) ) in
  3267. ctx.jtparams <- old_types;
  3268. ret
  3269. end
  3270. with
  3271. | JReader.Error_message msg ->
  3272. prerr_endline ("Class reader failed: " ^ msg);
  3273. None
  3274. | e ->
  3275. if com.verbose then begin
  3276. (* prerr_endline (Printexc.get_backtrace ()); requires ocaml 3.11 *)
  3277. prerr_endline (Printexc.to_string e)
  3278. end;
  3279. None
  3280. in
  3281. let build path p = build (create_ctx com) path p (ref [["java";"lang"], "String"]) in
  3282. let cached_files = ref None in
  3283. let list_all_files () = match !cached_files with
  3284. | None ->
  3285. let ret = list_all_files () in
  3286. cached_files := Some ret;
  3287. ret
  3288. | Some r -> r
  3289. in
  3290. (* TODO: add_dependency m mdep *)
  3291. com.load_extern_type <- com.load_extern_type @ [build];
  3292. com.java_libs <- (file, std, close, list_all_files, get_raw_class) :: com.java_libs