gencpp.ml 211 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380
  1. (*
  2. * Copyright (C)2005-2013 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. *)
  22. open Ast
  23. open Type
  24. open Common
  25. let unsupported p = error "This expression cannot be generated to Cpp" p
  26. (*
  27. Generators do not care about non-core-type abstracts, so let us follow them
  28. away by default.
  29. *)
  30. let follow = Abstract.follow_with_abstracts
  31. (*
  32. Code for generating source files.
  33. It manages creating diretories, indents, blocks and only modifying files
  34. when the content changes.
  35. *)
  36. (*
  37. A class_path is made from a package (array of strings) and a class name.
  38. Join these together, inclding a separator. eg, "/" for includes : pack1/pack2/Name or "::"
  39. for namespace "pack1::pack2::Name"
  40. *)
  41. let join_class_path path separator =
  42. let result = match fst path, snd path with
  43. | [], s -> s
  44. | el, s -> String.concat separator el ^ separator ^ s in
  45. if (String.contains result '+') then begin
  46. let idx = String.index result '+' in
  47. (String.sub result 0 idx) ^ (String.sub result (idx+1) ((String.length result) - idx -1 ) )
  48. end else
  49. result;;
  50. (* The internal classes are implemented by the core hxcpp system, so the cpp
  51. classes should not be generated *)
  52. let is_internal_class = function
  53. | ([],"Int") | ([],"Void") | ([],"String") | ([], "Null") | ([], "Float")
  54. | ([],"Array") | ([], "Class") | ([], "Enum") | ([], "Bool")
  55. | ([], "Dynamic") | ([], "ArrayAccess") | (["cpp"], "FastIterator")
  56. | (["cpp"],"Pointer") | (["cpp"],"ConstPointer")
  57. | (["cpp"],"RawPointer") | (["cpp"],"RawConstPointer")
  58. | (["cpp"],"Function") -> true
  59. | ([],"Math") | (["haxe";"io"], "Unsigned_char__") -> true
  60. | (["cpp"],"Int8") | (["cpp"],"UInt8") | (["cpp"],"Char")
  61. | (["cpp"],"Int16") | (["cpp"],"UInt16")
  62. | (["cpp"],"Int32") | (["cpp"],"UInt32")
  63. | (["cpp"],"Int64") | (["cpp"],"UInt64")
  64. | (["cpp"],"Float32") | (["cpp"],"Float64") -> true
  65. | _ -> false;;
  66. let get_include_prefix common_ctx with_slash =
  67. try
  68. (Common.defined_value common_ctx Define.IncludePrefix) ^ (if with_slash then "/" else "")
  69. with
  70. Not_found -> ""
  71. ;;
  72. let should_prefix_include = function
  73. | x when is_internal_class x -> false
  74. | ([],"hxMath") -> true
  75. | _ -> false;;
  76. class source_writer common_ctx write_func close_func =
  77. object(this)
  78. val indent_str = "\t"
  79. val mutable indent = ""
  80. val mutable indents = []
  81. val mutable just_finished_block = false
  82. method close = close_func(); ()
  83. method write x = write_func x; just_finished_block <- false
  84. method indent_one = this#write indent_str
  85. method push_indent = indents <- indent_str::indents; indent <- String.concat "" indents
  86. method pop_indent = match indents with
  87. | h::tail -> indents <- tail; indent <- String.concat "" indents
  88. | [] -> indent <- "/*?*/";
  89. method write_i x = this#write (indent ^ x)
  90. method get_indent = indent
  91. method begin_block = this#write ("{\n"); this#push_indent
  92. method end_block = this#pop_indent; this#write_i "}\n"; just_finished_block <- true
  93. method end_block_line = this#pop_indent; this#write_i "}"; just_finished_block <- true
  94. method terminate_line = this#write (if just_finished_block then "" else ";\n")
  95. method add_include class_path =
  96. ( match class_path with
  97. | (["@verbatim"],file) -> this#write ("#include <" ^ file ^ ">\n");
  98. | _ ->
  99. let prefix = if should_prefix_include class_path then "" else get_include_prefix common_ctx true in
  100. this#write ("#ifndef INCLUDED_" ^ (join_class_path class_path "_") ^ "\n");
  101. this#write ("#include <" ^ prefix ^ (join_class_path class_path "/") ^ ".h>\n");
  102. this#write ("#endif\n")
  103. )
  104. end;;
  105. let file_source_writer common_ctx filename =
  106. let out_file = open_out filename in
  107. new source_writer common_ctx (output_string out_file) (fun ()-> close_out out_file);;
  108. let read_whole_file chan =
  109. Std.input_all chan;;
  110. (* The cached_source_writer will not write to the file if it has not changed,
  111. thus allowing the makefile dependencies to work correctly *)
  112. let cached_source_writer common_ctx filename =
  113. try
  114. let in_file = open_in filename in
  115. let old_contents = read_whole_file in_file in
  116. close_in in_file;
  117. let buffer = Buffer.create 0 in
  118. let add_buf str = Buffer.add_string buffer str in
  119. let close = fun () ->
  120. let contents = Buffer.contents buffer in
  121. if (not (contents=old_contents) ) then begin
  122. let out_file = open_out filename in
  123. output_string out_file contents;
  124. close_out out_file;
  125. end;
  126. in
  127. new source_writer common_ctx (add_buf) (close);
  128. with _ ->
  129. file_source_writer common_ctx filename;;
  130. let make_class_directories = Common.mkdir_recursive;;
  131. let make_base_directory dir =
  132. make_class_directories "" ( ( Str.split_delim (Str.regexp "[\\/]+") dir ) );;
  133. let new_source_file common_ctx base_dir sub_dir extension class_path =
  134. let include_prefix = get_include_prefix common_ctx true in
  135. let full_dir =
  136. if (sub_dir="include") && (include_prefix<>"") then begin
  137. let dir = match fst class_path with
  138. | [] -> base_dir ^ "/include/" ^ (get_include_prefix common_ctx false)
  139. | path -> base_dir ^ "/include/" ^ include_prefix ^ ( String.concat "/" path )
  140. in
  141. make_base_directory dir;
  142. dir
  143. end else begin
  144. make_class_directories base_dir ( sub_dir :: (fst class_path));
  145. base_dir ^ "/" ^ sub_dir ^ "/" ^ ( String.concat "/" (fst class_path) )
  146. end
  147. in
  148. cached_source_writer common_ctx (full_dir ^ "/" ^ ((snd class_path) ^ extension));;
  149. let source_file_extension common_ctx =
  150. try
  151. "." ^ (Common.defined_value common_ctx Define.FileExtension)
  152. with
  153. Not_found -> ".cpp"
  154. ;;
  155. let new_cpp_file common_ctx base_dir = new_source_file common_ctx base_dir "src" (source_file_extension common_ctx);;
  156. let new_header_file common_ctx base_dir =
  157. new_source_file common_ctx base_dir "include" ".h";;
  158. (* CPP code generation context *)
  159. type context =
  160. {
  161. mutable ctx_common : Common.context;
  162. mutable ctx_output : string -> unit;
  163. mutable ctx_dbgout : string -> unit;
  164. mutable ctx_writer : source_writer;
  165. mutable ctx_calling : bool;
  166. mutable ctx_assigning : bool;
  167. mutable ctx_return_from_block : bool;
  168. mutable ctx_tcall_expand_args : bool;
  169. (* This is for returning from the child nodes of TMatch, TSwitch && TTry *)
  170. mutable ctx_return_from_internal_node : bool;
  171. mutable ctx_debug_level : int;
  172. mutable ctx_real_this_ptr : bool;
  173. mutable ctx_real_void : bool;
  174. mutable ctx_dynamic_this_ptr : bool;
  175. mutable ctx_dump_src_pos : unit -> unit;
  176. mutable ctx_static_id_curr : int;
  177. mutable ctx_static_id_used : int;
  178. mutable ctx_static_id_depth : int;
  179. mutable ctx_switch_id : int;
  180. mutable ctx_class_name : string;
  181. mutable ctx_class_super_name : string;
  182. mutable ctx_local_function_args : (string,string) Hashtbl.t;
  183. mutable ctx_local_return_block_args : (string,string) Hashtbl.t;
  184. mutable ctx_class_member_types : (string,string) Hashtbl.t;
  185. mutable ctx_file_info : (string,string) PMap.t ref;
  186. mutable ctx_for_extern : bool;
  187. }
  188. let new_context common_ctx writer debug file_info =
  189. {
  190. ctx_common = common_ctx;
  191. ctx_writer = writer;
  192. ctx_output = (writer#write);
  193. ctx_dbgout = if debug>1 then (writer#write) else (fun _ -> ());
  194. ctx_calling = false;
  195. ctx_assigning = false;
  196. ctx_debug_level = debug;
  197. ctx_dump_src_pos = (fun() -> ());
  198. ctx_return_from_block = false;
  199. ctx_tcall_expand_args = false;
  200. ctx_return_from_internal_node = false;
  201. ctx_real_this_ptr = true;
  202. ctx_real_void = false;
  203. ctx_dynamic_this_ptr = false;
  204. ctx_static_id_curr = 0;
  205. ctx_static_id_used = 0;
  206. ctx_static_id_depth = 0;
  207. ctx_switch_id = 0;
  208. ctx_class_name = "";
  209. ctx_class_super_name = "";
  210. ctx_local_function_args = Hashtbl.create 0;
  211. ctx_local_return_block_args = Hashtbl.create 0;
  212. ctx_class_member_types = Hashtbl.create 0;
  213. ctx_file_info = file_info;
  214. ctx_for_extern = false;
  215. }
  216. let new_extern_context common_ctx writer debug file_info =
  217. let ctx = new_context common_ctx writer debug file_info in
  218. ctx.ctx_for_extern <- true;
  219. ctx
  220. ;;
  221. (* The internal header files are also defined in the hx/Object.h file, so you do
  222. #include them separately. However, Math classes has its
  223. own header file (under the hxcpp tree) so these should be included *)
  224. let include_class_header = function
  225. | ([],"@Main") -> false
  226. | ([],"Math") -> true
  227. | path -> not ( is_internal_class path )
  228. let is_cpp_class = function
  229. | ("cpp"::_ , _) -> true
  230. | ( [] , "EReg" ) -> true
  231. | ( ["haxe"] , "Log" ) -> true
  232. | _ -> false;;
  233. let is_scalar typename = match typename with
  234. | "int" | "unsigned int" | "signed int"
  235. | "char" | "unsigned char"
  236. | "short" | "unsigned short"
  237. | "float" | "double"
  238. | "bool" -> true
  239. | _ -> false
  240. ;;
  241. let is_block exp = match exp.eexpr with | TBlock _ -> true | _ -> false ;;
  242. let to_block expression =
  243. if is_block expression then expression else (mk_block expression);;
  244. (* todo - is this how it's done? *)
  245. let hash_keys hash =
  246. let key_list = ref [] in
  247. Hashtbl.iter (fun key value -> key_list := key :: !key_list ) hash;
  248. !key_list;;
  249. let pmap_keys pmap =
  250. let key_list = ref [] in
  251. PMap.iter (fun key _ -> key_list := key :: !key_list ) pmap;
  252. !key_list;;
  253. let pmap_values pmap =
  254. let value_list = ref [] in
  255. PMap.iter (fun _ value -> value_list := value :: !value_list ) pmap;
  256. !value_list;;
  257. (* The Hashtbl structure seems a little odd - but here is a helper function *)
  258. let hash_iterate hash visitor =
  259. let result = ref [] in
  260. Hashtbl.iter (fun key value -> result := (visitor key value) :: !result ) hash;
  261. !result
  262. (* Convert function names that can't be written in c++ ... *)
  263. let keyword_remap name =
  264. match name with
  265. | "int"
  266. | "auto" | "char" | "const" | "delete" | "double" | "Float" | "enum"
  267. | "extern" | "float" | "friend" | "goto" | "long" | "operator" | "protected"
  268. | "register" | "short" | "signed" | "sizeof" | "template" | "typedef"
  269. | "union" | "unsigned" | "void" | "volatile" | "or" | "and" | "xor" | "or_eq" | "not"
  270. | "and_eq" | "xor_eq" | "typeof" | "stdin" | "stdout" | "stderr" | "system"
  271. | "BIG_ENDIAN" | "LITTLE_ENDIAN" | "assert" | "NULL" | "wchar_t" | "EOF"
  272. | "bool" | "const_cast" | "dynamic_cast" | "explicit" | "export" | "mutable" | "namespace"
  273. | "reinterpret_cast" | "static_cast" | "typeid" | "typename" | "virtual"
  274. | "_Complex" | "INFINITY" | "NAN"
  275. | "struct" -> "_" ^ name
  276. | "asm" -> "_asm_"
  277. | x -> x
  278. ;;
  279. let remap_class_path class_path =
  280. (List.map keyword_remap (fst class_path)) , (snd class_path)
  281. ;;
  282. let join_class_path_remap path separator =
  283. match join_class_path (remap_class_path path) separator with
  284. | "Class" -> "hx::Class"
  285. | x -> x
  286. ;;
  287. let get_meta_string meta key =
  288. let rec loop = function
  289. | [] -> ""
  290. | (k,[Ast.EConst (Ast.String name),_],_) :: _ when k=key-> name
  291. | _ :: l -> loop l
  292. in
  293. loop meta
  294. ;;
  295. let has_meta_key meta key =
  296. List.exists (fun m -> match m with | (k,_,_) when k=key-> true | _ -> false ) meta
  297. ;;
  298. let get_field_access_meta field_access key =
  299. match field_access with
  300. | FInstance(_,_,class_field)
  301. | FStatic(_,class_field) -> get_meta_string class_field.cf_meta key
  302. | _ -> ""
  303. ;;
  304. let get_code meta key =
  305. let code = get_meta_string meta key in
  306. if (code<>"") then code ^ "\n" else code
  307. ;;
  308. (* Add include to source code *)
  309. let add_include writer class_path =
  310. writer#add_include class_path;;
  311. (* This gets the class include order correct. In the header files, we forward declare
  312. the class types so the header file does not have any undefined variables.
  313. In the cpp files, we include all the required header files, providing the actual
  314. types for everything. This way there is no problem with circular class references.
  315. *)
  316. let gen_forward_decl writer class_path =
  317. begin
  318. let output = writer#write in
  319. match class_path with
  320. | (["@verbatim"],file) -> writer#write ("#include <" ^ file ^ ">\n");
  321. | _ ->
  322. let name = fst (remap_class_path class_path) in
  323. output ("HX_DECLARE_CLASS" ^ (string_of_int (List.length name ) ) ^ "(");
  324. List.iter (fun package_part -> output (package_part ^ ",") ) name;
  325. output ( (snd class_path) ^ ")\n")
  326. end;;
  327. let real_interfaces =
  328. List.filter (function (t,pl) ->
  329. match t, pl with
  330. | { cl_path = ["cpp";"rtti"],_ },[] -> false
  331. | _ -> true
  332. );;
  333. let rec is_function_expr expr =
  334. match expr.eexpr with
  335. | TParenthesis expr | TMeta(_,expr) -> is_function_expr expr
  336. | TCast (e,None) -> is_function_expr e
  337. | TFunction _ -> true
  338. | _ -> false;;
  339. let is_var_field field =
  340. match field.cf_kind with
  341. | Var _ -> true
  342. | Method MethDynamic -> true
  343. | _ -> false
  344. ;;
  345. let rec has_rtti_interface c interface =
  346. List.exists (function (t,pl) ->
  347. (snd t.cl_path) = interface && (match fst t.cl_path with | ["cpp";"rtti"] -> true | _ -> false )
  348. ) c.cl_implements ||
  349. (match c.cl_super with None -> false | Some (c,_) -> has_rtti_interface c interface);;
  350. let has_field_integer_lookup class_def =
  351. has_rtti_interface class_def "FieldIntegerLookup";;
  352. let has_field_integer_numeric_lookup class_def =
  353. has_rtti_interface class_def "FieldNumericIntegerLookup";;
  354. (* Output required code to place contents in required namespace *)
  355. let gen_open_namespace output class_path =
  356. List.iter (fun namespace -> output ("namespace " ^ namespace ^ "{\n")) (List.map keyword_remap (fst class_path));;
  357. let gen_close_namespace output class_path =
  358. List.iter
  359. (fun namespace -> output ( "}" ^ " // end namespace " ^ namespace ^"\n"))
  360. (fst class_path);;
  361. (* The basic types can have default values and are passesby value *)
  362. let is_numeric = function
  363. | "Int" | "Bool" | "Float" | "::haxe::io::Unsigned_char__" | "unsigned char" -> true
  364. | "::cpp::UInt8" | "::cpp::Int8" | "::cpp::Char"
  365. | "::cpp::UInt16" | "::cpp::Int16"
  366. | "::cpp::UInt32" | "::cpp::Int32"
  367. | "::cpp::UInt64" | "::cpp::Int64"
  368. | "::cpp::Float32" | "::cpp::Float64"
  369. | "int" | "bool" | "double" | "float" -> true
  370. | _ -> false
  371. let rec remove_parens expression =
  372. match expression.eexpr with
  373. | TParenthesis e -> remove_parens e
  374. | TMeta(_,e) -> remove_parens e
  375. | TCast ( e,None) -> remove_parens e
  376. | _ -> expression
  377. ;;
  378. let cant_be_null type_string =
  379. is_numeric type_string
  380. ;;
  381. let is_object type_string =
  382. not (is_numeric type_string || type_string="::String");
  383. ;;
  384. let is_interface_type t =
  385. match follow t with
  386. | TInst (klass,params) -> klass.cl_interface
  387. | _ -> false
  388. ;;
  389. let is_cpp_function_instance haxe_type =
  390. match follow haxe_type with
  391. | TInst (klass,params) ->
  392. (match klass.cl_path with
  393. | ["cpp"] , "Function" -> true
  394. | _ -> false )
  395. | _ -> false
  396. ;;
  397. let is_cpp_function_class haxe_type =
  398. match follow haxe_type with
  399. | TType (klass,params) ->
  400. (match klass.t_path with
  401. | ["cpp"] , "Function" -> true
  402. | _ -> false )
  403. | _ -> false
  404. ;;
  405. let is_fromStaticFunction_call func =
  406. match (remove_parens func).eexpr with
  407. | TField (_,FStatic ({cl_path=["cpp"],"Function"},{cf_name="fromStaticFunction"} ) ) -> true
  408. | _ -> false
  409. ;;
  410. let is_addressOf_call func =
  411. match (remove_parens func).eexpr with
  412. | TField (_,FStatic ({cl_path=["cpp"],"Pointer"},{cf_name="addressOf"} ) ) -> true
  413. | _ -> false
  414. ;;
  415. let is_lvalue var =
  416. match (remove_parens var).eexpr with
  417. | TLocal _ -> true
  418. | TField (_,FStatic(_,field) ) | TField (_,FInstance(_,_,field) ) -> is_var_field field
  419. | _ -> false
  420. ;;
  421. let is_pointer haxe_type includeRaw =
  422. match follow haxe_type with
  423. | TInst (klass,params) ->
  424. (match klass.cl_path with
  425. | ["cpp"] , "Pointer"
  426. | ["cpp"] , "ConstPointer"
  427. | ["cpp"] , "Function" -> true
  428. | ["cpp"] , "RawPointer" when includeRaw -> true
  429. | ["cpp"] , "RawConstPointer" when includeRaw -> true
  430. | _ -> false )
  431. | TType (type_def,params) ->
  432. (match type_def.t_path with
  433. | ["cpp"] , "Pointer"
  434. | ["cpp"] , "ConstPointer"
  435. | ["cpp"] , "Function" -> true
  436. | ["cpp"] , "RawPointer" when includeRaw -> true
  437. | ["cpp"] , "RawConstPointer" when includeRaw -> true
  438. | _ -> false )
  439. | _ -> false
  440. ;;
  441. let is_dynamic_type_param class_kind =
  442. match class_kind with
  443. | KTypeParameter _ -> true
  444. | _ -> false
  445. ;;
  446. (* Get a string to represent a type.
  447. The "suffix" will be nothing or "_obj", depending if we want the name of the
  448. pointer class or the pointee (_obj class *)
  449. let rec class_string klass suffix params =
  450. (match klass.cl_path with
  451. (* Array class *)
  452. | ([],"Array") when is_dynamic_array_param (List.hd params) -> "Dynamic"
  453. | ([],"Array") -> (snd klass.cl_path) ^ suffix ^ "< " ^ (String.concat ","
  454. (List.map array_element_type params) ) ^ " >"
  455. (* FastIterator class *)
  456. | (["cpp"],"FastIterator") -> "::cpp::FastIterator" ^ suffix ^ "< " ^ (String.concat ","
  457. (List.map type_string params) ) ^ " >"
  458. | (["cpp"],"Pointer")
  459. | (["cpp"],"ConstPointer") ->
  460. "::cpp::Pointer< " ^ (String.concat "," (List.map type_string params) ) ^ " >"
  461. | (["cpp"],"RawPointer") ->
  462. " " ^ (String.concat "," (List.map type_string params) ) ^ " * "
  463. | (["cpp"],"RawConstPointer") ->
  464. " const " ^ (String.concat "," (List.map type_string params) ) ^ " * "
  465. | (["cpp"],"Function") ->
  466. "::cpp::Function< " ^ (cpp_function_signature_params params) ^ " >"
  467. | _ when is_dynamic_type_param klass.cl_kind -> "Dynamic"
  468. | ([],"#Int") -> "/* # */int"
  469. | (["haxe";"io"],"Unsigned_char__") -> "unsigned char"
  470. | ([],"Class") -> "hx::Class"
  471. | ([],"EnumValue") -> "Dynamic"
  472. | ([],"Null") -> (match params with
  473. | [t] ->
  474. (match follow t with
  475. | TAbstract ({ a_path = [],"Int" },_)
  476. | TAbstract ({ a_path = [],"Float" },_)
  477. | TAbstract ({ a_path = [],"Bool" },_)
  478. | TInst ({ cl_path = [],"Int" },_)
  479. | TInst ({ cl_path = [],"Float" },_)
  480. | TEnum ({ e_path = [],"Bool" },_) -> "Dynamic"
  481. | _ -> "/*NULL*/" ^ (type_string t) )
  482. | _ -> assert false);
  483. (* Normal class *)
  484. | path when klass.cl_extern && (not (is_internal_class path) )->
  485. (join_class_path_remap klass.cl_path "::") ^ suffix
  486. | _ -> "::" ^ (join_class_path_remap klass.cl_path "::") ^ suffix
  487. )
  488. and type_string_suff suffix haxe_type =
  489. (match haxe_type with
  490. | TMono r -> (match !r with None -> "Dynamic" ^ suffix | Some t -> type_string_suff suffix t)
  491. | TAbstract ({ a_path = ([],"Void") },[]) -> "Void"
  492. | TAbstract ({ a_path = ([],"Bool") },[]) -> "bool"
  493. | TAbstract ({ a_path = ([],"Float") },[]) -> "Float"
  494. | TAbstract ({ a_path = ([],"Int") },[]) -> "int"
  495. | TAbstract( { a_path = ([], "EnumValue") }, _ ) -> "Dynamic"
  496. | TEnum (enum,params) -> "::" ^ (join_class_path_remap enum.e_path "::") ^ suffix
  497. | TInst (klass,params) -> (class_string klass suffix params)
  498. | TType (type_def,params) ->
  499. (match type_def.t_path with
  500. | [] , "Null" ->
  501. (match params with
  502. | [t] ->
  503. (match follow t with
  504. | TAbstract ({ a_path = [],"Int" },_)
  505. | TAbstract ({ a_path = [],"Float" },_)
  506. | TAbstract ({ a_path = [],"Bool" },_)
  507. | TInst ({ cl_path = [],"Int" },_)
  508. | TInst ({ cl_path = [],"Float" },_)
  509. | TEnum ({ e_path = [],"Bool" },_) -> "Dynamic" ^ suffix
  510. | _ -> type_string_suff suffix t)
  511. | _ -> assert false);
  512. | [] , "Array" ->
  513. (match params with
  514. | [t] when (type_string (follow t)) = "Dynamic" -> "Dynamic"
  515. | [t] -> "Array< " ^ (type_string (follow t) ) ^ " >"
  516. | _ -> assert false)
  517. | ["cpp"] , "FastIterator" ->
  518. (match params with
  519. | [t] -> "::cpp::FastIterator< " ^ (type_string (follow t) ) ^ " >"
  520. | _ -> assert false)
  521. | ["cpp"] , "Pointer"
  522. | ["cpp"] , "ConstPointer" ->
  523. (match params with
  524. | [t] -> "::cpp::Pointer< " ^ (type_string (follow t) ) ^ " >"
  525. | _ -> assert false)
  526. | ["cpp"] , "RawPointer" ->
  527. (match params with
  528. | [t] -> " " ^ (type_string (follow t) ) ^ " *"
  529. | _ -> assert false)
  530. | ["cpp"] , "RawConstPointer" ->
  531. (match params with
  532. | [t] -> "const " ^ (type_string (follow t) ) ^ " *"
  533. | _ -> assert false)
  534. | ["cpp"] , "Function" -> "::cpp::Function< " ^ (cpp_function_signature_params params) ^ " >"
  535. | _ -> type_string_suff suffix (apply_params type_def.t_params params type_def.t_type)
  536. )
  537. | TFun (args,haxe_type) -> "Dynamic" ^ suffix
  538. | TAnon a -> "Dynamic"
  539. (*
  540. (match !(a.a_status) with
  541. | Statics c -> type_string_suff suffix (TInst (c,List.map snd c.cl_params))
  542. | EnumStatics e -> type_string_suff suffix (TEnum (e,List.map snd e.e_params))
  543. | _ -> "Dynamic" ^ suffix )
  544. *)
  545. | TDynamic haxe_type -> "Dynamic" ^ suffix
  546. | TLazy func -> type_string_suff suffix ((!func)())
  547. | TAbstract (abs,pl) when abs.a_impl <> None ->
  548. type_string_suff suffix (Abstract.get_underlying_type abs pl)
  549. | TAbstract (abs,pl) ->
  550. "::" ^ (join_class_path_remap abs.a_path "::") ^ suffix
  551. )
  552. and type_string haxe_type =
  553. type_string_suff "" haxe_type
  554. and array_element_type haxe_type =
  555. match type_string haxe_type with
  556. | x when cant_be_null x -> x
  557. | x when is_interface_type (follow haxe_type) -> x
  558. | "::String" -> "::String"
  559. | _ -> "::Dynamic"
  560. and is_dynamic_array_param haxe_type =
  561. if (type_string (follow haxe_type)) = "Dynamic" then true
  562. else (match follow haxe_type with
  563. | TInst (klass,params) ->
  564. (match klass.cl_path with
  565. | ([],"Array") | ([],"Class") | (["cpp"],"FastIterator")
  566. | (["cpp"],"RawPointer") |(["cpp"],"ConstRawPointer")
  567. | (["cpp"],"Pointer") |(["cpp"],"ConstPointer")|(["cpp"],"Function") -> false
  568. | _ -> (match klass.cl_kind with KTypeParameter _ -> true | _ -> false)
  569. )
  570. | _ -> false
  571. )
  572. and cpp_function_signature tfun =
  573. match follow tfun with
  574. | TFun(args,ret) -> (type_string ret) ^ "(" ^ (gen_tfun_interface_arg_list args) ^ ")"
  575. | _ -> "void *"
  576. and cpp_function_signature_params params = match params with
  577. | [t] -> cpp_function_signature t
  578. | _ -> assert false;
  579. and gen_interface_arg_type_name name opt typ =
  580. let type_str = (type_string typ) in
  581. (if (opt && (cant_be_null type_str) ) then
  582. "hx::Null< " ^ type_str ^ " > "
  583. else
  584. type_str )
  585. ^ " " ^ (keyword_remap name)
  586. and gen_tfun_interface_arg_list args =
  587. String.concat "," (List.map (fun (name,opt,typ) -> gen_interface_arg_type_name name opt typ) args)
  588. ;;
  589. let is_array haxe_type =
  590. match follow haxe_type with
  591. | TInst (klass,params) ->
  592. (match klass.cl_path with
  593. | [] , "Array" -> not (is_dynamic_array_param (List.hd params))
  594. | _ -> false )
  595. | TType (type_def,params) ->
  596. (match type_def.t_path with
  597. | [] , "Array" -> not (is_dynamic_array_param (List.hd params))
  598. | _ -> false )
  599. | _ -> false
  600. ;;
  601. let is_array_or_dyn_array haxe_type =
  602. match follow haxe_type with
  603. | TInst (klass,params) ->
  604. (match klass.cl_path with | [] , "Array" -> true | _ -> false )
  605. | TType (type_def,params) ->
  606. (match type_def.t_path with | [] , "Array" -> true | _ -> false )
  607. | _ -> false
  608. ;;
  609. let is_array_implementer haxe_type =
  610. match follow haxe_type with
  611. | TInst (klass,params) ->
  612. (match klass.cl_array_access with
  613. | Some _ -> true
  614. | _ -> false )
  615. | _ -> false
  616. ;;
  617. let is_numeric_field field =
  618. match field.cf_kind with
  619. | Var _ -> is_numeric (type_string field.cf_type)
  620. | _ -> false;
  621. ;;
  622. let is_static_access obj =
  623. match (remove_parens obj).eexpr with
  624. | TTypeExpr _ -> true
  625. | _ -> false
  626. ;;
  627. let is_native_with_space func =
  628. match (remove_parens func).eexpr with
  629. | TField(obj,field) when is_static_access obj ->
  630. String.contains (get_field_access_meta field Meta.Native) ' '
  631. | _ -> false
  632. ;;
  633. let rec is_cpp_function_member func =
  634. match (remove_parens func).eexpr with
  635. | TField(obj,field) when is_cpp_function_instance obj.etype -> true
  636. | TCall(obj,_) -> is_cpp_function_member obj
  637. | _ -> false
  638. ;;
  639. (* Get the type and output it to the stream *)
  640. let gen_type ctx haxe_type =
  641. ctx.ctx_output (type_string haxe_type)
  642. ;;
  643. (* Get the type and output it to the stream *)
  644. let gen_type_suff ctx haxe_type suff =
  645. ctx.ctx_output (type_string_suff suff haxe_type);;
  646. let member_type ctx field_object member =
  647. let name = (if (is_array field_object.etype) then "::Array"
  648. else (type_string field_object.etype)) ^ "." ^ member in
  649. try ( Hashtbl.find ctx.ctx_class_member_types name )
  650. with Not_found -> "?";;
  651. let is_interface obj = is_interface_type obj.etype;;
  652. let should_implement_field x = not (is_extern_field x);;
  653. let is_function_member expression =
  654. match (follow expression.etype) with | TFun (_,_) -> true | _ -> false;;
  655. let is_internal_member member =
  656. match member with
  657. | "__Field" | "__IField" | "__Run" | "__Is" | "__GetClass" | "__GetType" | "__ToString"
  658. | "__s" | "__GetPtr" | "__SetField" | "__length" | "__IsArray" | "__SetThis" | "__Internal"
  659. | "__EnumParams" | "__Index" | "__Tag" | "__GetFields" | "toString" | "__HasField"
  660. | "__GetRealObject"
  661. -> true
  662. | _ -> false;;
  663. let is_extern_class class_def =
  664. class_def.cl_extern || (has_meta_key class_def.cl_meta Meta.Extern) ||
  665. (match class_def.cl_kind with
  666. | KAbstractImpl abstract_def -> (has_meta_key abstract_def.a_meta Meta.Extern)
  667. | _ -> false );
  668. ;;
  669. let is_extern_class_instance obj =
  670. match follow obj.etype with
  671. | TInst (klass,params) -> klass.cl_extern
  672. | _ -> false
  673. ;;
  674. let is_struct_access t =
  675. match follow t with
  676. | TInst (class_def,_) -> (has_meta_key class_def.cl_meta Meta.StructAccess)
  677. | _ -> false
  678. ;;
  679. let rec is_dynamic_accessor name acc field class_def =
  680. ( ( acc ^ "_" ^ field.cf_name) = name ) &&
  681. ( not (List.exists (fun f -> f.cf_name=name) class_def.cl_ordered_fields) )
  682. && (match class_def.cl_super with None -> true | Some (parent,_) -> is_dynamic_accessor name acc field parent )
  683. ;;
  684. let gen_arg_type_name name default_val arg_type prefix =
  685. let remap_name = keyword_remap name in
  686. let type_str = (type_string arg_type) in
  687. match default_val with
  688. | Some TNull -> (type_str,remap_name)
  689. | Some constant when (cant_be_null type_str) -> ("hx::Null< " ^ type_str ^ " > ",prefix ^ remap_name)
  690. | Some constant -> (type_str,prefix ^ remap_name)
  691. | _ -> (type_str,remap_name);;
  692. (* Generate prototype text, including allowing default values to be null *)
  693. let gen_arg name default_val arg_type prefix =
  694. let pair = gen_arg_type_name name default_val arg_type prefix in
  695. (fst pair) ^ " " ^ (snd pair);;
  696. let rec gen_arg_list arg_list prefix =
  697. String.concat "," (List.map (fun (v,o) -> (gen_arg v.v_name o v.v_type prefix) ) arg_list)
  698. let rec gen_tfun_arg_list arg_list =
  699. match arg_list with
  700. | [] -> ""
  701. | [(name,o,arg_type)] -> gen_arg name None arg_type ""
  702. | (name,o,arg_type) :: remaining ->
  703. (gen_arg name None arg_type "") ^ "," ^ (gen_tfun_arg_list remaining)
  704. (* Check to see if we are the first object in the parent tree to implement a dynamic interface *)
  705. let implement_dynamic_here class_def =
  706. let implements_dynamic c = match c.cl_dynamic with None -> false | _ -> true in
  707. let rec super_implements_dynamic c = match c.cl_super with
  708. | None -> false
  709. | Some (csup, _) -> if (implements_dynamic csup) then true else
  710. super_implements_dynamic csup;
  711. in
  712. ( (implements_dynamic class_def) && (not (super_implements_dynamic class_def) ) );;
  713. let gen_hash32 seed str =
  714. let h = ref (Int32.of_int seed) in
  715. let cycle = Int32.of_int 223 in
  716. for i = 0 to String.length str - 1 do
  717. h := Int32.add (Int32.mul !h cycle) (Int32.of_int (int_of_char (String.unsafe_get str i)));
  718. done;
  719. !h
  720. ;;
  721. let gen_hash seed str =
  722. Printf.sprintf "0x%08lx" (gen_hash32 seed str)
  723. ;;
  724. let gen_string_hash str =
  725. let h = gen_hash32 0 str in
  726. Printf.sprintf "\"\\x%02lx\",\"\\x%02lx\",\"\\x%02lx\",\"\\x%02lx\""
  727. (Int32.shift_right_logical (Int32.shift_left h 24) 24)
  728. (Int32.shift_right_logical (Int32.shift_left h 16) 24)
  729. (Int32.shift_right_logical (Int32.shift_left h 8) 24)
  730. (Int32.shift_right_logical h 24)
  731. ;;
  732. (* Make string printable for c++ code *)
  733. (* Here we know there are no utf8 characters, so use the L"" notation to avoid conversion *)
  734. let escape_stringw s l =
  735. let b = Buffer.create 0 in
  736. Buffer.add_char b 'L';
  737. Buffer.add_char b '"';
  738. let skip = ref 0 in
  739. for i = 0 to String.length s - 1 do
  740. if (!skip>0) then begin
  741. skip := !skip -1;
  742. l := !l-1;
  743. end else
  744. match Char.code (String.unsafe_get s i) with
  745. | c when (c>127) ->
  746. let encoded = ((c land 0x3F) lsl 6) lor ( Char.code ((String.unsafe_get s (i+1))) land 0x7F) in
  747. skip := 1;
  748. Buffer.add_string b (Printf.sprintf "\\x%X\"L\"" encoded)
  749. | c when (c < 32) -> Buffer.add_string b (Printf.sprintf "\\x%X\"L\"" c)
  750. | c -> Buffer.add_char b (Char.chr c)
  751. done;
  752. Buffer.add_char b '"';
  753. Buffer.contents b;;
  754. let special_to_hex s =
  755. let l = String.length s in
  756. let b = Buffer.create 0 in
  757. for i = 0 to l - 1 do
  758. match Char.code (String.unsafe_get s i) with
  759. | c when (c>127) || (c<32) ->
  760. Buffer.add_string b (Printf.sprintf "\\x%02x\"\"" c)
  761. | c -> Buffer.add_char b (Char.chr c)
  762. done;
  763. Buffer.contents b;;
  764. let escape_extern s =
  765. let l = String.length s in
  766. let b = Buffer.create 0 in
  767. for i = 0 to l - 1 do
  768. match Char.code (String.unsafe_get s i) with
  769. | c when (c>127) || (c<32) || (c=34) || (c=92) ->
  770. Buffer.add_string b (Printf.sprintf "\\x%02x" c)
  771. | c -> Buffer.add_char b (Char.chr c)
  772. done;
  773. Buffer.contents b;;
  774. let has_utf8_chars s =
  775. let result = ref false in
  776. for i = 0 to String.length s - 1 do
  777. result := !result || ( Char.code (String.unsafe_get s i) > 127 )
  778. done;
  779. !result;;
  780. let escape_command s =
  781. let b = Buffer.create 0 in
  782. String.iter (fun ch -> if (ch=='"' || ch=='\\' ) then Buffer.add_string b "\\"; Buffer.add_char b ch ) s;
  783. Buffer.contents b;;
  784. let str s =
  785. let rec split s plus =
  786. let escaped = Ast.s_escape ~hex:false s in
  787. let hexed = (special_to_hex escaped) in
  788. if (String.length hexed <= 16000 ) then
  789. plus ^ " HX_CSTRING(\"" ^ hexed ^ "\")"
  790. else begin
  791. let len = String.length s in
  792. let half = len lsr 1 in
  793. (split (String.sub s 0 half) plus ) ^ (split (String.sub s half (len-half)) "+" )
  794. end
  795. in
  796. let escaped = Ast.s_escape ~hex:false s in
  797. let hexed = (special_to_hex escaped) in
  798. if (String.length hexed <= 16000 ) then
  799. "HX_HCSTRING(\"" ^ hexed ^ "\"," ^ (gen_string_hash s) ^ ")"
  800. else
  801. "(" ^ (split s "" ) ^ ")"
  802. ;;
  803. let const_char_star s =
  804. let escaped = Ast.s_escape ~hex:false s in
  805. "\"" ^ special_to_hex escaped ^ "\"";
  806. ;;
  807. (* When we are in a "real" object, we refer to ourselves as "this", but
  808. if we are in a local class that is used to generate return values,
  809. we use the fake "__this" pointer.
  810. If we are in an "Anon" object, then the "this" refers to the anon object (eg List iterator) *)
  811. let clear_real_this_ptr ctx dynamic_this =
  812. let old_flag = ctx.ctx_real_this_ptr in
  813. let old_dynamic = ctx.ctx_dynamic_this_ptr in
  814. let old_void = ctx.ctx_real_void in
  815. ctx.ctx_real_this_ptr <- false;
  816. ctx.ctx_dynamic_this_ptr <- dynamic_this;
  817. fun () -> (
  818. ctx.ctx_real_this_ptr <- old_flag;
  819. ctx.ctx_dynamic_this_ptr <- old_dynamic;
  820. ctx.ctx_real_void <- old_void;
  821. )
  822. ;;
  823. (* Generate temp variable names *)
  824. let next_anon_function_name ctx =
  825. ctx.ctx_static_id_curr <- ctx.ctx_static_id_curr + 1;
  826. "_Function_" ^ (string_of_int ctx.ctx_static_id_depth) ^"_"^ (string_of_int ctx.ctx_static_id_curr);;
  827. let use_anon_function_name ctx =
  828. ctx.ctx_static_id_used <- ctx.ctx_static_id_used + 1;
  829. "_Function_" ^ (string_of_int ctx.ctx_static_id_depth) ^"_"^ (string_of_int ctx.ctx_static_id_used);;
  830. let push_anon_names ctx =
  831. let old_used = ctx.ctx_static_id_used in
  832. let old_curr = ctx.ctx_static_id_curr in
  833. let old_depth = ctx.ctx_static_id_depth in
  834. ctx.ctx_static_id_used <- 0;
  835. ctx.ctx_static_id_curr <- 0;
  836. ctx.ctx_static_id_depth <- ctx.ctx_static_id_depth + 1;
  837. ( function () -> (
  838. ctx.ctx_static_id_used <- old_used;
  839. ctx.ctx_static_id_curr <- old_curr;
  840. ctx.ctx_static_id_depth <- old_depth; ) )
  841. ;;
  842. let get_switch_var ctx =
  843. ctx.ctx_switch_id <- ctx.ctx_switch_id + 1;
  844. "_switch_" ^ (string_of_int ctx.ctx_switch_id)
  845. (* If you put on the "-debug" flag, you get extra comments in the source code *)
  846. let debug_expression expression type_too =
  847. "/* " ^ Type.s_expr_kind expression ^ (if (type_too) then " = " ^ (type_string expression.etype) else "") ^ " */";;
  848. (* This is like the Type.iter, but also keeps the "retval" flag up to date *)
  849. let rec iter_retval f retval e =
  850. match e.eexpr with
  851. | TConst _
  852. | TLocal _
  853. | TBreak
  854. | TContinue
  855. | TTypeExpr _ ->
  856. ()
  857. | TArray (e1,e2)
  858. | TBinop (_,e1,e2) ->
  859. f true e1;
  860. f true e2;
  861. | TWhile (e1,e2,_) ->
  862. f true e1;
  863. f false e2;
  864. | TFor (_,e1,e2) ->
  865. f true e1;
  866. f false e2;
  867. | TThrow e
  868. | TField (e,_)
  869. | TEnumParameter (e,_,_)
  870. | TUnop (_,_,e) ->
  871. f true e
  872. | TParenthesis e | TMeta(_,e) ->
  873. f retval e
  874. | TBlock expr_list when retval ->
  875. let rec return_last = function
  876. | [] -> ()
  877. | expr :: [] -> f true expr
  878. | expr :: exprs -> f false expr; return_last exprs in
  879. return_last expr_list
  880. | TArrayDecl el
  881. | TNew (_,_,el) ->
  882. List.iter (f true ) el
  883. | TBlock el ->
  884. List.iter (f false ) el
  885. | TObjectDecl fl ->
  886. List.iter (fun (_,e) -> f true e) fl
  887. | TCall (e,el) ->
  888. f true e;
  889. List.iter (f true) el
  890. | TVar (_,eo) ->
  891. (match eo with None -> () | Some e -> f true e)
  892. | TFunction fu ->
  893. f false fu.tf_expr
  894. | TIf (e,e1,e2) ->
  895. f true e;
  896. f retval e1;
  897. (match e2 with None -> () | Some e -> f retval e)
  898. | TSwitch (e,cases,def) ->
  899. f true e;
  900. List.iter (fun (el,e2) -> List.iter (f true) el; f retval e2) cases;
  901. (match def with None -> () | Some e -> f retval e)
  902. (* | TMatch (e,_,cases,def) ->
  903. f true e;
  904. List.iter (fun (_,_,e) -> f false e) cases;
  905. (match def with None -> () | Some e -> f false e) *)
  906. | TTry (e,catches) ->
  907. f retval e;
  908. List.iter (fun (_,e) -> f false e) catches
  909. | TReturn eo ->
  910. (match eo with None -> () | Some e -> f true e)
  911. | TCast (e,None) ->
  912. f retval e
  913. | TCast (e,_) ->
  914. f true e
  915. ;;
  916. (* Convert an array to a comma separated list of values *)
  917. let array_arg_list inList =
  918. let i = ref (0-1) in
  919. String.concat "," (List.map (fun _ -> incr i; "inArgs[" ^ (string_of_int !i) ^ "]" ) inList)
  920. let list_num l = string_of_int (List.length l);;
  921. let only_int_cases cases =
  922. match cases with
  923. | [] -> false
  924. | _ ->
  925. not (List.exists (fun (cases,expression) ->
  926. List.exists (fun case -> match case.eexpr with TConst (TInt _) -> false | _ -> true ) cases
  927. ) cases );;
  928. (* See if there is a haxe break statement that will be swollowed by c++ break *)
  929. exception BreakFound;;
  930. let contains_break expression =
  931. try (
  932. let rec check_all expression =
  933. Type.iter (fun expr -> match expr.eexpr with
  934. | TBreak -> raise BreakFound
  935. | TFor _
  936. | TFunction _
  937. | TWhile (_,_,_) -> ()
  938. | _ -> check_all expr;
  939. ) expression in
  940. check_all expression;
  941. false;
  942. ) with BreakFound -> true;;
  943. (* Decide is we should look the field up by name *)
  944. let dynamic_internal = function | "__Is" -> true | _ -> false
  945. let rec is_null expr =
  946. match expr.eexpr with
  947. | TConst TNull -> true
  948. | TParenthesis expr | TMeta (_,expr) -> is_null expr
  949. | TCast (e,None) -> is_null e
  950. | _ -> false
  951. ;;
  952. let find_undeclared_variables_ctx ctx undeclared declarations this_suffix allow_this expression =
  953. let output = ctx.ctx_output in
  954. let rec find_undeclared_variables undeclared declarations this_suffix allow_this expression =
  955. match expression.eexpr with
  956. | TVar (tvar,optional_init) ->
  957. Hashtbl.add declarations (keyword_remap tvar.v_name) ();
  958. if (ctx.ctx_debug_level>1) then
  959. output ("/* found var " ^ tvar.v_name ^ "*/ ");
  960. (match optional_init with
  961. | Some expression -> find_undeclared_variables undeclared declarations this_suffix allow_this expression
  962. | _ -> ())
  963. | TFunction func -> List.iter ( fun (tvar, opt_val) ->
  964. if (ctx.ctx_debug_level>1) then
  965. output ("/* found arg " ^ tvar.v_name ^ " = " ^ (type_string tvar.v_type) ^ " */ ");
  966. Hashtbl.add declarations (keyword_remap tvar.v_name) () ) func.tf_args;
  967. find_undeclared_variables undeclared declarations this_suffix false func.tf_expr
  968. | TTry (try_block,catches) ->
  969. find_undeclared_variables undeclared declarations this_suffix allow_this try_block;
  970. List.iter (fun (tvar,catch_expt) ->
  971. let old_decs = Hashtbl.copy declarations in
  972. Hashtbl.add declarations (keyword_remap tvar.v_name) ();
  973. find_undeclared_variables undeclared declarations this_suffix allow_this catch_expt;
  974. Hashtbl.clear declarations;
  975. Hashtbl.iter ( Hashtbl.add declarations ) old_decs
  976. ) catches;
  977. | TLocal tvar ->
  978. let name = keyword_remap tvar.v_name in
  979. if not (Hashtbl.mem declarations name) then
  980. Hashtbl.replace undeclared name (type_string expression.etype)
  981. (* | TMatch (condition, enum, cases, default) ->
  982. find_undeclared_variables undeclared declarations this_suffix allow_this condition;
  983. List.iter (fun (case_ids,params,expression) ->
  984. let old_decs = Hashtbl.copy declarations in
  985. (match params with
  986. | None -> ()
  987. | Some l -> List.iter (fun (opt_var) ->
  988. match opt_var with | Some v -> Hashtbl.add declarations (keyword_remap v.v_name) () | _ -> () )
  989. l );
  990. find_undeclared_variables undeclared declarations this_suffix allow_this expression;
  991. Hashtbl.clear declarations;
  992. Hashtbl.iter ( Hashtbl.add declarations ) old_decs
  993. ) cases;
  994. (match default with | None -> ()
  995. | Some expr ->
  996. find_undeclared_variables undeclared declarations this_suffix allow_this expr;
  997. ); *)
  998. | TFor (tvar, init, loop) ->
  999. let old_decs = Hashtbl.copy declarations in
  1000. Hashtbl.add declarations (keyword_remap tvar.v_name) ();
  1001. find_undeclared_variables undeclared declarations this_suffix allow_this init;
  1002. find_undeclared_variables undeclared declarations this_suffix allow_this loop;
  1003. Hashtbl.clear declarations;
  1004. Hashtbl.iter ( Hashtbl.add declarations ) old_decs
  1005. | TConst TSuper
  1006. | TConst TThis ->
  1007. if ((not (Hashtbl.mem declarations "this")) && allow_this) then
  1008. Hashtbl.replace undeclared "this" (type_string_suff this_suffix expression.etype)
  1009. | TBlock expr_list ->
  1010. let old_decs = Hashtbl.copy declarations in
  1011. List.iter (find_undeclared_variables undeclared declarations this_suffix allow_this ) expr_list;
  1012. (* what is the best way for this ? *)
  1013. Hashtbl.clear declarations;
  1014. Hashtbl.iter ( Hashtbl.add declarations ) old_decs
  1015. | _ -> Type.iter (find_undeclared_variables undeclared declarations this_suffix allow_this) expression
  1016. in
  1017. find_undeclared_variables undeclared declarations this_suffix allow_this expression
  1018. ;;
  1019. let rec is_dynamic_in_cpp ctx expr =
  1020. let expr_type = type_string ( match follow expr.etype with TFun (args,ret) -> ret | _ -> expr.etype) in
  1021. ctx.ctx_dbgout ( "/* idic: " ^ expr_type ^ " */" );
  1022. if ( expr_type="Dynamic" ) then
  1023. true
  1024. else begin
  1025. let result = (
  1026. match expr.eexpr with
  1027. | TEnumParameter( obj, _, index ) ->
  1028. true (* TODO? *)
  1029. | TField( obj, field ) ->
  1030. let name = field_name field in
  1031. ctx.ctx_dbgout ("/* ?tfield "^name^" */");
  1032. if (is_dynamic_member_lookup_in_cpp ctx obj field) then
  1033. (
  1034. ctx.ctx_dbgout "/* tf=dynobj */";
  1035. true
  1036. )
  1037. else if (is_dynamic_member_return_in_cpp ctx obj field) then
  1038. (
  1039. ctx.ctx_dbgout "/* tf=dynret */";
  1040. true
  1041. )
  1042. else
  1043. (
  1044. ctx.ctx_dbgout "/* tf=notdyn */";
  1045. false
  1046. )
  1047. | TConst TThis when ((not ctx.ctx_real_this_ptr) && ctx.ctx_dynamic_this_ptr) ->
  1048. ctx.ctx_dbgout ("/* dthis */"); true
  1049. | TArray (obj,index) -> let dyn = is_dynamic_in_cpp ctx obj in
  1050. ctx.ctx_dbgout ("/* aidr:" ^ (if dyn then "Dyn" else "Not") ^ " */");
  1051. dyn;
  1052. | TTypeExpr _ -> false
  1053. | TCall(func,args) ->
  1054. (match follow func.etype with
  1055. | TFun (args,ret) -> ctx.ctx_dbgout ("/* ret = "^ (type_string ret) ^" */");
  1056. is_dynamic_in_cpp ctx func
  1057. | _ -> ctx.ctx_dbgout "/* not TFun */"; true
  1058. );
  1059. | TParenthesis(expr) | TMeta(_,expr) -> is_dynamic_in_cpp ctx expr
  1060. | TCast (e,None) -> is_dynamic_in_cpp ctx e
  1061. | TLocal { v_name = "__global__" } -> false
  1062. | TConst TNull -> true
  1063. | _ -> ctx.ctx_dbgout "/* other */"; false (* others ? *) )
  1064. in
  1065. ctx.ctx_dbgout (if result then "/* Y */" else "/* N */" );
  1066. result
  1067. end
  1068. and is_dynamic_member_lookup_in_cpp ctx field_object field =
  1069. let member = field_name field in
  1070. ctx.ctx_dbgout ("/*mem."^member^".*/");
  1071. if (is_internal_member member) then false else
  1072. if (is_pointer field_object.etype true) then false else
  1073. if (match field_object.eexpr with | TTypeExpr _ -> ctx.ctx_dbgout "/*!TTypeExpr*/"; true | _ -> false) then false else
  1074. if (is_dynamic_in_cpp ctx field_object) then true else
  1075. if (is_array field_object.etype) then false else (
  1076. let tstr = type_string field_object.etype in
  1077. ctx.ctx_dbgout ("/* ts:"^tstr^"*/");
  1078. match tstr with
  1079. (* Internal classes have no dynamic members *)
  1080. | "::String" | "Null" | "::hx::Class" | "::Enum" | "::Math" | "::ArrayAccess" -> ctx.ctx_dbgout ("/* ok:" ^ (type_string field_object.etype) ^ " */"); false
  1081. | "Dynamic" -> true
  1082. | name ->
  1083. let full_name = name ^ "." ^ member in
  1084. ctx.ctx_dbgout ("/* t:" ^ full_name ^ " */");
  1085. try ( let mem_type = (Hashtbl.find ctx.ctx_class_member_types full_name) in
  1086. ctx.ctx_dbgout ("/* =" ^ mem_type ^ "*/");
  1087. false )
  1088. with Not_found -> not (is_extern_class_instance field_object)
  1089. )
  1090. and is_dynamic_member_return_in_cpp ctx field_object field =
  1091. let member = field_name field in
  1092. if (is_array field_object.etype) then false else
  1093. if (is_pointer field_object.etype true) then false else
  1094. if (is_internal_member member) then false else
  1095. match field_object.eexpr with
  1096. | TTypeExpr t ->
  1097. let full_name = "::" ^ (join_class_path (t_path t) "::" ) ^ "." ^ member in
  1098. ctx.ctx_dbgout ("/*static:"^ full_name^"*/");
  1099. ( try ( let mem_type = (Hashtbl.find ctx.ctx_class_member_types full_name) in mem_type="Dynamic" )
  1100. with Not_found -> true )
  1101. | _ ->
  1102. let tstr = type_string field_object.etype in
  1103. (match tstr with
  1104. (* Internal classes have no dynamic members *)
  1105. | "::String" | "Null" | "::hx::Class" | "::Enum" | "::Math" | "::ArrayAccess" -> false
  1106. | "Dynamic" -> ctx.ctx_dbgout "/*D*/"; true
  1107. | name ->
  1108. let full_name = name ^ "." ^ member in
  1109. ctx.ctx_dbgout ("/*R:"^full_name^"*/");
  1110. try ( let mem_type = (Hashtbl.find ctx.ctx_class_member_types full_name) in mem_type="Dynamic" )
  1111. with Not_found -> true )
  1112. ;;
  1113. let cast_if_required ctx expr to_type =
  1114. let expr_type = (type_string expr.etype) in
  1115. ctx.ctx_dbgout ( "/* cir: " ^ expr_type ^ " */" );
  1116. if (is_dynamic_in_cpp ctx expr) then
  1117. ctx.ctx_output (".Cast< " ^ to_type ^ " >()" )
  1118. ;;
  1119. let is_matching_interface_type t0 t1 =
  1120. (match (follow t0),(follow t1) with
  1121. | TInst (k0,_), TInst(k1,_) -> k0==k1
  1122. | _ -> false
  1123. )
  1124. ;;
  1125. let default_value_string = function
  1126. | TInt i -> Printf.sprintf "%ld" i
  1127. | TFloat float_as_string -> "((Float)" ^ float_as_string ^ ")"
  1128. | TString s -> str s
  1129. | TBool b -> (if b then "true" else "false")
  1130. | TNull -> "null()"
  1131. | _ -> "/* Hmmm */"
  1132. ;;
  1133. let generate_default_values ctx args prefix =
  1134. List.iter ( fun (v,o) -> let type_str = type_string v.v_type in
  1135. let name = (keyword_remap v.v_name) in
  1136. match o with
  1137. | Some TNull -> ()
  1138. | Some const ->
  1139. ctx.ctx_output (type_str ^ " " ^ name ^ " = " ^ prefix ^ name ^ ".Default(" ^
  1140. (default_value_string const) ^ ");\n")
  1141. | _ -> () ) args;;
  1142. let return_type_string t =
  1143. match t with
  1144. | TFun (_,ret) -> type_string ret
  1145. | _ -> ""
  1146. ;;
  1147. let get_return_type field =
  1148. match follow field.cf_type with
  1149. | TFun (_,return_type) -> return_type
  1150. | _ -> raise Not_found
  1151. ;;
  1152. (*
  1153. let rec has_side_effects expr =
  1154. match expr.eexpr with
  1155. | TConst _ | TLocal _ | TFunction _ | TTypeExpr _ -> false
  1156. | TUnop(Increment,_,_) | TUnop(Decrement,_,_) | TBinop(OpAssign,_,_) | TBinop(OpAssignOp _,_,_) -> true
  1157. | TUnop(_,_,e) -> has_side_effects e
  1158. | TArray(e1,e2) | TBinop(_,e1,e2) -> has_side_effects e1 || has_side_effects e2
  1159. | TIf(cond,e1,Some e2) -> has_side_effects cond || has_side_effects e1 || has_side_effects e2
  1160. | TField(e,_) | TParenthesis e -> has_side_effects e
  1161. | TArrayDecl el -> List.exists has_side_effects el
  1162. | TObjectDecl decls -> List.exists (fun (_,e) -> has_side_effects e) decls
  1163. | TCast(e,_) -> has_side_effects e
  1164. | _ -> true
  1165. ;;
  1166. let rec can_be_affected expr =
  1167. match expr.eexpr with
  1168. | TConst _ | TFunction _ | TTypeExpr _ -> false
  1169. | TLocal _ -> true
  1170. | TUnop(Increment,_,_) | TUnop(Decrement,_,_) -> true
  1171. | TUnop(_,_,e) -> can_be_affected e
  1172. | TBinop(OpAssign,_,_) | TBinop(OpAssignOp _,_,_) -> true
  1173. | TBinop(_,e1,e2) -> can_be_affected e1 || can_be_affected e2
  1174. | TField(e,_) -> can_be_affected e
  1175. | TParenthesis e -> can_be_affected e
  1176. | TCast(e,_) -> can_be_affected e
  1177. | TArrayDecl el -> List.exists can_be_affected el
  1178. | TObjectDecl decls -> List.exists (fun (_,e) -> can_be_affected e) decls
  1179. | _ -> true
  1180. ;;
  1181. let call_has_side_effects func args =
  1182. let effects = (if has_side_effects func then 1 else 0) + (List.length (List.filter has_side_effects args)) in
  1183. let affected = (if can_be_affected func then 1 else 0) + (List.length (List.filter can_be_affected args)) in
  1184. effects + affected > 22;
  1185. ;;
  1186. The above code may be overly pessimistic - will have to check performance
  1187. *)
  1188. let has_side_effects expr = false;;
  1189. let call_has_side_effects func args = false;;
  1190. let has_default_values args =
  1191. List.exists ( fun (_,o) -> match o with
  1192. | Some TNull -> false
  1193. | Some _ -> true
  1194. | _ -> false ) args ;;
  1195. exception PathFound of string;;
  1196. let strip_file ctx file = (match Common.defined ctx Common.Define.AbsolutePath with
  1197. | true -> file
  1198. | false -> let flen = String.length file in
  1199. (* Not quite right - should probably test is file exists *)
  1200. try
  1201. List.iter (fun path ->
  1202. let plen = String.length path in
  1203. if (flen>plen && path=(String.sub file 0 plen ))
  1204. then raise (PathFound (String.sub file plen (flen-plen)) ) )
  1205. (ctx.class_path @ ctx.std_path);
  1206. file;
  1207. with PathFound tail ->
  1208. tail)
  1209. ;;
  1210. let hx_stack_push ctx output clazz func_name pos =
  1211. if ctx.ctx_debug_level > 0 then begin
  1212. let stripped_file = strip_file ctx.ctx_common pos.pfile in
  1213. let qfile = "\"" ^ (Ast.s_escape stripped_file) ^ "\"" in
  1214. ctx.ctx_file_info := PMap.add stripped_file pos.pfile !(ctx.ctx_file_info);
  1215. if (ctx.ctx_debug_level>0) then begin
  1216. let hash_class_func = gen_hash 0 (clazz^"."^func_name) in
  1217. let hash_file = gen_hash 0 stripped_file in
  1218. output ("HX_STACK_FRAME(\"" ^ clazz ^ "\",\"" ^ func_name ^ "\"," ^ hash_class_func ^ ",\"" ^
  1219. clazz ^ "." ^ func_name ^ "\"," ^ qfile ^ "," ^
  1220. (string_of_int (Lexer.get_error_line pos) ) ^ "," ^ hash_file ^ ")\n")
  1221. end
  1222. end
  1223. ;;
  1224. (*
  1225. This is the big one.
  1226. Once you get inside a function, all code is generated (recursively) as a "expression".
  1227. "retval" is tracked to determine whether the value on an expression is actually used.
  1228. eg, if the result of a block (ie, the last expression in the list) is used, then
  1229. we have to do some funky stuff to generate a local function.
  1230. Some things that change less often are stored in the context and are extracted
  1231. at the top for simplicity.
  1232. *)
  1233. let rec define_local_function_ctx ctx func_name func_def =
  1234. let writer = ctx.ctx_writer in
  1235. let output_i = writer#write_i in
  1236. let output = ctx.ctx_output in
  1237. let remap_this = function | "this" -> "__this" | other -> other in
  1238. let rec define_local_function func_name func_def =
  1239. let declarations = Hashtbl.create 0 in
  1240. let undeclared = Hashtbl.create 0 in
  1241. (* '__global__', '__cpp__' are always defined *)
  1242. Hashtbl.add declarations "__global__" ();
  1243. Hashtbl.add declarations "__cpp__" ();
  1244. Hashtbl.add declarations "__trace" ();
  1245. (* Add args as defined variables *)
  1246. List.iter ( fun (arg_var, opt_val) ->
  1247. if (ctx.ctx_debug_level>1) then
  1248. output ("/* found arg " ^ arg_var.v_name ^ " = " ^ (type_string arg_var.v_type) ^" */ ");
  1249. Hashtbl.add declarations (keyword_remap arg_var.v_name) () ) func_def.tf_args;
  1250. find_undeclared_variables_ctx ctx undeclared declarations "" true func_def.tf_expr;
  1251. let has_this = Hashtbl.mem undeclared "this" in
  1252. if (has_this) then Hashtbl.remove undeclared "this";
  1253. let typed_vars = hash_iterate undeclared (fun key value -> value ^ "," ^ (keyword_remap key) ) in
  1254. let func_name_sep = func_name ^ (if List.length typed_vars > 0 then "," else "") in
  1255. output_i ("HX_BEGIN_LOCAL_FUNC_S" ^ (list_num typed_vars) ^ "(" ^
  1256. (if has_this then "hx::LocalThisFunc," else "hx::LocalFunc,") ^ func_name_sep ^
  1257. (String.concat "," typed_vars) ^ ")\n" );
  1258. (* actual function, called "run" *)
  1259. let args_and_types = List.map
  1260. (fun (v,_) -> (type_string v.v_type) ^ " " ^ (keyword_remap v.v_name) ) func_def.tf_args in
  1261. let block = is_block func_def.tf_expr in
  1262. let func_type = type_string func_def.tf_type in
  1263. output_i (func_type ^ " run(" ^ (gen_arg_list func_def.tf_args "__o_") ^ ")");
  1264. let close_defaults =
  1265. if (has_default_values func_def.tf_args) then begin
  1266. writer#begin_block;
  1267. output_i "";
  1268. generate_default_values ctx func_def.tf_args "__o_";
  1269. output_i "";
  1270. true;
  1271. end
  1272. else
  1273. false in
  1274. let pop_real_this_ptr = clear_real_this_ptr ctx true in
  1275. writer#begin_block;
  1276. if (ctx.ctx_debug_level>0) then begin
  1277. hx_stack_push ctx output_i "*" func_name func_def.tf_expr.epos;
  1278. if (has_this && ctx.ctx_debug_level>0) then
  1279. output_i ("HX_STACK_THIS(__this.mPtr)\n");
  1280. List.iter (fun (v,_) -> output_i ("HX_STACK_ARG(" ^ (keyword_remap v.v_name) ^ ",\"" ^ v.v_name ^"\")\n") )
  1281. func_def.tf_args;
  1282. end;
  1283. if (block) then begin
  1284. output_i "";
  1285. gen_expression ctx false func_def.tf_expr;
  1286. output_i "return null();\n";
  1287. end else begin
  1288. (* Save old values, and equalize for new input ... *)
  1289. let pop_names = push_anon_names ctx in
  1290. find_local_functions_and_return_blocks_ctx ctx false func_def.tf_expr;
  1291. (match func_def.tf_expr.eexpr with
  1292. | TReturn (Some return_expression) when (func_type<>"Void") ->
  1293. output_i "return ";
  1294. gen_expression ctx true return_expression;
  1295. | TReturn (Some return_expression) ->
  1296. output_i "";
  1297. gen_expression ctx false return_expression;
  1298. | _ ->
  1299. output_i "";
  1300. gen_expression ctx false (to_block func_def.tf_expr);
  1301. );
  1302. output ";\n";
  1303. output_i "return null();\n";
  1304. pop_names();
  1305. end;
  1306. writer#end_block;
  1307. if close_defaults then writer#end_block;
  1308. pop_real_this_ptr();
  1309. let return = if (type_string func_def.tf_type ) = "Void" then "(void)" else "return" in
  1310. output_i ("HX_END_LOCAL_FUNC" ^ (list_num args_and_types) ^ "(" ^ return ^ ")\n\n");
  1311. Hashtbl.replace ctx.ctx_local_function_args func_name
  1312. (if (ctx.ctx_real_this_ptr) then
  1313. String.concat "," (hash_keys undeclared)
  1314. else
  1315. String.concat "," (List.map remap_this (hash_keys undeclared)) )
  1316. in
  1317. define_local_function func_name func_def
  1318. and find_local_functions_and_return_blocks_ctx ctx retval expression =
  1319. let output = ctx.ctx_output in
  1320. let rec find_local_functions_and_return_blocks retval expression =
  1321. match expression.eexpr with
  1322. | TBlock _ ->
  1323. if (retval) then begin
  1324. define_local_return_block_ctx ctx expression (next_anon_function_name ctx) true;
  1325. end (* else we are done *)
  1326. | TTry (_, _)
  1327. | TSwitch (_, _, _) when retval ->
  1328. define_local_return_block_ctx ctx expression (next_anon_function_name ctx) true;
  1329. | TObjectDecl ( ("fileName" , { eexpr = (TConst (TString file)) }) ::
  1330. ("lineNumber" , { eexpr = (TConst (TInt line)) }) ::
  1331. ("className" , { eexpr = (TConst (TString class_name)) }) ::
  1332. ("methodName", { eexpr = (TConst (TString meth)) }) :: [] ) -> ()
  1333. | TObjectDecl decl_list ->
  1334. let name = next_anon_function_name ctx in
  1335. define_local_return_block_ctx ctx expression name true;
  1336. | TCall(func,args) when call_has_side_effects func args ->
  1337. define_local_return_block_ctx ctx expression (next_anon_function_name ctx) retval
  1338. (*| TCall (e,el) -> (* visit function object first, then args *)
  1339. find_local_functions_and_return_blocks e;
  1340. List.iter find_local_functions_and_return_blocks el *)
  1341. | TFunction func ->
  1342. let func_name = next_anon_function_name ctx in
  1343. output "\n";
  1344. define_local_function_ctx ctx func_name func
  1345. | TField (obj,_) | TEnumParameter (obj,_,_) when (is_null obj) -> ( )
  1346. | TArray (obj,_) when (is_null obj) -> ( )
  1347. | TIf ( _ , _ , _ ) when retval -> (* ? operator style *)
  1348. iter_retval find_local_functions_and_return_blocks retval expression
  1349. | TSwitch (_, _, _) when retval -> ( )
  1350. (* | TMatch ( cond , _, _, _) *)
  1351. | TWhile ( cond , _, _ )
  1352. | TIf ( cond , _, _ )
  1353. | TSwitch ( cond , _, _) -> iter_retval find_local_functions_and_return_blocks true cond
  1354. | _ -> iter_retval find_local_functions_and_return_blocks retval expression
  1355. in find_local_functions_and_return_blocks retval expression
  1356. and define_local_return_block_ctx ctx expression name retval =
  1357. let writer = ctx.ctx_writer in
  1358. let output_i = writer#write_i in
  1359. let output = ctx.ctx_output in
  1360. let check_this = function | "this" when not ctx.ctx_real_this_ptr -> "__this" | x -> x in
  1361. let rec define_local_return_block expression =
  1362. let declarations = Hashtbl.create 0 in
  1363. let undeclared = Hashtbl.create 0 in
  1364. (* '__global__' is always defined *)
  1365. Hashtbl.add declarations "__global__" ();
  1366. Hashtbl.add declarations "__cpp__" ();
  1367. Hashtbl.add declarations "__trace" ();
  1368. find_undeclared_variables_ctx ctx undeclared declarations "_obj" true expression;
  1369. let vars = (hash_keys undeclared) in
  1370. let args = String.concat "," (List.map check_this (hash_keys undeclared)) in
  1371. Hashtbl.replace ctx.ctx_local_return_block_args name args;
  1372. output_i ("struct " ^ name);
  1373. writer#begin_block;
  1374. let ret_type = if (not retval) then "Void" else
  1375. match expression.eexpr with
  1376. | TObjectDecl _ -> "Dynamic"
  1377. | _ -> type_string expression.etype in
  1378. (* TODO - analyse usage *)
  1379. let pass_by_value name = (String.length name >=5 ) && (String.sub name 0 5 = "_this") in
  1380. output_i ("inline static " ^ ret_type ^ " Block( ");
  1381. output (String.concat "," (
  1382. (List.map
  1383. (fun var ->
  1384. let var_type = Hashtbl.find undeclared var in
  1385. (* Args passed into inline-block should be references, so they can be changed.
  1386. Fake 'this' pointers can't be changed, so needn't be references *)
  1387. match var with
  1388. | "this" -> "hx::ObjectPtr< " ^ var_type ^ " > __this"
  1389. | name when (pass_by_value name) -> var_type ^ " " ^ name
  1390. | name -> var_type ^ " &" ^name
  1391. ) vars) ) );
  1392. output (")");
  1393. let return_data = ret_type <> "Void" in
  1394. writer#begin_block;
  1395. hx_stack_push ctx output_i "*" "closure" expression.epos;
  1396. output_i "";
  1397. let pop_real_this_ptr = clear_real_this_ptr ctx false in
  1398. (match expression.eexpr with
  1399. | TObjectDecl decl_list ->
  1400. writer#begin_block;
  1401. output_i "hx::Anon __result = hx::Anon_obj::Create();\n";
  1402. let pop_names = push_anon_names ctx in
  1403. List.iter (function (name,value) ->
  1404. find_local_functions_and_return_blocks_ctx ctx true value;
  1405. output_i ( "__result->Add(" ^ (str name) ^ " , ");
  1406. gen_expression ctx true value;
  1407. output (if is_function_expr value then ",true" else ",false" );
  1408. output (");\n");
  1409. ) decl_list;
  1410. pop_names();
  1411. output_i "return __result;\n";
  1412. writer#end_block;
  1413. | TBlock _ ->
  1414. ctx.ctx_return_from_block <- return_data;
  1415. ctx.ctx_return_from_internal_node <- false;
  1416. gen_expression ctx false expression;
  1417. | TCall(func,args) ->
  1418. writer#begin_block;
  1419. let pop_names = push_anon_names ctx in
  1420. find_local_functions_and_return_blocks_ctx ctx true func;
  1421. List.iter (find_local_functions_and_return_blocks_ctx ctx true) args;
  1422. ctx.ctx_tcall_expand_args <- true;
  1423. gen_expression ctx return_data expression;
  1424. output ";\n";
  1425. pop_names();
  1426. writer#end_block;
  1427. | _ ->
  1428. ctx.ctx_return_from_block <- false;
  1429. ctx.ctx_return_from_internal_node <- return_data;
  1430. gen_expression ctx false (to_block expression);
  1431. );
  1432. output_i "return null();\n";
  1433. writer#end_block;
  1434. pop_real_this_ptr();
  1435. writer#end_block_line;
  1436. output ";\n";
  1437. in
  1438. define_local_return_block expression
  1439. and gen_expression ctx retval expression =
  1440. let output = ctx.ctx_output in
  1441. let writer = ctx.ctx_writer in
  1442. let output_i = writer#write_i in
  1443. let calling = ctx.ctx_calling in
  1444. ctx.ctx_calling <- false;
  1445. let assigning = ctx.ctx_assigning in
  1446. ctx.ctx_assigning <- false;
  1447. let return_from_block = ctx.ctx_return_from_block in
  1448. ctx.ctx_return_from_block <- false;
  1449. let tcall_expand_args = ctx.ctx_tcall_expand_args in
  1450. ctx.ctx_tcall_expand_args <- false;
  1451. let return_from_internal_node = ctx.ctx_return_from_internal_node in
  1452. ctx.ctx_return_from_internal_node <- false;
  1453. let dump_src_pos = ctx.ctx_dump_src_pos in
  1454. ctx.ctx_dump_src_pos <- (fun() -> ());
  1455. (* Annotate source code with debug - can get a bit verbose. Mainly for debugging code gen,
  1456. rather than the run time *)
  1457. if (ctx.ctx_debug_level>1) then begin
  1458. (*if calling then output "/* Call */";*)
  1459. (*if ctx.ctx_real_this_ptr then output "/* this */" else output "/* FAKE __this */";*)
  1460. output (debug_expression expression (ctx.ctx_debug_level>1) );
  1461. end;
  1462. (* Write comma separated list of variables - useful for function args. *)
  1463. let rec gen_expression_list expressions =
  1464. (match expressions with
  1465. | [] -> ()
  1466. | [single] -> gen_expression ctx true single
  1467. | first :: remaining ->
  1468. gen_expression ctx true first;
  1469. output ",";
  1470. gen_expression_list remaining
  1471. ) in
  1472. let rec gen_bin_op_string expr1 op expr2 =
  1473. let cast = (match op with
  1474. | ">>" | "<<" | "&" | "|" | "^" -> "int("
  1475. | "&&" | "||" -> "bool("
  1476. | "/" -> "Float("
  1477. | _ -> "") in
  1478. if (op <> "=") then output "(";
  1479. if ( cast <> "") then output cast;
  1480. gen_expression ctx true expr1;
  1481. if ( cast <> "") then output ")";
  1482. output (" " ^ op ^ " ");
  1483. if ( cast <> "") then output cast;
  1484. gen_expression ctx true expr2;
  1485. if ( cast <> "") then output ")";
  1486. if (op <> "=") then output ")";
  1487. in
  1488. let rec is_const_string_term expr =
  1489. match expr.eexpr with
  1490. | TConst( TString _ ) -> true
  1491. | TBinop (OpAdd,e1,e2) -> (is_const_string_term e1) && (is_const_string_term e2 )
  1492. | _ -> false
  1493. in
  1494. let rec combine_string_terms expr =
  1495. match expr.eexpr with
  1496. | TConst( TString s ) -> s
  1497. | TBinop (OpAdd,e1,e2) -> (combine_string_terms e1) ^ (combine_string_terms e2 )
  1498. | _ -> ""
  1499. in
  1500. let rec gen_bin_op op expr1 expr2 =
  1501. match op with
  1502. | Ast.OpAdd when (is_const_string_term expr1) && (is_const_string_term expr2) ->
  1503. output (str ((combine_string_terms expr1) ^ (combine_string_terms expr2)) )
  1504. | Ast.OpAssign -> ctx.ctx_assigning <- true;
  1505. gen_bin_op_string expr1 "=" expr2
  1506. | Ast.OpUShr ->
  1507. output "hx::UShr(";
  1508. gen_expression ctx true expr1;
  1509. output ",";
  1510. gen_expression ctx true expr2;
  1511. output ")";
  1512. | Ast.OpMod ->
  1513. output "hx::Mod(";
  1514. gen_expression ctx true expr1;
  1515. output ",";
  1516. gen_expression ctx true expr2;
  1517. output ")";
  1518. | Ast.OpAssignOp bin_op ->
  1519. output (match bin_op with
  1520. | Ast.OpAdd -> "hx::AddEq("
  1521. | Ast.OpMult -> "hx::MultEq("
  1522. | Ast.OpDiv -> "hx::DivEq("
  1523. | Ast.OpSub -> "hx::SubEq("
  1524. | Ast.OpAnd -> "hx::AndEq("
  1525. | Ast.OpOr -> "hx::OrEq("
  1526. | Ast.OpXor -> "hx::XorEq("
  1527. | Ast.OpShl -> "hx::ShlEq("
  1528. | Ast.OpShr -> "hx::ShrEq("
  1529. | Ast.OpUShr -> "hx::UShrEq("
  1530. | Ast.OpMod -> "hx::ModEq("
  1531. | _ -> error "Unknown OpAssignOp" expression.epos );
  1532. ctx.ctx_assigning <- true;
  1533. gen_expression ctx true expr1;
  1534. output ",";
  1535. gen_expression ctx true expr2;
  1536. output ")"
  1537. | Ast.OpNotEq -> gen_bin_op_string expr1 "!=" expr2
  1538. | Ast.OpEq -> gen_bin_op_string expr1 "==" expr2
  1539. | _ -> gen_bin_op_string expr1 (Ast.s_binop op) expr2
  1540. in
  1541. let gen_array_cast cast_name real_type call =
  1542. output (cast_name ^ "< " ^ real_type ^ " >" ^ call)
  1543. in
  1544. let rec check_array_element_cast array_type cast_name call =
  1545. match follow array_type with
  1546. | TInst (klass,[element]) ->
  1547. ( match type_string element with
  1548. | _ when is_struct_access element -> ()
  1549. | x when cant_be_null x -> ()
  1550. | _ when is_interface_type element -> ()
  1551. | "::String" | "Dynamic" -> ()
  1552. | real_type -> gen_array_cast cast_name real_type call
  1553. )
  1554. | TAbstract (abs,pl) when abs.a_impl <> None ->
  1555. check_array_element_cast (Abstract.get_underlying_type abs pl) cast_name call
  1556. | _ -> ()
  1557. in
  1558. let rec check_array_cast array_type =
  1559. match follow array_type with
  1560. | x when is_interface_type x -> ()
  1561. | TInst (klass,[element]) ->
  1562. let name = type_string element in
  1563. if ( is_object name ) then
  1564. gen_array_cast ".StaticCast" "Array<Dynamic>" "()"
  1565. else
  1566. gen_array_cast ".StaticCast" (type_string array_type) "()"
  1567. | TAbstract (abs,pl) when abs.a_impl <> None ->
  1568. check_array_cast (Abstract.get_underlying_type abs pl)
  1569. | _ -> ()
  1570. in
  1571. let rec gen_tfield field_object field =
  1572. let member = (field_name field) in
  1573. let remap_name = keyword_remap member in
  1574. let already_dynamic = ref false in
  1575. (match field_object.eexpr with
  1576. (* static access ... *)
  1577. | TTypeExpr type_def ->
  1578. (match get_field_access_meta field Meta.Native with
  1579. | "" ->
  1580. let class_name = "::" ^ (join_class_path_remap (t_path type_def) "::" ) in
  1581. if (class_name="::String") then
  1582. output ("::String::" ^ remap_name)
  1583. else
  1584. output (class_name ^ "_obj::" ^ remap_name);
  1585. | native -> output native
  1586. )
  1587. (* Special internal access *)
  1588. | TLocal { v_name = "__global__" } ->
  1589. output ("::" ^ member )
  1590. | TConst TSuper -> output (if ctx.ctx_real_this_ptr then "this" else "__this");
  1591. output ("->super::" ^ remap_name)
  1592. | TConst TThis when ctx.ctx_real_this_ptr -> output ( "this->" ^ remap_name )
  1593. | TConst TNull -> output "null()"
  1594. | _ ->
  1595. gen_expression ctx true field_object;
  1596. ctx.ctx_dbgout "/* TField */";
  1597. (* toString is the only internal member that can be set... *)
  1598. let settingInternal = assigning && member="toString" in
  1599. let isString = (type_string field_object.etype)="::String" in
  1600. if (is_struct_access field_object.etype) then
  1601. output ( "." ^ member )
  1602. else if (is_internal_member member && not settingInternal) then begin
  1603. output ( (if isString then "." else "->") ^ member );
  1604. end else if (settingInternal || is_dynamic_member_lookup_in_cpp ctx field_object field) then begin
  1605. if assigning then
  1606. output ( "->__FieldRef(" ^ (str member) ^ ")" )
  1607. else
  1608. output ( "->__Field(" ^ (str member) ^ ", hx::paccDynamic )" );
  1609. already_dynamic := true;
  1610. end else begin
  1611. if (isString) then
  1612. output ( "." ^ remap_name )
  1613. else begin
  1614. cast_if_required ctx field_object (type_string field_object.etype);
  1615. output ( "->" ^ remap_name );
  1616. if (calling && (is_array field_object.etype) && remap_name="iterator" ) then
  1617. check_array_element_cast field_object.etype "Fast" "";
  1618. already_dynamic := (match field with
  1619. | FInstance(_,_,var) when is_var_field var -> true
  1620. | _ -> false);
  1621. end;
  1622. end;
  1623. );
  1624. if ( (not !already_dynamic) && (not calling) && (not assigning) && (is_function_member expression) ) then
  1625. output "_dyn()";
  1626. in
  1627. let gen_local_block_call () =
  1628. let func_name = use_anon_function_name ctx in (
  1629. try
  1630. output ( func_name ^ "::Block(" ^
  1631. (Hashtbl.find ctx.ctx_local_return_block_args func_name) ^ ")" )
  1632. with Not_found ->
  1633. (*error ("Block function " ^ func_name ^ " not found" ) expression.epos;*)
  1634. output ("/* Block function " ^ func_name ^ " not found */" );
  1635. )
  1636. in
  1637. (match expression.eexpr with
  1638. | TConst TNull when not retval ->
  1639. output "Dynamic()";
  1640. | TCall (func, arg_list) when (match func.eexpr with
  1641. | TLocal { v_name = "__cpp__" } -> true
  1642. | _ -> false) ->
  1643. ( match arg_list with
  1644. | [{ eexpr = TConst (TString code) }] -> output code;
  1645. | ({ eexpr = TConst (TString code) } as ecode) :: tl ->
  1646. Codegen.interpolate_code ctx.ctx_common code tl output (gen_expression ctx true) ecode.epos
  1647. | _ -> error "__cpp__'s first argument must be a string" func.epos;
  1648. )
  1649. | TCall (func, arg_list) when tcall_expand_args->
  1650. let use_temp_func = has_side_effects func in
  1651. if (use_temp_func) then begin
  1652. output_i "Dynamic __func = ";
  1653. gen_expression ctx true func;
  1654. output ";\n";
  1655. end;
  1656. let arg_string = ref "" in
  1657. let idx = ref 0 in
  1658. List.iter (fun arg ->
  1659. let a_name = "__a" ^ string_of_int(!idx) in
  1660. arg_string := !arg_string ^ (if !arg_string<>"" then "," else "") ^ a_name;
  1661. idx := !idx + 1;
  1662. output_i ( (type_string arg.etype) ^ " " ^ a_name ^ " = ");
  1663. gen_expression ctx true arg;
  1664. output ";\n";
  1665. ) arg_list;
  1666. output_i (if retval then "return " else "");
  1667. if use_temp_func then
  1668. output "__func"
  1669. else begin
  1670. ctx.ctx_calling <- true;
  1671. gen_expression ctx true func;
  1672. end;
  1673. output ("(" ^ !arg_string ^ ");\n");
  1674. | TCall (func, arg_list) when is_fromStaticFunction_call func ->
  1675. (match arg_list with
  1676. | [ {eexpr = TField( _, FStatic(klass,field)) } ] ->
  1677. let signature = cpp_function_signature field.cf_type in
  1678. let name = keyword_remap field.cf_name in
  1679. let void_cast = has_meta_key field.cf_meta Meta.Void in
  1680. output ("::cpp::Function<" ^ signature ^">(");
  1681. if (void_cast) then output "hx::AnyCast(";
  1682. output ("&::" ^(join_class_path klass.cl_path "::")^ "_obj::" ^ name );
  1683. if (void_cast) then output ")";
  1684. output (" )");
  1685. | _ -> error "fromStaticFunction must take a static function" expression.epos;
  1686. )
  1687. | TCall (func, [arg]) when is_addressOf_call func && not (is_lvalue arg) ->
  1688. error "addressOf must take a local or member variable" expression.epos;
  1689. | TCall (func, arg_list) ->
  1690. let rec is_variable e = match e.eexpr with
  1691. | TField _ | TEnumParameter _ -> false
  1692. | TLocal { v_name = "__global__" } -> false
  1693. | TParenthesis p | TMeta(_,p) -> is_variable p
  1694. | TCast (e,None) -> is_variable e
  1695. | _ -> true
  1696. in
  1697. let expr_type = type_string expression.etype in
  1698. let rec is_fixed_override e = (not (is_scalar expr_type)) && match e.eexpr with
  1699. | TField(obj,FInstance(_,_,field) ) ->
  1700. let cpp_type = member_type ctx obj field.cf_name in
  1701. (not (is_scalar cpp_type)) && (
  1702. let fixed = (cpp_type<>"?") && (expr_type<>"Dynamic") && (cpp_type<>"Dynamic") &&
  1703. (cpp_type<>expr_type) && (expr_type<>"Void") in
  1704. if (fixed && (ctx.ctx_debug_level>1) ) then begin
  1705. output ("/* " ^ (cpp_type) ^ " != " ^ expr_type ^ " -> cast */");
  1706. end;
  1707. fixed
  1708. )
  1709. | TParenthesis p | TMeta(_,p) -> is_fixed_override p
  1710. | _ -> false
  1711. in
  1712. let check_extern_pointer_cast e = match (remove_parens e).eexpr with
  1713. | TField (_,FInstance(class_def,_,_) )
  1714. | TField (_,FStatic(class_def,_) )
  1715. when class_def.cl_extern ->
  1716. (try
  1717. let return_type = expression.etype in
  1718. (is_pointer return_type false) &&
  1719. ( output ( (type_string return_type) ^ "(" ); true; )
  1720. with Not_found -> false )
  1721. | _ -> false
  1722. in
  1723. let is_super = (match func.eexpr with | TConst TSuper -> true | _ -> false ) in
  1724. if (ctx.ctx_debug_level>1) then output ("/* TCALL ret=" ^ expr_type ^ "*/");
  1725. let is_block_call = call_has_side_effects func arg_list in
  1726. let cast_result = (not is_super) && (is_fixed_override func) in
  1727. if (cast_result) then output ("hx::TCast< " ^ expr_type ^ " >::cast(");
  1728. let cast_result = cast_result || check_extern_pointer_cast func in
  1729. if (is_block_call) then
  1730. gen_local_block_call()
  1731. else begin
  1732. (* If a static function has @:native('new abc')
  1733. c++ new has lower precedence than in haxe so ( ) must be used *)
  1734. let paren_result =
  1735. if is_native_with_space func then
  1736. ( output "("; true )
  1737. else
  1738. false
  1739. in
  1740. ctx.ctx_calling <- true;
  1741. gen_expression ctx true func;
  1742. output "(";
  1743. gen_expression_list arg_list;
  1744. output ")";
  1745. if paren_result then
  1746. output ")";
  1747. end;
  1748. if (cast_result) then output (")");
  1749. if ( (is_variable func) && (not (is_cpp_function_member func) ) &&
  1750. (expr_type<>"Dynamic") && (not is_super) && (not is_block_call)) then
  1751. ctx.ctx_output (".Cast< " ^ expr_type ^ " >()" );
  1752. let rec cast_array_output func =
  1753. match func.eexpr with
  1754. | TField(obj,field) when is_array obj.etype ->
  1755. (match field_name field with
  1756. | "pop" | "shift" -> check_array_element_cast obj.etype ".StaticCast" "()"
  1757. | "map" -> check_array_cast expression.etype
  1758. | _ -> ()
  1759. )
  1760. | TParenthesis p | TMeta(_,p) -> cast_array_output p
  1761. | _ -> ()
  1762. in
  1763. cast_array_output func;
  1764. | TBlock expr_list ->
  1765. if (retval) then
  1766. gen_local_block_call()
  1767. else begin
  1768. writer#begin_block;
  1769. dump_src_pos();
  1770. (* Save old values, and equalize for new input ... *)
  1771. let pop_names = push_anon_names ctx in
  1772. let remaining = ref (List.length expr_list) in
  1773. List.iter (fun expression ->
  1774. let want_value = (return_from_block && !remaining = 1) in
  1775. find_local_functions_and_return_blocks_ctx ctx want_value expression;
  1776. if (ctx.ctx_debug_level>0) then
  1777. output_i ("HX_STACK_LINE(" ^ (string_of_int (Lexer.get_error_line expression.epos)) ^ ")\n" );
  1778. output_i "";
  1779. ctx.ctx_return_from_internal_node <- return_from_internal_node;
  1780. if (want_value) then output "return ";
  1781. gen_expression ctx want_value expression;
  1782. decr remaining;
  1783. writer#terminate_line
  1784. ) expr_list;
  1785. writer#end_block;
  1786. pop_names()
  1787. end
  1788. | TTypeExpr type_expr ->
  1789. let klass = "::" ^ (join_class_path_remap (t_path type_expr) "::" ) in
  1790. let klass1 = if klass="::Array" then "Array<int>" else klass in
  1791. output ("hx::ClassOf< " ^ klass1 ^ " >()")
  1792. | TReturn _ when retval ->
  1793. unsupported expression.epos
  1794. | TReturn optional_expr ->
  1795. output "";
  1796. ( match optional_expr with
  1797. | Some return_expression when ( (type_string expression.etype)="Void") ->
  1798. output "return null(";
  1799. gen_expression ctx true return_expression;
  1800. output ")";
  1801. | Some return_expression ->
  1802. output "return ";
  1803. gen_expression ctx true return_expression
  1804. | _ -> output (if ctx.ctx_real_void then "return" else "return null()")
  1805. )
  1806. | TConst const ->
  1807. (match const with
  1808. | TInt i when ctx.ctx_for_extern -> output (Printf.sprintf "%ld" i)
  1809. | TInt i -> output (Printf.sprintf "(int)%ld" i)
  1810. | TFloat float_as_string -> output ("((Float)" ^ float_as_string ^")")
  1811. | TString s when ctx.ctx_for_extern -> output ("\"" ^ (escape_extern s) ^ "\"")
  1812. | TString s -> output (str s)
  1813. | TBool b -> output (if b then "true" else "false")
  1814. (*| TNull -> output ("((" ^ (type_string expression.etype) ^ ")null())")*)
  1815. | TNull -> output (if ctx.ctx_for_extern then "null" else "null()")
  1816. | TThis -> output (if ctx.ctx_real_this_ptr then "hx::ObjectPtr<OBJ_>(this)" else "__this")
  1817. | TSuper when calling ->
  1818. output (if ctx.ctx_real_this_ptr then
  1819. "super::__construct"
  1820. else
  1821. ("__this->" ^ ctx.ctx_class_super_name ^ "::__construct") )
  1822. | TSuper -> output ("hx::ObjectPtr<super>(" ^ (if ctx.ctx_real_this_ptr then "this" else "__this.mPtr") ^ ")")
  1823. )
  1824. | TLocal v -> output (keyword_remap v.v_name);
  1825. | TArray (array_expr,_) when (is_null array_expr) -> output "Dynamic()"
  1826. | TArray (array_expr,index) ->
  1827. let dynamic = is_dynamic_in_cpp ctx array_expr in
  1828. if ( assigning && (not dynamic) ) then begin
  1829. if (is_array_implementer array_expr.etype) then begin
  1830. output "hx::__ArrayImplRef(";
  1831. gen_expression ctx true array_expr;
  1832. output ",";
  1833. gen_expression ctx true index;
  1834. output ")";
  1835. end else begin
  1836. gen_expression ctx true array_expr;
  1837. output "[";
  1838. gen_expression ctx true index;
  1839. output "]";
  1840. end
  1841. end else if (assigning) then begin
  1842. (* output (" /*" ^ (type_string array_expr.etype) ^ " */ "); *)
  1843. output "hx::IndexRef((";
  1844. gen_expression ctx true array_expr;
  1845. output ").mPtr,";
  1846. gen_expression ctx true index;
  1847. output ")";
  1848. end else if ( dynamic ) then begin
  1849. gen_expression ctx true array_expr;
  1850. output "->__GetItem(";
  1851. gen_expression ctx true index;
  1852. output ")";
  1853. end else begin
  1854. gen_expression ctx true array_expr;
  1855. output "->__get(";
  1856. gen_expression ctx true index;
  1857. output ")";
  1858. if not (is_pointer array_expr.etype true) then
  1859. check_array_element_cast array_expr.etype ".StaticCast" "()";
  1860. end
  1861. (* Get precidence matching haxe ? *)
  1862. | TBinop (op,expr1,expr2) -> gen_bin_op op expr1 expr2
  1863. | TField (expr,_) | TEnumParameter (expr,_,_) when (is_null expr) -> output "Dynamic()"
  1864. | TEnumParameter (expr,ef,i) ->
  1865. let enum = match follow ef.ef_type with
  1866. | TEnum(en,_) | TFun(_,TEnum(en,_)) -> en
  1867. | _ -> assert false
  1868. in
  1869. output ( "(::" ^ (join_class_path_remap enum.e_path "::") ^ "(");
  1870. gen_expression ctx true expr;
  1871. output ( "))->__Param(" ^ (string_of_int i) ^ ")")
  1872. | TField (field_object,field) ->
  1873. gen_tfield field_object field
  1874. | TParenthesis expr when not retval ->
  1875. gen_expression ctx retval expr;
  1876. | TParenthesis expr -> output "("; gen_expression ctx retval expr; output ")"
  1877. | TMeta (_,expr) -> gen_expression ctx retval expr;
  1878. | TObjectDecl (
  1879. ("fileName" , { eexpr = (TConst (TString file)) }) ::
  1880. ("lineNumber" , { eexpr = (TConst (TInt line)) }) ::
  1881. ("className" , { eexpr = (TConst (TString class_name)) }) ::
  1882. ("methodName", { eexpr = (TConst (TString meth)) }) :: [] ) ->
  1883. output ("hx::SourceInfo(" ^ (str file) ^ "," ^ (Printf.sprintf "%ld" line) ^ "," ^
  1884. (str class_name) ^ "," ^ (str meth) ^ ")" )
  1885. | TObjectDecl decl_list -> gen_local_block_call()
  1886. | TArrayDecl decl_list ->
  1887. (* gen_type output expression.etype; *)
  1888. let tstr = (type_string_suff "_obj" expression.etype) in
  1889. if tstr="Dynamic" then
  1890. output "Dynamic( Array_obj<Dynamic>::__new()"
  1891. else
  1892. output ( (type_string_suff "_obj" expression.etype) ^ "::__new()");
  1893. List.iter ( fun elem -> output ".Add(";
  1894. gen_expression ctx true elem;
  1895. output ")" ) decl_list;
  1896. if tstr="Dynamic" then output ")";
  1897. | TNew (klass,params,expressions) ->
  1898. let is_param_array = match klass.cl_path with
  1899. | ([],"Array") when is_dynamic_array_param (List.hd params) -> true | _ -> false
  1900. in
  1901. if is_param_array then
  1902. output "Dynamic( Array_obj<Dynamic>::__new() )"
  1903. else begin
  1904. if (klass.cl_path = ([],"String")) then
  1905. output "::String("
  1906. else
  1907. output ( ( class_string klass "_obj" params) ^ "::__new(" );
  1908. gen_expression_list expressions;
  1909. output ")"
  1910. end
  1911. | TUnop (Ast.NegBits,Ast.Prefix,expr) ->
  1912. output "~(int)(";
  1913. gen_expression ctx true expr;
  1914. output ")"
  1915. | TUnop (op,Ast.Prefix,expr) ->
  1916. ctx.ctx_assigning <- (match op with Ast.Increment | Ast.Decrement -> true | _ ->false);
  1917. output (Ast.s_unop op);
  1918. output "(";
  1919. gen_expression ctx true expr;
  1920. output ")"
  1921. | TUnop (op,Ast.Postfix,expr) ->
  1922. ctx.ctx_assigning <- true;
  1923. output "(";
  1924. gen_expression ctx true expr;
  1925. output ")";
  1926. output (Ast.s_unop op)
  1927. | TFunction func ->
  1928. let func_name = use_anon_function_name ctx in
  1929. (
  1930. try
  1931. output ( " Dynamic(new " ^ func_name ^ "(" ^
  1932. (Hashtbl.find ctx.ctx_local_function_args func_name) ^ "))" )
  1933. with Not_found ->
  1934. (*error ("function " ^ func_name ^ " not found.") expression.epos; *)
  1935. output ("function " ^ func_name ^ " not found.");
  1936. )
  1937. | TVar (tvar,optional_init) ->
  1938. let count = ref 1 in (* TODO: this section can be simplified *)
  1939. if (retval && !count==1) then
  1940. (match optional_init with
  1941. | None -> output "null()"
  1942. | Some expression -> gen_expression ctx true expression )
  1943. else begin
  1944. let type_name = (type_string tvar.v_type) in
  1945. output (if type_name="Void" then "Dynamic" else type_name );
  1946. let name = (keyword_remap tvar.v_name) in
  1947. output (" " ^ name );
  1948. (match optional_init with
  1949. | None -> ()
  1950. | Some expression -> output " = "; gen_expression ctx true expression);
  1951. count := !count -1;
  1952. if (ctx.ctx_debug_level>0) then
  1953. output (";\t\tHX_STACK_VAR(" ^name ^",\""^ tvar.v_name ^"\")");
  1954. if (!count > 0) then begin output ";\n"; output_i "" end
  1955. end
  1956. | TFor (tvar, init, loop) ->
  1957. output ("for(::cpp::FastIterator_obj< " ^ (type_string tvar.v_type) ^
  1958. " > *__it = ::cpp::CreateFastIterator< "^(type_string tvar.v_type) ^ " >(");
  1959. gen_expression ctx true init;
  1960. output ("); __it->hasNext(); )");
  1961. ctx.ctx_writer#begin_block;
  1962. output_i ( (type_string tvar.v_type) ^ " " ^ (keyword_remap tvar.v_name) ^ " = __it->next();\n" );
  1963. output_i "";
  1964. gen_expression ctx false loop;
  1965. output ";\n";
  1966. ctx.ctx_writer#end_block;
  1967. | TIf (condition, if_expr, optional_else_expr) ->
  1968. (match optional_else_expr with
  1969. | Some else_expr ->
  1970. if (retval) then begin
  1971. output "( (";
  1972. gen_expression ctx true condition;
  1973. output ") ? ";
  1974. let type_str = match (type_string expression.etype) with
  1975. | "Void" -> "Dynamic"
  1976. | other -> other
  1977. in
  1978. output (type_str ^ "(");
  1979. gen_expression ctx true if_expr;
  1980. output ") : ";
  1981. output (type_str ^ "(");
  1982. gen_expression ctx true else_expr;
  1983. output ") )";
  1984. end else begin
  1985. output "if (";
  1986. gen_expression ctx true condition;
  1987. output ")";
  1988. gen_expression ctx false (to_block if_expr);
  1989. output_i "else";
  1990. gen_expression ctx false (to_block else_expr);
  1991. end
  1992. | _ -> output "if (";
  1993. gen_expression ctx true condition;
  1994. output ")";
  1995. gen_expression ctx false (to_block if_expr);
  1996. )
  1997. | TWhile (condition, repeat, Ast.NormalWhile ) ->
  1998. output "while(";
  1999. gen_expression ctx true condition;
  2000. output ")";
  2001. gen_expression ctx false (to_block repeat)
  2002. | TWhile (condition, repeat, Ast.DoWhile ) ->
  2003. output "do";
  2004. gen_expression ctx false (to_block repeat);
  2005. output "while(";
  2006. gen_expression ctx true condition;
  2007. output ")"
  2008. (* These have already been defined in find_local_return_blocks ... *)
  2009. | TTry (_,_)
  2010. | TSwitch (_,_,_) when (retval && (not return_from_internal_node) ) ->
  2011. gen_local_block_call()
  2012. | TSwitch (condition,cases,optional_default) ->
  2013. let switch_on_int_constants = (only_int_cases cases) && (not (contains_break expression)) in
  2014. if (switch_on_int_constants) then begin
  2015. output "switch( (int)";
  2016. gen_expression ctx true condition;
  2017. output ")";
  2018. ctx.ctx_writer#begin_block;
  2019. List.iter (fun (cases_list,expression) ->
  2020. output_i "";
  2021. List.iter (fun value -> output "case ";
  2022. gen_expression ctx true value;
  2023. output ": " ) cases_list;
  2024. ctx.ctx_return_from_block <- return_from_internal_node;
  2025. gen_expression ctx false (to_block expression);
  2026. output_i ";break;\n";
  2027. ) cases;
  2028. (match optional_default with | None -> ()
  2029. | Some default ->
  2030. output_i "default: ";
  2031. ctx.ctx_return_from_block <- return_from_internal_node;
  2032. gen_expression ctx false (to_block default);
  2033. );
  2034. ctx.ctx_writer#end_block;
  2035. end else begin
  2036. let tmp_name = get_switch_var ctx in
  2037. output ( (type_string condition.etype) ^ " " ^ tmp_name ^ " = " );
  2038. gen_expression ctx true condition;
  2039. output ";\n";
  2040. let else_str = ref "" in
  2041. if (List.length cases > 0) then
  2042. List.iter (fun (cases,expression) ->
  2043. output_i ( !else_str ^ "if ( ");
  2044. else_str := "else ";
  2045. let or_str = ref "" in
  2046. List.iter (fun value ->
  2047. output (!or_str ^ " ( " ^ tmp_name ^ "==");
  2048. gen_expression ctx true value;
  2049. output ")";
  2050. or_str := " || ";
  2051. ) cases;
  2052. output (")");
  2053. ctx.ctx_return_from_block <- return_from_internal_node;
  2054. gen_expression ctx false (to_block expression);
  2055. ) cases;
  2056. (match optional_default with | None -> ()
  2057. | Some default ->
  2058. output_i ( !else_str ^ " ");
  2059. ctx.ctx_return_from_block <- return_from_internal_node;
  2060. gen_expression ctx false (to_block default);
  2061. output ";\n";
  2062. );
  2063. end
  2064. | TTry (expression, catch_list) ->
  2065. output "try\n";
  2066. output_i "{\n";
  2067. let counter = ref 0 in
  2068. List.iter (fun (v, e) ->
  2069. let type_name = type_string v.v_type in
  2070. output_i ("HX_STACK_CATCHABLE(" ^ type_name ^ ", " ^ string_of_int !counter ^ ");\n");
  2071. counter := !counter + 1;)
  2072. catch_list;
  2073. output_i("");
  2074. (* Move this "inside" the try call ... *)
  2075. ctx.ctx_return_from_block <-return_from_internal_node;
  2076. gen_expression ctx false (to_block expression);
  2077. output_i "}\n";
  2078. if (List.length catch_list > 0 ) then begin
  2079. output_i "catch(Dynamic __e)";
  2080. ctx.ctx_writer#begin_block;
  2081. let seen_dynamic = ref false in
  2082. let else_str = ref "" in
  2083. List.iter (fun (v,expression) ->
  2084. let type_name = type_string v.v_type in
  2085. if (type_name="Dynamic") then begin
  2086. seen_dynamic := true;
  2087. output_i !else_str;
  2088. end else
  2089. output_i (!else_str ^ "if (__e.IsClass< " ^ type_name ^ " >() )");
  2090. ctx.ctx_writer#begin_block;
  2091. output_i "HX_STACK_BEGIN_CATCH\n";
  2092. output_i (type_name ^ " " ^ v.v_name ^ " = __e;");
  2093. (* Move this "inside" the catch call too ... *)
  2094. ctx.ctx_return_from_block <-return_from_internal_node;
  2095. gen_expression ctx false (to_block expression);
  2096. ctx.ctx_writer#end_block;
  2097. else_str := "else ";
  2098. ) catch_list;
  2099. if (not !seen_dynamic) then begin
  2100. output_i "else {\n";
  2101. output_i " HX_STACK_DO_THROW(__e);\n";
  2102. output_i "}\n";
  2103. end;
  2104. ctx.ctx_writer#end_block;
  2105. end;
  2106. | TBreak -> output "break"
  2107. | TContinue -> output "continue"
  2108. | TThrow expression ->
  2109. output "HX_STACK_DO_THROW(";
  2110. gen_expression ctx true expression;
  2111. output ")";
  2112. | TCast (cast,None) ->
  2113. let void_cast = retval && ((type_string expression.etype)="Void" ) in
  2114. if (void_cast) then output "Void(";
  2115. gen_expression ctx retval cast;
  2116. if (void_cast) then output ")";
  2117. | TCast (e1,Some t) ->
  2118. let class_name = (join_class_path_remap (t_path t) "::" ) in
  2119. if (class_name="Array") then
  2120. output ("hx::TCastToArray(" )
  2121. else
  2122. output ("hx::TCast< ::" ^ class_name ^ " >::cast(" );
  2123. gen_expression ctx true e1;
  2124. output ")";
  2125. );;
  2126. (*
  2127. let is_dynamic_haxe_method f =
  2128. match follow f.cf_type with
  2129. | TFun _ when f.cf_expr = None -> true
  2130. | _ ->
  2131. (match f.cf_expr with
  2132. | Some { eexpr = TFunction fd } when f.cf_set = MethodAccess true -> true
  2133. | Some { eexpr = TFunction fd } when f.cf_set = NormalAccess -> true
  2134. | _ -> false);;
  2135. *)
  2136. let is_dynamic_haxe_method f =
  2137. (match f.cf_expr, f.cf_kind with
  2138. | Some { eexpr = TFunction _ }, (Var _ | Method MethDynamic) -> true
  2139. | _ -> false);;
  2140. let is_data_member field =
  2141. match field.cf_expr with
  2142. | Some { eexpr = TFunction function_def } -> is_dynamic_haxe_method field
  2143. | _ -> true;;
  2144. let is_override class_def field =
  2145. List.exists (fun f -> f.cf_name = field) class_def.cl_overrides
  2146. ;;
  2147. let rec all_virtual_functions clazz =
  2148. (List.fold_left (fun result elem -> match follow elem.cf_type, elem.cf_kind with
  2149. | _, Method MethDynamic -> result
  2150. | TFun (args,return_type), Method _ when not (is_override clazz elem.cf_name ) -> (elem,args,return_type) :: result
  2151. | _,_ -> result ) [] clazz.cl_ordered_fields)
  2152. @ (match clazz.cl_super with
  2153. | Some def -> all_virtual_functions (fst def)
  2154. | _ -> [] )
  2155. ;;
  2156. let field_arg_count field =
  2157. match follow field.cf_type, field.cf_kind with
  2158. | _, Method MethDynamic -> -1
  2159. | TFun (args,return_type), Method _ -> List.length args
  2160. | _,_ -> -1
  2161. ;;
  2162. (* external mem Dynamic & *)
  2163. let gen_field ctx class_def class_name ptr_name dot_name is_static is_interface field =
  2164. let output = ctx.ctx_output in
  2165. ctx.ctx_real_this_ptr <- not is_static;
  2166. let remap_name = keyword_remap field.cf_name in
  2167. let decl = get_meta_string field.cf_meta Meta.Decl in
  2168. let has_decl = decl <> "" in
  2169. if (is_interface) then begin
  2170. (* Just the dynamic glue - not even that ... *)
  2171. ()
  2172. end else (match field.cf_expr with
  2173. (* Function field *)
  2174. | Some { eexpr = TFunction function_def } ->
  2175. let return_type = (type_string function_def.tf_type) in
  2176. let nargs = string_of_int (List.length function_def.tf_args) in
  2177. let is_void = (type_string function_def.tf_type ) = "Void" in
  2178. let ret = if is_void then "(void)" else "return " in
  2179. let output_i = ctx.ctx_writer#write_i in
  2180. let orig_debug = ctx.ctx_debug_level in
  2181. let dump_src = if ((Meta.has Meta.NoStack field.cf_meta)||(Meta.has Meta.NoDebug field.cf_meta) || orig_debug<1) then begin
  2182. ctx.ctx_debug_level <- 0;
  2183. (fun()->())
  2184. end else begin
  2185. (fun() ->
  2186. hx_stack_push ctx output_i dot_name field.cf_name function_def.tf_expr.epos;
  2187. if (not is_static) then output_i ("HX_STACK_THIS(this)\n");
  2188. List.iter (fun (v,_) -> output_i ("HX_STACK_ARG(" ^ (keyword_remap v.v_name) ^ ",\"" ^ v.v_name ^"\")\n") )
  2189. function_def.tf_args )
  2190. end in
  2191. if (not (is_dynamic_haxe_method field)) then begin
  2192. (* The actual function definition *)
  2193. let real_void = is_void && (has_meta_key field.cf_meta Meta.Void) in
  2194. let fake_void = is_void && not real_void in
  2195. output (if real_void then "void" else return_type );
  2196. output (" " ^ class_name ^ "::" ^ remap_name ^ "( " );
  2197. output (gen_arg_list function_def.tf_args "__o_");
  2198. output ")";
  2199. ctx.ctx_real_this_ptr <- true;
  2200. ctx.ctx_real_void <- real_void;
  2201. ctx.ctx_dynamic_this_ptr <- false;
  2202. let code = (get_code field.cf_meta Meta.FunctionCode) in
  2203. let tail_code = (get_code field.cf_meta Meta.FunctionTailCode) in
  2204. if (has_default_values function_def.tf_args) then begin
  2205. ctx.ctx_writer#begin_block;
  2206. generate_default_values ctx function_def.tf_args "__o_";
  2207. dump_src();
  2208. output code;
  2209. gen_expression ctx false function_def.tf_expr;
  2210. output tail_code;
  2211. if (fake_void) then output "return null();\n";
  2212. ctx.ctx_writer#end_block;
  2213. end else begin
  2214. let add_block = is_void || (code <> "") || (tail_code <> "") in
  2215. if (add_block) then ctx.ctx_writer#begin_block;
  2216. ctx.ctx_dump_src_pos <- dump_src;
  2217. output code;
  2218. gen_expression ctx false (to_block function_def.tf_expr);
  2219. output tail_code;
  2220. if (add_block) then begin
  2221. if (fake_void) then output "return null();\n";
  2222. ctx.ctx_writer#end_block;
  2223. end;
  2224. end;
  2225. output "\n\n";
  2226. (* generate dynamic version too ... *)
  2227. if ( not (is_override class_def field.cf_name ) ) then begin
  2228. if (is_static) then output "STATIC_";
  2229. output ("HX_DEFINE_DYNAMIC_FUNC" ^ nargs ^ "(" ^ class_name ^ "," ^
  2230. remap_name ^ "," ^ ret ^ ")\n\n");
  2231. end;
  2232. end else begin
  2233. ctx.ctx_real_this_ptr <- false;
  2234. ctx.ctx_dynamic_this_ptr <- false;
  2235. let func_name = "__default_" ^ (remap_name) in
  2236. output ("HX_BEGIN_DEFAULT_FUNC(" ^ func_name ^ "," ^ class_name ^ ")\n");
  2237. output return_type;
  2238. output (" run(" ^ (gen_arg_list function_def.tf_args "") ^ ")");
  2239. ctx.ctx_dump_src_pos <- dump_src;
  2240. if (is_void) then begin
  2241. ctx.ctx_writer#begin_block;
  2242. gen_expression ctx false function_def.tf_expr;
  2243. output "return null();\n";
  2244. ctx.ctx_writer#end_block;
  2245. end else
  2246. gen_expression ctx false (to_block function_def.tf_expr);
  2247. output ("HX_END_LOCAL_FUNC" ^ nargs ^ "(" ^ ret ^ ")\n");
  2248. output ("HX_END_DEFAULT_FUNC\n\n");
  2249. if (is_static) then
  2250. output ( "Dynamic " ^ class_name ^ "::" ^ remap_name ^ ";\n\n");
  2251. end;
  2252. ctx.ctx_debug_level <- orig_debug
  2253. (* Data field *)
  2254. | _ when has_decl ->
  2255. if is_static then begin
  2256. output ( class_name ^ "::" ^ remap_name ^ "_decl ");
  2257. output ( " " ^ class_name ^ "::" ^ remap_name ^ ";\n\n");
  2258. end
  2259. | _ ->
  2260. if is_static && (not (is_extern_field field)) then begin
  2261. gen_type ctx field.cf_type;
  2262. output ( " " ^ class_name ^ "::" ^ remap_name ^ ";\n\n");
  2263. end
  2264. )
  2265. ;;
  2266. let gen_field_init ctx field =
  2267. let output = ctx.ctx_output in
  2268. let remap_name = keyword_remap field.cf_name in
  2269. (match field.cf_expr with
  2270. (* Function field *)
  2271. | Some { eexpr = TFunction function_def } ->
  2272. if (is_dynamic_haxe_method field) then begin
  2273. let func_name = "__default_" ^ (remap_name) in
  2274. output ( "\t" ^ remap_name ^ " = new " ^ func_name ^ ";\n\n" );
  2275. end
  2276. (* Data field *)
  2277. | _ -> (match field.cf_expr with
  2278. | Some expr ->
  2279. find_local_functions_and_return_blocks_ctx ctx true expr;
  2280. output ( match remap_name with "__meta__" -> "\t__mClass->__meta__=" | _ -> "\t" ^ remap_name ^ "= ");
  2281. gen_expression ctx true expr;
  2282. output ";\n"
  2283. | _ -> ( )
  2284. );
  2285. )
  2286. ;;
  2287. let has_field_init field =
  2288. match field.cf_expr with
  2289. (* Function field *)
  2290. | Some { eexpr = TFunction function_def } -> is_dynamic_haxe_method field
  2291. (* Data field *)
  2292. | Some _ -> true
  2293. | _ -> false
  2294. ;;
  2295. let gen_member_def ctx class_def is_static is_interface field =
  2296. let output = ctx.ctx_output in
  2297. let remap_name = keyword_remap field.cf_name in
  2298. if (is_interface) then begin
  2299. match follow field.cf_type, field.cf_kind with
  2300. | _, Method MethDynamic -> ()
  2301. | TFun (args,return_type), Method _ ->
  2302. output ( (if (not is_static) then " virtual " else " " ) ^ type_string return_type);
  2303. output (" " ^ remap_name ^ "( " );
  2304. output (gen_tfun_interface_arg_list args);
  2305. output (if (not is_static) then ")=0;\n" else ");\n");
  2306. output (if is_static then "\t\tstatic " else "\t\t");
  2307. output ("virtual Dynamic " ^ remap_name ^ "_dyn()=0;\n" );
  2308. | _ -> ( )
  2309. end else begin
  2310. let decl = get_meta_string field.cf_meta Meta.Decl in
  2311. let has_decl = decl <> "" in
  2312. if (has_decl) then
  2313. output ( " typedef " ^ decl ^ ";\n" );
  2314. output (if is_static then "\t\tstatic " else "\t\t");
  2315. (match field.cf_expr with
  2316. | Some { eexpr = TFunction function_def } ->
  2317. if ( is_dynamic_haxe_method field ) then begin
  2318. if ( not (is_override class_def field.cf_name ) ) then begin
  2319. output ("Dynamic " ^ remap_name ^ ";\n");
  2320. output (if is_static then "\t\tstatic " else "\t\t");
  2321. output ("inline Dynamic &" ^ remap_name ^ "_dyn() " ^ "{return " ^ remap_name^ "; }\n")
  2322. end
  2323. end else begin
  2324. let return_type = (type_string function_def.tf_type) in
  2325. if (not is_static) then output "virtual ";
  2326. output (if return_type="Void" && (has_meta_key field.cf_meta Meta.Void) then "void" else return_type );
  2327. output (" " ^ remap_name ^ "( " );
  2328. output (gen_arg_list function_def.tf_args "" );
  2329. output ");\n";
  2330. if ( not (is_override class_def field.cf_name ) ) then begin
  2331. output (if is_static then "\t\tstatic " else "\t\t");
  2332. output ("Dynamic " ^ remap_name ^ "_dyn();\n" )
  2333. end;
  2334. end;
  2335. output "\n";
  2336. | _ when has_decl ->
  2337. output ( remap_name ^ "_decl " ^ remap_name ^ ";\n" );
  2338. (* Variable access *)
  2339. | _ ->
  2340. (* Variable access *)
  2341. gen_type ctx field.cf_type;
  2342. output (" " ^ remap_name ^ ";\n" );
  2343. (* Add a "dyn" function for variable to unify variable/function access *)
  2344. (match follow field.cf_type with
  2345. | TFun (_,_) ->
  2346. output (if is_static then "\t\tstatic " else "\t\t");
  2347. gen_type ctx field.cf_type;
  2348. output (" &" ^ remap_name ^ "_dyn() { return " ^ remap_name ^ ";}\n" )
  2349. | _ -> (match field.cf_kind with
  2350. | Var { v_read = AccCall } when (not is_static) && (is_dynamic_accessor ("get_" ^ field.cf_name) "get" field class_def) ->
  2351. output ("\t\tDynamic get_" ^ field.cf_name ^ ";\n" )
  2352. | _ -> ()
  2353. );
  2354. (match field.cf_kind with
  2355. | Var { v_write = AccCall } when (not is_static) && (is_dynamic_accessor ("set_" ^ field.cf_name) "set" field class_def) ->
  2356. output ("\t\tDynamic set_" ^ field.cf_name ^ ";\n" )
  2357. | _ -> ()
  2358. )
  2359. )
  2360. );
  2361. end
  2362. ;;
  2363. let path_of_string path =
  2364. ["@verbatim"], path
  2365. ;;
  2366. (*
  2367. Get a list of all classes referred to by the class/enum definition
  2368. These are used for "#include"ing the appropriate header files,
  2369. or for building the dependencies in the Build.xml file
  2370. *)
  2371. let find_referenced_types ctx obj super_deps constructor_deps header_only for_depends include_super_args =
  2372. let types = ref PMap.empty in
  2373. let rec add_type in_path =
  2374. if ( not (PMap.mem in_path !types)) then begin
  2375. types := (PMap.add in_path () !types);
  2376. try
  2377. List.iter add_type (Hashtbl.find super_deps in_path);
  2378. with Not_found -> ()
  2379. end
  2380. in
  2381. let add_extern_class klass =
  2382. let include_file = get_meta_string klass.cl_meta (if for_depends then Meta.Depend else Meta.Include) in
  2383. if (include_file<>"") then
  2384. add_type ( path_of_string include_file )
  2385. else if (not for_depends) && (has_meta_key klass.cl_meta Meta.Include) then
  2386. add_type klass.cl_path
  2387. in
  2388. let visited = ref [] in
  2389. let rec visit_type in_type =
  2390. if not (List.exists (fun t2 -> Type.fast_eq in_type t2) !visited) then begin
  2391. visited := in_type :: !visited;
  2392. begin match follow in_type with
  2393. | TMono r -> (match !r with None -> () | Some t -> visit_type t)
  2394. | TEnum (enum,params) -> add_type enum.e_path
  2395. (* If a class has a template parameter, then we treat it as dynamic - except
  2396. for the Array, Class, FastIterator or Pointer classes, for which we do a fully typed object *)
  2397. | TInst (klass,params) ->
  2398. (match klass.cl_path with
  2399. | ([],"Array") | ([],"Class") | (["cpp"],"FastIterator")
  2400. | (["cpp"],"Pointer") | (["cpp"],"ConstPointer") | (["cpp"],"Function")
  2401. | (["cpp"],"RawPointer") | (["cpp"],"RawConstPointer") -> List.iter visit_type params
  2402. | _ when is_extern_class klass -> add_extern_class klass
  2403. | _ -> (match klass.cl_kind with KTypeParameter _ -> () | _ -> add_type klass.cl_path);
  2404. )
  2405. | TFun (args,haxe_type) -> visit_type haxe_type;
  2406. List.iter (fun (_,_,t) -> visit_type t; ) args;
  2407. | _ -> ()
  2408. end;
  2409. visited := List.tl !visited;
  2410. end
  2411. in
  2412. let rec visit_params expression =
  2413. begin
  2414. let rec visit_expression = fun expression ->
  2415. (* Expand out TTypeExpr (ie, the name of a class, as used for static access etc ... *)
  2416. (match expression.eexpr with
  2417. | TTypeExpr type_def -> ( match type_def with
  2418. | TClassDecl class_def when is_extern_class class_def -> add_extern_class class_def
  2419. | _ -> add_type (t_path type_def)
  2420. )
  2421. (* Must visit the types, Type.iter will visit the expressions ... *)
  2422. | TTry (e,catches) ->
  2423. List.iter (fun (v,_) -> visit_type v.v_type) catches
  2424. (* Must visit the enum param types, Type.iter will visit the rest ... *)
  2425. (* | TMatch (_,enum,cases,_) ->
  2426. add_type (fst enum).e_path;
  2427. List.iter (fun (case_ids,params,expression) ->
  2428. (match params with
  2429. | None -> ()
  2430. | Some l -> List.iter (function None -> () | Some v -> visit_type v.v_type) l ) ) cases; *)
  2431. (* Must visit type too, Type.iter will visit the expressions ... *)
  2432. | TNew (klass,params,_) -> begin
  2433. visit_type (TInst (klass,params));
  2434. try
  2435. let construct_type = Hashtbl.find constructor_deps klass.cl_path in
  2436. visit_type construct_type.cf_type
  2437. with Not_found -> ();
  2438. end
  2439. (* Must visit type too, Type.iter will visit the expressions ... *)
  2440. | TVar (v,_) ->
  2441. visit_type v.v_type
  2442. (* Must visit enum type too, Type.iter will visit the expressions ... *)
  2443. | TEnumParameter (_,ef,_) -> visit_type (follow ef.ef_type)
  2444. (* Must visit args too, Type.iter will visit the expressions ... *)
  2445. | TFunction func_def ->
  2446. List.iter (fun (v,_) -> visit_type v.v_type) func_def.tf_args;
  2447. | TConst TSuper ->
  2448. (match follow expression.etype with
  2449. | TInst (klass,params) ->
  2450. (try let construct_type = Hashtbl.find constructor_deps klass.cl_path in
  2451. visit_type construct_type.cf_type
  2452. with Not_found -> () )
  2453. | _ -> print_endline ("TSuper : Odd etype ?" ^ ( (type_string expression.etype)) )
  2454. )
  2455. | _ -> ()
  2456. );
  2457. Type.iter visit_expression expression;
  2458. visit_type (follow expression.etype)
  2459. in
  2460. visit_expression expression
  2461. end
  2462. in
  2463. let visit_field field =
  2464. (* Add the type of the expression ... *)
  2465. visit_type field.cf_type;
  2466. if (not header_only) then
  2467. (match field.cf_expr with
  2468. | Some expression -> visit_params expression | _ -> ());
  2469. in
  2470. let visit_class class_def =
  2471. let fields = List.append class_def.cl_ordered_fields class_def.cl_ordered_statics in
  2472. let fields_and_constructor = List.append fields
  2473. (match class_def.cl_constructor with | Some expr -> [expr] | _ -> [] ) in
  2474. List.iter visit_field fields_and_constructor;
  2475. if (include_super_args) then
  2476. List.iter visit_field (List.map (fun (a,_,_) -> a ) (all_virtual_functions class_def ));
  2477. (* Add super & interfaces *)
  2478. add_type class_def.cl_path;
  2479. in
  2480. let visit_enum enum_def =
  2481. add_type enum_def.e_path;
  2482. PMap.iter (fun _ constructor ->
  2483. (match constructor.ef_type with
  2484. | TFun (args,_) ->
  2485. List.iter (fun (_,_,t) -> visit_type t; ) args;
  2486. | _ -> () );
  2487. ) enum_def.e_constrs;
  2488. if (not header_only) then begin
  2489. let meta = Codegen.build_metadata ctx (TEnumDecl enum_def) in
  2490. match meta with Some expr -> visit_params expr | _ -> ();
  2491. end;
  2492. in
  2493. let inc_cmp i1 i2 =
  2494. String.compare (join_class_path i1 ".") (join_class_path i2 ".")
  2495. in
  2496. (* Body of main function *)
  2497. (match obj with
  2498. | TClassDecl class_def -> visit_class class_def;
  2499. (match class_def.cl_init with Some expression -> visit_params expression | _ -> ())
  2500. | TEnumDecl enum_def -> visit_enum enum_def
  2501. | TTypeDecl _ | TAbstractDecl _ -> (* These are expanded *) ());
  2502. List.sort inc_cmp (List.filter (fun path -> (include_class_header path) ) (pmap_keys !types))
  2503. ;;
  2504. let generate_main_header output_main =
  2505. output_main "#include <hxcpp.h>\n\n";
  2506. output_main "#include <stdio.h>\n\n";
  2507. output_main "extern \"C\" void __hxcpp_main();\n\n";
  2508. output_main "extern \"C\" void __hxcpp_lib_main();\n\n"
  2509. ;;
  2510. let generate_main_footer1 output_main =
  2511. output_main "void __hxcpp_main() {\n";;
  2512. let generate_main_footer2 output_main =
  2513. output_main " }\n\n";
  2514. output_main "void __hxcpp_lib_main() {\n";
  2515. output_main " HX_TOP_OF_STACK\n";
  2516. output_main " hx::Boot();\n";
  2517. output_main " __boot_all();\n";
  2518. output_main " __hxcpp_main();\n";
  2519. output_main " }\n"
  2520. ;;
  2521. let generate_main common_ctx member_types super_deps class_def file_info =
  2522. (* main routine should be a single static function *)
  2523. let main_expression =
  2524. (match class_def.cl_ordered_statics with
  2525. | [{ cf_expr = Some expression }] -> expression;
  2526. | _ -> assert false ) in
  2527. ignore(find_referenced_types common_ctx (TClassDecl class_def) super_deps (Hashtbl.create 0) false false false);
  2528. let depend_referenced = find_referenced_types common_ctx (TClassDecl class_def) super_deps (Hashtbl.create 0) false true false in
  2529. let generate_startup filename is_main =
  2530. (*make_class_directories base_dir ( "src" :: []);*)
  2531. let cpp_file = new_cpp_file common_ctx common_ctx.file ([],filename) in
  2532. let output_main = (cpp_file#write) in
  2533. generate_main_header output_main;
  2534. List.iter ( add_include cpp_file ) depend_referenced;
  2535. output_main "\n\n";
  2536. if is_main then output_main "\n#include <hx/HxcppMain.h>\n\n";
  2537. generate_main_footer1 output_main;
  2538. gen_expression (new_context common_ctx cpp_file 1 file_info) false main_expression;
  2539. output_main ";\n";
  2540. generate_main_footer2 output_main;
  2541. cpp_file#close;
  2542. in
  2543. generate_startup "__main__" true;
  2544. generate_startup "__lib__" false
  2545. ;;
  2546. let generate_dummy_main common_ctx =
  2547. let generate_startup filename is_main =
  2548. let main_file = new_cpp_file common_ctx common_ctx.file ([],filename) in
  2549. let output_main = (main_file#write) in
  2550. generate_main_header output_main;
  2551. if is_main then output_main "\n#include <hx/HxcppMain.h\n\n";
  2552. generate_main_footer1 output_main;
  2553. generate_main_footer2 output_main;
  2554. main_file#close;
  2555. in
  2556. generate_startup "__main__" true;
  2557. generate_startup "__lib__" false
  2558. ;;
  2559. let generate_boot common_ctx boot_enums boot_classes nonboot_classes init_classes =
  2560. (* Write boot class too ... *)
  2561. let base_dir = common_ctx.file in
  2562. let boot_file = new_cpp_file common_ctx base_dir ([],"__boot__") in
  2563. let output_boot = (boot_file#write) in
  2564. output_boot "#include <hxcpp.h>\n\n";
  2565. List.iter ( fun class_path -> boot_file#add_include class_path )
  2566. (boot_enums @ boot_classes @ nonboot_classes);
  2567. output_boot "\nvoid __files__boot();\n";
  2568. output_boot "\nvoid __boot_all()\n{\n";
  2569. output_boot "__files__boot();\n";
  2570. output_boot "hx::RegisterResources( hx::GetResources() );\n";
  2571. List.iter ( fun class_path ->
  2572. output_boot ("::" ^ ( join_class_path_remap class_path "::" ) ^ "_obj::__register();\n") )
  2573. (boot_enums @ boot_classes @ nonboot_classes);
  2574. let dump_boot =
  2575. List.iter ( fun class_path ->
  2576. output_boot ("::" ^ ( join_class_path_remap class_path "::" ) ^ "_obj::__boot();\n") ) in
  2577. dump_boot boot_enums;
  2578. List.iter ( fun class_path ->
  2579. output_boot ("::" ^ ( join_class_path_remap class_path "::" ) ^ "_obj::__init__();\n") ) (List.rev init_classes);
  2580. dump_boot (List.filter (fun path -> is_cpp_class path ) (List.rev boot_classes));
  2581. dump_boot (List.filter (fun path -> not (is_cpp_class path) ) (List.rev boot_classes));
  2582. output_boot "}\n\n";
  2583. boot_file#close;;
  2584. let generate_files common_ctx file_info =
  2585. (* Write __files__ class too ... *)
  2586. let base_dir = common_ctx.file in
  2587. let files_file = new_cpp_file common_ctx base_dir ([],"__files__") in
  2588. let output_files = (files_file#write) in
  2589. let types = common_ctx.types in
  2590. output_files "#include <hxcpp.h>\n\n";
  2591. output_files "namespace hx {\n";
  2592. output_files "const char *__hxcpp_all_files[] = {\n";
  2593. output_files "#ifdef HXCPP_DEBUGGER\n";
  2594. List.iter ( fun file -> output_files ((const_char_star file)^",\n" ) )
  2595. ( List.sort String.compare ( pmap_keys !file_info) );
  2596. output_files "#endif\n";
  2597. output_files " 0 };\n";
  2598. output_files "\n";
  2599. output_files "const char *__hxcpp_all_files_fullpath[] = {\n";
  2600. output_files "#ifdef HXCPP_DEBUGGER\n";
  2601. List.iter ( fun file -> output_files ((const_char_star (
  2602. Common.get_full_path (try Common.find_file common_ctx file with Not_found -> file)
  2603. ))^",\n" ) )
  2604. ( List.sort String.compare ( pmap_keys !file_info) );
  2605. output_files "#endif\n";
  2606. output_files " 0 };\n";
  2607. output_files "\n";
  2608. output_files "const char *__hxcpp_all_classes[] = {\n";
  2609. output_files "#ifdef HXCPP_DEBUGGER\n";
  2610. List.iter ( fun object_def ->
  2611. (match object_def with
  2612. | TClassDecl class_def when is_extern_class class_def -> ( )
  2613. | TClassDecl class_def when class_def.cl_interface -> ( )
  2614. | TClassDecl class_def ->
  2615. output_files ((const_char_star (join_class_path class_def.cl_path "." )) ^ ",\n")
  2616. | _ -> ( )
  2617. )
  2618. ) types;
  2619. output_files "#endif\n";
  2620. output_files " 0 };\n";
  2621. output_files "} // namespace hx\n";
  2622. output_files "void __files__boot() { __hxcpp_set_debugger_info(hx::__hxcpp_all_classes, hx::__hxcpp_all_files_fullpath); }\n";
  2623. files_file#close;;
  2624. let begin_header_file output_h def_string =
  2625. output_h ("#ifndef INCLUDED_" ^ def_string ^ "\n");
  2626. output_h ("#define INCLUDED_" ^ def_string ^ "\n\n");
  2627. output_h "#ifndef HXCPP_H\n";
  2628. output_h "#include <hxcpp.h>\n";
  2629. output_h "#endif\n\n";;
  2630. let end_header_file output_h def_string =
  2631. output_h ("\n#endif /* INCLUDED_" ^ def_string ^ " */ \n");;
  2632. let new_placed_cpp_file common_ctx class_path =
  2633. let base_dir = common_ctx.file in
  2634. if (Common.defined common_ctx Define.Vcproj ) then begin
  2635. make_class_directories base_dir ("src"::[]);
  2636. cached_source_writer common_ctx
  2637. ( base_dir ^ "/src/" ^ ( String.concat "-" (fst class_path) ) ^ "-" ^
  2638. (snd class_path) ^ (source_file_extension common_ctx) )
  2639. end else
  2640. new_cpp_file common_ctx common_ctx.file class_path;;
  2641. let generate_enum_files common_ctx enum_def super_deps meta file_info =
  2642. let class_path = enum_def.e_path in
  2643. let just_class_name = (snd class_path) in
  2644. let class_name = just_class_name ^ "_obj" in
  2645. let smart_class_name = ("::" ^ (join_class_path class_path "::") ) in
  2646. (*let cpp_file = new_cpp_file common_ctx.file class_path in*)
  2647. let cpp_file = new_placed_cpp_file common_ctx class_path in
  2648. let output_cpp = (cpp_file#write) in
  2649. let debug = if (has_meta_key enum_def.e_meta Meta.NoDebug) || ( Common.defined common_ctx Define.NoDebug)
  2650. then 0 else 1 in
  2651. let ctx = new_context common_ctx cpp_file debug file_info in
  2652. if (debug>1) then
  2653. print_endline ("Found enum definition:" ^ (join_class_path class_path "::" ));
  2654. output_cpp "#include <hxcpp.h>\n\n";
  2655. let referenced = find_referenced_types common_ctx (TEnumDecl enum_def) super_deps (Hashtbl.create 0) false false false in
  2656. List.iter (add_include cpp_file) referenced;
  2657. gen_open_namespace output_cpp class_path;
  2658. output_cpp "\n";
  2659. PMap.iter (fun _ constructor ->
  2660. let name = keyword_remap constructor.ef_name in
  2661. match constructor.ef_type with
  2662. | TFun (args,_) ->
  2663. output_cpp (smart_class_name ^ " " ^ class_name ^ "::" ^ name ^ "(" ^
  2664. (gen_tfun_arg_list args) ^")\n");
  2665. output_cpp ("\t{ return hx::CreateEnum< " ^ class_name ^ " >(" ^ (str name) ^ "," ^
  2666. (string_of_int constructor.ef_index) ^ ",hx::DynamicArray(0," ^
  2667. (string_of_int (List.length args)) ^ ")" );
  2668. List.iter (fun (arg,_,_) -> output_cpp (".Add(" ^ (keyword_remap arg) ^ ")")) args;
  2669. output_cpp "); }\n\n"
  2670. | _ ->
  2671. output_cpp ( smart_class_name ^ " " ^ class_name ^ "::" ^ name ^ ";\n\n" )
  2672. ) enum_def.e_constrs;
  2673. output_cpp ("HX_DEFINE_CREATE_ENUM(" ^ class_name ^ ")\n\n");
  2674. output_cpp ("int " ^ class_name ^ "::__FindIndex(::String inName)\n{\n");
  2675. PMap.iter (fun _ constructor ->
  2676. let name = constructor.ef_name in
  2677. let idx = string_of_int constructor.ef_index in
  2678. output_cpp ("\tif (inName==" ^ (str name) ^ ") return " ^ idx ^ ";\n") ) enum_def.e_constrs;
  2679. output_cpp ("\treturn super::__FindIndex(inName);\n");
  2680. output_cpp ("}\n\n");
  2681. let constructor_arg_count constructor =
  2682. (match constructor.ef_type with | TFun(args,_) -> List.length args | _ -> 0 )
  2683. in
  2684. (* Dynamic versions of constructors *)
  2685. let dump_dynamic_constructor _ constr =
  2686. let count = constructor_arg_count constr in
  2687. if (count>0) then begin
  2688. let nargs = string_of_int count in
  2689. output_cpp ("STATIC_HX_DEFINE_DYNAMIC_FUNC" ^ nargs ^ "(" ^ class_name ^ "," ^
  2690. (keyword_remap constr.ef_name) ^ ",return)\n\n");
  2691. end
  2692. in
  2693. PMap.iter dump_dynamic_constructor enum_def.e_constrs;
  2694. output_cpp ("int " ^ class_name ^ "::__FindArgCount(::String inName)\n{\n");
  2695. PMap.iter (fun _ constructor ->
  2696. let name = constructor.ef_name in
  2697. let count = string_of_int (constructor_arg_count constructor) in
  2698. output_cpp ("\tif (inName==" ^ (str name) ^ ") return " ^ count ^ ";\n") ) enum_def.e_constrs;
  2699. output_cpp ("\treturn super::__FindArgCount(inName);\n");
  2700. output_cpp ("}\n\n");
  2701. (* Dynamic "Get" Field function - string version *)
  2702. output_cpp ("Dynamic " ^ class_name ^ "::__Field(const ::String &inName,hx::PropertyAccess inCallProp)\n{\n");
  2703. let dump_constructor_test _ constr =
  2704. output_cpp ("\tif (inName==" ^ (str constr.ef_name) ^ ") return " ^
  2705. (keyword_remap constr.ef_name) );
  2706. if ( (constructor_arg_count constr) > 0 ) then output_cpp "_dyn()";
  2707. output_cpp (";\n")
  2708. in
  2709. PMap.iter dump_constructor_test enum_def.e_constrs;
  2710. output_cpp ("\treturn super::__Field(inName,inCallProp);\n}\n\n");
  2711. output_cpp "static ::String sStaticFields[] = {\n";
  2712. let sorted =
  2713. List.sort (fun f1 f2 -> (PMap.find f1 enum_def.e_constrs ).ef_index -
  2714. (PMap.find f2 enum_def.e_constrs ).ef_index )
  2715. (pmap_keys enum_def.e_constrs) in
  2716. List.iter (fun name -> output_cpp ("\t" ^ (str name) ^ ",\n") ) sorted;
  2717. output_cpp "\t::String(null()) };\n\n";
  2718. (* ENUM - Mark static as used by GC *)
  2719. output_cpp "static void sMarkStatics(HX_MARK_PARAMS) {\n";
  2720. PMap.iter (fun _ constructor ->
  2721. let name = keyword_remap constructor.ef_name in
  2722. match constructor.ef_type with
  2723. | TFun (_,_) -> ()
  2724. | _ -> output_cpp ("\tHX_MARK_MEMBER_NAME(" ^ class_name ^ "::" ^ name ^ ",\"" ^ name ^ "\");\n") )
  2725. enum_def.e_constrs;
  2726. output_cpp "};\n\n";
  2727. (* ENUM - Visit static as used by GC *)
  2728. output_cpp "#ifdef HXCPP_VISIT_ALLOCS\n";
  2729. output_cpp "static void sVisitStatic(HX_VISIT_PARAMS) {\n";
  2730. output_cpp ("\tHX_VISIT_MEMBER_NAME(" ^ class_name ^ "::__mClass,\"__mClass\");\n");
  2731. PMap.iter (fun _ constructor ->
  2732. let name = keyword_remap constructor.ef_name in
  2733. match constructor.ef_type with
  2734. | TFun (_,_) -> ()
  2735. | _ -> output_cpp ("\tHX_VISIT_MEMBER_NAME(" ^ class_name ^ "::" ^ name ^ ",\"" ^ name ^ "\");\n") )
  2736. enum_def.e_constrs;
  2737. output_cpp "};\n";
  2738. output_cpp "#endif\n\n";
  2739. output_cpp "static ::String sMemberFields[] = { ::String(null()) };\n";
  2740. output_cpp ("hx::Class " ^ class_name ^ "::__mClass;\n\n");
  2741. output_cpp ("Dynamic __Create_" ^ class_name ^ "() { return new " ^ class_name ^ "; }\n\n");
  2742. output_cpp ("void " ^ class_name ^ "::__register()\n{\n");
  2743. let text_name = str (join_class_path class_path ".") in
  2744. output_cpp ("\nhx::Static(__mClass) = hx::RegisterClass(" ^ text_name ^
  2745. ", hx::TCanCast< " ^ class_name ^ " >,sStaticFields,sMemberFields,\n");
  2746. output_cpp ("\t&__Create_" ^ class_name ^ ", &__Create,\n");
  2747. output_cpp ("\t&super::__SGetClass(), &Create" ^ class_name ^ ", sMarkStatics\n");
  2748. output_cpp("#ifdef HXCPP_VISIT_ALLOCS\n , sVisitStatic\n#endif\n");
  2749. output_cpp ("#ifdef HXCPP_SCRIPTABLE\n , 0\n#endif\n");
  2750. output_cpp (");\n}\n\n");
  2751. output_cpp ("void " ^ class_name ^ "::__boot()\n{\n");
  2752. (match meta with
  2753. | Some expr ->
  2754. let ctx = new_context common_ctx cpp_file 1 file_info in
  2755. find_local_functions_and_return_blocks_ctx ctx true expr;
  2756. output_cpp ("__mClass->__meta__ = ");
  2757. gen_expression ctx true expr;
  2758. output_cpp ";\n"
  2759. | _ -> () );
  2760. PMap.iter (fun _ constructor ->
  2761. let name = constructor.ef_name in
  2762. match constructor.ef_type with
  2763. | TFun (_,_) -> ()
  2764. | _ ->
  2765. output_cpp ( "hx::Static(" ^ (keyword_remap name) ^ ") = hx::CreateEnum< " ^ class_name ^ " >(" ^ (str name) ^ "," ^
  2766. (string_of_int constructor.ef_index) ^ ");\n" )
  2767. ) enum_def.e_constrs;
  2768. output_cpp ("}\n\n");
  2769. output_cpp "\n";
  2770. gen_close_namespace output_cpp class_path;
  2771. cpp_file#close;
  2772. let h_file = new_header_file common_ctx common_ctx.file class_path in
  2773. let super = "hx::EnumBase_obj" in
  2774. let output_h = (h_file#write) in
  2775. let def_string = join_class_path class_path "_" in
  2776. ctx.ctx_output <- output_h;
  2777. begin_header_file output_h def_string;
  2778. List.iter (gen_forward_decl h_file ) referenced;
  2779. gen_open_namespace output_h class_path;
  2780. output_h "\n\n";
  2781. output_h ("class " ^ class_name ^ " : public " ^ super ^ "\n");
  2782. output_h ("{\n\ttypedef " ^ super ^ " super;\n");
  2783. output_h ("\t\ttypedef " ^ class_name ^ " OBJ_;\n");
  2784. output_h "\n\tpublic:\n";
  2785. output_h ("\t\t" ^ class_name ^ "() {};\n");
  2786. output_h ("\t\tHX_DO_ENUM_RTTI;\n");
  2787. output_h ("\t\tstatic void __boot();\n");
  2788. output_h ("\t\tstatic void __register();\n");
  2789. output_h ("\t\t::String GetEnumName( ) const { return " ^
  2790. (str (join_class_path class_path ".")) ^ "; }\n" );
  2791. output_h ("\t\t::String __ToString() const { return " ^
  2792. (str (just_class_name ^ ".") )^ " + tag; }\n\n");
  2793. PMap.iter (fun _ constructor ->
  2794. let name = keyword_remap constructor.ef_name in
  2795. output_h ( "\t\tstatic " ^ smart_class_name ^ " " ^ name );
  2796. match constructor.ef_type with
  2797. | TFun (args,_) ->
  2798. output_h ( "(" ^ (gen_tfun_arg_list args) ^");\n");
  2799. output_h ( "\t\tstatic Dynamic " ^ name ^ "_dyn();\n");
  2800. | _ ->
  2801. output_h ";\n";
  2802. output_h ( "\t\tstatic inline " ^ smart_class_name ^ " " ^ name ^
  2803. "_dyn() { return " ^name ^ "; }\n" );
  2804. ) enum_def.e_constrs;
  2805. output_h "};\n\n";
  2806. gen_close_namespace output_h class_path;
  2807. end_header_file output_h def_string;
  2808. h_file#close;
  2809. let depend_referenced = find_referenced_types common_ctx (TEnumDecl enum_def) super_deps (Hashtbl.create 0) false true false in
  2810. depend_referenced;;
  2811. let list_iteri func in_list =
  2812. let idx = ref 0 in
  2813. List.iter (fun elem -> func !idx elem; idx := !idx + 1 ) in_list
  2814. ;;
  2815. let has_new_gc_references class_def =
  2816. match class_def.cl_dynamic with
  2817. | Some _ -> true
  2818. | _ -> (
  2819. let is_gc_reference field =
  2820. (should_implement_field field) && (is_data_member field) &&
  2821. match type_string field.cf_type with
  2822. | "bool" | "int" | "Float" -> false
  2823. | _ -> true
  2824. in
  2825. List.exists is_gc_reference class_def.cl_ordered_fields
  2826. )
  2827. ;;
  2828. let rec has_gc_references class_def =
  2829. ( match class_def.cl_super with
  2830. | Some def when has_gc_references (fst def) -> true
  2831. | _ -> false )
  2832. || has_new_gc_references class_def
  2833. ;;
  2834. let rec find_next_super_iteration class_def =
  2835. match class_def.cl_super with
  2836. | Some (klass,params) when has_new_gc_references klass -> class_string klass "_obj" params
  2837. | Some (klass,_) -> find_next_super_iteration klass
  2838. | _ -> "";
  2839. ;;
  2840. let has_init_field class_def =
  2841. match class_def.cl_init with
  2842. | Some _ -> true
  2843. | _ -> false;;
  2844. let is_abstract_impl class_def = match class_def.cl_kind with
  2845. | KAbstractImpl _ -> true
  2846. | _ -> false
  2847. ;;
  2848. let variable_field field =
  2849. (match field.cf_expr with
  2850. | Some { eexpr = TFunction function_def } -> is_dynamic_haxe_method field
  2851. | _ -> true)
  2852. ;;
  2853. let is_readable class_def field =
  2854. (match field.cf_kind with
  2855. | Var { v_read = AccNever } when (is_extern_field field) -> false
  2856. | Var { v_read = AccInline } -> false
  2857. | Var _ when is_abstract_impl class_def -> false
  2858. | _ -> true)
  2859. ;;
  2860. let is_writable class_def field =
  2861. (match field.cf_kind with
  2862. | Var { v_write = AccNever } when (is_extern_field field) -> false
  2863. | Var { v_read = AccInline } -> false
  2864. | Var _ when is_abstract_impl class_def -> false
  2865. | _ -> true)
  2866. ;;
  2867. let reflective class_def field = not (
  2868. (Meta.has Meta.Unreflective class_def.cl_meta) ||
  2869. (Meta.has Meta.Unreflective field.cf_meta) ||
  2870. (match field.cf_type with
  2871. | TInst (klass,_) -> Meta.has Meta.Unreflective klass.cl_meta
  2872. | _ -> false
  2873. )
  2874. )
  2875. ;;
  2876. let statics_except_meta class_def = (List.filter (fun static -> static.cf_name <> "__meta__") class_def.cl_ordered_statics);;
  2877. let has_set_field class_def =
  2878. implement_dynamic_here class_def || (
  2879. let reflect_fields = List.filter (reflective class_def) ((statics_except_meta class_def) @ class_def.cl_ordered_fields) in
  2880. let reflect_writable = List.filter (is_writable class_def) reflect_fields in
  2881. List.exists variable_field reflect_writable
  2882. )
  2883. ;;
  2884. let has_get_fields class_def =
  2885. implement_dynamic_here class_def || (
  2886. let is_data_field field = (match follow field.cf_type with | TFun _ -> false | _ -> true) in
  2887. List.exists is_data_field class_def.cl_ordered_fields
  2888. )
  2889. ;;
  2890. let has_get_field class_def =
  2891. implement_dynamic_here class_def || (
  2892. let reflect_fields = List.filter (reflective class_def) ((statics_except_meta class_def) @ class_def.cl_ordered_fields) in
  2893. List.exists (is_readable class_def) reflect_fields
  2894. )
  2895. ;;
  2896. let has_boot_field class_def =
  2897. List.exists has_field_init (List.filter should_implement_field class_def.cl_ordered_statics);
  2898. ;;
  2899. let is_macro meta =
  2900. Meta.has Meta.Macro meta
  2901. ;;
  2902. let access_str a = match a with
  2903. | AccNormal -> "AccNormal"
  2904. | AccNo -> "AccNo"
  2905. | AccNever -> "AccNever"
  2906. | AccResolve -> "AccResolve"
  2907. | AccCall -> "AccCall"
  2908. | AccInline -> "AccInline"
  2909. | AccRequire(_,_) -> "AccRequire" ;;
  2910. let generate_class_files common_ctx member_types super_deps constructor_deps class_def file_info inScriptable =
  2911. let class_path = class_def.cl_path in
  2912. let class_name = (snd class_path) ^ "_obj" in
  2913. let dot_name = join_class_path class_path "." in
  2914. let smart_class_name = (snd class_path) in
  2915. (*let cpp_file = new_cpp_file common_ctx.file class_path in*)
  2916. let cpp_file = new_placed_cpp_file common_ctx class_path in
  2917. let output_cpp = (cpp_file#write) in
  2918. let debug = if (has_meta_key class_def.cl_meta Meta.NoDebug) || ( Common.defined common_ctx Define.NoDebug)
  2919. then 0 else 1 in
  2920. let scriptable = inScriptable && not class_def.cl_private in
  2921. let ctx = new_context common_ctx cpp_file debug file_info in
  2922. ctx.ctx_class_name <- "::" ^ (join_class_path class_def.cl_path "::");
  2923. ctx.ctx_class_super_name <- (match class_def.cl_super with
  2924. | Some (klass, params) -> class_string klass "_obj" params
  2925. | _ -> "");
  2926. ctx.ctx_class_member_types <- member_types;
  2927. if (debug>1) then print_endline ("Found class definition:" ^ ctx.ctx_class_name);
  2928. let ptr_name = "hx::ObjectPtr< " ^ class_name ^ " >" in
  2929. let constructor_arg_var_list =
  2930. match class_def.cl_constructor with
  2931. | Some definition ->
  2932. (match definition.cf_expr with
  2933. | Some { eexpr = TFunction function_def } ->
  2934. List.map (fun (v,o) -> (v.v_name, gen_arg_type_name v.v_name o v.v_type "__o_"))
  2935. function_def.tf_args;
  2936. | _ ->
  2937. (match follow definition.cf_type with
  2938. | TFun (args,_) -> List.map (fun (a,_,t) -> (a, (type_string t, a)) ) args
  2939. | _ -> [])
  2940. )
  2941. | _ -> [] in
  2942. let constructor_type_var_list =
  2943. List.map snd constructor_arg_var_list in
  2944. let constructor_var_list = List.map snd constructor_type_var_list in
  2945. let constructor_type_args = String.concat ","
  2946. (List.map (fun (t,a) -> t ^ " " ^ a) constructor_type_var_list) in
  2947. let constructor_args = String.concat "," constructor_var_list in
  2948. let implement_dynamic = implement_dynamic_here class_def in
  2949. output_cpp "#include <hxcpp.h>\n\n";
  2950. let force_field = scriptable && (has_get_field class_def) in
  2951. let field_integer_dynamic = force_field || (has_field_integer_lookup class_def) in
  2952. let field_integer_numeric = force_field || (has_field_integer_numeric_lookup class_def) in
  2953. let all_referenced = find_referenced_types ctx.ctx_common (TClassDecl class_def) super_deps constructor_deps false false scriptable in
  2954. List.iter ( add_include cpp_file ) all_referenced;
  2955. (* All interfaces (and sub-interfaces) implemented *)
  2956. let implemented_hash = Hashtbl.create 0 in
  2957. List.iter (fun imp ->
  2958. let rec descend_interface interface =
  2959. let imp_path = (fst interface).cl_path in
  2960. let interface_name = "::" ^ (join_class_path imp_path "::" ) in
  2961. if ( not (Hashtbl.mem implemented_hash interface_name) ) then begin
  2962. Hashtbl.add implemented_hash interface_name ();
  2963. List.iter descend_interface (fst interface).cl_implements;
  2964. end;
  2965. match (fst interface).cl_super with
  2966. | Some (interface,params) -> descend_interface (interface,params)
  2967. | _ -> ()
  2968. in descend_interface imp
  2969. ) (real_interfaces class_def.cl_implements);
  2970. let implemented = hash_keys implemented_hash in
  2971. if (scriptable) then
  2972. output_cpp "#include <hx/Scriptable.h>\n";
  2973. output_cpp ( get_code class_def.cl_meta Meta.CppFileCode );
  2974. gen_open_namespace output_cpp class_path;
  2975. output_cpp "\n";
  2976. output_cpp ( get_code class_def.cl_meta Meta.CppNamespaceCode );
  2977. if (not class_def.cl_interface) then begin
  2978. output_cpp ("Void " ^ class_name ^ "::__construct(" ^ constructor_type_args ^ ")\n{\n");
  2979. (match class_def.cl_constructor with
  2980. | Some definition ->
  2981. (match definition.cf_expr with
  2982. | Some { eexpr = TFunction function_def } ->
  2983. if has_meta_key definition.cf_meta Meta.NoDebug then ctx.ctx_debug_level <- 0;
  2984. if ctx.ctx_debug_level >0 then begin
  2985. hx_stack_push ctx output_cpp dot_name "new" function_def.tf_expr.epos;
  2986. output_cpp "HX_STACK_THIS(this)\n";
  2987. List.iter (fun (a,(t,o)) -> output_cpp ("HX_STACK_ARG(" ^ (keyword_remap o) ^ ",\"" ^ a ^"\")\n") ) constructor_arg_var_list;
  2988. end;
  2989. if (has_default_values function_def.tf_args) then begin
  2990. generate_default_values ctx function_def.tf_args "__o_";
  2991. gen_expression ctx false (to_block function_def.tf_expr);
  2992. output_cpp ";\n";
  2993. end else begin
  2994. gen_expression ctx false (to_block function_def.tf_expr);
  2995. output_cpp ";\n";
  2996. (*gen_expression (new_context common_ctx cpp_file debug ) false function_def.tf_expr;*)
  2997. end;
  2998. ctx.ctx_debug_level <- debug;
  2999. | _ -> ()
  3000. )
  3001. | _ -> ());
  3002. output_cpp "\treturn null();\n";
  3003. output_cpp "}\n\n";
  3004. (* Destructor goes in the cpp file so we can "see" the full definition of the member vars *)
  3005. output_cpp ( "//" ^ class_name ^ "::~" ^ class_name ^ "() { }\n\n");
  3006. output_cpp ("Dynamic " ^ class_name ^ "::__CreateEmpty() { return new " ^ class_name ^ "; }\n");
  3007. output_cpp (ptr_name ^ " " ^ class_name ^ "::__new(" ^constructor_type_args ^")\n");
  3008. let create_result () =
  3009. output_cpp ("{ " ^ ptr_name ^ " result = new " ^ class_name ^ "();\n");
  3010. in
  3011. create_result ();
  3012. output_cpp ("\tresult->__construct(" ^ constructor_args ^ ");\n");
  3013. output_cpp ("\treturn result;}\n\n");
  3014. output_cpp ("Dynamic " ^ class_name ^ "::__Create(hx::DynamicArray inArgs)\n");
  3015. create_result ();
  3016. output_cpp ("\tresult->__construct(" ^ (array_arg_list constructor_var_list) ^ ");\n");
  3017. output_cpp ("\treturn result;}\n\n");
  3018. if ( (List.length implemented) > 0 ) then begin
  3019. output_cpp ("hx::Object *" ^ class_name ^ "::__ToInterface(const hx::type_info &inType) {\n");
  3020. List.iter (fun interface_name ->
  3021. output_cpp ("\tif (inType==typeid( " ^ interface_name ^ "_obj)) " ^
  3022. "return operator " ^ interface_name ^ "_obj *();\n");
  3023. ) implemented;
  3024. output_cpp ("\treturn super::__ToInterface(inType);\n}\n\n");
  3025. List.iter (fun interface_name ->
  3026. output_cpp (class_name ^ "::operator " ^ interface_name ^ "_obj *()\n\t" ^
  3027. "{ return new " ^ interface_name ^ "_delegate_< " ^ class_name ^" >(this); }\n" );
  3028. ) implemented;
  3029. end;
  3030. end;
  3031. (match class_def.cl_init with
  3032. | Some expression ->
  3033. output_cpp ("void " ^ class_name^ "::__init__() {\n");
  3034. hx_stack_push ctx output_cpp dot_name "__init__" expression.epos;
  3035. gen_expression (new_context common_ctx cpp_file debug file_info) false (to_block expression);
  3036. output_cpp "}\n\n";
  3037. | _ -> ());
  3038. let statics_except_meta = statics_except_meta class_def in
  3039. let implemented_fields = List.filter should_implement_field statics_except_meta in
  3040. let dump_field_name = (fun field -> output_cpp ("\t" ^ (str field.cf_name) ^ ",\n")) in
  3041. let implemented_instance_fields = List.filter should_implement_field class_def.cl_ordered_fields in
  3042. List.iter
  3043. (gen_field ctx class_def class_name smart_class_name dot_name false class_def.cl_interface)
  3044. class_def.cl_ordered_fields;
  3045. List.iter
  3046. (gen_field ctx class_def class_name smart_class_name dot_name true class_def.cl_interface) statics_except_meta;
  3047. output_cpp "\n";
  3048. let override_iteration = has_new_gc_references class_def in
  3049. (* Initialise non-static variables *)
  3050. if (not class_def.cl_interface) then begin
  3051. output_cpp (class_name ^ "::" ^ class_name ^ "()\n{\n");
  3052. if (implement_dynamic) then
  3053. output_cpp "\tHX_INIT_IMPLEMENT_DYNAMIC;\n";
  3054. List.iter
  3055. (fun field -> let remap_name = keyword_remap field.cf_name in
  3056. match field.cf_expr with
  3057. | Some { eexpr = TFunction function_def } ->
  3058. if (is_dynamic_haxe_method field) then
  3059. output_cpp ("\t" ^ remap_name ^ " = new __default_" ^ remap_name ^ "(this);\n")
  3060. | _ -> ()
  3061. )
  3062. class_def.cl_ordered_fields;
  3063. output_cpp "}\n\n";
  3064. let dump_field_iterator macro field =
  3065. if (is_data_member field) then begin
  3066. let remap_name = keyword_remap field.cf_name in
  3067. output_cpp ("\t" ^ macro ^ "(" ^ remap_name ^ ",\"" ^ field.cf_name^ "\");\n");
  3068. (match field.cf_kind with Var { v_read = AccCall } when (is_dynamic_accessor ("get_" ^ field.cf_name) "get" field class_def) ->
  3069. let name = "get_" ^ field.cf_name in
  3070. output_cpp ("\t" ^ macro ^ "(" ^ name ^ "," ^ "\"" ^ name ^ "\");\n" ) | _ -> ());
  3071. (match field.cf_kind with Var { v_write = AccCall } when (is_dynamic_accessor ("set_" ^ field.cf_name) "set" field class_def) ->
  3072. let name = "set_" ^ field.cf_name in
  3073. output_cpp ("\t" ^ macro ^ "(" ^ name ^ "," ^ "\"" ^ name ^ "\");\n" ) | _ -> ());
  3074. end
  3075. in
  3076. if (override_iteration) then begin
  3077. let super_needs_iteration = find_next_super_iteration class_def in
  3078. (* MARK function - explicitly mark all child pointers *)
  3079. output_cpp ("void " ^ class_name ^ "::__Mark(HX_MARK_PARAMS)\n{\n");
  3080. output_cpp ("\tHX_MARK_BEGIN_CLASS(" ^ smart_class_name ^ ");\n");
  3081. if (implement_dynamic) then
  3082. output_cpp "\tHX_MARK_DYNAMIC;\n";
  3083. List.iter (dump_field_iterator "HX_MARK_MEMBER_NAME") implemented_instance_fields;
  3084. (match super_needs_iteration with
  3085. | "" -> ()
  3086. | super -> output_cpp ("\t" ^ super^"::__Mark(HX_MARK_ARG);\n" ) );
  3087. output_cpp "\tHX_MARK_END_CLASS();\n";
  3088. output_cpp "}\n\n";
  3089. (* Visit function - explicitly visit all child pointers *)
  3090. output_cpp ("void " ^ class_name ^ "::__Visit(HX_VISIT_PARAMS)\n{\n");
  3091. if (implement_dynamic) then
  3092. output_cpp "\tHX_VISIT_DYNAMIC;\n";
  3093. List.iter (dump_field_iterator "HX_VISIT_MEMBER_NAME") implemented_instance_fields;
  3094. (match super_needs_iteration with
  3095. | "" -> ()
  3096. | super -> output_cpp ("\t" ^ super ^ "::__Visit(HX_VISIT_ARG);\n") );
  3097. output_cpp "}\n\n";
  3098. end;
  3099. let reflect_fields = List.filter (reflective class_def) (statics_except_meta @ class_def.cl_ordered_fields) in
  3100. let reflect_writable = List.filter (is_writable class_def) reflect_fields in
  3101. let reflect_readable = List.filter (is_readable class_def) reflect_fields in
  3102. let reflect_write_variables = List.filter variable_field reflect_writable in
  3103. let dump_quick_field_test fields =
  3104. if ( (List.length fields) > 0) then begin
  3105. let len = function (_,l,_) -> l in
  3106. let sfields = List.sort (fun f1 f2 -> (len f1)-(len f2)) fields in
  3107. let len_case = ref (-1) in
  3108. output_cpp "\tswitch(inName.length) {\n";
  3109. List.iter (fun (field,l,result) ->
  3110. if (l <> !len_case) then begin
  3111. if (!len_case>=0) then output_cpp "\t\tbreak;\n";
  3112. output_cpp ("\tcase " ^ (string_of_int l) ^ ":\n");
  3113. len_case := l;
  3114. end;
  3115. output_cpp ("\t\tif (HX_FIELD_EQ(inName,\"" ^ (Ast.s_escape field) ^ "\") ) { " ^ result ^ " }\n");
  3116. ) sfields;
  3117. output_cpp "\t}\n";
  3118. end;
  3119. in
  3120. let checkPropCall field = if ( (has_meta_key class_def.cl_meta Meta.NativeProperty) ||
  3121. (has_meta_key field.cf_meta Meta.NativeProperty) ||
  3122. (Common.defined common_ctx Define.ForceNativeProperty) )
  3123. then
  3124. "inCallProp != hx::paccNever"
  3125. else
  3126. "inCallProp == hx::paccAlways"
  3127. in
  3128. if (has_get_field class_def) then begin
  3129. (* Dynamic "Get" Field function - string version *)
  3130. output_cpp ("Dynamic " ^ class_name ^ "::__Field(const ::String &inName,hx::PropertyAccess inCallProp)\n{\n");
  3131. let get_field_dat = List.map (fun f ->
  3132. (f.cf_name, String.length f.cf_name,
  3133. (match f.cf_kind with
  3134. | Var { v_read = AccCall } when is_extern_field f -> "if (" ^ (checkPropCall f) ^ ") return " ^(keyword_remap ("get_" ^ f.cf_name)) ^ "()"
  3135. | Var { v_read = AccCall } -> "return " ^ (checkPropCall f) ^ " ? " ^ (keyword_remap ("get_" ^ f.cf_name)) ^ "() : " ^
  3136. ((keyword_remap f.cf_name) ^ if (variable_field f) then "" else "_dyn()")
  3137. | _ -> "return " ^ ((keyword_remap f.cf_name) ^ if (variable_field f) then "" else "_dyn()")
  3138. ) ^ ";"
  3139. ) )
  3140. in
  3141. dump_quick_field_test (get_field_dat reflect_readable);
  3142. if (implement_dynamic) then
  3143. output_cpp "\tHX_CHECK_DYNAMIC_GET_FIELD(inName);\n";
  3144. output_cpp ("\treturn super::__Field(inName,inCallProp);\n}\n\n");
  3145. (* Dynamic "Get" Field function - int version *)
  3146. if ( field_integer_numeric || field_integer_dynamic) then begin
  3147. let dump_static_ids = (fun field ->
  3148. let remap_name = keyword_remap field.cf_name in
  3149. output_cpp ("static int __id_" ^ remap_name ^ " = __hxcpp_field_to_id(\"" ^
  3150. (field.cf_name) ^ "\");\n");
  3151. ) in
  3152. List.iter dump_static_ids reflect_readable;
  3153. output_cpp "\n\n";
  3154. let output_ifield return_type function_name all_fields =
  3155. output_cpp (return_type ^" " ^ class_name ^ "::" ^ function_name ^ "(int inFieldID)\n{\n");
  3156. let dump_field_test = (fun f ->
  3157. let remap_name = keyword_remap f.cf_name in
  3158. output_cpp ("\tif (inFieldID==__id_" ^ remap_name ^ ") return " ^
  3159. ( if (return_type="Float") then "hx::ToDouble( " else "" ) ^
  3160. (match f.cf_kind with
  3161. | Var { v_read = AccCall } -> (keyword_remap ("get_" ^ f.cf_name)) ^ "()"
  3162. | _ -> (remap_name ^ if ( variable_field f) then "" else "_dyn()")
  3163. ) ^ ( if (return_type="Float") then " ) " else "" ) ^ ";\n");
  3164. ) in
  3165. List.iter dump_field_test (List.filter (fun f -> all_fields || (is_numeric_field f)) reflect_readable);
  3166. if (implement_dynamic) then
  3167. output_cpp "\tHX_CHECK_DYNAMIC_GET_INT_FIELD(inFieldID);\n";
  3168. output_cpp ("\treturn super::" ^ function_name ^ "(inFieldID);\n}\n\n");
  3169. in
  3170. if (field_integer_dynamic) then output_ifield "Dynamic" "__IField" true;
  3171. if (field_integer_numeric) then output_ifield "double" "__INumField" false;
  3172. end;
  3173. end;
  3174. (* Dynamic "Set" Field function *)
  3175. if (has_set_field class_def) then begin
  3176. output_cpp ("Dynamic " ^ class_name ^ "::__SetField(const ::String &inName,const Dynamic &inValue,hx::PropertyAccess inCallProp)\n{\n");
  3177. let set_field_dat = List.map (fun f ->
  3178. let default_action =
  3179. (keyword_remap f.cf_name) ^ "=inValue.Cast< " ^ (type_string f.cf_type) ^ " >();" ^
  3180. " return inValue;" in
  3181. (f.cf_name, String.length f.cf_name,
  3182. (match f.cf_kind with
  3183. | Var { v_write = AccCall } -> "if (" ^ (checkPropCall f) ^ ") return " ^ (keyword_remap ("set_" ^ f.cf_name)) ^ "(inValue);"
  3184. ^ ( if is_extern_field f then "" else default_action )
  3185. | _ -> default_action
  3186. )
  3187. )
  3188. ) in
  3189. dump_quick_field_test (set_field_dat reflect_write_variables);
  3190. if (implement_dynamic) then begin
  3191. output_cpp ("\ttry { return super::__SetField(inName,inValue,inCallProp); }\n");
  3192. output_cpp ("\tcatch(Dynamic e) { HX_DYNAMIC_SET_FIELD(inName,inValue); }\n");
  3193. output_cpp "\treturn inValue;\n}\n\n";
  3194. end else
  3195. output_cpp ("\treturn super::__SetField(inName,inValue,inCallProp);\n}\n\n");
  3196. end;
  3197. (* For getting a list of data members (eg, for serialization) *)
  3198. if (has_get_fields class_def) then begin
  3199. let append_field =
  3200. (fun field -> output_cpp ("\toutFields->push(" ^( str field.cf_name )^ ");\n")) in
  3201. let is_data_field field = (match follow field.cf_type with | TFun _ -> false | _ -> true) in
  3202. output_cpp ("void " ^ class_name ^ "::__GetFields(Array< ::String> &outFields)\n{\n");
  3203. List.iter append_field (List.filter is_data_field class_def.cl_ordered_fields);
  3204. if (implement_dynamic) then
  3205. output_cpp "\tHX_APPEND_DYNAMIC_FIELDS(outFields);\n";
  3206. output_cpp "\tsuper::__GetFields(outFields);\n";
  3207. output_cpp "};\n\n";
  3208. end;
  3209. let storage field = match type_string field.cf_type with
  3210. | "bool" -> "hx::fsBool"
  3211. | "int" -> "hx::fsInt"
  3212. | "Float" -> "hx::fsFloat"
  3213. | "::String" -> "hx::fsString"
  3214. | str -> "hx::fsObject" ^ " /*" ^ str ^ "*/ "
  3215. in
  3216. let dump_member_storage = (fun field ->
  3217. output_cpp ("\t{" ^ (storage field) ^ ",(int)offsetof(" ^ class_name ^"," ^ (keyword_remap field.cf_name) ^")," ^
  3218. (str field.cf_name) ^ "},\n")
  3219. )
  3220. in
  3221. let dump_static_storage = (fun field ->
  3222. output_cpp ("\t{" ^ (storage field) ^ ",(void *) &" ^ class_name ^"::" ^ (keyword_remap field.cf_name) ^"," ^
  3223. (str field.cf_name) ^ "},\n")
  3224. )
  3225. in
  3226. output_cpp "#if HXCPP_SCRIPTABLE\n";
  3227. let stored_fields = List.filter is_data_member implemented_instance_fields in
  3228. if ( (List.length stored_fields) > 0) then begin
  3229. output_cpp "static hx::StorageInfo sMemberStorageInfo[] = {\n";
  3230. List.iter dump_member_storage stored_fields;
  3231. output_cpp "\t{ hx::fsUnknown, 0, null()}\n};\n";
  3232. end else
  3233. output_cpp "static hx::StorageInfo *sMemberStorageInfo = 0;\n";
  3234. let stored_statics = List.filter is_data_member implemented_fields in
  3235. if ( (List.length stored_statics) > 0) then begin
  3236. output_cpp "static hx::StaticInfo sStaticStorageInfo[] = {\n";
  3237. List.iter dump_static_storage stored_statics;
  3238. output_cpp "\t{ hx::fsUnknown, 0, null()}\n};\n";
  3239. end else
  3240. output_cpp "static hx::StaticInfo *sStaticStorageInfo = 0;\n";
  3241. output_cpp "#endif\n\n";
  3242. end; (* cl_interface *)
  3243. let reflective_members = List.filter (reflective class_def) implemented_instance_fields in
  3244. let sMemberFields = if List.length reflective_members>0 then begin
  3245. output_cpp "static ::String sMemberFields[] = {\n";
  3246. List.iter dump_field_name reflective_members;
  3247. output_cpp "\tString(null()) };\n\n";
  3248. "sMemberFields"
  3249. end else
  3250. "0 /* sMemberFields */";
  3251. in
  3252. (* Mark static variables as used *)
  3253. output_cpp "static void sMarkStatics(HX_MARK_PARAMS) {\n";
  3254. output_cpp ("\tHX_MARK_MEMBER_NAME(" ^ class_name ^ "::__mClass,\"__mClass\");\n");
  3255. List.iter (fun field ->
  3256. if (is_data_member field) then
  3257. output_cpp ("\tHX_MARK_MEMBER_NAME(" ^ class_name ^ "::" ^ (keyword_remap field.cf_name) ^ ",\"" ^ field.cf_name ^ "\");\n") )
  3258. implemented_fields;
  3259. output_cpp "};\n\n";
  3260. (* Visit static variables *)
  3261. output_cpp "#ifdef HXCPP_VISIT_ALLOCS\n";
  3262. output_cpp "static void sVisitStatics(HX_VISIT_PARAMS) {\n";
  3263. output_cpp ("\tHX_VISIT_MEMBER_NAME(" ^ class_name ^ "::__mClass,\"__mClass\");\n");
  3264. List.iter (fun field ->
  3265. if (is_data_member field) then
  3266. output_cpp ("\tHX_VISIT_MEMBER_NAME(" ^ class_name ^ "::" ^ (keyword_remap field.cf_name) ^ ",\"" ^ field.cf_name ^ "\");\n") )
  3267. implemented_fields;
  3268. output_cpp "};\n\n";
  3269. output_cpp "#endif\n\n";
  3270. let script_type t optional = if optional then "Object" else
  3271. match type_string t with
  3272. | "bool" -> "Int"
  3273. | "int" -> "Int"
  3274. | "Float" -> "Float"
  3275. | "::String" -> "String"
  3276. | "Null" -> "Void"
  3277. | "Void" -> "Void"
  3278. | _ -> "Object"
  3279. in
  3280. let script_signature t optional = match script_type t optional with
  3281. | "Bool" -> "b"
  3282. | "Int" -> "i"
  3283. | "Float" -> "f"
  3284. | "String" -> "s"
  3285. | "Void" -> "v"
  3286. | _ -> "o"
  3287. in
  3288. let script_size_type t optional = match script_type t optional with
  3289. | "Object" -> "void *"
  3290. | x -> x
  3291. in
  3292. let generate_script_function isStatic field scriptName callName =
  3293. match follow field.cf_type with
  3294. | TFun (args,return_type) ->
  3295. output_cpp ("\nstatic void " ^ scriptName ^ "(hx::CppiaCtx *ctx) {\n");
  3296. let ret = script_signature return_type false in
  3297. if (ret<>"v") then output_cpp ("ctx->return" ^ (script_type return_type false) ^ "(");
  3298. if isStatic then
  3299. output_cpp (class_name ^ "::" ^ callName ^ "(")
  3300. else
  3301. output_cpp ("((" ^ class_name ^ "*)ctx->getThis())->" ^ callName ^ "(");
  3302. let (signature,_,_) = List.fold_left (fun (signature,sep,size) (_,opt,t) ->
  3303. output_cpp (sep ^ "ctx->get" ^ (script_type t opt) ^ "(" ^ size ^ ")");
  3304. (signature ^ (script_signature t opt ), ",", (size^"+sizeof(" ^ (script_size_type t opt) ^ ")") ) ) (ret,"","sizeof(void*)") args
  3305. in
  3306. output_cpp ")";
  3307. if (ret<>"v") then output_cpp (")");
  3308. output_cpp (";\n}\n");
  3309. signature;
  3310. | _ -> ""
  3311. in
  3312. if (scriptable ) then begin
  3313. let dump_script_field idx (field,f_args,return_t) =
  3314. let args = if (class_def.cl_interface) then
  3315. gen_tfun_interface_arg_list f_args
  3316. else
  3317. gen_tfun_arg_list f_args in
  3318. let names = List.map (fun (n,_,_) -> keyword_remap n) f_args in
  3319. let return_type = type_string return_t in
  3320. let ret = if (return_type="Void") then " " else "return " in
  3321. let name = keyword_remap field.cf_name in
  3322. let vtable = "__scriptVTable[" ^ (string_of_int (idx+1) ) ^ "] " in
  3323. let args_varray = (List.fold_left (fun l n -> l ^ ".Add(" ^ n ^ ")") "Array<Dynamic>()" names) in
  3324. output_cpp (" " ^ return_type ^ " " ^ name ^ "( " ^ args ^ " ) { ");
  3325. output_cpp ("\n\tif (" ^ vtable ^ ") {\n" );
  3326. output_cpp ("\t\thx::CppiaCtx *__ctx = hx::CppiaCtx::getCurrent();\n" );
  3327. output_cpp ("\t\thx::AutoStack __as(__ctx);\n" );
  3328. output_cpp ("\t\t__ctx->pushObject(" ^ (if class_def.cl_interface then "mDelegate.mPtr" else "this" ) ^");\n" );
  3329. List.iter (fun (name,opt, t ) ->
  3330. output_cpp ("\t\t__ctx->push" ^ (script_type t opt) ^ "(" ^ (keyword_remap name) ^ ");\n" );
  3331. ) f_args;
  3332. output_cpp ("\t\t" ^ ret ^ "__ctx->run" ^ (script_type return_t false) ^ "(" ^ vtable ^ ");\n" );
  3333. output_cpp ("\t} else " ^ ret );
  3334. if (class_def.cl_interface) then begin
  3335. output_cpp (" mDelegate->__Field(HX_CSTRING(\"" ^ field.cf_name ^ "\"), hx::paccNever)");
  3336. if (List.length names <= 5) then
  3337. output_cpp ("->__run(" ^ (String.concat "," names) ^ ");")
  3338. else
  3339. output_cpp ("->__Run(" ^ args_varray ^ ");");
  3340. end else
  3341. output_cpp (class_name ^ "::" ^ name ^ "(" ^ (String.concat "," names)^ ");");
  3342. output_cpp ("return null(); }\n");
  3343. if (class_def.cl_interface) then begin
  3344. output_cpp (" Dynamic " ^ name ^ "_dyn() { return mDelegate->__Field(HX_CSTRING(\"" ^ field.cf_name ^ "\"), hx::paccNever); }\n\n");
  3345. end
  3346. in
  3347. let not_toString = fun (field,args,_) -> field.cf_name<>"toString" || class_def.cl_interface in
  3348. let functions = List.filter not_toString (all_virtual_functions class_def) in
  3349. let new_sctipt_functions = List.filter (fun (f,_,_) -> not (is_override class_def f.cf_name) ) functions in
  3350. let sctipt_name = class_name ^ "__scriptable" in
  3351. output_cpp ("class " ^ sctipt_name ^ " : public " ^ class_name ^ " {\n" );
  3352. output_cpp (" typedef "^sctipt_name ^" __ME;\n");
  3353. output_cpp (" typedef "^class_name ^" super;\n");
  3354. let has_funky_toString = List.exists (fun f -> f.cf_name="toString") class_def.cl_ordered_statics ||
  3355. List.exists (fun f -> f.cf_name="toString" && field_arg_count f <> 0) class_def.cl_ordered_fields in
  3356. let super_string = if has_funky_toString then class_name ^ "::super" else class_name in
  3357. output_cpp (" typedef "^ super_string ^" __superString;\n");
  3358. if (class_def.cl_interface) then
  3359. output_cpp (" HX_DEFINE_SCRIPTABLE_INTERFACE\n")
  3360. else begin
  3361. output_cpp (" HX_DEFINE_SCRIPTABLE(HX_ARR_LIST" ^ (string_of_int (List.length constructor_var_list) ) ^ ")\n");
  3362. if (not implement_dynamic) then
  3363. output_cpp "\tHX_DEFINE_SCRIPTABLE_DYNAMIC;\n";
  3364. end;
  3365. list_iteri dump_script_field functions;
  3366. output_cpp ("};\n\n");
  3367. if (List.length new_sctipt_functions) > 0 then begin
  3368. let sigs = Hashtbl.create 0 in
  3369. List.iter (fun (f,_,_) ->
  3370. let s = generate_script_function false f ("__s_" ^f.cf_name) (keyword_remap f.cf_name) in
  3371. Hashtbl.add sigs f.cf_name s
  3372. ) new_sctipt_functions;
  3373. output_cpp "static hx::ScriptNamedFunction __scriptableFunctions[] = {\n";
  3374. List.iter (fun (f,_,_) ->
  3375. let s = try Hashtbl.find sigs f.cf_name with Not_found -> "v" in
  3376. output_cpp (" hx::ScriptNamedFunction(\"" ^ f.cf_name ^ "\",__s_" ^ f.cf_name ^ ",\"" ^ s ^ "\"),\n" ) ) new_sctipt_functions;
  3377. output_cpp " hx::ScriptNamedFunction(0,0,0) };\n";
  3378. end else
  3379. output_cpp "static hx::ScriptNamedFunction *__scriptableFunctions = 0;\n";
  3380. end;
  3381. (* Initialise static in boot function ... *)
  3382. if (not class_def.cl_interface) then begin
  3383. (* Remap the specialised "extern" classes back to the generic names *)
  3384. let class_name_text = match class_path with
  3385. | path -> join_class_path path "." in
  3386. output_cpp ("hx::Class " ^ class_name ^ "::__mClass;\n\n");
  3387. if (scriptable) then begin
  3388. (match class_def.cl_constructor with
  3389. | Some field ->
  3390. let signature = generate_script_function false field "__script_construct_func" "__construct" in
  3391. output_cpp ("hx::ScriptFunction " ^ class_name ^ "::__script_construct(__script_construct_func,\"" ^ signature ^ "\");\n");
  3392. | _ ->
  3393. output_cpp ("hx::ScriptFunction " ^ class_name ^ "::__script_construct(0,0);\n");
  3394. );
  3395. end;
  3396. let reflective_statics = List.filter (reflective class_def) implemented_fields in
  3397. let sStaticFields = if List.length reflective_statics > 0 then begin
  3398. output_cpp "static ::String sStaticFields[] = {\n";
  3399. List.iter dump_field_name reflective_statics;
  3400. output_cpp "\tString(null()) };\n\n";
  3401. "sStaticFields";
  3402. end else
  3403. "0 /* sStaticFields */"
  3404. in
  3405. output_cpp ("void " ^ class_name ^ "::__register()\n{\n");
  3406. output_cpp ("\thx::Static(__mClass) = hx::RegisterClass(" ^ (str class_name_text) ^
  3407. ", hx::TCanCast< " ^ class_name ^ "> ," ^ sStaticFields ^ "," ^ sMemberFields ^ ",\n");
  3408. output_cpp ("\t&__CreateEmpty, &__Create,\n");
  3409. output_cpp ("\t&super::__SGetClass(), 0, sMarkStatics\n");
  3410. output_cpp ("#ifdef HXCPP_VISIT_ALLOCS\n , sVisitStatics\n#endif\n");
  3411. output_cpp ("#ifdef HXCPP_SCRIPTABLE\n , sMemberStorageInfo, sStaticStorageInfo \n#endif\n");
  3412. output_cpp (");\n");
  3413. if (scriptable) then
  3414. output_cpp (" HX_SCRIPTABLE_REGISTER_CLASS(\""^class_name_text^"\"," ^ class_name ^ ");\n");
  3415. output_cpp ("}\n\n");
  3416. end else begin
  3417. let class_name_text = join_class_path class_path "." in
  3418. output_cpp ("hx::Class " ^ class_name ^ "::__mClass;\n\n");
  3419. output_cpp ("void " ^ class_name ^ "::__register()\n{\n");
  3420. output_cpp ("\thx::Static(__mClass) = hx::RegisterClass(" ^ (str class_name_text) ^
  3421. ", hx::TCanCast< " ^ class_name ^ "> ,0," ^ sMemberFields ^ ",\n");
  3422. output_cpp ("\t0, 0,\n");
  3423. output_cpp ("\t&super::__SGetClass(), 0, sMarkStatics\n");
  3424. output_cpp ("#ifdef HXCPP_VISIT_ALLOCS\n , sVisitStatics\n#endif\n");
  3425. output_cpp ("#ifdef HXCPP_SCRIPTABLE\n , 0\n#endif\n");
  3426. output_cpp (");\n");
  3427. if (scriptable) then
  3428. output_cpp (" HX_SCRIPTABLE_REGISTER_INTERFACE(\""^class_name_text^"\"," ^ class_name ^ ");\n");
  3429. output_cpp ("}\n\n");
  3430. end;
  3431. if (has_boot_field class_def) then begin
  3432. output_cpp ("void " ^ class_name ^ "::__boot()\n{\n");
  3433. List.iter (gen_field_init ctx ) (List.filter should_implement_field class_def.cl_ordered_statics);
  3434. output_cpp ("}\n\n");
  3435. end;
  3436. gen_close_namespace output_cpp class_path;
  3437. cpp_file#close;
  3438. let h_file = new_header_file common_ctx common_ctx.file class_path in
  3439. let super = match class_def.cl_super with
  3440. | Some (klass,params) -> (class_string klass "_obj" params)
  3441. | _ -> if (class_def.cl_interface) then "hx::Interface" else "hx::Object"
  3442. in
  3443. let output_h = (h_file#write) in
  3444. let def_string = join_class_path class_path "_" in
  3445. ctx.ctx_output <- output_h;
  3446. begin_header_file output_h def_string;
  3447. (* Include the real header file for the super class *)
  3448. (match class_def.cl_super with
  3449. | Some super ->
  3450. let super_path = (fst super).cl_path in
  3451. h_file#add_include super_path
  3452. | _ -> () );
  3453. (* And any interfaces ... *)
  3454. List.iter (fun imp-> h_file#add_include (fst imp).cl_path)
  3455. (real_interfaces class_def.cl_implements);
  3456. (* Only need to foreward-declare classes that are mentioned in the header file
  3457. (ie, not the implementation) *)
  3458. let referenced = find_referenced_types ctx.ctx_common (TClassDecl class_def) super_deps (Hashtbl.create 0) true false scriptable in
  3459. List.iter ( gen_forward_decl h_file ) referenced;
  3460. output_h ( get_code class_def.cl_meta Meta.HeaderCode );
  3461. gen_open_namespace output_h class_path;
  3462. output_h "\n\n";
  3463. output_h ( get_code class_def.cl_meta Meta.HeaderNamespaceCode );
  3464. let extern_class = Common.defined common_ctx Define.DllExport in
  3465. let attribs = "HXCPP_" ^ (if extern_class then "EXTERN_" else "") ^ "CLASS_ATTRIBUTES " in
  3466. output_h ("class " ^ attribs ^ " " ^ class_name ^ " : public " ^ super );
  3467. output_h "{\n\tpublic:\n";
  3468. output_h ("\t\ttypedef " ^ super ^ " super;\n");
  3469. output_h ("\t\ttypedef " ^ class_name ^ " OBJ_;\n");
  3470. if (not class_def.cl_interface) then begin
  3471. output_h ("\t\t" ^ class_name ^ "();\n");
  3472. output_h ("\t\tVoid __construct(" ^ constructor_type_args ^ ");\n");
  3473. output_h "\n\tpublic:\n";
  3474. let new_arg = if (has_gc_references class_def) then "true" else "false" in
  3475. output_h ("\t\tinline void *operator new( size_t inSize, bool inContainer=" ^ new_arg ^")\n" );
  3476. output_h ("\t\t\t{ return hx::Object::operator new(inSize,inContainer); }\n" );
  3477. output_h ("\t\tstatic " ^ptr_name^ " __new(" ^constructor_type_args ^");\n");
  3478. output_h ("\t\tstatic Dynamic __CreateEmpty();\n");
  3479. output_h ("\t\tstatic Dynamic __Create(hx::DynamicArray inArgs);\n");
  3480. if (scriptable) then
  3481. output_h ("\t\tstatic hx::ScriptFunction __script_construct;\n");
  3482. output_h ("\t\t//~" ^ class_name ^ "();\n\n");
  3483. output_h ("\t\tHX_DO_RTTI_ALL;\n");
  3484. if (has_get_field class_def) then
  3485. output_h ("Dynamic __Field(const ::String &inString, hx::PropertyAccess inCallProp);\n");
  3486. if (has_set_field class_def) then
  3487. output_h ("Dynamic __SetField(const ::String &inString,const Dynamic &inValue, hx::PropertyAccess inCallProp);\n");
  3488. if (has_get_fields class_def) then
  3489. output_h ("void __GetFields(Array< ::String> &outFields);\n");
  3490. if (field_integer_dynamic) then output_h "\t\tDynamic __IField(int inFieldID);\n";
  3491. if (field_integer_numeric) then output_h "\t\tdouble __INumField(int inFieldID);\n";
  3492. if (implement_dynamic) then
  3493. output_h ("\t\tHX_DECLARE_IMPLEMENT_DYNAMIC;\n");
  3494. output_h ("\t\tstatic void __register();\n");
  3495. if (override_iteration) then begin
  3496. output_h ("\t\tvoid __Mark(HX_MARK_PARAMS);\n");
  3497. output_h ("\t\tvoid __Visit(HX_VISIT_PARAMS);\n");
  3498. end;
  3499. if ( (List.length implemented) > 0 ) then begin
  3500. output_h "\t\thx::Object *__ToInterface(const hx::type_info &inType);\n";
  3501. List.iter (fun interface_name ->
  3502. output_h ("\t\toperator " ^ interface_name ^ "_obj *();\n")
  3503. ) implemented;
  3504. end;
  3505. if (has_init_field class_def) then
  3506. output_h "\t\tstatic void __init__();\n\n";
  3507. output_h ("\t\t::String __ToString() const { return " ^ (str smart_class_name) ^ "; }\n\n");
  3508. end else begin
  3509. output_h ("\t\tHX_DO_INTERFACE_RTTI;\n");
  3510. end;
  3511. if (has_boot_field class_def) then
  3512. output_h ("\t\tstatic void __boot();\n");
  3513. (match class_def.cl_array_access with
  3514. | Some t -> output_h ("\t\ttypedef " ^ (type_string t) ^ " __array_access;\n")
  3515. | _ -> ());
  3516. let interface = class_def.cl_interface in
  3517. List.iter (gen_member_def ctx class_def false interface) (List.filter should_implement_field class_def.cl_ordered_fields);
  3518. List.iter (gen_member_def ctx class_def true interface) (List.filter should_implement_field class_def.cl_ordered_statics);
  3519. output_h ( get_code class_def.cl_meta Meta.HeaderClassCode );
  3520. output_h "};\n\n";
  3521. if (class_def.cl_interface) then begin
  3522. output_h ("#define DELEGATE_" ^ (join_class_path class_path "_" ) ^ " \\\n");
  3523. List.iter (fun field ->
  3524. match follow field.cf_type, field.cf_kind with
  3525. | _, Method MethDynamic -> ()
  3526. | TFun (args,return_type), Method _ ->
  3527. let remap_name = keyword_remap field.cf_name in
  3528. output_h ( "virtual " ^ (type_string return_type) ^ " " ^ remap_name ^ "( " );
  3529. output_h (gen_tfun_interface_arg_list args);
  3530. output_h (") { return mDelegate->" ^ remap_name^ "(");
  3531. output_h (String.concat "," (List.map (fun (name,opt,typ) -> (keyword_remap name)) args));
  3532. output_h ");} \\\n";
  3533. output_h ("virtual Dynamic " ^ remap_name ^ "_dyn() { return mDelegate->" ^
  3534. remap_name ^ "_dyn();} \\\n");
  3535. | _ -> ()
  3536. ) class_def.cl_ordered_fields;
  3537. output_h ("\n\n");
  3538. output_h ("template<typename IMPL>\n");
  3539. output_h ("class " ^ smart_class_name ^ "_delegate_ : public " ^ class_name^"\n");
  3540. output_h "{\n\tprotected:\n";
  3541. output_h ("\t\tIMPL *mDelegate;\n");
  3542. output_h "\tpublic:\n";
  3543. output_h ("\t\t" ^ smart_class_name ^ "_delegate_(IMPL *inDelegate) : mDelegate(inDelegate) {}\n");
  3544. output_h ("\t\thx::Object *__GetRealObject() { return mDelegate; }\n");
  3545. output_h ("\t\tvoid __Visit(HX_VISIT_PARAMS) { HX_VISIT_OBJECT(mDelegate); }\n");
  3546. let rec dump_delegate interface =
  3547. output_h ("\t\tDELEGATE_" ^ (join_class_path interface.cl_path "_" ) ^ "\n");
  3548. match interface.cl_super with | Some super -> dump_delegate (fst super) | _ -> ();
  3549. in
  3550. dump_delegate class_def;
  3551. output_h "};\n\n";
  3552. end;
  3553. gen_close_namespace output_h class_path;
  3554. end_header_file output_h def_string;
  3555. h_file#close;
  3556. let depend_referenced = find_referenced_types ctx.ctx_common (TClassDecl class_def) super_deps constructor_deps false true false in
  3557. depend_referenced;;
  3558. let write_resources common_ctx =
  3559. let resource_file = new_cpp_file common_ctx common_ctx.file ([],"__resources__") in
  3560. resource_file#write "#include <hxcpp.h>\n\n";
  3561. let idx = ref 0 in
  3562. Hashtbl.iter (fun _ data ->
  3563. resource_file#write_i ("static unsigned char __res_" ^ (string_of_int !idx) ^ "[] = {\n");
  3564. resource_file#write_i "0xff, 0xff, 0xff, 0xff,\n";
  3565. for i = 0 to String.length data - 1 do
  3566. let code = Char.code (String.unsafe_get data i) in
  3567. resource_file#write (Printf.sprintf "0x%.2x, " code);
  3568. if ( (i mod 10) = 9) then resource_file#write "\n";
  3569. done;
  3570. resource_file#write ("0x00 };\n");
  3571. incr idx;
  3572. ) common_ctx.resources;
  3573. idx := 0;
  3574. resource_file#write "hx::Resource __Resources[] =";
  3575. resource_file#begin_block;
  3576. Hashtbl.iter (fun name data ->
  3577. resource_file#write_i
  3578. ("{ " ^ (str name) ^ "," ^ (string_of_int (String.length data)) ^ "," ^
  3579. "__res_" ^ (string_of_int !idx) ^ " + 4 },\n");
  3580. incr idx;
  3581. ) common_ctx.resources;
  3582. resource_file#write_i "{String(null()),0,0}";
  3583. resource_file#end_block_line;
  3584. resource_file#write ";\n\n";
  3585. resource_file#write "namespace hx { Resource *GetResources() { return __Resources; } } \n\n";
  3586. resource_file#close;;
  3587. let write_build_data common_ctx filename classes main_deps build_extra exe_name =
  3588. let buildfile = open_out filename in
  3589. let include_prefix = get_include_prefix common_ctx true in
  3590. let add_class_to_buildfile class_def =
  3591. let class_path = fst class_def in
  3592. let deps = snd class_def in
  3593. let cpp = (join_class_path class_path "/") ^ (source_file_extension common_ctx) in
  3594. output_string buildfile ( " <file name=\"src/" ^ cpp ^ "\">\n" );
  3595. let project_deps = List.filter (fun path -> not (is_internal_class path) ) deps in
  3596. List.iter (fun path-> output_string buildfile (" <depend name=\"" ^
  3597. ( match path with
  3598. | (["@verbatim"],file) -> file
  3599. | _ -> "include/" ^ include_prefix ^ (join_class_path path "/") ^ ".h" )
  3600. ^ "\"/>\n") ) project_deps;
  3601. output_string buildfile ( " </file>\n" )
  3602. in
  3603. output_string buildfile "<xml>\n";
  3604. output_string buildfile ("<set name=\"HXCPP_API_LEVEL\" value=\"" ^
  3605. (Common.defined_value common_ctx Define.HxcppApiLevel) ^ "\" />\n");
  3606. output_string buildfile "<files id=\"haxe\">\n";
  3607. output_string buildfile "<compilerflag value=\"-Iinclude\"/>\n";
  3608. List.iter add_class_to_buildfile classes;
  3609. add_class_to_buildfile ( ( [] , "__boot__") , [] );
  3610. add_class_to_buildfile ( ( [] , "__files__") , [] );
  3611. add_class_to_buildfile ( ( [] , "__resources__") , [] );
  3612. output_string buildfile "</files>\n";
  3613. output_string buildfile "<files id=\"__lib__\">\n";
  3614. output_string buildfile "<compilerflag value=\"-Iinclude\"/>\n";
  3615. add_class_to_buildfile ( ( [] , "__lib__") , main_deps );
  3616. output_string buildfile "</files>\n";
  3617. output_string buildfile "<files id=\"__main__\">\n";
  3618. output_string buildfile "<compilerflag value=\"-Iinclude\"/>\n";
  3619. add_class_to_buildfile ( ( [] , "__main__") , main_deps );
  3620. output_string buildfile "</files>\n";
  3621. output_string buildfile ("<set name=\"HAXE_OUTPUT\" value=\"" ^ exe_name ^ "\" />\n");
  3622. output_string buildfile "<include name=\"${HXCPP}/build-tool/BuildCommon.xml\"/>\n";
  3623. output_string buildfile build_extra;
  3624. output_string buildfile "</xml>\n";
  3625. close_out buildfile;;
  3626. let write_build_options common_ctx filename defines =
  3627. let writer = cached_source_writer common_ctx filename in
  3628. writer#write ( defines ^ "\n");
  3629. let cmd = Unix.open_process_in "haxelib path hxcpp" in
  3630. writer#write (Pervasives.input_line cmd);
  3631. Pervasives.ignore (Unix.close_process_in cmd);
  3632. writer#close;;
  3633. let create_member_types common_ctx =
  3634. let result = Hashtbl.create 0 in
  3635. let add_member class_name interface member =
  3636. match follow member.cf_type, member.cf_kind with
  3637. | _, Var _ when interface -> ()
  3638. | _, Method MethDynamic when interface -> ()
  3639. | TFun (_,ret), _ ->
  3640. (*print_endline (class_name ^ "." ^ member.cf_name ^ "=" ^ (type_string ret) );*)
  3641. Hashtbl.add result (class_name ^ "." ^ member.cf_name) (type_string ret)
  3642. | _,_ when not interface ->
  3643. Hashtbl.add result (class_name ^ "." ^ member.cf_name) (type_string member.cf_type)
  3644. | _ -> ()
  3645. in
  3646. List.iter (fun object_def ->
  3647. (match object_def with
  3648. | TClassDecl class_def ->
  3649. let class_name = "::" ^ (join_class_path class_def.cl_path "::") in
  3650. let rec add_all_fields class_def =
  3651. (match class_def.cl_super with Some super -> add_all_fields (fst super) | _->(););
  3652. List.iter (add_member class_name class_def.cl_interface) class_def.cl_ordered_fields;
  3653. List.iter (add_member class_name class_def.cl_interface) class_def.cl_ordered_statics
  3654. in
  3655. add_all_fields class_def
  3656. | _ -> ( )
  3657. ) ) common_ctx.types;
  3658. result;;
  3659. (* Builds inheritance tree, so header files can include parents defs. *)
  3660. let create_super_dependencies common_ctx =
  3661. let result = Hashtbl.create 0 in
  3662. List.iter (fun object_def ->
  3663. (match object_def with
  3664. | TClassDecl class_def when not class_def.cl_extern ->
  3665. let deps = ref [] in
  3666. (match class_def.cl_super with Some super ->
  3667. if not (fst super).cl_extern then
  3668. deps := ((fst super).cl_path) :: !deps
  3669. | _ ->() );
  3670. List.iter (fun imp -> if not (fst imp).cl_extern then deps := (fst imp).cl_path :: !deps) (real_interfaces class_def.cl_implements);
  3671. Hashtbl.add result class_def.cl_path !deps;
  3672. | TEnumDecl enum_def when not enum_def.e_extern ->
  3673. Hashtbl.add result enum_def.e_path [];
  3674. | _ -> () );
  3675. ) common_ctx.types;
  3676. result;;
  3677. let create_constructor_dependencies common_ctx =
  3678. let result = Hashtbl.create 0 in
  3679. List.iter (fun object_def ->
  3680. (match object_def with
  3681. | TClassDecl class_def when not class_def.cl_extern ->
  3682. (match class_def.cl_constructor with
  3683. | Some func_def -> Hashtbl.add result class_def.cl_path func_def
  3684. | _ -> () )
  3685. | _ -> () );
  3686. ) common_ctx.types;
  3687. result;;
  3688. (*
  3689. Exports can now be done with macros and a class list
  3690. let rec s_type t =
  3691. let result =
  3692. match t with
  3693. | TMono r -> (match !r with | None -> "Dynamic" | Some t -> s_type t)
  3694. | TEnum (e,tl) -> Ast.s_type_path e.e_path ^ s_type_params tl
  3695. | TInst (c,tl) -> Ast.s_type_path c.cl_path ^ s_type_params tl
  3696. | TType (t,tl) -> Ast.s_type_path t.t_path ^ s_type_params tl
  3697. | TAbstract (abs,pl) when abs.a_impl <> None ->
  3698. s_type (Abstract.get_underlying_type abs pl);
  3699. | TAbstract (a,tl) -> Ast.s_type_path a.a_path ^ s_type_params tl
  3700. | TFun ([],t) -> "Void -> " ^ s_fun t false
  3701. | TFun (l,t) ->
  3702. String.concat " -> " (List.map (fun (s,b,t) ->
  3703. (if b then "?" else "") ^ (""(*if s = "" then "" else s ^ " : "*)) ^ s_fun t true
  3704. ) l) ^ " -> " ^ s_fun t false
  3705. | TAnon a ->
  3706. let fl = PMap.fold (fun f acc -> ((if Meta.has Meta.Optional f.cf_meta then " ?" else " ") ^ f.cf_name ^ " : " ^ s_type f.cf_type) :: acc) a.a_fields [] in
  3707. "{" ^ (if not (is_closed a) then "+" else "") ^ String.concat "," fl ^ " }"
  3708. | TDynamic t2 -> "Dynamic" ^ s_type_params (if t == t2 then [] else [t2])
  3709. | TLazy f -> s_type (!f())
  3710. in
  3711. if result="Array<haxe.io.Unsigned_char__>" then "haxe.io.BytesData" else result
  3712. and s_fun t void =
  3713. match follow t with
  3714. | TFun _ -> "(" ^ s_type t ^ ")"
  3715. | TAbstract ({ a_path = ([],"Void") },[]) when void -> "(" ^ s_type t ^ ")"
  3716. | TMono r -> (match !r with | None -> s_type t | Some t -> s_fun t void)
  3717. | TLazy f -> s_fun (!f()) void
  3718. | _ -> (s_type t)
  3719. and s_type_params = function
  3720. | [] -> ""
  3721. | l -> "< " ^ String.concat ", " (List.map s_type l) ^ " >"
  3722. ;;
  3723. let gen_extern_class common_ctx class_def file_info =
  3724. let file = new_source_file common_ctx common_ctx.file "extern" ".hx" class_def.cl_path in
  3725. let path = class_def.cl_path in
  3726. let rec remove_all_prefix class_def field t =
  3727. let path = class_def.cl_path in
  3728. let filterPath = fst path @ [snd path] in
  3729. let rec remove_prefix t = match t with
  3730. | TInst ({cl_path=[f],suffix } as cval ,tl) when f=field ->
  3731. TInst ( { cval with cl_path = ([],suffix) }, List.map remove_prefix tl)
  3732. | TInst ({cl_path=cpath,suffix } as cval ,tl) when cpath=filterPath ->
  3733. TInst ( { cval with cl_path = ([],suffix) }, List.map remove_prefix tl)
  3734. | TInst (cval,tl) -> TInst ( cval, List.map remove_prefix tl)
  3735. (*| TInst ({cl_path=prefix} as cval ,tl) ->
  3736. TInst ( { cval with cl_path = ([],snd cval.cl_path) }, List.map (remove_prefix field) tl)*)
  3737. | t -> Type.map remove_prefix t
  3738. in
  3739. let t = remove_prefix t in
  3740. let superred = (match class_def.cl_super with
  3741. | Some (super,_) -> remove_all_prefix super field t
  3742. | _ -> t )
  3743. in
  3744. List.fold_left ( fun t (impl,_) -> remove_all_prefix impl field t ) superred class_def.cl_implements;
  3745. (*
  3746. remove_prefix t
  3747. *)
  3748. in
  3749. let params = function [] -> "" | l -> "< " ^ (String.concat "," (List.map (fun (n,t) -> n) l) ^ " >") in
  3750. let output = file#write in
  3751. let print_field stat f =
  3752. let s_type t = s_type (remove_all_prefix class_def f.cf_name t) in
  3753. let args = function TFun (args,_) ->
  3754. String.concat "," (List.map (fun (name,opt,t) -> (if opt then "?" else "") ^ name ^":"^ (s_type t)) args) | _ -> "" in
  3755. let ret = function TFun (_,ret) -> s_type ret | _ -> "Dynamic" in
  3756. let override = if (is_override class_def f.cf_name ) then "override " else "" in
  3757. output ("\t" ^ (if stat then "static " else "") ^ (if f.cf_public then "public " else "") );
  3758. let s_access mode op name = match mode with
  3759. | AccNormal -> "default"
  3760. | AccNo -> "null"
  3761. | AccNever -> "never"
  3762. | AccResolve -> "resolve"
  3763. | AccCall -> op ^ "_" ^ name
  3764. | AccInline -> "default"
  3765. | AccRequire (n,_) -> "require " ^ n
  3766. in
  3767. (match f.cf_kind, f.cf_name with
  3768. | Var { v_read = AccInline; v_write = AccNever },_ ->
  3769. (match f.cf_expr with Some expr ->
  3770. output ("inline var " ^ f.cf_name ^ ":" ^ (s_type f.cf_type) ^ "=" );
  3771. let ctx = (new_extern_context common_ctx file 1 file_info) in
  3772. gen_expression ctx true expr;
  3773. | _ -> () )
  3774. | Var { v_read = AccNormal; v_write = AccNormal },_ -> output ("var " ^ f.cf_name ^ ":" ^ (s_type f.cf_type))
  3775. | Var v,_ -> output ("var " ^ f.cf_name ^ "(" ^ (s_access v.v_read "get" f.cf_name) ^ "," ^ (s_access v.v_write "set" f.cf_name) ^ "):" ^ (s_type f.cf_type))
  3776. | Method _, "new" -> output ("function new(" ^ (args f.cf_type) ^ "):Void")
  3777. | Method MethDynamic, _ -> output ("dynamic function " ^ f.cf_name ^ (params f.cf_params) ^ "(" ^ (args f.cf_type) ^ "):" ^ (ret f.cf_type) )
  3778. | Method _, _ -> output (override ^ "function " ^ f.cf_name ^ (params f.cf_params) ^ "(" ^ (args f.cf_type) ^ "):" ^ (ret f.cf_type) )
  3779. );
  3780. output ";\n\n";
  3781. in
  3782. let s_type t = s_type (remove_all_prefix class_def "*" t) in
  3783. let c = class_def in
  3784. output ( "package " ^ (String.concat "." (fst path)) ^ ";\n" );
  3785. output ( "@:include extern " ^ (if c.cl_private then "private " else "") ^ (if c.cl_interface then "interface" else "class")
  3786. ^ " " ^ (snd path) ^ (params c.cl_params) );
  3787. (match c.cl_super with None -> () | Some (c,pl) -> output (" extends " ^ (s_type (TInst (c,pl)))));
  3788. List.iter (fun (c,pl) -> output ( " implements " ^ (s_type (TInst (c,pl))))) (real_interfaces c.cl_implements);
  3789. (match c.cl_dynamic with None -> () | Some t -> output (" implements Dynamic< " ^ (s_type t) ^ " >"));
  3790. (match c.cl_array_access with None -> () | Some t -> output (" implements ArrayAccess< " ^ (s_type t) ^ " >"));
  3791. output "{\n";
  3792. (match c.cl_constructor with
  3793. | None -> ()
  3794. | Some f -> print_field false f);
  3795. let is_public f = f.cf_public in
  3796. List.iter (print_field false) (List.filter is_public c.cl_ordered_fields);
  3797. List.iter (print_field true) (List.filter is_public c.cl_ordered_statics);
  3798. output "}";
  3799. output "\n";
  3800. file#close
  3801. ;;
  3802. let gen_extern_enum common_ctx enum_def file_info =
  3803. let path = enum_def.e_path in
  3804. let file = new_source_file common_ctx common_ctx.file "extern" ".hx" path in
  3805. let output = file#write in
  3806. let params = function [] -> "" | l -> "< " ^ (String.concat "," (List.map (fun (n,t) -> n) l) ^ " >") in
  3807. output ( "package " ^ (String.concat "." (fst path)) ^ ";\n" );
  3808. output ( "@:include extern " ^ (if enum_def.e_private then "private " else "")
  3809. ^ " enum " ^ (snd path) ^ (params enum_def.e_params) );
  3810. output " {\n";
  3811. let sorted_items = List.sort (fun f1 f2 -> (f1.ef_index - f2.ef_index ) ) (pmap_values enum_def.e_constrs) in
  3812. List.iter (fun constructor ->
  3813. let name = keyword_remap constructor.ef_name in
  3814. match constructor.ef_type with
  3815. | TFun (args,_) ->
  3816. output ( name ^ "(" );
  3817. output ( String.concat "," (List.map (fun (arg,_,t) -> arg ^ ":" ^ (s_type t) ) args) );
  3818. output ");\n\n";
  3819. | _ -> output ( name ^ ";\n\n" )
  3820. ) sorted_items;
  3821. output "}\n";
  3822. file#close
  3823. ;;
  3824. *)
  3825. let is_this expression =
  3826. match (remove_parens expression).eexpr with
  3827. | TConst TThis -> true
  3828. | _ -> false
  3829. ;;
  3830. let is_super expression =
  3831. match (remove_parens expression).eexpr with
  3832. | TConst TSuper -> true
  3833. | _ -> false
  3834. ;;
  3835. let is_assign_op op =
  3836. match op with
  3837. | OpAssign
  3838. | OpAssignOp _ -> true
  3839. | _ -> false
  3840. ;;
  3841. let rec script_type_string haxe_type =
  3842. match haxe_type with
  3843. | TType ({ t_path = ([],"Null") },[t]) ->
  3844. (match follow t with
  3845. | TAbstract ({ a_path = [],"Int" },_)
  3846. | TAbstract ({ a_path = [],"Float" },_)
  3847. | TAbstract ({ a_path = [],"Bool" },_)
  3848. | TInst ({ cl_path = [],"Int" },_)
  3849. | TInst ({ cl_path = [],"Float" },_)
  3850. | TEnum ({ e_path = [],"Bool" },_) -> "Dynamic"
  3851. | _ -> script_type_string t)
  3852. | TInst ({cl_path=[],"Null"},[t]) ->
  3853. (match follow t with
  3854. | TAbstract ({ a_path = [],"Int" },_)
  3855. | TAbstract ({ a_path = [],"Float" },_)
  3856. | TAbstract ({ a_path = [],"Bool" },_)
  3857. | TInst ({ cl_path = [],"Int" },_)
  3858. | TInst ({ cl_path = [],"Float" },_)
  3859. | TEnum ({ e_path = [],"Bool" },_) -> "Dynamic"
  3860. | _ -> script_type_string t )
  3861. | _ ->
  3862. match follow haxe_type with
  3863. | TType ({t_path = [],"Array"},params) -> "Array"
  3864. | TInst ({cl_path=[],"Array"},params) ->
  3865. (match params with
  3866. | [t] ->
  3867. (match type_string_suff "" t with
  3868. | "int" -> "Array.int"
  3869. | "Float" -> "Array.Float"
  3870. | "bool" -> "Array.bool"
  3871. | "::String" -> "Array.String"
  3872. | "unsigned char" -> "Array.unsigned char"
  3873. | "Dynamic" -> "Array.Any"
  3874. | _ -> "Array.Object"
  3875. )
  3876. | _ -> "Array.Object"
  3877. )
  3878. | TAbstract (abs,pl) when abs.a_impl <> None ->
  3879. script_type_string (Abstract.get_underlying_type abs pl);
  3880. | _ ->
  3881. type_string_suff "" haxe_type
  3882. ;;
  3883. type array_of =
  3884. | ArrayInterface of int
  3885. | ArrayData of string
  3886. | ArrayObject
  3887. | ArrayAny
  3888. | ArrayNone
  3889. ;;
  3890. let is_template_type t =
  3891. false
  3892. ;;
  3893. let rec is_dynamic_in_cppia ctx expr =
  3894. match expr.eexpr with
  3895. | TCast(_,None) -> true
  3896. | _ -> is_dynamic_in_cpp ctx expr
  3897. ;;
  3898. type cppia_op =
  3899. | IaFunction
  3900. | IaVar
  3901. | IaToInterface
  3902. | IaToDynArray
  3903. | IaToDataArray
  3904. | IaToInterfaceArray
  3905. | IaFun
  3906. | IaCast
  3907. | IaBlock
  3908. | IaBreak
  3909. | IaContinue
  3910. | IaIsNull
  3911. | IaNotNull
  3912. | IaSet
  3913. | IaCall
  3914. | IaCallGlobal
  3915. | IaCallStatic
  3916. | IaCallMember
  3917. | IaCallSuper
  3918. | IaCallThis
  3919. | IaCallSuperNew
  3920. | IaCreateEnum
  3921. | IaADef
  3922. | IaIf
  3923. | IaIfElse
  3924. | IaFStatic
  3925. | IaFName
  3926. | IaFThisInst
  3927. | IaFLink
  3928. | IaFThisName
  3929. | IaFEnum
  3930. | IaThrow
  3931. | IaArrayI
  3932. | IaPlusPlus
  3933. | IaPlusPlusPost
  3934. | IaMinusMinus
  3935. | IaMinusMinusPost
  3936. | IaNeg
  3937. | IaBitNot
  3938. | IaLogicNot
  3939. | IaTVars
  3940. | IaVarDecl
  3941. | IaVarDeclI
  3942. | IaNew
  3943. | IaReturn
  3944. | IaRetVal
  3945. | IaPosInfo
  3946. | IaObjDef
  3947. | IaClassOf
  3948. | IaWhile
  3949. | IaFor
  3950. | IaEnumI
  3951. | IaSwitch
  3952. | IaTry
  3953. | IaImplDynamic
  3954. | IaConstInt
  3955. | IaConstFloat
  3956. | IaConstString
  3957. | IaConstFalse
  3958. | IaConstTrue
  3959. | IaConstNull
  3960. | IaConsThis
  3961. | IaConstSuper
  3962. | IaCastInt
  3963. | IaCastBool
  3964. | IaInterface
  3965. | IaClass
  3966. | IaAccessNormal
  3967. | IaAccessNot
  3968. | IaAccessResolve
  3969. | IaAccessCall
  3970. | IaEnum
  3971. | IaInline
  3972. | IaMain
  3973. | IaNoMain
  3974. | IaResources
  3975. | IaReso
  3976. | IaBinOp of Ast.binop
  3977. ;;
  3978. let cppia_op_info = function
  3979. | IaFunction -> ("FUNCTION", 1)
  3980. | IaVar -> ("VAR", 2)
  3981. | IaToInterface -> ("TOINTERFACE", 3)
  3982. | IaToDynArray -> ("TODYNARRAY", 4)
  3983. | IaToDataArray -> ("TODATAARRAY", 5)
  3984. | IaToInterfaceArray -> ("TOINTERFACEARRAY", 6)
  3985. | IaFun -> ("FUN", 7)
  3986. | IaCast -> ("CAST", 8)
  3987. | IaBlock -> ("BLOCK", 9)
  3988. | IaBreak -> ("BREAK", 10)
  3989. | IaContinue -> ("CONTINUE", 11)
  3990. | IaIsNull -> ("ISNULL", 12)
  3991. | IaNotNull -> ("NOTNULL", 13)
  3992. | IaSet -> ("SET", 14)
  3993. | IaCall -> ("CALL", 15)
  3994. | IaCallGlobal -> ("CALLGLOBAL", 16)
  3995. | IaCallStatic -> ("CALLSTATIC", 17)
  3996. | IaCallMember -> ("CALLMEMBER", 18)
  3997. | IaCallSuper -> ("CALLSUPER", 19)
  3998. | IaCallThis -> ("CALLTHIS", 20)
  3999. | IaCallSuperNew -> ("CALLSUPERNEW", 21)
  4000. | IaCreateEnum -> ("CREATEENUM", 22)
  4001. | IaADef -> ("ADEF", 23)
  4002. | IaIf -> ("IF", 24)
  4003. | IaIfElse -> ("IFELSE", 25)
  4004. | IaFName -> ("FNAME", 27)
  4005. | IaFStatic -> ("FSTATIC", 28)
  4006. | IaFThisInst -> ("FTHISINST", 29)
  4007. | IaFLink -> ("FLINK", 30)
  4008. | IaFThisName -> ("FTHISNAME", 31)
  4009. | IaFEnum -> ("FENUM", 32)
  4010. | IaThrow -> ("THROW", 33)
  4011. | IaArrayI -> ("ARRAYI", 34)
  4012. | IaPlusPlus -> ("++", 35)
  4013. | IaPlusPlusPost -> ("+++", 36)
  4014. | IaMinusMinus -> ("--", 37)
  4015. | IaMinusMinusPost -> ("---", 38)
  4016. | IaNeg -> ("NEG", 39)
  4017. | IaBitNot -> ("~", 40)
  4018. | IaLogicNot -> ("!", 41)
  4019. | IaTVars -> ("TVARS", 42)
  4020. | IaVarDecl -> ("VARDECL", 43)
  4021. | IaVarDeclI -> ("VARDECLI", 44)
  4022. | IaNew -> ("NEW", 45)
  4023. | IaReturn -> ("RETURN", 46)
  4024. | IaRetVal -> ("RETVAL", 47)
  4025. | IaPosInfo -> ("POSINFO", 48)
  4026. | IaObjDef -> ("OBJDEF", 49)
  4027. | IaClassOf -> ("CLASSOF", 50)
  4028. | IaWhile -> ("WHILE", 51)
  4029. | IaFor -> ("FOR", 52)
  4030. | IaEnumI -> ("ENUMI", 53)
  4031. | IaSwitch -> ("SWITCH", 54)
  4032. | IaTry -> ("TRY", 55)
  4033. | IaImplDynamic -> ("IMPLDYNAMIC", 56)
  4034. | IaConstInt -> ("i", 57)
  4035. | IaConstFloat -> ("f", 58)
  4036. | IaConstString -> ("s", 59)
  4037. | IaConstFalse -> ("false", 60)
  4038. | IaConstTrue -> ("true", 61)
  4039. | IaConstNull -> ("NULL", 62)
  4040. | IaConsThis -> ("THIS", 63)
  4041. | IaConstSuper -> ("SUPER", 64)
  4042. | IaCastInt -> ("CASTINT", 65)
  4043. | IaCastBool -> ("CASTBOOL", 66)
  4044. | IaInterface -> ("INTERFACE", 67)
  4045. | IaClass -> ("CLASS", 68)
  4046. | IaAccessNormal -> ("N", 69)
  4047. | IaAccessNot -> ("n", 70)
  4048. | IaAccessResolve -> ("R", 71)
  4049. | IaAccessCall -> ("C", 72)
  4050. | IaEnum -> ("ENUM", 73)
  4051. | IaInline -> ("INLINE", 74)
  4052. | IaMain -> ("MAIN", 75)
  4053. | IaNoMain -> ("NOMAIN", 76)
  4054. | IaResources -> ("RESOURCES", 77)
  4055. | IaReso -> ("RESO", 78)
  4056. | IaBinOp OpAdd -> ("+", 101)
  4057. | IaBinOp OpMult -> ("*", 102)
  4058. | IaBinOp OpDiv -> ("/", 103)
  4059. | IaBinOp OpSub -> ("-", 104)
  4060. | IaBinOp OpAssign -> ("=", 105)
  4061. | IaBinOp OpEq -> ("==", 106)
  4062. | IaBinOp OpNotEq -> ("!=", 107)
  4063. | IaBinOp OpGte -> (">=", 108)
  4064. | IaBinOp OpLte -> ("<=", 109)
  4065. | IaBinOp OpGt -> (">", 110)
  4066. | IaBinOp OpLt -> ("<", 111)
  4067. | IaBinOp OpAnd -> ("&", 112)
  4068. | IaBinOp OpOr -> ("|", 113)
  4069. | IaBinOp OpXor -> ("^", 114)
  4070. | IaBinOp OpBoolAnd -> ("&&", 115)
  4071. | IaBinOp OpBoolOr -> ("||", 116)
  4072. | IaBinOp OpShr -> (">>", 117)
  4073. | IaBinOp OpUShr -> (">>>", 118)
  4074. | IaBinOp OpShl -> ("<<", 119)
  4075. | IaBinOp OpMod -> ("%", 120)
  4076. | IaBinOp OpInterval -> ("...", 121)
  4077. | IaBinOp OpArrow -> ("=>", 122)
  4078. | IaBinOp OpAssignOp OpAdd -> ("+=", 201)
  4079. | IaBinOp OpAssignOp OpMult -> ("*=", 202)
  4080. | IaBinOp OpAssignOp OpDiv -> ("/=", 203)
  4081. | IaBinOp OpAssignOp OpSub -> ("-=", 204)
  4082. | IaBinOp OpAssignOp OpAnd -> ("&=", 212)
  4083. | IaBinOp OpAssignOp OpOr -> ("|=", 213)
  4084. | IaBinOp OpAssignOp OpXor -> ("^=", 214)
  4085. | IaBinOp OpAssignOp OpBoolAnd -> ("&&=", 215)
  4086. | IaBinOp OpAssignOp OpBoolOr -> ("||=", 216)
  4087. | IaBinOp OpAssignOp OpShr -> (">>=", 217)
  4088. | IaBinOp OpAssignOp OpUShr -> (">>>=", 218)
  4089. | IaBinOp OpAssignOp OpShl -> ("<<=", 219)
  4090. | IaBinOp OpAssignOp OpMod -> ("%=", 220)
  4091. | IaBinOp OpAssignOp OpInterval
  4092. | IaBinOp OpAssignOp OpAssign
  4093. | IaBinOp OpAssignOp OpEq
  4094. | IaBinOp OpAssignOp OpNotEq
  4095. | IaBinOp OpAssignOp OpGte
  4096. | IaBinOp OpAssignOp OpLte
  4097. | IaBinOp OpAssignOp OpGt
  4098. | IaBinOp OpAssignOp OpLt
  4099. | IaBinOp OpAssignOp OpAssignOp _
  4100. | IaBinOp OpAssignOp OpArrow -> assert false
  4101. ;;
  4102. class script_writer common_ctx ctx filename asciiOut =
  4103. object(this)
  4104. val debug = asciiOut
  4105. val indent_str = if asciiOut then "\t" else ""
  4106. val mutable indent = ""
  4107. val mutable indents = []
  4108. val mutable just_finished_block = false
  4109. val mutable classCount = 0
  4110. val mutable return_type = TMono(ref None)
  4111. val buffer = Buffer.create 0
  4112. val identTable = Hashtbl.create 0
  4113. val fileTable = Hashtbl.create 0
  4114. val identBuffer = Buffer.create 0
  4115. method stringId name =
  4116. try ( Hashtbl.find identTable name )
  4117. with Not_found -> begin
  4118. let size = Hashtbl.length identTable in
  4119. Hashtbl.add identTable name size;
  4120. Buffer.add_string identBuffer ((string_of_int (String.length name)) ^ " " ^ name ^ "\n");
  4121. size;
  4122. end
  4123. method incClasses = classCount <- classCount +1
  4124. method stringText name = (string_of_int (this#stringId name)) ^ " "
  4125. val typeTable = Hashtbl.create 0
  4126. val typeBuffer = Buffer.create 0
  4127. method typeId name =
  4128. let name = if name="::hx::Class" then "::Class" else name in
  4129. try ( Hashtbl.find typeTable name )
  4130. with Not_found -> begin
  4131. let size = Hashtbl.length typeTable in
  4132. Hashtbl.add typeTable name size;
  4133. Buffer.add_string typeBuffer ((string_of_int (String.length name)) ^ " " ^ name ^ "\n");
  4134. size;
  4135. end
  4136. method write str = if asciiOut then
  4137. Buffer.add_string buffer str
  4138. else begin
  4139. let push i = Buffer.add_char buffer (Char.chr i) in
  4140. let pushI32 i = push (Int32.to_int (Int32.logand i (Int32.of_int 255))) in
  4141. List.iter (fun i ->
  4142. if ((Int32.compare i Int32.zero) >= 0) && ((Int32.compare i (Int32.of_int 254)) < 0) then
  4143. pushI32 i
  4144. else if ((Int32.compare i Int32.zero) >= 0) && ((Int32.compare i (Int32.of_int 65536)) < 0) then begin
  4145. push 254;
  4146. pushI32 i;
  4147. pushI32 (Int32.shift_right i 8);
  4148. end else begin
  4149. push 255;
  4150. pushI32 i;
  4151. pushI32 (Int32.shift_right i 8);
  4152. pushI32 (Int32.shift_right i 16);
  4153. pushI32 (Int32.shift_right i 24);
  4154. end
  4155. ) (List.map Int32.of_string (Str.split (Str.regexp "[\n\t ]+") str) );
  4156. end;
  4157. just_finished_block <- false
  4158. method typeTextString typeName = (string_of_int (this#typeId typeName)) ^ " "
  4159. method typeText typeT = (string_of_int (this#typeId (script_type_string typeT))) ^ " "
  4160. method writeType typeT = this#write (this#typeText typeT)
  4161. method boolText value = if value then "1" else "0"
  4162. method writeBool value = this#write (if value then "1 " else "0 ")
  4163. method staticText value = if value then "1" else "0"
  4164. method writeData str = Buffer.add_string buffer str;
  4165. method wint ival = this#write ((string_of_int ival)^" ")
  4166. method ident name = this#wint (this#stringId name)
  4167. method instText clazz = match clazz.cl_path with
  4168. | ([],"Array") -> string_of_int (this#typeId "Array< ::Dynamic >") ^ " "
  4169. | _ -> this#typeText (TInst(clazz,[]))
  4170. method instName clazz = this#write (this#instText clazz)
  4171. method enumText e = this#typeText (TEnum(e,[]))
  4172. method enumName e = this#write (this#enumText e)
  4173. method close =
  4174. let out_file = open_out_bin filename in
  4175. output_string out_file (if asciiOut then "CPPIA\n" else "CPPIB\n");
  4176. let idents = Buffer.contents identBuffer in
  4177. output_string out_file ((string_of_int (Hashtbl.length identTable)) ^ "\n");
  4178. output_string out_file idents;
  4179. let types = Buffer.contents typeBuffer in
  4180. output_string out_file ((string_of_int (Hashtbl.length typeTable)) ^ "\n");
  4181. output_string out_file types;
  4182. output_string out_file ( (string_of_int classCount) ^ "\n" );
  4183. let contents = Buffer.contents buffer in
  4184. output_string out_file contents;
  4185. close_out out_file
  4186. method fileId file =
  4187. try ( Hashtbl.find fileTable file )
  4188. with Not_found -> begin
  4189. let stripped_file = strip_file common_ctx file in
  4190. let result = this#stringId stripped_file in
  4191. Hashtbl.add fileTable file result;
  4192. result;
  4193. end
  4194. method constText c = match c with
  4195. | TInt i -> (this#op IaConstInt) ^ (Printf.sprintf "%ld " i)
  4196. | TFloat f -> (this#op IaConstFloat) ^ (this#stringText f)
  4197. | TString s -> (this#op IaConstString) ^ (this#stringText s)
  4198. | TBool true -> (this#op IaConstTrue)
  4199. | TBool false -> (this#op IaConstFalse)
  4200. | TNull -> (this#op IaConstNull)
  4201. | TThis -> (this#op IaConsThis)
  4202. | TSuper -> (this#op IaConstSuper)
  4203. method get_array_type t =
  4204. match follow t with
  4205. | TInst ({cl_path=[],"Array"},[param]) ->
  4206. let typeName = type_string_suff "" param in
  4207. (match typeName with
  4208. | "::String" -> ArrayData "String"
  4209. | "int" | "Float" | "bool" | "String" | "unsigned char" ->
  4210. ArrayData typeName
  4211. | "Dynamic" -> ArrayAny
  4212. | _ when is_interface_type param -> ArrayInterface (this#typeId (script_type_string param))
  4213. | _ -> ArrayObject
  4214. )
  4215. | TAbstract (abs,pl) when abs.a_impl <> None ->
  4216. this#get_array_type (Abstract.get_underlying_type abs pl);
  4217. | _ -> ArrayNone;
  4218. method pushReturn inType =
  4219. let oldReturnType = return_type in
  4220. return_type <- inType;
  4221. fun () -> return_type <- oldReturnType;
  4222. method fileText file = string_of_int (this#fileId file)
  4223. method indent_one = this#write indent_str
  4224. method push_indent = indents <- indent_str::indents; indent <- String.concat "" indents
  4225. method pop_indent = match indents with
  4226. | h::tail -> indents <- tail; indent <- String.concat "" indents
  4227. | [] -> indent <- "/*?*/";
  4228. method write_i x = this#write (indent ^ x)
  4229. method get_indent = indent
  4230. method begin_expr = this#push_indent
  4231. method end_expr = if not just_finished_block then this#write "\n"; this#pop_indent; just_finished_block <- true
  4232. method op x = match cppia_op_info x with
  4233. | (name,index) -> (if debug then name else string_of_int index) ^ " "
  4234. method writeOp o = this#write (this#op o)
  4235. method writeOpLine o = this#write ((this#op o) ^ "\n")
  4236. method voidFunc isStatic isDynamic funcName fieldExpression =
  4237. this#write ( (this#op IaFunction) ^ (this#staticText isStatic) ^ " " ^(this#boolText isDynamic) ^ " " ^(this#stringText funcName) ^ " ");
  4238. this#write ((this#typeTextString "Void") ^ "0\n");
  4239. this#gen_expression fieldExpression
  4240. method func isStatic isDynamic funcName ret args isInterface fieldExpression =
  4241. this#write ( (this#op IaFunction) ^ (this#staticText isStatic) ^ " " ^(this#boolText isDynamic) ^ " " ^(this#stringText funcName) ^ " ");
  4242. this#write ((this#typeText ret) ^ (string_of_int (List.length args)) ^ " ");
  4243. List.iter (fun (name,opt,typ) -> this#write ( (this#stringText name) ^ (this#boolText opt) ^ " " ^ (this#typeText typ) ^ " " )) args;
  4244. this#write "\n";
  4245. if (not isInterface) then begin
  4246. match fieldExpression with
  4247. | Some ({ eexpr = TFunction function_def } as e) -> this#gen_expression e
  4248. | _ -> print_endline ("Missing function body for " ^ funcName );
  4249. end
  4250. method var readAcc writeAcc isExtern isStatic name varType varExpr =
  4251. this#write ( (this#op IaVar) ^ (this#staticText isStatic) ^ " " ^ (this#op readAcc) ^ (this#op writeAcc) ^
  4252. (this#boolText isExtern) ^ " " ^ (this#stringText name)^ (this#typeText varType) ^
  4253. (match varExpr with Some _ -> "1\n" | _ -> "0\n" ) );
  4254. match varExpr with
  4255. | Some expression -> this#gen_expression expression
  4256. | _ -> ()
  4257. method implDynamic = this#writeOpLine IaImplDynamic;
  4258. method writeVar v =
  4259. this#ident v.v_name;
  4260. this#wint v.v_id;
  4261. this#writeBool v.v_capture;
  4262. this#writeType v.v_type;
  4263. method writeList prefix len = this#write (prefix ^" " ^ (string_of_int (len)) ^ "\n");
  4264. method writePos expr = if debug then
  4265. this#write ( (this#fileText expr.epos.pfile) ^ "\t" ^ (string_of_int (Lexer.get_error_line expr.epos) ) ^ indent);
  4266. method checkCast toType expr forceCast fromGenExpression=
  4267. let write_cast text =
  4268. if (not fromGenExpression) then
  4269. this#writePos expr;
  4270. this#write (text ^"\n" );
  4271. this#begin_expr;
  4272. this#gen_expression expr;
  4273. this#end_expr;
  4274. true;
  4275. in
  4276. let was_cast =
  4277. if (is_interface_type toType) then begin
  4278. if (is_dynamic_in_cppia ctx expr) then begin
  4279. write_cast ( (this#op IaToInterface) ^ (this#typeText toType) ^ " " ^ (this#typeTextString "Dynamic") )
  4280. end else if (not (is_matching_interface_type toType expr.etype)) then begin
  4281. write_cast ( (this#op IaToInterface) ^ (this#typeText toType) ^ " " ^ (this#typeText expr.etype) )
  4282. end else
  4283. false
  4284. end else begin
  4285. let get_array_expr_type expr =
  4286. if is_dynamic_in_cppia ctx expr then
  4287. ArrayNone
  4288. else
  4289. this#get_array_type expr.etype
  4290. in
  4291. match (this#get_array_type toType), (get_array_expr_type expr) with
  4292. | ArrayAny, _ -> false
  4293. | ArrayObject, ArrayData _ -> write_cast (this#op IaToDynArray)
  4294. | ArrayData t, ArrayNone
  4295. | ArrayData t, ArrayObject
  4296. | ArrayData t, ArrayAny -> write_cast ((this#op IaToDataArray) ^ (this#typeTextString ("Array." ^ t)))
  4297. | ArrayInterface t, ArrayNone
  4298. | ArrayInterface t, ArrayAny -> write_cast ((this#op IaToInterfaceArray) ^ (string_of_int t))
  4299. | _,_ -> (* a0,a1 ->
  4300. let arrayString a =
  4301. match a with
  4302. | ArrayNone -> "ArrayNone"
  4303. | ArrayAny -> "ArrayAny"
  4304. | ArrayObject -> "ArrayObject"
  4305. | ArrayData _ -> "ArrayData"
  4306. | ArrayInterface _ -> "ArrayInterface"
  4307. in
  4308. this#write ("NOCAST " ^ (arrayString a0) ^ "=" ^ (arrayString a1)); *)
  4309. false
  4310. end
  4311. in
  4312. if (not was_cast) then begin
  4313. if (forceCast) then begin
  4314. let toType = (type_string expr.etype) in
  4315. this#writeOpLine (if toType="int" then IaCastInt else if toType=="bool" then IaCastBool else IaCast);
  4316. end;
  4317. this#gen_expression expr;
  4318. end
  4319. method gen_expression expr =
  4320. (* Redefine to allow different interpretation of cast *)
  4321. let rec remove_parens expression =
  4322. match expression.eexpr with
  4323. | TParenthesis e -> remove_parens e
  4324. | TMeta(_,e) -> remove_parens e
  4325. | _ -> expression
  4326. in
  4327. let expression = remove_parens expr in
  4328. this#begin_expr;
  4329. (*this#write ( (this#fileText expression.epos.pfile) ^ "\t" ^ (string_of_int (Lexer.get_error_line expression.epos) ) ^ indent);*)
  4330. this#writePos expression;
  4331. (match expression.eexpr with
  4332. | TFunction function_def -> this#write ( (this#op IaFun) ^ (this#typeText function_def.tf_type) ^ (string_of_int (List.length function_def.tf_args)) ^ "\n" );
  4333. List.iter (fun(arg,init) ->
  4334. this#write (indent ^ indent_str );
  4335. this#writeVar arg;
  4336. match init with
  4337. | Some const -> this#write ("1 " ^ (this#constText const) ^ "\n")
  4338. | _ -> this#write "0\n";
  4339. ) function_def.tf_args;
  4340. let pop = this#pushReturn function_def.tf_type in
  4341. this#gen_expression function_def.tf_expr;
  4342. pop ();
  4343. | TBlock expr_list -> this#writeList (this#op IaBlock) (List.length expr_list);
  4344. List.iter this#gen_expression expr_list;
  4345. | TConst const -> this#write (this#constText const)
  4346. | TBreak -> this#writeOp IaBreak
  4347. | TContinue -> this#writeOp IaContinue
  4348. | TBinop (op,e1,e2) when op=OpAssign ->
  4349. this#writeOpLine IaSet;
  4350. this#gen_expression e1;
  4351. this#checkCast e1.etype e2 false false;
  4352. | TBinop (OpEq ,e1, { eexpr = TConst TNull } ) -> this#writeOpLine IaIsNull;
  4353. this#gen_expression e1;
  4354. | TBinop (OpNotEq ,e1, { eexpr = TConst TNull }) -> this#writeOpLine IaNotNull;
  4355. this#gen_expression e1;
  4356. | TBinop (OpEq , { eexpr = TConst TNull }, e1) -> this#writeOpLine IaIsNull;
  4357. this#gen_expression e1;
  4358. | TBinop (OpNotEq, { eexpr = TConst TNull }, e1) -> this#writeOpLine IaNotNull;
  4359. this#gen_expression e1;
  4360. | TBinop (op,e1,e2) -> this#writeOpLine (IaBinOp op);
  4361. this#gen_expression e1;
  4362. this#gen_expression e2;
  4363. | TThrow e -> this#writeOpLine IaThrow;
  4364. this#gen_expression e;
  4365. | TArrayDecl expr_list ->
  4366. this#write ( (this#op IaADef) ^ (this#typeText expression.etype) ^ " " ^(string_of_int (List.length expr_list))^"\n");
  4367. List.iter this#gen_expression expr_list;
  4368. | TIf (e,e1,e2) ->
  4369. (match e2 with
  4370. | None ->
  4371. this#writeOpLine IaIf;
  4372. this#gen_expression e;
  4373. this#gen_expression e1;
  4374. | Some elze ->
  4375. this#writeOpLine IaIfElse;
  4376. this#gen_expression e;
  4377. this#gen_expression e1;
  4378. this#gen_expression elze; )
  4379. | TCall (func, arg_list) ->
  4380. let argN = (string_of_int (List.length arg_list)) ^ " " in
  4381. let is_real_function field =
  4382. match field.cf_kind with
  4383. | Method MethNormal -> true
  4384. | _ -> false;
  4385. in
  4386. let gen_call () =
  4387. (match (remove_parens func).eexpr with
  4388. | TField ( { eexpr = TLocal { v_name = "__global__" }}, field ) ->
  4389. this#write ( (this#op IaCallGlobal) ^ (this#stringText (field_name field)) ^ argN ^ "\n");
  4390. | TField (obj,FStatic (class_def,field) ) when is_real_function field ->
  4391. this#write ( (this#op IaCallStatic) ^ (this#instText class_def) ^ " " ^ (this#stringText field.cf_name) ^
  4392. argN ^ "\n");
  4393. | TField (obj,FInstance (_,_,field) ) when (is_this obj) && (is_real_function field) ->
  4394. this#write ( (this#op IaCallThis) ^ (this#typeText obj.etype) ^ " " ^ (this#stringText field.cf_name) ^
  4395. argN ^ "\n");
  4396. | TField (obj,FInstance (_,_,field) ) when is_super obj ->
  4397. this#write ( (this#op IaCallSuper) ^ (this#typeText obj.etype) ^ " " ^ (this#stringText field.cf_name) ^
  4398. argN ^ "\n");
  4399. | TField (obj,FInstance (_,_,field) ) when is_real_function field ->
  4400. this#write ( (this#op IaCallMember) ^ (this#typeText obj.etype) ^ " " ^ (this#stringText field.cf_name) ^
  4401. argN ^ "\n");
  4402. this#gen_expression obj;
  4403. | TField (obj,FDynamic (name) ) when (is_internal_member name || (type_string obj.etype = "::String" && name="cca") ) ->
  4404. this#write ( (this#op IaCallMember) ^ (this#typeText obj.etype) ^ " " ^ (this#stringText name) ^
  4405. argN ^ "\n");
  4406. this#gen_expression obj;
  4407. | TConst TSuper -> this#write ((this#op IaCallSuperNew) ^ (this#typeText func.etype) ^ " " ^ argN ^ "\n");
  4408. | TField (_,FEnum (enum,field)) -> this#write ((this#op IaCreateEnum) ^ (this#enumText enum) ^ " " ^ (this#stringText field.ef_name) ^ argN ^ "\n");
  4409. | _ -> this#write ( (this#op IaCall) ^ argN ^ "\n");
  4410. this#gen_expression func;
  4411. );
  4412. let matched_args = match func.etype with
  4413. | TFun (args,_) ->
  4414. ( try (
  4415. List.iter2 (fun (_,_,protoT) arg -> this#checkCast protoT arg false false) args arg_list;
  4416. true; )
  4417. with Invalid_argument _ -> (*print_endline "Bad count?";*) false )
  4418. | _ -> false
  4419. in
  4420. if not matched_args then
  4421. List.iter this#gen_expression arg_list;
  4422. in
  4423. (match (remove_parens func).eexpr with
  4424. | TField(obj,field) when is_array_or_dyn_array obj.etype && (field_name field)="map" ->
  4425. (match this#get_array_type expression.etype with
  4426. | ArrayData t ->
  4427. this#write ( (this#op IaToDataArray) ^ (this#typeTextString ("Array." ^ t)) ^ "\n");
  4428. this#begin_expr;
  4429. this#writePos func;
  4430. gen_call();
  4431. this#end_expr;
  4432. | ArrayInterface t ->
  4433. this#write ( (this#op IaToInterfaceArray) ^ (string_of_int t) ^ "\n");
  4434. this#begin_expr;
  4435. this#writePos func;
  4436. gen_call();
  4437. this#end_expr;
  4438. | _ -> gen_call();
  4439. )
  4440. | _ -> gen_call();
  4441. );
  4442. | TField (obj, acc) ->
  4443. let typeText = this#typeText obj.etype in
  4444. (match acc with
  4445. | FDynamic name -> this#write ( (this#op IaFName) ^ typeText ^ " " ^ (this#stringText name) ^ "\n");
  4446. this#gen_expression obj;
  4447. | FStatic (class_def,field) -> this#write ( (this#op IaFStatic) ^ (this#instText class_def) ^ " " ^ (this#stringText field.cf_name) );
  4448. | FInstance (_,_,field) when is_this obj -> this#write ( (this#op IaFThisInst) ^ typeText ^ " " ^ (this#stringText field.cf_name) );
  4449. | FInstance (_,_,field) -> this#write ( (this#op IaFLink) ^ typeText ^ " " ^ (this#stringText field.cf_name) ^ "\n");
  4450. this#gen_expression obj;
  4451. | FClosure (_,field) when is_this obj -> this#write ( (this#op IaFThisName) ^typeText ^ " " ^ (this#stringText field.cf_name) ^ "\n")
  4452. | FAnon (field) when is_this obj -> this#write ( (this#op IaFThisName) ^typeText ^ " " ^ (this#stringText field.cf_name) ^ "\n")
  4453. | FClosure (_,field)
  4454. | FAnon (field) -> this#write ( (this#op IaFName) ^typeText ^ " " ^ (this#stringText field.cf_name) ^ "\n");
  4455. this#gen_expression obj;
  4456. | FEnum (enum,field) -> this#write ( (this#op IaFEnum) ^ (this#enumText enum) ^ " " ^ (this#stringText field.ef_name) );
  4457. )
  4458. | TArray (e1, e2) -> this#write ((this#op IaArrayI) ^ (this#typeText e1.etype) ^ "\n");
  4459. this#gen_expression e1;
  4460. this#gen_expression e2;
  4461. | TUnop (op, flag, e) ->
  4462. this#writeOpLine (match op,flag with
  4463. | Increment, Prefix -> IaPlusPlus
  4464. | Increment, _ -> IaPlusPlusPost
  4465. | Decrement, Prefix -> IaMinusMinus
  4466. | Decrement, _ -> IaMinusMinusPost
  4467. | Not, _ -> IaLogicNot
  4468. | Neg, _ -> IaNeg
  4469. | NegBits, _ -> IaBitNot );
  4470. this#gen_expression e;
  4471. (* TODO - lval op-assign local/member/array *)
  4472. | TLocal var -> this#write ((this#op IaVar) ^ (string_of_int var.v_id) );
  4473. | TVar (tvar,optional_init) ->
  4474. this#write ( (this#op IaTVars) ^ (string_of_int (1)) ^ "\n");
  4475. this#write ("\t\t" ^ indent);
  4476. (match optional_init with
  4477. | None -> this#writeOp IaVarDecl;
  4478. this#writeVar tvar;
  4479. | Some init ->this#writeOp IaVarDeclI;
  4480. let init = remove_parens init in
  4481. this#writeVar tvar;
  4482. this#write (" " ^ (this#typeText init.etype));
  4483. this#write "\n";
  4484. this#checkCast tvar.v_type init false false);
  4485. | TNew (clazz,params,arg_list) ->
  4486. this#write ((this#op IaNew) ^ (this#typeText (TInst(clazz,params))) ^ (string_of_int (List.length arg_list)) ^ "\n");
  4487. let rec matched_args clazz = match clazz.cl_constructor, clazz.cl_super with
  4488. | None, Some super -> matched_args (fst super)
  4489. | None, _ -> false
  4490. | Some ctr, _ ->
  4491. (match ctr.cf_type with
  4492. | TFun(args,_) ->
  4493. ( try (
  4494. List.iter2 (fun (_,_,protoT) arg -> this#checkCast protoT arg false false) args arg_list;
  4495. true; )
  4496. with Invalid_argument _ -> (*print_endline "Bad count?";*) false )
  4497. | _ -> false
  4498. )
  4499. in
  4500. if not (matched_args clazz) then
  4501. List.iter this#gen_expression arg_list;
  4502. | TReturn optval -> (match optval with
  4503. | None -> this#writeOpLine IaReturn;
  4504. | Some value -> this#write ( (this#op IaRetVal) ^ (this#typeText value.etype) ^ "\n");
  4505. this#checkCast return_type value false false;
  4506. )
  4507. | TObjectDecl (
  4508. ("fileName" , { eexpr = (TConst (TString file)) }) ::
  4509. ("lineNumber" , { eexpr = (TConst (TInt line)) }) ::
  4510. ("className" , { eexpr = (TConst (TString class_name)) }) ::
  4511. ("methodName", { eexpr = (TConst (TString meth)) }) :: [] ) ->
  4512. this#write ( (this#op IaPosInfo) ^ (this#stringText file) ^ (Printf.sprintf "%ld" line) ^ " " ^
  4513. (this#stringText class_name) ^ " " ^ (this#stringText meth))
  4514. | TObjectDecl values ->this#write ( (this#op IaObjDef) ^ (string_of_int (List.length values)));
  4515. this#write " ";
  4516. List.iter (fun (name,_) -> this#write (this#stringText name) ) values;
  4517. this#write "\n";
  4518. List.iter (fun (_,e) -> this#gen_expression e ) values;
  4519. | TTypeExpr type_expr ->
  4520. let klass = "::" ^ (join_class_path_remap (t_path type_expr) "::" ) in
  4521. this#write ((this#op IaClassOf) ^ (string_of_int (this#typeId klass)))
  4522. | TWhile (e1,e2,flag) -> this#write ( (this#op IaWhile) ^ (if flag=NormalWhile then "1" else "0" ) ^ "\n");
  4523. this#gen_expression e1;
  4524. this#gen_expression e2;
  4525. | TFor (tvar,init,loop) -> this#writeOp IaFor;
  4526. this#writeVar tvar;
  4527. this#write "\n";
  4528. this#gen_expression init;
  4529. this#gen_expression loop;
  4530. | TEnumParameter (expr,ef,i) ->
  4531. let enum = match follow ef.ef_type with
  4532. | TEnum(en,_) | TFun(_,TEnum(en,_)) -> en
  4533. | _ -> assert false
  4534. in
  4535. this#write ( (this#op IaEnumI) ^ (this#typeText (TEnum(enum,[])) ) ^ (string_of_int i) ^ "\n");
  4536. this#gen_expression expr;
  4537. | TSwitch (condition,cases,optional_default) ->
  4538. this#write ( (this#op IaSwitch) ^ (string_of_int (List.length cases)) ^ " " ^
  4539. (match optional_default with None -> "0" | Some _ -> "1") ^ "\n");
  4540. this#gen_expression condition;
  4541. List.iter (fun (cases_list,expression) ->
  4542. this#writeList ("\t\t\t"^indent) (List.length cases_list);
  4543. List.iter (fun value -> this#gen_expression value ) cases_list;
  4544. this#gen_expression expression;
  4545. ) cases;
  4546. (match optional_default with None -> () | Some expr -> this#gen_expression expr);
  4547. | TTry (e,catches) ->
  4548. this#writeList (this#op IaTry) (List.length catches);
  4549. this#gen_expression e;
  4550. List.iter ( fun (tvar,catch_expr) ->
  4551. this#write ("\t\t\t"^indent);
  4552. this#writeVar tvar;
  4553. this#write "\n";
  4554. this#gen_expression catch_expr;
  4555. ) catches;
  4556. | TCast (cast,None) -> this#checkCast expression.etype cast true true;
  4557. | TCast (cast,Some _) -> this#checkCast expression.etype cast true true;
  4558. | TParenthesis _ -> error "Unexpected parens" expression.epos
  4559. | TMeta(_,_) -> error "Unexpected meta" expression.epos
  4560. );
  4561. this#end_expr;
  4562. end;;
  4563. let generate_script_class common_ctx script class_def =
  4564. script#incClasses;
  4565. script#writeOp (if class_def.cl_interface then IaInterface else IaClass );
  4566. script#instName class_def;
  4567. (match class_def.cl_super with
  4568. | None -> script#ident ""
  4569. | Some (c,_) -> script#instName c);
  4570. script#wint (List.length class_def.cl_implements);
  4571. List.iter (fun(c,_) -> script#instName c) class_def.cl_implements;
  4572. script#write "\n";
  4573. (* Looks like some map impl classes have their bodies discarded - not sure best way to filter *)
  4574. let non_dodgy_function field =
  4575. class_def.cl_interface ||
  4576. match field.cf_kind, field.cf_expr with
  4577. | Var _, _ -> true
  4578. | Method MethDynamic, _ -> true
  4579. | Method _, Some _ -> true
  4580. | _ -> false
  4581. in
  4582. let ordered_statics = List.filter non_dodgy_function class_def.cl_ordered_statics in
  4583. let ordered_fields = List.filter non_dodgy_function class_def.cl_ordered_fields in
  4584. script#write ((string_of_int ( (List.length ordered_fields) +
  4585. (List.length ordered_statics) +
  4586. (match class_def.cl_constructor with Some _ -> 1 | _ -> 0 ) +
  4587. (if (implement_dynamic_here class_def) then 1 else 0) +
  4588. (match class_def.cl_init with Some _ -> 1 | _ -> 0 ) ) )
  4589. ^ "\n");
  4590. let generate_field isStatic field =
  4591. match field.cf_kind, follow field.cf_type with
  4592. | Var { v_read = AccInline; v_write = AccNever },_ ->
  4593. script#writeOpLine IaInline;
  4594. | Var v,_ ->
  4595. let mode_code mode = match mode with
  4596. | AccNormal -> IaAccessNormal
  4597. | AccNo -> IaAccessNot
  4598. | AccNever -> IaAccessNot
  4599. | AccResolve -> IaAccessResolve
  4600. | AccCall -> IaAccessCall
  4601. | AccInline -> IaAccessNormal
  4602. | AccRequire (_,_) -> IaAccessNormal
  4603. in
  4604. let isExtern = is_extern_field field in
  4605. script#var (mode_code v.v_read) (mode_code v.v_write) isExtern isStatic field.cf_name field.cf_type field.cf_expr
  4606. | Method MethDynamic, TFun(args,ret) ->
  4607. script#func isStatic true field.cf_name ret args class_def.cl_interface field.cf_expr
  4608. | Method _, TFun(args,ret) when field.cf_name="new" ->
  4609. script#func true false "new" (TInst(class_def,[])) args false field.cf_expr
  4610. | Method _, TFun (args,ret) ->
  4611. script#func isStatic false field.cf_name ret args class_def.cl_interface field.cf_expr
  4612. | Method _, _ -> print_endline ("Unknown method type " ^ (join_class_path class_def.cl_path "." )
  4613. ^ "." ^field.cf_name )
  4614. in
  4615. (match class_def.cl_constructor with
  4616. | Some field -> generate_field true field
  4617. | _ -> () );
  4618. (match class_def.cl_init with
  4619. | Some expression -> script#voidFunc true false "__init__" expression
  4620. | _ -> () );
  4621. List.iter (generate_field false) ordered_fields;
  4622. List.iter (generate_field true) ordered_statics;
  4623. if (implement_dynamic_here class_def) then
  4624. script#implDynamic;
  4625. script#write "\n";
  4626. ;;
  4627. let generate_script_enum common_ctx script enum_def meta =
  4628. script#incClasses;
  4629. let sorted_items = List.sort (fun f1 f2 -> (f1.ef_index - f2.ef_index ) ) (pmap_values enum_def.e_constrs) in
  4630. script#writeList ((script#op IaEnum) ^ (script#enumText enum_def)) (List.length sorted_items);
  4631. List.iter (fun constructor ->
  4632. let name = script#stringText constructor.ef_name in
  4633. match constructor.ef_type with
  4634. | TFun (args,_) ->
  4635. script#write ( name ^ " " ^ (string_of_int (List.length args)) );
  4636. List.iter (fun (arg,_,t) -> script#write ( " " ^ (script#stringText arg) ^ " " ^ (script#typeText t) ) ) args;
  4637. script#write "\n";
  4638. | _ -> script#write ( name ^ " 0\n" )
  4639. ) sorted_items;
  4640. match meta with
  4641. | Some expr -> script#write "1\n";
  4642. script#gen_expression expr
  4643. | _ -> script#write "0\n";
  4644. script#write "\n"
  4645. ;;
  4646. let generate_cppia common_ctx =
  4647. let debug = 1 in
  4648. let null_file = new source_writer common_ctx ignore (fun () -> () ) in
  4649. let ctx = new_context common_ctx null_file debug (ref PMap.empty) in
  4650. ctx.ctx_class_member_types <- create_member_types common_ctx;
  4651. let script = new script_writer common_ctx ctx common_ctx.file common_ctx.debug in
  4652. ignore (script#stringId "");
  4653. ignore (script#typeId "");
  4654. List.iter (fun object_def ->
  4655. (match object_def with
  4656. | TClassDecl class_def when class_def.cl_extern ->
  4657. () (*if (gen_externs) then gen_extern_class common_ctx class_def;*)
  4658. | TClassDecl class_def ->
  4659. let is_internal = is_internal_class class_def.cl_path in
  4660. if (is_internal || (is_macro class_def.cl_meta)) then
  4661. ( if (debug>1) then print_endline (" internal class " ^ (join_class_path class_def.cl_path ".") ))
  4662. else begin
  4663. ctx.ctx_class_name <- "::" ^ (join_class_path class_def.cl_path "::");
  4664. generate_script_class common_ctx script class_def
  4665. end
  4666. | TEnumDecl enum_def when enum_def.e_extern -> ()
  4667. | TEnumDecl enum_def ->
  4668. let is_internal = is_internal_class enum_def.e_path in
  4669. if (is_internal) then
  4670. (if (debug>1) then print_endline (" internal enum " ^ (join_class_path enum_def.e_path ".") ))
  4671. else begin
  4672. let meta = Codegen.build_metadata common_ctx object_def in
  4673. if (enum_def.e_extern) then
  4674. (if (debug>1) then print_endline ("external enum " ^ (join_class_path enum_def.e_path ".") ));
  4675. ctx.ctx_class_name <- "*";
  4676. generate_script_enum common_ctx script enum_def meta
  4677. end
  4678. | TTypeDecl _ | TAbstractDecl _ -> (* already done *) ()
  4679. );
  4680. ) common_ctx.types;
  4681. (match common_ctx.main with
  4682. | None -> script#writeOpLine IaNoMain;
  4683. | Some e -> script#writeOpLine IaMain;
  4684. script#gen_expression e
  4685. );
  4686. script#write ( (script#op IaResources) ^ (string_of_int (Hashtbl.length common_ctx.resources)) ^ "\n");
  4687. Hashtbl.iter (fun name data ->
  4688. script#write ((script#op IaReso) ^ (script#stringText name) ^ (string_of_int (String.length data)) ^ "\n");
  4689. ) common_ctx.resources;
  4690. Hashtbl.iter (fun _ data -> script#writeData data) common_ctx.resources;
  4691. script#close
  4692. ;;
  4693. (*
  4694. The common_ctx contains the haxe AST in the "types" field and the resources
  4695. *)
  4696. let generate_source common_ctx =
  4697. make_base_directory common_ctx.file;
  4698. let debug = 1 in
  4699. let exe_classes = ref [] in
  4700. let boot_classes = ref [] in
  4701. let boot_enums = ref [] in
  4702. let nonboot_classes = ref [] in
  4703. let init_classes = ref [] in
  4704. let file_info = ref PMap.empty in
  4705. let class_text path = join_class_path path "::" in
  4706. let member_types = create_member_types common_ctx in
  4707. let super_deps = create_super_dependencies common_ctx in
  4708. let constructor_deps = create_constructor_dependencies common_ctx in
  4709. let main_deps = ref [] in
  4710. let build_xml = ref "" in
  4711. let scriptable = (Common.defined common_ctx Define.Scriptable) in
  4712. List.iter (fun object_def ->
  4713. (match object_def with
  4714. | TClassDecl class_def when is_extern_class class_def -> ()
  4715. | TClassDecl class_def ->
  4716. let name = class_text class_def.cl_path in
  4717. let is_internal = is_internal_class class_def.cl_path in
  4718. if (is_internal || (is_macro class_def.cl_meta)) then
  4719. ( if (debug>1) then print_endline (" internal class " ^ name ))
  4720. else begin
  4721. build_xml := !build_xml ^ (get_code class_def.cl_meta Meta.BuildXml);
  4722. if (has_init_field class_def) then
  4723. init_classes := class_def.cl_path :: !init_classes;
  4724. if (has_boot_field class_def) then
  4725. boot_classes := class_def.cl_path :: !boot_classes
  4726. else
  4727. nonboot_classes := class_def.cl_path :: !nonboot_classes;
  4728. let deps = generate_class_files common_ctx
  4729. member_types super_deps constructor_deps class_def file_info scriptable in
  4730. exe_classes := (class_def.cl_path, deps) :: !exe_classes;
  4731. end
  4732. | TEnumDecl enum_def when enum_def.e_extern -> ()
  4733. | TEnumDecl enum_def ->
  4734. let name = class_text enum_def.e_path in
  4735. let is_internal = is_internal_class enum_def.e_path in
  4736. if (is_internal) then
  4737. (if (debug>1) then print_endline (" internal enum " ^ name ))
  4738. else begin
  4739. let meta = Codegen.build_metadata common_ctx object_def in
  4740. if (enum_def.e_extern) then
  4741. (if (debug>1) then print_endline ("external enum " ^ name ));
  4742. boot_enums := enum_def.e_path :: !boot_enums;
  4743. let deps = generate_enum_files common_ctx enum_def super_deps meta file_info in
  4744. exe_classes := (enum_def.e_path, deps) :: !exe_classes;
  4745. end
  4746. | TTypeDecl _ | TAbstractDecl _ -> (* already done *) ()
  4747. );
  4748. ) common_ctx.types;
  4749. (match common_ctx.main with
  4750. | None -> generate_dummy_main common_ctx
  4751. | Some e ->
  4752. let main_field = { cf_name = "__main__"; cf_type = t_dynamic; cf_expr = Some e; cf_pos = e.epos; cf_public = true; cf_meta = []; cf_overloads = []; cf_doc = None; cf_kind = Var { v_read = AccNormal; v_write = AccNormal; }; cf_params = [] } in
  4753. let class_def = { null_class with cl_path = ([],"@Main"); cl_ordered_statics = [main_field] } in
  4754. main_deps := find_referenced_types common_ctx (TClassDecl class_def) super_deps constructor_deps false true false;
  4755. generate_main common_ctx member_types super_deps class_def file_info
  4756. );
  4757. generate_boot common_ctx !boot_enums !boot_classes !nonboot_classes !init_classes;
  4758. generate_files common_ctx file_info;
  4759. write_resources common_ctx;
  4760. (* Output class list if requested *)
  4761. if (scriptable || (Common.defined common_ctx Define.DllExport) ) then begin
  4762. let filename = match Common.defined_value_safe common_ctx Define.DllExport with
  4763. | "" -> "exe.classes"
  4764. | x -> x
  4765. in
  4766. let exeClasses = open_out filename in
  4767. List.iter (fun x -> output_string exeClasses ((join_class_path (fst x) ".") ^ "\n") ) !exe_classes;
  4768. close_out exeClasses;
  4769. end;
  4770. let output_name = match common_ctx.main_class with
  4771. | Some path -> (snd path)
  4772. | _ -> "output" in
  4773. write_build_data common_ctx (common_ctx.file ^ "/Build.xml") !exe_classes !main_deps !build_xml output_name;
  4774. let cmd_defines = ref "" in
  4775. PMap.iter ( fun name value -> match name with
  4776. | "true" | "sys" | "dce" | "cpp" | "debug" -> ()
  4777. | _ -> cmd_defines := !cmd_defines ^ " -D" ^ name ^ "=\"" ^ (escape_command value) ^ "\"" ) common_ctx.defines;
  4778. write_build_options common_ctx (common_ctx.file ^ "/Options.txt") !cmd_defines;
  4779. if ( not (Common.defined common_ctx Define.NoCompilation) ) then begin
  4780. let old_dir = Sys.getcwd() in
  4781. Sys.chdir common_ctx.file;
  4782. let cmd = ref "haxelib run hxcpp Build.xml haxe" in
  4783. if (common_ctx.debug) then cmd := !cmd ^ " -Ddebug";
  4784. cmd := !cmd ^ !cmd_defines;
  4785. cmd := List.fold_left (fun cmd path -> cmd ^ " -I\"" ^ (escape_command path) ^ "\"" ) !cmd common_ctx.class_path;
  4786. print_endline !cmd;
  4787. if common_ctx.run_command !cmd <> 0 then failwith "Build failed";
  4788. Sys.chdir old_dir;
  4789. end
  4790. ;;
  4791. let generate common_ctx =
  4792. if (Common.defined common_ctx Define.Cppia) then
  4793. generate_cppia common_ctx
  4794. else
  4795. generate_source common_ctx
  4796. ;;