genjava.ml 126 KB

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