genjava.ml 128 KB

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