gencommon.ml 421 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676
  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. (*
  23. Gen Common API
  24. This module intends to be a common set of utilities common to all targets.
  25. It's intended to provide a set of tools to be able to make targets in Haxe more easily, and to
  26. allow the programmer to have more control of how the target language will handle the program.
  27. For example, as of now, the hxcpp target, while greatly done, relies heavily on cpp's own operator
  28. overloading, and implicit conversions, which make it very hard to deliver a similar solution for languages
  29. that lack these features.
  30. So this little framework is here so you can manipulate the Haxe AST and start bringing the AST closer
  31. to how it's intenteded to be in your host language.
  32. Rules
  33. Design goals
  34. Naming convention
  35. Weaknesses and TODO's
  36. *)
  37. open Ast
  38. open Type
  39. open Common
  40. open Option
  41. open Printf
  42. let debug_type_ctor = function
  43. | TMono _ -> "TMono"
  44. | TEnum _ -> "TEnum"
  45. | TInst _ -> "TInst"
  46. | TType _ -> "TType"
  47. | TFun _ -> "TFun"
  48. | TAnon _ -> "TAnon"
  49. | TDynamic _ -> "TDynamic"
  50. | TLazy _ -> "TLazy"
  51. | TAbstract _ -> "TAbstract"
  52. let debug_type = (s_type (print_context()))
  53. let debug_expr = s_expr debug_type
  54. let rec like_float t =
  55. match follow t with
  56. | TAbstract({ a_path = ([], "Float") },[])
  57. | TAbstract({ a_path = ([], "Int") },[]) -> true
  58. | TAbstract(a, _) -> List.exists (fun (t,_) -> like_float t) a.a_from || List.exists (fun (t,_) -> like_float t) a.a_to
  59. | _ -> false
  60. let rec like_int t =
  61. match follow t with
  62. | TAbstract({ a_path = ([], "Int") },[]) -> true
  63. | TAbstract(a, _) -> List.exists (fun (t,_) -> like_int t) a.a_from || List.exists (fun (t,_) -> like_int t) a.a_to
  64. | _ -> false
  65. let follow_once t =
  66. match t with
  67. | TMono r ->
  68. (match !r with
  69. | Some t -> t
  70. | _ -> t_dynamic (* avoid infinite loop / should be the same in this context *))
  71. | TLazy f ->
  72. !f()
  73. | TType (t,tl) ->
  74. apply_params t.t_types tl t.t_type
  75. | _ -> t
  76. let t_empty = TAnon({ a_fields = PMap.empty; a_status = ref (Closed) })
  77. (* the undefined is a special var that works like null, but can have special meaning *)
  78. let v_undefined = alloc_var "__undefined__" t_dynamic
  79. let undefined pos = { eexpr = TLocal(v_undefined); etype = t_dynamic; epos = pos }
  80. module ExprHashtblHelper =
  81. struct
  82. type hash_texpr_t =
  83. {
  84. hepos : pos;
  85. heexpr : int;
  86. hetype : int;
  87. }
  88. let mk_heexpr = function
  89. | TConst _ -> 0 | TLocal _ -> 1 | TArray _ -> 3 | TBinop _ -> 4 | TField _ -> 5 | TTypeExpr _ -> 7 | TParenthesis _ -> 8 | TObjectDecl _ -> 9
  90. | TArrayDecl _ -> 10 | TCall _ -> 11 | TNew _ -> 12 | TUnop _ -> 13 | TFunction _ -> 14 | TVar _ -> 15 | TBlock _ -> 16 | TFor _ -> 17 | TIf _ -> 18 | TWhile _ -> 19
  91. | TSwitch _ -> 20 | TPatMatch _ -> 21 | TTry _ -> 22 | TReturn _ -> 23 | TBreak -> 24 | TContinue -> 25 | TThrow _ -> 26 | TCast _ -> 27 | TMeta _ -> 28 | TEnumParameter _ -> 29
  92. let mk_heetype = function
  93. | TMono _ -> 0 | TEnum _ -> 1 | TInst _ -> 2 | TType _ -> 3 | TFun _ -> 4
  94. | TAnon _ -> 5 | TDynamic _ -> 6 | TLazy _ -> 7 | TAbstract _ -> 8
  95. let mk_type e =
  96. {
  97. hepos = e.epos;
  98. heexpr = mk_heexpr e.eexpr;
  99. hetype = mk_heetype e.etype;
  100. }
  101. end;;
  102. open ExprHashtblHelper;;
  103. (* Expression Hashtbl. This shouldn't be kept indefinately as it's not a weak Hashtbl. *)
  104. module ExprHashtbl = Hashtbl.Make(
  105. struct
  106. type t = Type.texpr
  107. let equal = (==)
  108. let hash t = Hashtbl.hash (mk_type t)
  109. end
  110. );;
  111. (* ******************************************* *)
  112. (* Gen Common
  113. This is the key module for generation of Java and C# sources
  114. In order for both modules to share as much code as possible, some
  115. rules were devised:
  116. - every feature has its own submodule, and may contain the following methods:
  117. - configure
  118. sets all the configuration variables for the module to run. If a module has this method,
  119. it *should* be called once before running any filter
  120. - run_filter ->
  121. runs the filter immediately on the context
  122. - add_filter ->
  123. adds the filter to an expr->expr list. Most filter modules will provide this option so the filter
  124. function can only run once.
  125. - most submodules will have side-effects so the order of operations will matter.
  126. When running configure / add_filter this might be taken care of with the rule-based dispatch system working
  127. underneath, but still there might be some incompatibilities. There will be an effort to document it.
  128. The modules can hint on the order by suffixing their functions with _first or _last.
  129. - any of those methods might have different parameters, that configure how the filter will run.
  130. For example, a simple filter that maps switch() expressions to if () .. else if... might receive
  131. a function that filters what content should be mapped
  132. - Other targets can use those filters on their own code. In order to do that,
  133. a simple configuration step is needed: you need to initialize a generator_ctx type with
  134. Gencommon.new_gen (context:Common.context)
  135. with a generator_ctx context you will be able to add filters to your code, and execute them with
  136. Gencommon.run_filters (gen_context:Gencommon.generator_ctx)
  137. After running the filters, you can run your own generator normally.
  138. (* , or you can run
  139. Gencommon.generate_modules (gen_context:Gencommon.generator_ctx) (extension:string) (module_gen:module_type list->bool)
  140. where module_gen will take a whole module (can be *)
  141. *)
  142. (* ******************************************* *)
  143. (* common helpers *)
  144. (* ******************************************* *)
  145. let assertions = false (* when assertions == true, many assertions will be made to guarantee the quality of the data input *)
  146. let debug_mode = ref false
  147. let trace s = if !debug_mode then print_endline s else ()
  148. let timer name = if !debug_mode then Common.timer name else fun () -> ()
  149. let is_string t = match follow t with | TInst({ cl_path = ([], "String") }, []) -> true | _ -> false
  150. (* helper function for creating Anon types of class / enum modules *)
  151. let anon_of_classtype cl =
  152. TAnon {
  153. a_fields = cl.cl_statics;
  154. a_status = ref (Statics cl)
  155. }
  156. let anon_of_enum e =
  157. TAnon {
  158. a_fields = PMap.empty;
  159. a_status = ref (EnumStatics e)
  160. }
  161. let anon_of_abstract a =
  162. TAnon {
  163. a_fields = PMap.empty;
  164. a_status = ref (AbstractStatics a)
  165. }
  166. let anon_of_mt mt = match mt with
  167. | TClassDecl cl -> anon_of_classtype cl
  168. | TEnumDecl e -> anon_of_enum e
  169. | TAbstractDecl a -> anon_of_abstract a
  170. | _ -> assert false
  171. let anon_class t =
  172. match follow t with
  173. | TAnon anon ->
  174. (match !(anon.a_status) with
  175. | Statics (cl) -> Some(TClassDecl(cl))
  176. | EnumStatics (e) -> Some(TEnumDecl(e))
  177. | AbstractStatics (a) -> Some(TAbstractDecl(a))
  178. | _ -> None)
  179. | _ -> None
  180. let path_s path =
  181. match path with | ([], s) -> s | (p, s) -> (String.concat "." (fst path)) ^ "." ^ (snd path)
  182. let rec t_to_md t = match t with
  183. | TInst (cl,_) -> TClassDecl cl
  184. | TEnum (e,_) -> TEnumDecl e
  185. | TType (t,_) -> TTypeDecl t
  186. | TAbstract (a,_) -> TAbstractDecl a
  187. | TAnon anon ->
  188. (match !(anon.a_status) with
  189. | EnumStatics e -> TEnumDecl e
  190. | Statics cl -> TClassDecl cl
  191. | AbstractStatics a -> TAbstractDecl a
  192. | _ -> assert false)
  193. | TLazy f -> t_to_md (!f())
  194. | TMono r -> (match !r with | Some t -> t_to_md t | None -> assert false)
  195. | _ -> assert false
  196. let get_cl mt = match mt with | TClassDecl cl -> cl | _ -> failwith ("Unexpected module type of '" ^ path_s (t_path mt) ^ "'")
  197. let get_tdef mt = match mt with | TTypeDecl t -> t | _ -> assert false
  198. let mk_mt_access mt pos = { eexpr = TTypeExpr(mt); etype = anon_of_mt mt; epos = pos }
  199. let is_void t = match follow t with
  200. | TEnum({ e_path = ([], "Void") }, [])
  201. | TAbstract ({ a_path = ([], "Void") },[]) ->
  202. true
  203. | _ -> false
  204. let mk_local var pos = { eexpr = TLocal(var); etype = var.v_type; epos = pos }
  205. (* this function is used by CastDetection module *)
  206. let get_fun t =
  207. match follow t with | TFun(r1,r2) -> (r1,r2) | _ -> (trace (s_type (print_context()) (follow t) )); assert false
  208. let mk_cast t e =
  209. { eexpr = TCast(e, None); etype = t; epos = e.epos }
  210. let mk_classtype_access cl pos =
  211. { eexpr = TTypeExpr(TClassDecl(cl)); etype = anon_of_classtype cl; epos = pos }
  212. let mk_static_field_access_infer cl field pos params =
  213. try
  214. let cf = (PMap.find field cl.cl_statics) in
  215. { eexpr = TField(mk_classtype_access cl pos, FStatic(cl, cf)); etype = (if params = [] then cf.cf_type else apply_params cf.cf_params params cf.cf_type); epos = pos }
  216. with | Not_found -> failwith ("Cannot find field " ^ field ^ " in type " ^ (path_s cl.cl_path))
  217. let mk_static_field_access cl field fieldt pos =
  218. { (mk_static_field_access_infer cl field pos []) with etype = fieldt }
  219. (* stolen from Hugh's sources ;-) *)
  220. (* this used to be a class, but there was something in there that crashed ocaml native compiler in windows *)
  221. module SourceWriter =
  222. struct
  223. type source_writer =
  224. {
  225. sw_buf : Buffer.t;
  226. mutable sw_has_content : bool;
  227. mutable sw_indent : string;
  228. mutable sw_indents : string list;
  229. }
  230. let new_source_writer () =
  231. {
  232. sw_buf = Buffer.create 0;
  233. sw_has_content = false;
  234. sw_indent = "";
  235. sw_indents = [];
  236. }
  237. let add_writer w_write w_read = Buffer.add_buffer w_read.sw_buf w_write.sw_buf
  238. let contents w = Buffer.contents w.sw_buf
  239. let len w = Buffer.length w.sw_buf
  240. let write w x =
  241. (if not w.sw_has_content then begin w.sw_has_content <- true; Buffer.add_string w.sw_buf w.sw_indent; Buffer.add_string w.sw_buf x; end else Buffer.add_string w.sw_buf x);
  242. let len = (String.length x)-1 in
  243. if len >= 0 && String.get x len = '\n' then begin w.sw_has_content <- false end else w.sw_has_content <- true
  244. let push_indent w = w.sw_indents <- "\t"::w.sw_indents; w.sw_indent <- String.concat "" w.sw_indents
  245. let pop_indent w =
  246. match w.sw_indents with
  247. | h::tail -> w.sw_indents <- tail; w.sw_indent <- String.concat "" w.sw_indents
  248. | [] -> w.sw_indent <- "/*?*/"
  249. let newline w = write w "\n"
  250. let begin_block w = (if w.sw_has_content then newline w); write w "{"; push_indent w; newline w
  251. let end_block w = pop_indent w; (if w.sw_has_content then newline w); write w "}"; newline w
  252. let print w =
  253. (if not w.sw_has_content then begin w.sw_has_content <- true; Buffer.add_string w.sw_buf w.sw_indent end);
  254. bprintf w.sw_buf;
  255. end;;
  256. (* rule_dispatcher's priority *)
  257. type priority =
  258. | PFirst
  259. | PLast
  260. | PZero
  261. | PCustom of float
  262. exception DuplicateName of string
  263. exception NoRulesApplied
  264. let indent = ref []
  265. (* the rule dispatcher is the primary way to deal with distributed "plugins" *)
  266. (* we will define rules that will form a distributed / extensible match system *)
  267. class ['tp, 'ret] rule_dispatcher name ignore_not_found =
  268. object(self)
  269. val tbl = Hashtbl.create 16
  270. val mutable keys = []
  271. val names = Hashtbl.create 16
  272. val mutable temp = 0
  273. method add ?(name : string option) (* name helps debugging *) ?(priority : priority = PZero) (rule : 'tp->'ret option) =
  274. let p = match priority with
  275. | PFirst -> infinity
  276. | PLast -> neg_infinity
  277. | PZero -> 0.0
  278. | PCustom i -> i
  279. in
  280. let q = if not( Hashtbl.mem tbl p ) then begin
  281. let q = Stack.create() in
  282. Hashtbl.add tbl p q;
  283. keys <- p :: keys;
  284. keys <- List.sort (fun x y -> - (compare x y)) keys;
  285. q
  286. end else Hashtbl.find tbl p in
  287. let name = match name with
  288. | None -> temp <- temp + 1; "$_" ^ (string_of_int temp)
  289. | Some s -> s
  290. in
  291. (if Hashtbl.mem names name then raise (DuplicateName(name)));
  292. Hashtbl.add names name q;
  293. Stack.push (name, rule) q
  294. method describe =
  295. Hashtbl.iter (fun s _ -> (trace s)) names;
  296. method remove (name : string) =
  297. if Hashtbl.mem names name then begin
  298. let q = Hashtbl.find names name in
  299. let q_temp = Stack.create () in
  300. Stack.iter (function
  301. | (n, _) when n = name -> ()
  302. | _ as r -> Stack.push r q_temp
  303. ) q;
  304. Stack.clear q;
  305. Stack.iter (fun r -> Stack.push r q) q_temp;
  306. Hashtbl.remove names name;
  307. true
  308. end else false
  309. method run_f tp = get (self#run tp)
  310. method did_run tp = is_some (self#run tp)
  311. method get_list =
  312. let ret = ref [] in
  313. List.iter (fun key ->
  314. let q = Hashtbl.find tbl key in
  315. Stack.iter (fun (_, rule) -> ret := rule :: !ret) q
  316. ) keys;
  317. List.rev !ret
  318. method run_from (priority:float) (tp:'tp) : 'ret option =
  319. let ok = ref ignore_not_found in
  320. let ret = ref None in
  321. indent := "\t" :: !indent;
  322. (try begin
  323. List.iter (fun key ->
  324. if key < priority then begin
  325. let q = Hashtbl.find tbl key in
  326. Stack.iter (fun (n, rule) ->
  327. let t = if !debug_mode then Common.timer ("rule dispatcher rule: " ^ n) else fun () -> () in
  328. let r = rule(tp) in
  329. t();
  330. if is_some r then begin ret := r; raise Exit end
  331. ) q
  332. end
  333. ) keys
  334. end with Exit -> ok := true);
  335. (match !indent with
  336. | [] -> ()
  337. | h::t -> indent := t);
  338. (if not (!ok) then raise NoRulesApplied);
  339. !ret
  340. method run (tp:'tp) : 'ret option =
  341. self#run_from infinity tp
  342. end;;
  343. (* this is a special case where tp = tret and you stack their output as the next's input *)
  344. class ['tp] rule_map_dispatcher name =
  345. object(self)
  346. inherit ['tp, 'tp] rule_dispatcher name true as super
  347. method run_f tp = get (self#run tp)
  348. method run_from (priority:float) (tp:'tp) : 'ret option =
  349. let cur = ref tp in
  350. (try begin
  351. List.iter (fun key ->
  352. if key < priority then begin
  353. let q = Hashtbl.find tbl key in
  354. Stack.iter (fun (n, rule) ->
  355. trace ("running rule " ^ n);
  356. let t = if !debug_mode then Common.timer ("rule map dispatcher rule: " ^ n) else fun () -> () in
  357. let r = rule(!cur) in
  358. t();
  359. if is_some r then begin cur := get r end
  360. ) q
  361. end
  362. ) keys
  363. end with Exit -> ());
  364. Some (!cur)
  365. end;;
  366. type generator_ctx =
  367. {
  368. (* these are the basic context fields. If another target is using this context, *)
  369. (* this is all you need to care about *)
  370. mutable gcon : Common.context;
  371. gclasses : gen_classes;
  372. gtools : gen_tools;
  373. (*
  374. configurable function that receives a desired name and makes it "internal", doing the best
  375. to ensure that it will not be called from outside.
  376. To avoid name clashes between internal names, user must specify two strings: a "namespace" and the name itself
  377. *)
  378. mutable gmk_internal_name : string->string->string;
  379. (*
  380. module filters run before module filters and they should generate valid haxe syntax as a result.
  381. Module filters shouldn't go through the expressions as it adds an unnecessary burden to the GC,
  382. and it can all be done in a single step with gexpr_filters and proper priority selection.
  383. As a convention, Module filters should end their name with Modf, so they aren't mistaken with expression filters
  384. *)
  385. gmodule_filters : (module_type) rule_map_dispatcher;
  386. (*
  387. expression filters are the most common filters to be applied.
  388. They should also generate only valid haxe expressions, so e.g. calls to non-existant methods
  389. should be avoided, although there are some ways around them (like gspecial_methods)
  390. *)
  391. gexpr_filters : (texpr) rule_map_dispatcher;
  392. (*
  393. syntax filters are also expression filters but they no longer require
  394. that the resulting expressions be valid haxe expressions.
  395. They then have no guarantee that either the input expressions or the output one follow the same
  396. rules as normal haxe code.
  397. *)
  398. gsyntax_filters : (texpr) rule_map_dispatcher;
  399. (* these are more advanced features, but they would require a rewrite of targets *)
  400. (* they are just helpers to ditribute functions like "follow" or "type to string" *)
  401. (* so adding a module will already take care of correctly following a certain type of *)
  402. (* variable, for example *)
  403. (* follows the type through typedefs, lazy typing, etc. *)
  404. (* it's the place to put specific rules to handle typedefs, like *)
  405. (* other basic types like UInt *)
  406. gfollow : (t, t) rule_dispatcher;
  407. gtypes : (path, module_type) Hashtbl.t;
  408. (* cast detection helpers / settings *)
  409. (* this is a cache for all field access types *)
  410. greal_field_types : (path * string, (tclass_field (* does the cf exist *) * t (*cf's type in relation to current class type params *) * t * tclass (* declared class *) ) option) Hashtbl.t;
  411. (* this function allows any code to handle casts as if it were inside the cast_detect module *)
  412. mutable ghandle_cast : t->t->texpr->texpr;
  413. (* when an unsafe cast is made, we can warn the user *)
  414. mutable gon_unsafe_cast : t->t->pos->unit;
  415. (* does this type needs to be boxed? Normally always false, unless special type handling must be made *)
  416. mutable gneeds_box : t->bool;
  417. (* does this 'special type' needs cast to this other type? *)
  418. (* this is here so we can implement custom behavior for "opaque" typedefs *)
  419. mutable gspecial_needs_cast : t->t->bool;
  420. (* sometimes we may want to support unrelated conversions on cast detection *)
  421. (* for example, haxe.lang.Null<T> -> T on C# *)
  422. (* every time an unrelated conversion is found, each to/from path is searched on this hashtbl *)
  423. (* if found, the function will be executed with from_type, to_type. If returns true, it means that *)
  424. (* it is a supported conversion, and the unsafe cast routine changes to a simple cast *)
  425. gsupported_conversions : (path, t->t->bool) Hashtbl.t;
  426. (* API for filters *)
  427. (* add type can be called at any time, and will add a new module_def that may or may not be filtered *)
  428. (* module_type -> should_filter *)
  429. mutable gadd_type : module_type -> bool -> unit;
  430. (* during expr filters, add_to_module will be available so module_types can be added to current module_def. we must pass the priority argument so the filters can be resumed *)
  431. mutable gadd_to_module : module_type -> float -> unit;
  432. (* during expr filters, shows the current class path *)
  433. mutable gcurrent_path : path;
  434. (* current class *)
  435. mutable gcurrent_class : tclass option;
  436. (* current class field, if any *)
  437. mutable gcurrent_classfield : tclass_field option;
  438. (* events *)
  439. (* is executed once every new classfield *)
  440. mutable gon_classfield_start : (unit -> unit) list;
  441. (* is executed once every new module type *)
  442. mutable gon_new_module_type : (unit -> unit) list;
  443. (* after module filters ended *)
  444. mutable gafter_mod_filters_ended : (unit -> unit) list;
  445. (* after expression filters ended *)
  446. mutable gafter_expr_filters_ended : (unit -> unit) list;
  447. (* after all filters are run *)
  448. mutable gafter_filters_ended : (unit -> unit) list;
  449. mutable gbase_class_fields : (string, tclass_field) PMap.t;
  450. (* real type is the type as it is read by the target. *)
  451. (* This function is here because most targets don't have *)
  452. (* a 1:1 translation between haxe types and its native types *)
  453. (* But types aren't changed to this representation as we might lose *)
  454. (* some valuable type information in the process *)
  455. mutable greal_type : t -> t;
  456. (*
  457. the same as greal_type but for type parameters.
  458. *)
  459. mutable greal_type_param : module_type -> tparams -> tparams;
  460. (*
  461. is the type a value type?
  462. This may be used in some optimizations where reference types and value types
  463. are handled differently. At first the default is very good to use, and if tweaks are needed,
  464. it's best to be done by adding @:struct meta to the value types
  465. *
  466. mutable gis_value_type : t -> bool;*)
  467. (* misc configuration *)
  468. (*
  469. Should the target allow type parameter dynamic conversion,
  470. or should we add a cast to those cases as well?
  471. *)
  472. mutable gallow_tp_dynamic_conversion : bool;
  473. (*
  474. Does the target support type parameter constraints?
  475. If not, they will be ignored when detecting casts
  476. *)
  477. mutable guse_tp_constraints : bool;
  478. (* internal apis *)
  479. (* param_func_call : used by TypeParams and CastDetection *)
  480. mutable gparam_func_call : texpr->texpr->tparams->texpr list->texpr;
  481. (* does it already have a type parameter cast handler? This is used by CastDetect to know if it should handle type parameter casts *)
  482. mutable ghas_tparam_cast_handler : bool;
  483. (* type parameter casts - special cases *)
  484. (* function cast_from, cast_to -> texpr *)
  485. gtparam_cast : (path, (texpr->t->texpr)) Hashtbl.t;
  486. (*
  487. special vars are used for adding special behavior to
  488. *)
  489. gspecial_vars : (string, bool) Hashtbl.t;
  490. }
  491. and gen_classes =
  492. {
  493. cl_reflect : tclass;
  494. cl_type : tclass;
  495. cl_dyn : tclass;
  496. t_iterator : tdef;
  497. }
  498. (* add here all reflection transformation additions *)
  499. and gen_tools =
  500. {
  501. (* (klass : texpr, t : t) : texpr *)
  502. mutable r_create_empty : texpr->t->texpr;
  503. (* Reflect.fields(). The bool is if we are iterating in a read-only manner. If it is read-only we might not need to allocate a new array *)
  504. mutable r_fields : bool->texpr->texpr;
  505. (* (first argument = return type. should be void in most cases) Reflect.setField(obj, field, val) *)
  506. mutable r_set_field : t->texpr->texpr->texpr->texpr;
  507. (* Reflect.field. bool indicates if is safe (no error throwing) or unsafe; t is the expected return type true = safe *)
  508. mutable r_field : bool->t->texpr->texpr->texpr;
  509. (*
  510. these are now the functions that will later be used when creating the reflection classes
  511. *)
  512. (* on the default implementation (at OverloadingCtors), it will be new SomeClass<params>(EmptyInstance) *)
  513. mutable rf_create_empty : tclass->tparams->pos->texpr;
  514. }
  515. let get_type types path =
  516. List.find (fun md -> match md with
  517. | TClassDecl cl when cl.cl_path = path -> true
  518. | TEnumDecl e when e.e_path = path -> true
  519. | TTypeDecl t when t.t_path = path -> true
  520. | TAbstractDecl a when a.a_path = path -> true
  521. | _ -> false
  522. ) types
  523. let new_ctx con =
  524. let types = Hashtbl.create (List.length con.types) in
  525. List.iter (fun mt ->
  526. match mt with
  527. | TClassDecl cl -> Hashtbl.add types cl.cl_path mt
  528. | TEnumDecl e -> Hashtbl.add types e.e_path mt
  529. | TTypeDecl t -> Hashtbl.add types t.t_path mt
  530. | TAbstractDecl a -> Hashtbl.add types a.a_path mt
  531. ) con.types;
  532. let cl_dyn = match get_type con.types ([], "Dynamic") with
  533. | TClassDecl c -> c
  534. | TAbstractDecl a ->
  535. mk_class a.a_module ([], "Dynamic") a.a_pos
  536. | _ -> assert false
  537. in
  538. let rec gen = {
  539. gcon = con;
  540. gclasses = {
  541. cl_reflect = get_cl (get_type con.types ([], "Reflect"));
  542. cl_type = get_cl (get_type con.types ([], "Type"));
  543. cl_dyn = cl_dyn;
  544. t_iterator = get_tdef (get_type con.types ([], "Iterator"));
  545. };
  546. gtools = {
  547. r_create_empty = (fun eclass t ->
  548. let fieldcall = mk_static_field_access_infer gen.gclasses.cl_type "createEmptyInstance" eclass.epos [t] in
  549. { eexpr = TCall(fieldcall, [eclass]); etype = t; epos = eclass.epos }
  550. );
  551. r_fields = (fun is_used_only_by_iteration expr ->
  552. let fieldcall = mk_static_field_access_infer gen.gclasses.cl_reflect "fields" expr.epos [] in
  553. { eexpr = TCall(fieldcall, [expr]); etype = gen.gcon.basic.tarray gen.gcon.basic.tstring; epos = expr.epos }
  554. );
  555. (* Reflect.setField(obj, field, val). t by now is ignored. FIXME : fix this implementation *)
  556. r_set_field = (fun t obj field v ->
  557. let fieldcall = mk_static_field_access_infer gen.gclasses.cl_reflect "setField" v.epos [] in
  558. { eexpr = TCall(fieldcall, [obj; field; v]); etype = t_dynamic; epos = v.epos }
  559. );
  560. (* Reflect.field. bool indicates if is safe (no error throwing) or unsafe. true = safe *)
  561. r_field = (fun is_safe t obj field ->
  562. let fieldcall = mk_static_field_access_infer gen.gclasses.cl_reflect "field" obj.epos [] in
  563. (* FIXME: should we see if needs to cast? *)
  564. mk_cast t { eexpr = TCall(fieldcall, [obj; field]); etype = t_dynamic; epos = obj.epos }
  565. );
  566. rf_create_empty = (fun cl p pos ->
  567. gen.gtools.r_create_empty { eexpr = TTypeExpr(TClassDecl cl); epos = pos; etype = t_dynamic } (TInst(cl,p))
  568. ); (* TODO: Maybe implement using normal reflection? Type.createEmpty(MyClass) *)
  569. };
  570. gmk_internal_name = (fun ns s -> sprintf "__%s_%s" ns s);
  571. gexpr_filters = new rule_map_dispatcher "gexpr_filters";
  572. gmodule_filters = new rule_map_dispatcher "gmodule_filters";
  573. gsyntax_filters = new rule_map_dispatcher "gsyntax_filters";
  574. gfollow = new rule_dispatcher "gfollow" false;
  575. gtypes = types;
  576. greal_field_types = Hashtbl.create 0;
  577. ghandle_cast = (fun to_t from_t e -> mk_cast to_t e);
  578. gon_unsafe_cast = (fun t t2 pos -> (gen.gcon.warning ("Type " ^ (debug_type t2) ^ " is being cast to the unrelated type " ^ (s_type (print_context()) t)) pos));
  579. gneeds_box = (fun t -> false);
  580. gspecial_needs_cast = (fun to_t from_t -> true);
  581. gsupported_conversions = Hashtbl.create 0;
  582. gadd_type = (fun md should_filter ->
  583. if should_filter then begin
  584. con.types <- md :: con.types;
  585. con.modules <- { m_id = alloc_mid(); m_path = (t_path md); m_types = [md]; m_extra = module_extra "" "" 0. MFake } :: con.modules
  586. end else gen.gafter_filters_ended <- (fun () ->
  587. con.types <- md :: con.types;
  588. con.modules <- { m_id = alloc_mid(); m_path = (t_path md); m_types = [md]; m_extra = module_extra "" "" 0. MFake } :: con.modules
  589. ) :: gen.gafter_filters_ended;
  590. );
  591. gadd_to_module = (fun md pr -> failwith "module added outside expr filters");
  592. gcurrent_path = ([],"");
  593. gcurrent_class = None;
  594. gcurrent_classfield = None;
  595. gon_classfield_start = [];
  596. gon_new_module_type = [];
  597. gafter_mod_filters_ended = [];
  598. gafter_expr_filters_ended = [];
  599. gafter_filters_ended = [];
  600. gbase_class_fields = PMap.empty;
  601. greal_type = (fun t -> t);
  602. greal_type_param = (fun _ t -> t);
  603. gallow_tp_dynamic_conversion = false;
  604. guse_tp_constraints = false;
  605. (* as a default, ignore the params *)
  606. gparam_func_call = (fun ecall efield params elist -> { ecall with eexpr = TCall(efield, elist) });
  607. ghas_tparam_cast_handler = false;
  608. gtparam_cast = Hashtbl.create 0;
  609. gspecial_vars = Hashtbl.create 0;
  610. } in
  611. (*gen.gtools.r_create_empty <-
  612. gen.gtools.r_get_class <-
  613. gen.gtools.r_fields <- *)
  614. gen
  615. let init_ctx gen =
  616. (* ultimately add a follow once handler as the last follow handler *)
  617. let follow_f = gen.gfollow#run in
  618. let follow t =
  619. match t with
  620. | TMono r ->
  621. (match !r with
  622. | Some t -> follow_f t
  623. | _ -> Some t)
  624. | TLazy f ->
  625. follow_f (!f())
  626. | TType (t,tl) ->
  627. follow_f (apply_params t.t_types tl t.t_type)
  628. | _ -> Some t
  629. in
  630. gen.gfollow#add ~name:"final" ~priority:PLast follow
  631. (* run_follow (gen:generator_ctx) (t:t) *)
  632. let run_follow gen = gen.gfollow#run_f
  633. let reorder_modules gen =
  634. let modules = Hashtbl.create 20 in
  635. List.iter (fun md ->
  636. Hashtbl.add modules ( (t_infos md).mt_module ).m_path md
  637. ) gen.gcon.types;
  638. let con = gen.gcon in
  639. con.modules <- [];
  640. let processed = Hashtbl.create 20 in
  641. Hashtbl.iter (fun md_path _ ->
  642. if not (Hashtbl.mem processed md_path) then begin
  643. Hashtbl.add processed md_path true;
  644. con.modules <- { m_id = alloc_mid(); m_path = md_path; m_types = List.rev ( Hashtbl.find_all modules md_path ); m_extra = module_extra "" "" 0. MFake } :: con.modules
  645. end
  646. ) modules
  647. let run_filters_from gen t filters =
  648. match t with
  649. | TClassDecl c ->
  650. trace (snd c.cl_path);
  651. gen.gcurrent_path <- c.cl_path;
  652. gen.gcurrent_class <- Some(c);
  653. List.iter (fun fn -> fn()) gen.gon_new_module_type;
  654. gen.gcurrent_classfield <- None;
  655. let rec process_field f =
  656. gen.gcurrent_classfield <- Some(f);
  657. List.iter (fun fn -> fn()) gen.gon_classfield_start;
  658. trace f.cf_name;
  659. (match f.cf_expr with
  660. | None -> ()
  661. | Some e ->
  662. f.cf_expr <- Some (List.fold_left (fun e f -> f e) e filters));
  663. List.iter process_field f.cf_overloads;
  664. in
  665. List.iter process_field c.cl_ordered_fields;
  666. List.iter process_field c.cl_ordered_statics;
  667. gen.gcurrent_classfield <- None;
  668. (match c.cl_constructor with
  669. | None -> ()
  670. | Some f -> process_field f);
  671. (match c.cl_init with
  672. | None -> ()
  673. | Some e ->
  674. c.cl_init <- Some (List.fold_left (fun e f -> f e) e filters));
  675. | TEnumDecl _ -> ()
  676. | TTypeDecl _ -> ()
  677. | TAbstractDecl _ -> ()
  678. let run_filters gen =
  679. (* first of all, we have to make sure that the filters won't trigger a major Gc collection *)
  680. let t = Common.timer "gencommon_filters" in
  681. (if Common.defined gen.gcon Define.GencommonDebug then debug_mode := true);
  682. let run_filters filter =
  683. let rec loop acc mds =
  684. match mds with
  685. | [] -> acc
  686. | md :: tl ->
  687. let filters = [ filter#run_f ] in
  688. let added_types = ref [] in
  689. gen.gadd_to_module <- (fun md_type priority ->
  690. gen.gcon.types <- md_type :: gen.gcon.types;
  691. added_types := (md_type, priority) :: !added_types
  692. );
  693. run_filters_from gen md filters;
  694. let added_types = List.map (fun (t,p) ->
  695. run_filters_from gen t [ fun e -> get (filter#run_from p e) ];
  696. if Hashtbl.mem gen.gtypes (t_path t) then begin
  697. let rec loop i =
  698. let p = t_path t in
  699. let new_p = (fst p, snd p ^ "_" ^ (string_of_int i)) in
  700. if Hashtbl.mem gen.gtypes new_p then
  701. loop (i+1)
  702. else
  703. match t with
  704. | TClassDecl cl -> cl.cl_path <- new_p
  705. | TEnumDecl e -> e.e_path <- new_p
  706. | TTypeDecl _ | TAbstractDecl _ -> ()
  707. in
  708. loop 0
  709. end;
  710. Hashtbl.add gen.gtypes (t_path t) t;
  711. t
  712. ) !added_types in
  713. loop (added_types @ (md :: acc)) tl
  714. in
  715. List.rev (loop [] gen.gcon.types)
  716. in
  717. let run_mod_filter filter =
  718. let last_add_to_module = gen.gadd_to_module in
  719. let added_types = ref [] in
  720. gen.gadd_to_module <- (fun md_type priority ->
  721. Hashtbl.add gen.gtypes (t_path md_type) md_type;
  722. added_types := (md_type, priority) :: !added_types
  723. );
  724. let rec loop processed not_processed =
  725. match not_processed with
  726. | hd :: tl ->
  727. let new_hd = filter#run_f hd in
  728. let added_types_new = !added_types in
  729. added_types := [];
  730. let added_types = List.map (fun (t,p) ->
  731. get (filter#run_from p t)
  732. ) added_types_new in
  733. loop ( added_types @ (new_hd :: processed) ) tl
  734. | [] ->
  735. processed
  736. in
  737. let filtered = loop [] gen.gcon.types in
  738. gen.gadd_to_module <- last_add_to_module;
  739. gen.gcon.types <- List.rev (filtered)
  740. in
  741. run_mod_filter gen.gmodule_filters;
  742. List.iter (fun fn -> fn()) gen.gafter_mod_filters_ended;
  743. let last_add_to_module = gen.gadd_to_module in
  744. gen.gcon.types <- run_filters gen.gexpr_filters;
  745. gen.gadd_to_module <- last_add_to_module;
  746. List.iter (fun fn -> fn()) gen.gafter_expr_filters_ended;
  747. (* Codegen.post_process gen.gcon.types [gen.gexpr_filters#run_f]; *)
  748. gen.gcon.types <- run_filters gen.gsyntax_filters;
  749. List.iter (fun fn -> fn()) gen.gafter_filters_ended;
  750. reorder_modules gen;
  751. t()
  752. (* ******************************************* *)
  753. (* basic generation module that source code compilation implementations can use *)
  754. (* ******************************************* *)
  755. let write_file gen w source_dir path extension =
  756. let t = timer "write file" in
  757. let s_path = gen.gcon.file ^ "/" ^ source_dir ^ "/" ^ (String.concat "/" (fst path)) ^ "/" ^ (snd path) ^ "." ^ (extension) in
  758. (* create the folders if they don't exist *)
  759. let rec create acc = function
  760. | [] -> ()
  761. | d :: l ->
  762. let dir = String.concat "/" (List.rev (d :: acc)) in
  763. if not (Sys.file_exists dir) then Unix.mkdir dir 0o755;
  764. create (d :: acc) l
  765. in
  766. let p = gen.gcon.file :: source_dir :: fst path in
  767. create [] p;
  768. let contents = SourceWriter.contents w in
  769. let should_write = if not (Common.defined gen.gcon Define.ReplaceFiles) && Sys.file_exists s_path then begin
  770. let in_file = open_in s_path in
  771. let old_contents = Std.input_all in_file in
  772. close_in in_file;
  773. contents <> old_contents
  774. end else true in
  775. if should_write then begin
  776. let f = open_out s_path in
  777. output_string f contents;
  778. close_out f
  779. end;
  780. t()
  781. let dump_descriptor gen name path_s module_s =
  782. let w = SourceWriter.new_source_writer () in
  783. (* dump called path *)
  784. SourceWriter.write w (Sys.getcwd());
  785. SourceWriter.newline w;
  786. (* dump all defines. deprecated *)
  787. SourceWriter.write w "begin defines";
  788. SourceWriter.newline w;
  789. PMap.iter (fun name _ ->
  790. SourceWriter.write w name;
  791. SourceWriter.newline w
  792. ) gen.gcon.defines;
  793. SourceWriter.write w "end defines";
  794. SourceWriter.newline w;
  795. (* dump all defines with their values; keeping the old defines for compatibility *)
  796. SourceWriter.write w "begin defines_data";
  797. SourceWriter.newline w;
  798. PMap.iter (fun name v ->
  799. SourceWriter.write w name;
  800. SourceWriter.write w "=";
  801. SourceWriter.write w v;
  802. SourceWriter.newline w
  803. ) gen.gcon.defines;
  804. SourceWriter.write w "end defines_data";
  805. SourceWriter.newline w;
  806. (* dump all generated types *)
  807. SourceWriter.write w "begin modules";
  808. SourceWriter.newline w;
  809. let main_paths = Hashtbl.create 0 in
  810. List.iter (fun md_def ->
  811. SourceWriter.write w "M ";
  812. SourceWriter.write w (path_s md_def.m_path);
  813. SourceWriter.newline w;
  814. List.iter (fun m ->
  815. match m with
  816. | TClassDecl cl when not cl.cl_extern ->
  817. SourceWriter.write w "C ";
  818. let s = module_s m in
  819. Hashtbl.add main_paths cl.cl_path s;
  820. SourceWriter.write w (s);
  821. SourceWriter.newline w
  822. | TEnumDecl e when not e.e_extern ->
  823. SourceWriter.write w "E ";
  824. SourceWriter.write w (module_s m);
  825. SourceWriter.newline w
  826. | _ -> () (* still no typedef or abstract is generated *)
  827. ) md_def.m_types
  828. ) gen.gcon.modules;
  829. SourceWriter.write w "end modules";
  830. SourceWriter.newline w;
  831. (* dump all resources *)
  832. (match gen.gcon.main_class with
  833. | Some path ->
  834. SourceWriter.write w "begin main";
  835. SourceWriter.newline w;
  836. (try
  837. SourceWriter.write w (Hashtbl.find main_paths path)
  838. with
  839. | Not_found -> SourceWriter.write w (path_s path));
  840. SourceWriter.newline w;
  841. SourceWriter.write w "end main";
  842. SourceWriter.newline w
  843. | _ -> ()
  844. );
  845. SourceWriter.write w "begin resources";
  846. SourceWriter.newline w;
  847. Hashtbl.iter (fun name _ ->
  848. SourceWriter.write w name;
  849. SourceWriter.newline w
  850. ) gen.gcon.resources;
  851. SourceWriter.write w "end resources";
  852. SourceWriter.newline w;
  853. SourceWriter.write w "begin libs";
  854. SourceWriter.newline w;
  855. if Common.platform gen.gcon Java then
  856. List.iter (fun (s,std,_,_,_) ->
  857. if not std then begin
  858. SourceWriter.write w s;
  859. SourceWriter.newline w;
  860. end
  861. ) gen.gcon.java_libs
  862. else if Common.platform gen.gcon Cs then
  863. List.iter (fun (s,std,_,_) ->
  864. if not std then begin
  865. SourceWriter.write w s;
  866. SourceWriter.newline w;
  867. end
  868. ) gen.gcon.net_libs;
  869. SourceWriter.write w "end libs";
  870. let contents = SourceWriter.contents w in
  871. let f = open_out (gen.gcon.file ^ "/" ^ name) in
  872. output_string f contents;
  873. close_out f
  874. (*
  875. helper function to create the source structure. Will send each module_def to the function passed.
  876. If received true, it means that module_gen has generated this content, so the file must be saved.
  877. See that it will write a whole module
  878. *)
  879. let generate_modules gen extension source_dir (module_gen : SourceWriter.source_writer->module_def->bool) =
  880. List.iter (fun md_def ->
  881. let w = SourceWriter.new_source_writer () in
  882. (*let should_write = List.fold_left (fun should md -> module_gen w md or should) false md_def.m_types in*)
  883. let should_write = module_gen w md_def in
  884. if should_write then begin
  885. let path = md_def.m_path in
  886. write_file gen w source_dir path extension;
  887. end
  888. ) gen.gcon.modules
  889. let generate_modules_t gen extension source_dir change_path (module_gen : SourceWriter.source_writer->module_type->bool) =
  890. List.iter (fun md ->
  891. let w = SourceWriter.new_source_writer () in
  892. (*let should_write = List.fold_left (fun should md -> module_gen w md or should) false md_def.m_types in*)
  893. let should_write = module_gen w md in
  894. if should_write then begin
  895. let path = change_path (t_path md) in
  896. write_file gen w source_dir path extension;
  897. end
  898. ) gen.gcon.types
  899. (*
  900. various helper functions
  901. *)
  902. let mk_paren e =
  903. match e.eexpr with | TParenthesis _ -> e | _ -> { e with eexpr=TParenthesis(e) }
  904. (* private *)
  905. let tmp_count = ref 0
  906. let get_real_fun gen t =
  907. match follow t with
  908. | TFun(args,t) -> TFun(List.map (fun (n,o,t) -> n,o,gen.greal_type t) args, gen.greal_type t)
  909. | _ -> t
  910. let mk_int gen i pos = { eexpr = TConst(TInt ( Int32.of_int i)); etype = gen.gcon.basic.tint; epos = pos }
  911. let mk_return e = { eexpr = TReturn (Some e); etype = e.etype; epos = e.epos }
  912. let mk_temp gen name t =
  913. incr tmp_count;
  914. let name = gen.gmk_internal_name "temp" (name ^ (string_of_int !tmp_count)) in
  915. alloc_var name t
  916. let ensure_local gen block name e =
  917. match e.eexpr with
  918. | TLocal _ -> e
  919. | _ ->
  920. let var = mk_temp gen name e.etype in
  921. block := { e with eexpr = TVar(var, Some e); etype = gen.gcon.basic.tvoid; } :: !block;
  922. { e with eexpr = TLocal var }
  923. let reset_temps () = tmp_count := 0
  924. let follow_module follow_func md = match md with
  925. | TClassDecl _
  926. | TEnumDecl _
  927. | TAbstractDecl _ -> md
  928. | TTypeDecl tdecl -> match (follow_func (TType(tdecl, List.map snd tdecl.t_types))) with
  929. | TInst(cl,_) -> TClassDecl cl
  930. | TEnum(e,_) -> TEnumDecl e
  931. | TType(t,_) -> TTypeDecl t
  932. | TAbstract(a,_) -> TAbstractDecl a
  933. | _ -> assert false
  934. (*
  935. hxgen means if the type was generated by haxe. If a type was generated by haxe, it means
  936. it will contain special constructs for speedy reflection, for example
  937. @see SetHXGen module
  938. *)
  939. let rec is_hxgen md =
  940. match md with
  941. | TClassDecl cl -> Meta.has Meta.HxGen cl.cl_meta
  942. | TEnumDecl e -> Meta.has Meta.HxGen e.e_meta
  943. | TTypeDecl t -> Meta.has Meta.HxGen t.t_meta || ( match follow t.t_type with | TInst(cl,_) -> is_hxgen (TClassDecl cl) | TEnum(e,_) -> is_hxgen (TEnumDecl e) | _ -> false )
  944. | TAbstractDecl a -> Meta.has Meta.HxGen a.a_meta
  945. let is_hxgen_t t =
  946. match t with
  947. | TInst (cl, _) -> Meta.has Meta.HxGen cl.cl_meta
  948. | TEnum (e, _) -> Meta.has Meta.HxGen e.e_meta
  949. | TAbstract (a, _) -> Meta.has Meta.HxGen a.a_meta
  950. | TType (t, _) -> Meta.has Meta.HxGen t.t_meta
  951. | _ -> false
  952. let mt_to_t_dyn md =
  953. match md with
  954. | TClassDecl cl -> TInst(cl, List.map (fun _ -> t_dynamic) cl.cl_types)
  955. | TEnumDecl e -> TEnum(e, List.map (fun _ -> t_dynamic) e.e_types)
  956. | TAbstractDecl a -> TAbstract(a, List.map (fun _ -> t_dynamic) a.a_types)
  957. | TTypeDecl t -> TType(t, List.map (fun _ -> t_dynamic) t.t_types)
  958. let mt_to_t mt params =
  959. match mt with
  960. | TClassDecl (cl) -> TInst(cl, params)
  961. | TEnumDecl (e) -> TEnum(e, params)
  962. | TAbstractDecl a -> TAbstract(a, params)
  963. | _ -> assert false
  964. let t_to_mt t =
  965. match follow t with
  966. | TInst(cl, _) -> TClassDecl(cl)
  967. | TEnum(e, _) -> TEnumDecl(e)
  968. | TAbstract(a, _) -> TAbstractDecl a
  969. | _ -> assert false
  970. let mk_paren e =
  971. match e.eexpr with
  972. | TParenthesis _ -> e
  973. | _ -> { e with eexpr = TParenthesis(e) }
  974. let rec get_last_ctor cl =
  975. Option.map_default (fun (super,_) -> if is_some super.cl_constructor then Some(get super.cl_constructor) else get_last_ctor super) None cl.cl_super
  976. let add_constructor cl cf =
  977. match cl.cl_constructor with
  978. | None -> cl.cl_constructor <- Some cf
  979. | Some ctor ->
  980. if ctor != cf && not (List.memq cf ctor.cf_overloads) then
  981. ctor.cf_overloads <- cf :: ctor.cf_overloads
  982. (* replace open TMonos with TDynamic *)
  983. let rec replace_mono t =
  984. match follow t with
  985. | TMono t -> t := Some t_dynamic
  986. | TEnum (_,p) | TInst (_,p) | TType (_,p) | TAbstract (_,p) ->
  987. List.iter replace_mono p
  988. | TFun (args,ret) ->
  989. List.iter (fun (_,_,t) -> replace_mono t) args;
  990. replace_mono ret
  991. | TAnon _
  992. | TDynamic _ -> ()
  993. | _ -> assert false
  994. (* helper *)
  995. let mk_class_field name t public pos kind params =
  996. {
  997. cf_name = name;
  998. cf_type = t;
  999. cf_public = public;
  1000. cf_pos = pos;
  1001. cf_doc = None;
  1002. cf_meta = [ Meta.CompilerGenerated, [], Ast.null_pos ]; (* annotate that this class field was generated by the compiler *)
  1003. cf_kind = kind;
  1004. cf_params = params;
  1005. cf_expr = None;
  1006. cf_overloads = [];
  1007. }
  1008. (* this helper just duplicates the type parameter class, which is assumed that cl is. *)
  1009. (* This is so we can use class parameters on function parameters, without running the risk of name clash *)
  1010. (* between both *)
  1011. let map_param cl =
  1012. let ret = mk_class cl.cl_module (fst cl.cl_path, snd cl.cl_path ^ "_c") cl.cl_pos in
  1013. ret.cl_implements <- cl.cl_implements;
  1014. ret.cl_kind <- cl.cl_kind;
  1015. ret
  1016. let get_cl_t t =
  1017. match follow t with | TInst (cl,_) -> cl | _ -> assert false
  1018. let mk_class m path pos =
  1019. let cl = Type.mk_class m path pos in
  1020. cl.cl_meta <- [ Meta.CompilerGenerated, [], Ast.null_pos ];
  1021. cl
  1022. type tfield_access =
  1023. | FClassField of tclass * tparams * tclass (* declared class *) * tclass_field * bool (* is static? *) * t (* the actual cf type, in relation to the class type params *) * t (* declared type *)
  1024. | FEnumField of tenum * tenum_field * bool (* is parameterized enum ? *)
  1025. | FAnonField of tclass_field
  1026. | FDynamicField of t
  1027. | FNotFound
  1028. let find_first_declared_field gen orig_cl ?exact_field field =
  1029. let chosen = ref None in
  1030. let is_overload = ref false in
  1031. let rec loop_cl depth c tl tlch =
  1032. (try
  1033. let ret = PMap.find field c.cl_fields in
  1034. if Meta.has Meta.Overload ret.cf_meta then is_overload := true;
  1035. match !chosen, exact_field with
  1036. | Some(d,_,_,_,_), _ when depth <= d -> ()
  1037. | _, None ->
  1038. chosen := Some(depth,ret,c,tl,tlch)
  1039. | _, Some f2 ->
  1040. List.iter (fun f ->
  1041. let declared_t = apply_params c.cl_types tl f.cf_type in
  1042. if Typeload.same_overload_args declared_t f2.cf_type f f2 then
  1043. chosen := Some(depth,f,c,tl,tlch)
  1044. ) (ret :: ret.cf_overloads)
  1045. with | Not_found -> ());
  1046. (match c.cl_super with
  1047. | Some (sup,stl) ->
  1048. let tl = List.map (apply_params c.cl_types tl) stl in
  1049. let stl = gen.greal_type_param (TClassDecl sup) stl in
  1050. let tlch = List.map (apply_params c.cl_types tlch) stl in
  1051. loop_cl (depth+1) sup tl tlch
  1052. | None -> ());
  1053. if c.cl_interface then
  1054. List.iter (fun (sup,stl) ->
  1055. let tl = List.map (apply_params c.cl_types tl) stl in
  1056. let stl = gen.greal_type_param (TClassDecl sup) stl in
  1057. let tlch = List.map (apply_params c.cl_types tlch) stl in
  1058. loop_cl (depth+1) sup tl tlch
  1059. ) c.cl_implements
  1060. in
  1061. loop_cl 0 orig_cl (List.map snd orig_cl.cl_types) (List.map snd orig_cl.cl_types);
  1062. match !chosen with
  1063. | None -> None
  1064. | Some(_,f,c,tl,tlch) ->
  1065. if !is_overload && not (Meta.has Meta.Overload f.cf_meta) then
  1066. f.cf_meta <- (Meta.Overload,[],f.cf_pos) :: f.cf_meta;
  1067. let declared_t = apply_params c.cl_types tl f.cf_type in
  1068. let params_t = apply_params c.cl_types tlch f.cf_type in
  1069. let actual_t = match follow params_t with
  1070. | TFun(args,ret) -> TFun(List.map (fun (n,o,t) -> (n,o,gen.greal_type t)) args, gen.greal_type ret)
  1071. | _ -> gen.greal_type params_t in
  1072. Some(f,actual_t,declared_t,params_t,c,tl,tlch)
  1073. let field_access gen (t:t) (field:string) : (tfield_access) =
  1074. (*
  1075. t can be either an haxe-type as a real-type;
  1076. 'follow' should be applied here since we can generalize that a TType will be accessible as its
  1077. underlying type.
  1078. *)
  1079. match follow t with
  1080. | TInst(cl, params) ->
  1081. let orig_cl = cl in
  1082. let orig_params = params in
  1083. let rec not_found cl params =
  1084. match cl.cl_dynamic with
  1085. | Some t ->
  1086. let t = apply_params cl.cl_types params t in
  1087. FDynamicField t
  1088. | None ->
  1089. match cl.cl_super with
  1090. | None -> FNotFound
  1091. | Some (super,p) -> not_found super p
  1092. in
  1093. let not_found () =
  1094. try
  1095. let cf = PMap.find field gen.gbase_class_fields in
  1096. FClassField (orig_cl, orig_params, gen.gclasses.cl_dyn, cf, false, cf.cf_type, cf.cf_type)
  1097. with
  1098. | Not_found -> not_found cl params
  1099. in
  1100. (* this is a hack for C#'s different generic types with same path *)
  1101. let hashtbl_field = (String.concat "" (List.map (fun _ -> "]") cl.cl_types)) ^ field in
  1102. let types = try
  1103. Hashtbl.find gen.greal_field_types (orig_cl.cl_path, hashtbl_field)
  1104. with | Not_found ->
  1105. let ret = find_first_declared_field gen cl field in
  1106. let ret = match ret with
  1107. | None -> None
  1108. | Some(cf,t,dt,_,cl,_,_) -> Some(cf,t,dt,cl)
  1109. in
  1110. Hashtbl.add gen.greal_field_types (orig_cl.cl_path, hashtbl_field) ret;
  1111. ret
  1112. in
  1113. (match types with
  1114. | None -> not_found()
  1115. | Some (cf, actual_t, declared_t, declared_cl) ->
  1116. FClassField(orig_cl, orig_params, declared_cl, cf, false, actual_t, declared_t))
  1117. | TEnum _ | TAbstract _ ->
  1118. (* enums have no field *) FNotFound
  1119. | TAnon anon ->
  1120. (try match !(anon.a_status) with
  1121. | Statics cl ->
  1122. let cf = PMap.find field cl.cl_statics in
  1123. FClassField(cl, List.map (fun _ -> t_dynamic) cl.cl_types, cl, cf, true, cf.cf_type, cf.cf_type)
  1124. | EnumStatics e ->
  1125. let f = PMap.find field e.e_constrs in
  1126. let is_param = match follow f.ef_type with | TFun _ -> true | _ -> false in
  1127. FEnumField(e, f, is_param)
  1128. | _ when PMap.mem field gen.gbase_class_fields ->
  1129. let cf = PMap.find field gen.gbase_class_fields in
  1130. FClassField(gen.gclasses.cl_dyn, [t_dynamic], gen.gclasses.cl_dyn, cf, false, cf.cf_type, cf.cf_type)
  1131. | _ ->
  1132. FAnonField(PMap.find field anon.a_fields)
  1133. with | Not_found -> FNotFound)
  1134. | _ when PMap.mem field gen.gbase_class_fields ->
  1135. let cf = PMap.find field gen.gbase_class_fields in
  1136. FClassField(gen.gclasses.cl_dyn, [t_dynamic], gen.gclasses.cl_dyn, cf, false, cf.cf_type, cf.cf_type)
  1137. | TDynamic t -> FDynamicField t
  1138. | TMono _ -> FDynamicField t_dynamic
  1139. | _ -> FNotFound
  1140. let field_access_esp gen t field = match field with
  1141. | FStatic(cl,cf) | FInstance(cl,cf) when Meta.has Meta.Extern cf.cf_meta ->
  1142. let static = match field with
  1143. | FStatic _ -> true
  1144. | _ -> false
  1145. in
  1146. let p = match follow (run_follow gen t) with
  1147. | TInst(_,p) -> p
  1148. | _ -> List.map snd cl.cl_types
  1149. in
  1150. FClassField(cl,p,cl,cf,static,cf.cf_type,cf.cf_type)
  1151. | _ -> field_access gen t (field_name field)
  1152. let mk_field_access gen expr field pos =
  1153. match field_access gen expr.etype field with
  1154. | FClassField(c,p,dc,cf,false,at,_) ->
  1155. { eexpr = TField(expr, FInstance(dc,cf)); etype = apply_params c.cl_types p at; epos = pos }
  1156. | FClassField(c,p,dc,cf,true,at,_) ->
  1157. { eexpr = TField(expr, FStatic(dc,cf)); etype = at; epos = pos }
  1158. | FAnonField cf ->
  1159. { eexpr = TField(expr, FAnon cf); etype = cf.cf_type; epos = pos }
  1160. | FDynamicField t ->
  1161. { eexpr = TField(expr, FDynamic field); etype = t; epos = pos }
  1162. | FNotFound ->
  1163. { eexpr = TField(expr, FDynamic field); etype = t_dynamic; epos = pos }
  1164. | FEnumField _ -> assert false
  1165. let mk_iterator_access gen t expr =
  1166. let pos = expr.epos in
  1167. let itf = mk_field_access gen expr "iterator" pos in
  1168. { eexpr = TCall(itf, []); epos = pos; etype = snd (get_fun itf.etype) }
  1169. (* ******************************************* *)
  1170. (* Module dependency resolution *)
  1171. (* ******************************************* *)
  1172. type t_dependency =
  1173. | DAfter of float
  1174. | DBefore of float
  1175. exception ImpossibleDependency of string
  1176. let max_dep = 10000.0
  1177. let min_dep = - (10000.0)
  1178. let solve_deps name (deps:t_dependency list) =
  1179. let vmin = min_dep -. 1.0 in
  1180. let vmax = max_dep +. 1.0 in
  1181. let rec loop dep vmin vmax =
  1182. match dep with
  1183. | [] ->
  1184. (if vmin >= vmax then raise (ImpossibleDependency name));
  1185. (vmin +. vmax) /. 2.0
  1186. | head :: tail ->
  1187. match head with
  1188. | DBefore f ->
  1189. loop tail (max vmin f) vmax
  1190. | DAfter f ->
  1191. loop tail vmin (min vmax f)
  1192. in
  1193. loop deps vmin vmax
  1194. (* type resolution *)
  1195. exception TypeNotFound of path
  1196. let get_type gen path =
  1197. try Hashtbl.find gen.gtypes path with | Not_found -> raise (TypeNotFound path)
  1198. (* ******************************************* *)
  1199. (* follow all module *)
  1200. (* ******************************************* *)
  1201. (*
  1202. this module will follow each and every type using the rules defined in
  1203. gen.gfollow. This is a minor helper module, so we don't end up
  1204. having to follow the same time multiple times in the many filter iterations
  1205. because of this, it will be one of the first modules to run.
  1206. *)
  1207. module FollowAll =
  1208. struct
  1209. let follow gen e =
  1210. let follow_func = gen.gfollow#run_f in
  1211. Some (Type.map_expr_type (fun e->e) (follow_func) (fun tvar-> tvar.v_type <- (follow_func tvar.v_type); tvar) e)
  1212. let priority = max_dep
  1213. (* will add an expression filter as the first filter *)
  1214. let configure gen =
  1215. gen.gexpr_filters#add ~name:"follow_all" ~priority:(PCustom(priority)) (follow gen)
  1216. end;;
  1217. (* ******************************************* *)
  1218. (* set hxgen module *)
  1219. (* ******************************************* *)
  1220. (*
  1221. goes through all module types and sets the :hxgen meta on all which
  1222. then is_hxgen_func returns true. There is a default is_hxgen_func implementation also
  1223. *)
  1224. module SetHXGen =
  1225. struct
  1226. (*
  1227. basically, everything that is extern is assumed to not be hxgen, unless meta :hxgen is set, and
  1228. everything that is not extern is assumed to be hxgen, unless meta :nativegen is set
  1229. *)
  1230. let default_hxgen_func md =
  1231. match md with
  1232. | TClassDecl cl ->
  1233. let rec is_hxgen_class c =
  1234. if c.cl_extern then begin
  1235. if Meta.has Meta.HxGen c.cl_meta then true else Option.map_default (fun (c,_) -> is_hxgen_class c) false c.cl_super
  1236. end else begin
  1237. if Meta.has Meta.NativeGen c.cl_meta then Option.map_default (fun (c, _) -> is_hxgen_class c) false c.cl_super else true
  1238. end
  1239. in
  1240. is_hxgen_class cl
  1241. | TEnumDecl e -> if e.e_extern then Meta.has Meta.HxGen e.e_meta else not (Meta.has Meta.NativeGen e.e_meta)
  1242. | TAbstractDecl a -> not (Meta.has Meta.NativeGen a.a_meta)
  1243. | TTypeDecl t -> (* TODO see when would we use this *)
  1244. false
  1245. (*
  1246. by now the only option is to run it eagerly, because it must be one of the first filters to run,
  1247. since many others depend of it
  1248. *)
  1249. let run_filter gen is_hxgen_func =
  1250. let filter md =
  1251. if is_hxgen_func md then begin
  1252. match md with
  1253. | TClassDecl cl -> cl.cl_meta <- (Meta.HxGen, [], cl.cl_pos) :: cl.cl_meta
  1254. | TEnumDecl e -> e.e_meta <- (Meta.HxGen, [], e.e_pos) :: e.e_meta
  1255. | TTypeDecl t -> t.t_meta <- (Meta.HxGen, [], t.t_pos) :: t.t_meta
  1256. | TAbstractDecl a -> a.a_meta <- (Meta.HxGen, [], a.a_pos) :: a.a_meta
  1257. end
  1258. in
  1259. List.iter filter gen.gcon.types
  1260. end;;
  1261. (* ******************************************* *)
  1262. (* overloading reflection constructors *)
  1263. (* ******************************************* *)
  1264. (*
  1265. this module works on languages that support function overloading and
  1266. enable function hiding via static functions.
  1267. it takes the constructor body out of the constructor and adds it to a special ctor
  1268. static function. The static function will receive the same parameters as the constructor,
  1269. plus the special "me" var, which will replace "this"
  1270. Then it always adds two constructors to the function: one that receives a special class,
  1271. indicating that it should be constructed without any parameters, and one that receives its normal constructor.
  1272. Both will only include a super() call to the superclasses' emtpy constructor.
  1273. This enables two things:
  1274. empty construction without the need of incompatibility with the platform's native construction method
  1275. the ability to call super() constructor in any place in the constructor
  1276. This will insert itself in the default reflection-related module filter
  1277. *)
  1278. module OverloadingConstructor =
  1279. struct
  1280. let priority = 0.0
  1281. let name = "overloading_constructor"
  1282. let set_new_create_empty gen empty_ctor_expr =
  1283. let old = gen.gtools.rf_create_empty in
  1284. gen.gtools.rf_create_empty <- (fun cl params pos ->
  1285. if is_hxgen (TClassDecl cl) then
  1286. { eexpr = TNew(cl,params,[empty_ctor_expr]); etype = TInst(cl,params); epos = pos }
  1287. else
  1288. old cl params pos
  1289. )
  1290. let rec cur_ctor c tl =
  1291. match c.cl_constructor with
  1292. | Some ctor -> ctor, c, tl
  1293. | None -> match c.cl_super with
  1294. | None -> raise Not_found
  1295. | Some (sup,stl) ->
  1296. cur_ctor sup (List.map (apply_params c.cl_types tl) stl)
  1297. let rec prev_ctor c tl =
  1298. match c.cl_super with
  1299. | None -> raise Not_found
  1300. | Some (sup,stl) -> let stl = List.map (apply_params c.cl_types tl) stl in
  1301. match sup.cl_constructor with
  1302. | None -> prev_ctor sup stl
  1303. | Some ctor -> ctor, sup, stl
  1304. (* replaces super() call with last static constructor call *)
  1305. let replace_super_call gen name c tl with_params me p =
  1306. let rec loop_super c tl = match c.cl_super with
  1307. | None -> raise Not_found
  1308. | Some(sup,stl) ->
  1309. let stl = List.map (apply_params c.cl_types tl) stl in
  1310. try
  1311. let static_ctor_name = name ^ "_" ^ (String.concat "_" (fst sup.cl_path)) ^ "_" ^ (snd sup.cl_path) in
  1312. sup, stl, PMap.find static_ctor_name sup.cl_statics
  1313. with | Not_found ->
  1314. loop_super sup stl
  1315. in
  1316. let sup, stl, cf = loop_super c tl in
  1317. let with_params = { eexpr = TLocal me; etype = me.v_type; epos = p } :: with_params in
  1318. let cf = match cf.cf_overloads with
  1319. (* | [] -> cf *)
  1320. | _ -> try
  1321. (* choose best super function *)
  1322. List.iter (fun e -> replace_mono e.etype) with_params;
  1323. List.find (fun cf ->
  1324. replace_mono cf.cf_type;
  1325. let args, _ = get_fun (apply_params cf.cf_params stl cf.cf_type) in
  1326. try
  1327. List.for_all2 (fun (_,_,t) e -> try
  1328. unify e.etype t; true
  1329. with | Unify_error _ -> false) args with_params
  1330. with | Invalid_argument("List.for_all2") -> false
  1331. ) (cf :: cf.cf_overloads)
  1332. with | Not_found ->
  1333. gen.gcon.error "No suitable overload for the super call arguments was found" p; cf
  1334. in
  1335. {
  1336. eexpr = TCall({
  1337. eexpr = TField(
  1338. mk_classtype_access sup p,
  1339. FStatic(sup,cf));
  1340. etype = apply_params cf.cf_params stl cf.cf_type;
  1341. epos = p},
  1342. with_params);
  1343. etype = gen.gcon.basic.tvoid;
  1344. epos = p;
  1345. }
  1346. (* will create a static counterpart of 'ctor', and replace its contents to a call to the static version*)
  1347. let create_static_ctor gen ~empty_ctor_expr cl name ctor =
  1348. match Meta.has Meta.SkipCtor ctor.cf_meta with
  1349. | true -> ()
  1350. | false when is_none ctor.cf_expr -> ()
  1351. | false ->
  1352. let static_ctor_name = name ^ "_" ^ (String.concat "_" (fst cl.cl_path)) ^ "_" ^ (snd cl.cl_path) in
  1353. (* create the static constructor *)
  1354. let basic = gen.gcon.basic in
  1355. let ctor_types = List.map (fun (s,t) -> (s, TInst(map_param (get_cl_t t), []))) cl.cl_types in
  1356. let me = mk_temp gen "me" (TInst(cl, List.map snd ctor_types)) in
  1357. me.v_capture <- true;
  1358. let fn_args, _ = get_fun ctor.cf_type in
  1359. let ctor_params = List.map snd ctor_types in
  1360. let fn_type = TFun((me.v_name,false, me.v_type) :: List.map (fun (n,o,t) -> (n,o,apply_params cl.cl_types ctor_params t)) fn_args, basic.tvoid) in
  1361. let cur_tf_args = match ctor.cf_expr with
  1362. | Some { eexpr = TFunction(tf) } -> tf.tf_args
  1363. | _ -> assert false
  1364. in
  1365. let changed_tf_args = List.map (fun (v,_) -> (v,None)) cur_tf_args in
  1366. let local_map = Hashtbl.create (List.length cur_tf_args) in
  1367. let static_tf_args = (me, None) :: List.map (fun (v,b) ->
  1368. let new_v = alloc_var v.v_name (apply_params cl.cl_types ctor_params v.v_type) in
  1369. Hashtbl.add local_map v.v_id new_v;
  1370. (new_v, b)
  1371. ) cur_tf_args in
  1372. let static_ctor = mk_class_field static_ctor_name fn_type false ctor.cf_pos (Method MethNormal) ctor_types in
  1373. (* change ctor contents to reference the 'me' var instead of 'this' *)
  1374. let actual_super_call = ref None in
  1375. let rec map_expr ~is_first e = match e.eexpr with
  1376. | TCall (({ eexpr = TConst TSuper } as tsuper), params) -> (try
  1377. let params = List.map (fun e -> map_expr ~is_first:false e) params in
  1378. actual_super_call := Some { e with eexpr = TCall(tsuper, [empty_ctor_expr]) };
  1379. replace_super_call gen name cl ctor_params params me e.epos
  1380. with | Not_found ->
  1381. (* last static function was not found *)
  1382. actual_super_call := Some e;
  1383. if not is_first then
  1384. gen.gcon.error "Super call must be the first call when extending native types" e.epos;
  1385. { e with eexpr = TBlock([]) })
  1386. | TFunction tf when is_first ->
  1387. do_map ~is_first:true e
  1388. | TConst TThis ->
  1389. mk_local me e.epos
  1390. | TBlock (fst :: bl) ->
  1391. let fst = map_expr ~is_first:is_first fst in
  1392. { e with eexpr = TBlock(fst :: List.map (fun e -> map_expr ~is_first:false e) bl); etype = apply_params cl.cl_types ctor_params e.etype }
  1393. | _ ->
  1394. do_map e
  1395. and do_map ?(is_first=false) e =
  1396. let do_t = apply_params cl.cl_types ctor_params in
  1397. let do_v v = try
  1398. Hashtbl.find local_map v.v_id
  1399. with | Not_found ->
  1400. v.v_type <- do_t v.v_type; v
  1401. in
  1402. Type.map_expr_type (map_expr ~is_first:is_first) do_t do_v e
  1403. in
  1404. let expr = do_map ~is_first:true (get ctor.cf_expr) in
  1405. let expr = match expr.eexpr with
  1406. | TFunction(tf) ->
  1407. { expr with etype = fn_type; eexpr = TFunction({ tf with tf_args = static_tf_args }) }
  1408. | _ -> assert false in
  1409. static_ctor.cf_expr <- Some expr;
  1410. (* add to the statics *)
  1411. (try
  1412. let stat = PMap.find static_ctor_name cl.cl_statics in
  1413. stat.cf_overloads <- static_ctor :: stat.cf_overloads
  1414. with | Not_found ->
  1415. cl.cl_ordered_statics <- static_ctor :: cl.cl_ordered_statics;
  1416. cl.cl_statics <- PMap.add static_ctor_name static_ctor cl.cl_statics);
  1417. (* change current super call *)
  1418. match ctor.cf_expr with
  1419. | Some({ eexpr = TFunction(tf) } as e) ->
  1420. let block_contents, p = match !actual_super_call with
  1421. | None -> [], ctor.cf_pos
  1422. | Some super -> [super], super.epos
  1423. in
  1424. let block_contents = block_contents @ [{
  1425. eexpr = TCall(
  1426. {
  1427. eexpr = TField(
  1428. mk_classtype_access cl p,
  1429. FStatic(cl, static_ctor));
  1430. etype = apply_params static_ctor.cf_params (List.map snd cl.cl_types) static_ctor.cf_type;
  1431. epos = p
  1432. },
  1433. [{ eexpr = TConst TThis; etype = TInst(cl, List.map snd cl.cl_types); epos = p }]
  1434. @ List.map (fun (v,_) -> mk_local v p) cur_tf_args
  1435. );
  1436. etype = basic.tvoid;
  1437. epos = p
  1438. }] in
  1439. ctor.cf_expr <- Some { e with eexpr = TFunction({ tf with tf_expr = { tf.tf_expr with eexpr = TBlock block_contents }; tf_args = changed_tf_args }) }
  1440. | _ -> assert false
  1441. (* makes constructors that only call super() for the 'ctor' argument *)
  1442. let clone_ctors gen ctor sup stl cl =
  1443. let basic = gen.gcon.basic in
  1444. let rec clone cf =
  1445. let ncf = mk_class_field "new" (apply_params sup.cl_types stl cf.cf_type) cf.cf_public cf.cf_pos cf.cf_kind cf.cf_params in
  1446. let args, ret = get_fun ncf.cf_type in
  1447. (* single expression: call to super() *)
  1448. let tf_args = List.map (fun (name,_,t) ->
  1449. (* the constructor will have no optional arguments, as presumably this will be handled by the underlying expr *)
  1450. alloc_var name t, None
  1451. ) args in
  1452. let super_call =
  1453. {
  1454. eexpr = TCall(
  1455. { eexpr = TConst TSuper; etype = TInst(cl, List.map snd cl.cl_types); epos = ctor.cf_pos },
  1456. List.map (fun (v,_) -> mk_local v ctor.cf_pos) tf_args);
  1457. etype = basic.tvoid;
  1458. epos = ctor.cf_pos;
  1459. } in
  1460. ncf.cf_expr <- Some
  1461. {
  1462. eexpr = TFunction {
  1463. tf_args = tf_args;
  1464. tf_type = basic.tvoid;
  1465. tf_expr = mk_block super_call;
  1466. };
  1467. etype = ncf.cf_type;
  1468. epos = ctor.cf_pos;
  1469. };
  1470. ncf
  1471. in
  1472. (* take off createEmpty *)
  1473. let all = List.filter (fun cf -> replace_mono cf.cf_type; not (Meta.has Meta.SkipCtor cf.cf_meta)) (ctor :: ctor.cf_overloads) in
  1474. let clones = List.map clone all in
  1475. match clones with
  1476. | [] ->
  1477. (* raise Not_found *)
  1478. assert false (* should never happen *)
  1479. | cf :: [] -> cf
  1480. | cf :: overl ->
  1481. cf.cf_meta <- (Meta.Overload,[],cf.cf_pos) :: cf.cf_meta;
  1482. cf.cf_overloads <- overl; cf
  1483. let rec descends_from_native_or_skipctor cl =
  1484. not (is_hxgen (TClassDecl cl)) || Meta.has Meta.SkipCtor cl.cl_meta || match cl.cl_super with
  1485. | None -> false
  1486. | Some(c,_) -> descends_from_native_or_skipctor c
  1487. let ensure_super_is_first gen cf =
  1488. let rec loop e =
  1489. match e.eexpr with
  1490. | TBlock (b :: block) ->
  1491. loop b
  1492. | TBlock []
  1493. | TCall({ eexpr = TConst TSuper },_) -> ()
  1494. | _ ->
  1495. gen.gcon.error "Types that derive from a native class must have its super() call as the first statement in the constructor" cf.cf_pos
  1496. in
  1497. match cf.cf_expr with
  1498. | None -> ()
  1499. | Some e -> Type.iter loop e
  1500. (* major restructring made at r6493 *)
  1501. let configure ~(empty_ctor_type : t) ~(empty_ctor_expr : texpr) ~supports_ctor_inheritance gen =
  1502. set_new_create_empty gen empty_ctor_expr;
  1503. let basic = gen.gcon.basic in
  1504. let should_change cl = not cl.cl_interface && (not cl.cl_extern || is_hxgen (TClassDecl cl)) && (match cl.cl_kind with KAbstractImpl _ -> false | _ -> true) in
  1505. let static_ctor_name = gen.gmk_internal_name "hx" "ctor" in
  1506. let msize = List.length gen.gcon.types in
  1507. let processed, empty_ctors = Hashtbl.create msize, Hashtbl.create msize in
  1508. let rec get_last_empty cl =
  1509. try
  1510. Hashtbl.find empty_ctors cl.cl_path
  1511. with | Not_found ->
  1512. match cl.cl_super with
  1513. | None -> raise Not_found
  1514. | Some (sup,_) -> get_last_empty sup
  1515. in
  1516. let rec change cl =
  1517. match Hashtbl.mem processed cl.cl_path with
  1518. | true -> ()
  1519. | false ->
  1520. Hashtbl.add processed cl.cl_path true;
  1521. (* make sure we've processed the super types *)
  1522. (match cl.cl_super with
  1523. | Some (super,_) when should_change super && not (Hashtbl.mem processed super.cl_path) ->
  1524. change super
  1525. | _ -> ());
  1526. (* implement static hx_ctor and reimplement constructors *)
  1527. (try
  1528. let ctor = match cl.cl_constructor with
  1529. | Some ctor -> ctor
  1530. | None -> try
  1531. let sctor, sup, stl = prev_ctor cl (List.map snd cl.cl_types) in
  1532. (* we have a previous constructor. if we support inheritance, exit *)
  1533. if supports_ctor_inheritance then raise Exit;
  1534. (* we'll make constructors that will only call super() *)
  1535. let ctor = clone_ctors gen sctor sup stl cl in
  1536. cl.cl_constructor <- Some ctor;
  1537. ctor
  1538. with | Not_found -> (* create default constructor *)
  1539. let ctor = mk_class_field "new" (TFun([], basic.tvoid)) false cl.cl_pos (Method MethNormal) [] in
  1540. ctor.cf_expr <- Some
  1541. {
  1542. eexpr = TFunction {
  1543. tf_args = [];
  1544. tf_type = basic.tvoid;
  1545. tf_expr = { eexpr = TBlock[]; etype = basic.tvoid; epos = cl.cl_pos };
  1546. };
  1547. etype = ctor.cf_type;
  1548. epos = ctor.cf_pos;
  1549. };
  1550. cl.cl_constructor <- Some ctor;
  1551. ctor
  1552. in
  1553. (* now that we made sure we have a constructor, exit if native gen *)
  1554. if not (is_hxgen (TClassDecl cl)) || Meta.has Meta.SkipCtor cl.cl_meta then raise Exit;
  1555. (* if cl descends from a native class, we cannot use the static constructor strategy *)
  1556. if descends_from_native_or_skipctor cl && is_some cl.cl_super then
  1557. List.iter (fun cf -> ensure_super_is_first gen cf) (ctor :: ctor.cf_overloads)
  1558. else
  1559. (* now that we have a current ctor, create the static counterparts *)
  1560. List.iter (fun cf ->
  1561. create_static_ctor gen ~empty_ctor_expr:empty_ctor_expr cl static_ctor_name cf
  1562. ) (ctor :: ctor.cf_overloads)
  1563. with | Exit -> ());
  1564. (* implement empty ctor *)
  1565. (try
  1566. (* now that we made sure we have a constructor, exit if native gen *)
  1567. if not (is_hxgen (TClassDecl cl)) then raise Exit;
  1568. (* get first *)
  1569. let empty_type = TFun(["empty",false,empty_ctor_type],basic.tvoid) in
  1570. let super = match cl.cl_super with
  1571. | None -> (* implement empty *)
  1572. []
  1573. | Some (sup,_) -> try
  1574. ignore (get_last_empty sup);
  1575. if supports_ctor_inheritance && is_none cl.cl_constructor then raise Exit;
  1576. [{
  1577. eexpr = TCall(
  1578. { eexpr = TConst TSuper; etype = TInst(cl, List.map snd cl.cl_types); epos = cl.cl_pos },
  1579. [ empty_ctor_expr ]);
  1580. etype = basic.tvoid;
  1581. epos = cl.cl_pos
  1582. }]
  1583. with | Not_found -> try
  1584. (* super type is native: find super constructor with least arguments *)
  1585. let sctor, sup, stl = prev_ctor cl (List.map snd cl.cl_types) in
  1586. let rec loop remaining (best,n) =
  1587. match remaining with
  1588. | [] -> best
  1589. | cf :: r ->
  1590. let args,_ = get_fun cf.cf_type in
  1591. if (List.length args) < n then
  1592. loop r (cf,List.length args)
  1593. else
  1594. loop r (best,n)
  1595. in
  1596. let args,_ = get_fun sctor.cf_type in
  1597. let best = loop sctor.cf_overloads (sctor, List.length args) in
  1598. let args,_ = get_fun best.cf_type in
  1599. [{
  1600. eexpr = TCall(
  1601. { eexpr = TConst TSuper; etype = TInst(cl, List.map snd cl.cl_types); epos = cl.cl_pos },
  1602. List.map (fun (n,o,t) -> null t cl.cl_pos) args);
  1603. etype = basic.tvoid;
  1604. epos = cl.cl_pos
  1605. }]
  1606. with | Not_found ->
  1607. (* extends native type, but no ctor found *)
  1608. []
  1609. in
  1610. let ctor = mk_class_field "new" empty_type false cl.cl_pos (Method MethNormal) [] in
  1611. ctor.cf_expr <- Some {
  1612. eexpr = TFunction {
  1613. tf_type = basic.tvoid;
  1614. tf_args = [alloc_var "empty" empty_ctor_type, None];
  1615. tf_expr = { eexpr = TBlock super; etype = basic.tvoid; epos = cl.cl_pos }
  1616. };
  1617. etype = empty_type;
  1618. epos = cl.cl_pos;
  1619. };
  1620. ctor.cf_meta <- [Meta.SkipCtor, [], ctor.cf_pos];
  1621. Hashtbl.add empty_ctors cl.cl_path ctor;
  1622. match cl.cl_constructor with
  1623. | None -> cl.cl_constructor <- Some ctor
  1624. | Some c -> c.cf_overloads <- ctor :: c.cf_overloads
  1625. with | Exit -> ());
  1626. in
  1627. let module_filter md = match md with
  1628. | TClassDecl cl when should_change cl && not (Hashtbl.mem processed cl.cl_path) ->
  1629. change cl;
  1630. None
  1631. | _ -> None
  1632. in
  1633. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) module_filter
  1634. end;;
  1635. (* ******************************************* *)
  1636. (* init function module *)
  1637. (* ******************************************* *)
  1638. (*
  1639. This module will take proper care of the init function, by taking off all expressions from static vars and putting them
  1640. in order in the init function.
  1641. It will also initialize dynamic functions, both by putting them in the constructor and in the init function
  1642. depends on:
  1643. (syntax) must run before ExprStatement module
  1644. (ok) must run before OverloadingCtor module so the constructor can be in the correct place
  1645. (syntax) must run before FunctionToClass module
  1646. *)
  1647. module InitFunction =
  1648. struct
  1649. let name = "init_funcs"
  1650. let priority = solve_deps name [DBefore OverloadingConstructor.priority]
  1651. let configure gen should_handle_dynamic_functions =
  1652. let handle_override_dynfun acc e this field =
  1653. let add_expr = ref None in
  1654. let v = mk_temp gen ("super_" ^ field) e.etype in
  1655. v.v_capture <- true;
  1656. let rec loop e =
  1657. match e.eexpr with
  1658. | TField({ eexpr = TConst(TSuper) }, f) ->
  1659. let n = field_name f in
  1660. (if n <> field then assert false);
  1661. let local = mk_local v e.epos in
  1662. (match !add_expr with
  1663. | None ->
  1664. add_expr := Some { e with eexpr = TVar(v, Some this) }
  1665. | Some _ -> ());
  1666. local
  1667. | TConst TSuper -> assert false
  1668. | _ -> Type.map_expr loop e
  1669. in
  1670. let e = loop e in
  1671. match !add_expr with
  1672. | None -> e :: acc
  1673. | Some add_expr -> add_expr :: e :: acc
  1674. in
  1675. let handle_class cl =
  1676. let init = match cl.cl_init with
  1677. | None -> []
  1678. | Some i -> [i]
  1679. in
  1680. let init = List.fold_left (fun acc cf ->
  1681. match cf.cf_kind, should_handle_dynamic_functions with
  1682. | (Var _, _)
  1683. | (Method (MethDynamic), true) when not (Type.is_extern_field cf) ->
  1684. (match cf.cf_expr with
  1685. | Some e ->
  1686. (match cf.cf_params with
  1687. | [] ->
  1688. let var = { eexpr = TField(mk_classtype_access cl cf.cf_pos, FStatic(cl,cf)); etype = cf.cf_type; epos = cf.cf_pos } in
  1689. let ret = ({ eexpr = TBinop(Ast.OpAssign, var, e); etype = cf.cf_type; epos = cf.cf_pos; }) in
  1690. cf.cf_expr <- None;
  1691. ret :: acc
  1692. | _ ->
  1693. let params = List.map (fun _ -> t_dynamic) cf.cf_params in
  1694. let fn = apply_params cf.cf_params params in
  1695. let var = { eexpr = TField(mk_classtype_access cl cf.cf_pos, FStatic(cl,cf)); etype = fn cf.cf_type; epos = cf.cf_pos } in
  1696. let rec change_expr e =
  1697. Type.map_expr_type (change_expr) fn (fun v -> v.v_type <- fn v.v_type; v) e
  1698. in
  1699. let ret = ({ eexpr = TBinop(Ast.OpAssign, var, change_expr e); etype = fn cf.cf_type; epos = cf.cf_pos; }) in
  1700. cf.cf_expr <- None;
  1701. ret :: acc
  1702. )
  1703. | None -> acc)
  1704. | _ -> acc
  1705. ) init cl.cl_ordered_statics
  1706. in
  1707. let init = List.rev init in
  1708. (match init with
  1709. | [] -> cl.cl_init <- None
  1710. | _ -> cl.cl_init <- Some { eexpr = TBlock(init); epos = cl.cl_pos; etype = gen.gcon.basic.tvoid; });
  1711. (* FIXME: find a way to tell OverloadingCtors to execute this code even with empty constructors *)
  1712. if should_handle_dynamic_functions then begin
  1713. let funs = List.fold_left (fun acc cf ->
  1714. match cf.cf_kind with
  1715. | Var _
  1716. | Method(MethDynamic) ->
  1717. (match cf.cf_expr, cf.cf_params with
  1718. | Some e, [] ->
  1719. let var = { eexpr = TField({ eexpr = TConst(TThis); epos = cf.cf_pos; etype = TInst(cl, List.map snd cl.cl_types); }, FInstance(cl, cf)); etype = cf.cf_type; epos = cf.cf_pos } in
  1720. let ret = ({ eexpr = TBinop(Ast.OpAssign, var, e); etype = cf.cf_type; epos = cf.cf_pos; }) in
  1721. cf.cf_expr <- None;
  1722. let is_override = List.memq cf cl.cl_overrides in
  1723. if is_override then begin
  1724. cl.cl_ordered_fields <- List.filter (fun f -> f.cf_name <> cf.cf_name) cl.cl_ordered_fields;
  1725. cl.cl_fields <- PMap.remove cf.cf_name cl.cl_fields;
  1726. handle_override_dynfun acc ret var cf.cf_name
  1727. end else ret :: acc
  1728. | Some e, _ ->
  1729. let params = List.map (fun _ -> t_dynamic) cf.cf_params in
  1730. let fn = apply_params cf.cf_params params in
  1731. let var = { eexpr = TField({ eexpr = TConst(TThis); epos = cf.cf_pos; etype = TInst(cl, List.map snd cl.cl_types); }, FInstance(cl, cf)); etype = cf.cf_type; epos = cf.cf_pos } in
  1732. let rec change_expr e =
  1733. Type.map_expr_type (change_expr) fn (fun v -> v.v_type <- fn v.v_type; v) e
  1734. in
  1735. let ret = ({ eexpr = TBinop(Ast.OpAssign, var, change_expr e); etype = fn cf.cf_type; epos = cf.cf_pos; }) in
  1736. cf.cf_expr <- None;
  1737. let is_override = List.memq cf cl.cl_overrides in
  1738. if is_override then begin
  1739. cl.cl_ordered_fields <- List.filter (fun f -> f.cf_name <> cf.cf_name) cl.cl_ordered_fields;
  1740. cl.cl_fields <- PMap.remove cf.cf_name cl.cl_fields;
  1741. handle_override_dynfun acc ret var cf.cf_name
  1742. end else ret :: acc
  1743. | None, _ -> acc)
  1744. | _ -> acc
  1745. ) [] cl.cl_ordered_fields
  1746. in
  1747. (* see if there is any *)
  1748. (match funs with
  1749. | [] -> ()
  1750. | _ ->
  1751. (* if there is, we need to find the constructor *)
  1752. let ctors = match cl.cl_constructor with
  1753. | Some ctor -> ctor
  1754. | None -> try
  1755. let sctor, sup, stl = OverloadingConstructor.prev_ctor cl (List.map snd cl.cl_types) in
  1756. let ctor = OverloadingConstructor.clone_ctors gen sctor sup stl cl in
  1757. cl.cl_constructor <- Some ctor;
  1758. ctor
  1759. with | Not_found ->
  1760. let basic = gen.gcon.basic in
  1761. let ctor = mk_class_field "new" (TFun([], basic.tvoid)) false cl.cl_pos (Method MethNormal) [] in
  1762. ctor.cf_expr <- Some
  1763. {
  1764. eexpr = TFunction {
  1765. tf_args = [];
  1766. tf_type = basic.tvoid;
  1767. tf_expr = { eexpr = TBlock[]; etype = basic.tvoid; epos = cl.cl_pos };
  1768. };
  1769. etype = ctor.cf_type;
  1770. epos = ctor.cf_pos;
  1771. };
  1772. cl.cl_constructor <- Some ctor;
  1773. ctor
  1774. in
  1775. let process ctor =
  1776. let func = match ctor.cf_expr with
  1777. | Some({eexpr = TFunction(tf)} as e) ->
  1778. let rec add_fn e = match e.eexpr with
  1779. | TBlock(hd :: tl) -> (match hd.eexpr with
  1780. | TCall({ eexpr = TConst TSuper }, _) ->
  1781. { e with eexpr = TBlock(hd :: (funs @ tl)) }
  1782. | TBlock(_) ->
  1783. { e with eexpr = TBlock( (add_fn hd) :: tl ) }
  1784. | _ ->
  1785. { e with eexpr = TBlock( funs @ (hd :: tl) ) })
  1786. | _ -> Type.concat { e with eexpr = TBlock(funs) } e
  1787. in
  1788. let tf_expr = add_fn (mk_block tf.tf_expr) in
  1789. { e with eexpr = TFunction({ tf with tf_expr = tf_expr }) }
  1790. | _ -> assert false
  1791. in
  1792. ctor.cf_expr <- Some(func)
  1793. in
  1794. List.iter process (ctors :: ctors.cf_overloads)
  1795. )
  1796. end
  1797. in
  1798. let mod_filter = function
  1799. | TClassDecl cl -> (if not cl.cl_extern then handle_class cl); None
  1800. | _ -> None in
  1801. gen.gmodule_filters#add ~name:"init_funcs" ~priority:(PCustom priority) mod_filter
  1802. end;;
  1803. (* ******************************************* *)
  1804. (* Dynamic Binop/Unop handler *)
  1805. (* ******************************************* *)
  1806. (*
  1807. On some languages there is limited support for operations on
  1808. dynamic variables, so those operations must be changed.
  1809. There are 5 types of binary operators:
  1810. 1 - can take any variable and returns a bool (== and !=)
  1811. 2 - can take either a string, or a number and returns either a bool or the underlying type ( >, < for bool and + for returning its type)
  1812. 3 - take numbers and return a number ( *, /, ...)
  1813. 4 - take ints and return an int (bit manipulation)
  1814. 5 - take a bool and returns a bool ( &&, || ...)
  1815. On the default implementation, type 1 and the plus function will be handled with a function call;
  1816. Type 2 will be handled with the parameter "compare_handler", which will do something like Reflect.compare(x1, x2);
  1817. Types 3, 4 and 5 will perform a cast to double, int and bool, which will then be handled normally by the platform
  1818. Unary operators are the most difficult to handle correctly.
  1819. With unary operators, there are 2 types:
  1820. 1 - can take a number, changes and returns the result (++, --, ~)
  1821. 2 - can take a number (-) or bool (!), and returns the result
  1822. The first case is much trickier, because it doesn't seem a good idea to change any variable to double just because it is dynamic,
  1823. but this is how we will handle right now.
  1824. something like that:
  1825. var x:Dynamic = 10;
  1826. x++;
  1827. will be:
  1828. object x = 10;
  1829. x = ((IConvertible)x).ToDouble(null) + 1;
  1830. depends on:
  1831. (syntax) must run before expression/statment normalization because it may generate complex expressions
  1832. must run before OverloadingCtor due to later priority conflicts. Since ExpressionUnwrap is only
  1833. defined afterwards, we will set this value with absolute values
  1834. *)
  1835. module DynamicOperators =
  1836. struct
  1837. let name = "dyn_ops"
  1838. let priority = 0.0
  1839. let priority_as_synf = 100.0 (*solve_deps name [DBefore ExpressionUnwrap.priority]*)
  1840. let abstract_implementation gen ?(handle_strings = true) (should_change:texpr->bool) (equals_handler:texpr->texpr->texpr) (dyn_plus_handler:texpr->texpr->texpr->texpr) (compare_handler:texpr->texpr->texpr) =
  1841. let get_etype_one e =
  1842. if like_int e.etype then
  1843. (gen.gcon.basic.tint, { eexpr = TConst(TInt(Int32.one)); etype = gen.gcon.basic.tint; epos = e.epos })
  1844. else
  1845. (gen.gcon.basic.tfloat, { eexpr = TConst(TFloat("1.0")); etype = gen.gcon.basic.tfloat; epos = e.epos })
  1846. in
  1847. let basic = gen.gcon.basic in
  1848. let rec run e =
  1849. match e.eexpr with
  1850. | TBinop (OpAssignOp op, e1, e2) when should_change e -> (* e1 will never contain another TBinop *)
  1851. (match e1.eexpr with
  1852. | TLocal _ ->
  1853. mk_paren { e with eexpr = TBinop(OpAssign, e1, run { e with eexpr = TBinop(op, e1, e2) }) }
  1854. | TField _ | TArray _ ->
  1855. let eleft, rest = match e1.eexpr with
  1856. | TField(ef, f) ->
  1857. let v = mk_temp gen "dynop" ef.etype in
  1858. { e1 with eexpr = TField(mk_local v ef.epos, f) }, [ { eexpr = TVar(v,Some (run ef)); etype = basic.tvoid; epos = ef.epos } ]
  1859. | TArray(e1a, e2a) ->
  1860. let v = mk_temp gen "dynop" e1a.etype in
  1861. let v2 = mk_temp gen "dynopi" e2a.etype in
  1862. { e1 with eexpr = TArray(mk_local v e1a.epos, mk_local v2 e2a.epos) }, [
  1863. { eexpr = TVar(v,Some (run e1a)); etype = basic.tvoid; epos = e1.epos };
  1864. { eexpr = TVar(v2, Some (run e2a)); etype = basic.tvoid; epos = e1.epos }
  1865. ]
  1866. | _ -> assert false
  1867. in
  1868. { e with
  1869. eexpr = TBlock (rest @ [ { e with eexpr = TBinop(OpAssign, eleft, run { e with eexpr = TBinop(op, eleft, e2) }) } ]);
  1870. }
  1871. | _ ->
  1872. assert false
  1873. )
  1874. | TBinop (OpAssign, e1, e2)
  1875. | TBinop (OpInterval, e1, e2) -> Type.map_expr run e
  1876. | TBinop (op, e1, e2) when should_change e->
  1877. (match op with
  1878. | OpEq -> (* type 1 *)
  1879. equals_handler (run e1) (run e2)
  1880. | OpNotEq -> (* != -> !equals() *)
  1881. mk_paren { eexpr = TUnop(Ast.Not, Prefix, (equals_handler (run e1) (run e2))); etype = gen.gcon.basic.tbool; epos = e.epos }
  1882. | OpAdd ->
  1883. if handle_strings && (is_string e.etype || is_string e1.etype || is_string e2.etype) then
  1884. { e with eexpr = TBinop(op, mk_cast gen.gcon.basic.tstring (run e1), mk_cast gen.gcon.basic.tstring (run e2)) }
  1885. else
  1886. dyn_plus_handler e (run e1) (run e2)
  1887. | OpGt | OpGte | OpLt | OpLte -> (* type 2 *)
  1888. { eexpr = TBinop(op, compare_handler (run e1) (run e2), { eexpr = TConst(TInt(Int32.zero)); etype = gen.gcon.basic.tint; epos = e.epos} ); etype = gen.gcon.basic.tbool; epos = e.epos }
  1889. | OpMult | OpDiv | OpSub -> (* always cast everything to double *)
  1890. let etype, _ = get_etype_one e in
  1891. { e with eexpr = TBinop(op, mk_cast etype (run e1), mk_cast etype (run e2)) }
  1892. | OpBoolAnd | OpBoolOr ->
  1893. { e with eexpr = TBinop(op, mk_cast gen.gcon.basic.tbool (run e1), mk_cast gen.gcon.basic.tbool (run e2)) }
  1894. | OpAnd | OpOr | OpXor | OpShl | OpShr | OpUShr | OpMod ->
  1895. { e with eexpr = TBinop(op, mk_cast gen.gcon.basic.tint (run e1), mk_cast gen.gcon.basic.tint (run e2)) }
  1896. | OpAssign | OpAssignOp _ | OpInterval | OpArrow -> assert false)
  1897. | TUnop (Increment as op, flag, e1)
  1898. | TUnop (Decrement as op, flag, e1) when should_change e ->
  1899. (*
  1900. some naming definitions:
  1901. * ret => the returning variable
  1902. * _g => the get body
  1903. * getvar => the get variable expr
  1904. This will work like this:
  1905. - if e1 is a TField, set _g = get body, getvar = (get body).varname
  1906. - if Prefix, return getvar = getvar + 1.0
  1907. - if Postfix, set ret = getvar; getvar = getvar + 1.0; ret;
  1908. *)
  1909. let etype, one = get_etype_one e in
  1910. let op = (match op with Increment -> OpAdd | Decrement -> OpSub | _ -> assert false) in
  1911. let var, getvar =
  1912. match e1.eexpr with
  1913. | TField(fexpr, field) ->
  1914. let tmp = mk_temp gen "getvar" fexpr.etype in
  1915. let var = { eexpr = TVar(tmp, Some(run fexpr)); etype = gen.gcon.basic.tvoid; epos = e.epos } in
  1916. (Some var, { eexpr = TField( { fexpr with eexpr = TLocal(tmp) }, field); etype = etype; epos = e1.epos })
  1917. | _ ->
  1918. (None, e1)
  1919. in
  1920. (match flag with
  1921. | Prefix ->
  1922. let block = (match var with | Some e -> [e] | None -> []) @
  1923. [
  1924. mk_cast etype { e with eexpr = TBinop(OpAssign, getvar,{ eexpr = TBinop(op, mk_cast etype getvar, one); etype = etype; epos = e.epos }); etype = getvar.etype; }
  1925. ]
  1926. in
  1927. { eexpr = TBlock(block); etype = etype; epos = e.epos }
  1928. | Postfix ->
  1929. let ret = mk_temp gen "ret" etype in
  1930. let vars = (match var with Some e -> [e] | None -> []) @ [{ eexpr = TVar(ret, Some (mk_cast etype getvar)); etype = gen.gcon.basic.tvoid; epos = e.epos }] in
  1931. let retlocal = { eexpr = TLocal(ret); etype = etype; epos = e.epos } in
  1932. let block = vars @
  1933. [
  1934. { e with eexpr = TBinop(OpAssign, getvar, { eexpr = TBinop(op, retlocal, one); etype = getvar.etype; epos = e.epos }) };
  1935. retlocal
  1936. ] in
  1937. { eexpr = TBlock(block); etype = etype; epos = e.epos }
  1938. )
  1939. | TUnop (op, flag, e1) when should_change e ->
  1940. let etype = match op with | Not -> gen.gcon.basic.tbool | _ -> gen.gcon.basic.tint in
  1941. mk_paren { eexpr = TUnop(op, flag, mk_cast etype (run e1)); etype = etype; epos = e.epos }
  1942. | _ -> Type.map_expr run e
  1943. in
  1944. run
  1945. let configure gen (mapping_func:texpr->texpr) =
  1946. let map e = Some(mapping_func e) in
  1947. gen.gexpr_filters#add ~name:"dyn_ops" ~priority:(PCustom priority) map
  1948. let configure_as_synf gen (mapping_func:texpr->texpr) =
  1949. let map e = Some(mapping_func e) in
  1950. gen.gexpr_filters#add ~name:"dyn_ops" ~priority:(PCustom priority_as_synf) map
  1951. end;;
  1952. (* ******************************************* *)
  1953. (* Closure Detection *)
  1954. (* ******************************************* *)
  1955. (*
  1956. Just a small utility filter that detects when a closure must be created.
  1957. On the default implementation, this means when a function field is being accessed
  1958. not via reflection and not to be called instantly
  1959. *)
  1960. module FilterClosures =
  1961. struct
  1962. let priority = 0.0
  1963. let traverse gen (should_change:texpr->string->bool) (filter:texpr->texpr->string->bool->texpr) =
  1964. let rec run e =
  1965. match e.eexpr with
  1966. (*(* this is precisely the only case where we won't even ask if we should change, because it is a direct use of TClosure *)
  1967. | TCall ( {eexpr = TClosure(e1,s)} as clos, args ) ->
  1968. { e with eexpr = TCall({ clos with eexpr = TClosure(run e1, s) }, List.map run args ) }
  1969. | TCall ( clos, args ) ->
  1970. let rec loop clos = match clos.eexpr with
  1971. | TClosure(e1,s) -> Some (clos, e1, s)
  1972. | TParenthesis p -> loop p
  1973. | _ -> None
  1974. in
  1975. let clos = loop clos in
  1976. (match clos with
  1977. | Some (clos, e1, s) -> { e with eexpr = TCall({ clos with eexpr = TClosure(run e1, s) }, List.map run args ) }
  1978. | None -> Type.map_expr run e)*)
  1979. | TCall({ eexpr = TLocal{ v_name = "__delegate__" } } as local, [del]) ->
  1980. { e with eexpr = TCall(local, [Type.map_expr run del]) }
  1981. | TCall(({ eexpr = TField(_, _) } as ef), params) ->
  1982. { e with eexpr = TCall(Type.map_expr run ef, List.map run params) }
  1983. | TField(ef, FEnum(en, field)) ->
  1984. (* FIXME replace t_dynamic with actual enum Anon field *)
  1985. let ef = run ef in
  1986. (match follow field.ef_type with
  1987. | TFun _ when should_change ef field.ef_name ->
  1988. filter e ef field.ef_name true
  1989. | _ ->
  1990. { e with eexpr = TField(ef, FEnum(en,field)) }
  1991. )
  1992. | TField(({ eexpr = TTypeExpr _ } as tf), f) ->
  1993. (match field_access_esp gen tf.etype (f) with
  1994. | FClassField(_,_,_,cf,_,_,_) ->
  1995. (match cf.cf_kind with
  1996. | Method(MethDynamic)
  1997. | Var _ ->
  1998. e
  1999. | _ when should_change tf cf.cf_name ->
  2000. filter e tf cf.cf_name true
  2001. | _ ->
  2002. e
  2003. )
  2004. | _ -> e)
  2005. | TField(e1, FClosure (Some _, cf)) when should_change e1 cf.cf_name ->
  2006. (match cf.cf_kind with
  2007. | Method MethDynamic | Var _ ->
  2008. Type.map_expr run e
  2009. | _ ->
  2010. filter e (run e1) cf.cf_name false)
  2011. | _ -> Type.map_expr run e
  2012. in
  2013. run
  2014. let configure gen (mapping_func:texpr->texpr) =
  2015. let map e = Some(mapping_func e) in
  2016. gen.gexpr_filters#add ~name:"closures_filter" ~priority:(PCustom priority) map
  2017. end;;
  2018. (* ******************************************* *)
  2019. (* Dynamic Field Access *)
  2020. (* ******************************************* *)
  2021. (*
  2022. This module will filter every dynamic field access in haxe.
  2023. On platforms that do not support dynamic access, it is with this that you should
  2024. replace dynamic calls with x.field / Reflect.setField calls, and guess what -
  2025. this is the default implemenation!
  2026. Actually there is a problem with Reflect.setField because it returns void, which is a bad thing for us,
  2027. so even in the default implementation, the function call should be specified to a Reflect.setField version that returns
  2028. the value that was set
  2029. (TODO: should it be separated?)
  2030. As a plus, the default implementation adds something that doesn't hurt anybody, it looks for
  2031. TAnon with Statics / EnumStatics field accesses and transforms them into real static calls.
  2032. This means it will take this
  2033. var m = Math;
  2034. for (i in 0...1000) m.cos(10);
  2035. which is an optimization in dynamic platforms, but performs horribly on strongly typed platforms
  2036. and transform into:
  2037. var m = Math;
  2038. for (i in 0...1000) Math.cos(10);
  2039. (addendum:)
  2040. configure_generate_classes will already take care of generating the reflection-enabled class fields and calling abstract_implementation
  2041. with the right arguments.
  2042. Also
  2043. depends on:
  2044. (ok) must run AFTER Binop/Unop handler - so Unops / Binops are already unrolled
  2045. *)
  2046. module DynamicFieldAccess =
  2047. struct
  2048. let name = "dynamic_field_access"
  2049. let priority = solve_deps name [DAfter DynamicOperators.priority]
  2050. let priority_as_synf = solve_deps name [DAfter DynamicOperators.priority_as_synf]
  2051. (*
  2052. is_dynamic (expr) (field_access_expr) (field) : a function that indicates if the field access should be changed
  2053. change_expr (expr) (field_access_expr) (field) (setting expr) (is_unsafe) : changes the expression
  2054. call_expr (expr) (field_access_expr) (field) (call_params) : changes a call expression
  2055. *)
  2056. let abstract_implementation gen (is_dynamic:texpr->texpr->Type.tfield_access->bool) (change_expr:texpr->texpr->string->texpr option->bool->texpr) (call_expr:texpr->texpr->string->texpr list->texpr) =
  2057. let rec run e =
  2058. match e.eexpr with
  2059. (* class types *)
  2060. | TField(fexpr, f) when is_some (anon_class fexpr.etype) ->
  2061. let decl = get (anon_class fexpr.etype) in
  2062. let name = field_name f in
  2063. (try
  2064. match decl with
  2065. | TClassDecl cl ->
  2066. let cf = PMap.find name cl.cl_statics in
  2067. { e with eexpr = TField({ fexpr with eexpr = TTypeExpr decl }, FStatic(cl, cf)) }
  2068. | TEnumDecl en ->
  2069. let ef = PMap.find name en.e_constrs in
  2070. { e with eexpr = TField({ fexpr with eexpr = TTypeExpr decl }, FEnum(en, ef)) }
  2071. | TAbstractDecl _ -> (* abstracts don't have TFields *) assert false
  2072. | TTypeDecl _ -> (* anon_class doesn't return TTypeDecl *) assert false
  2073. with
  2074. | Not_found -> match f with
  2075. | FStatic(cl,cf) when Meta.has Meta.Extern cf.cf_meta ->
  2076. { e with eexpr = TField({ fexpr with eexpr = TTypeExpr decl }, FStatic(cl, cf)) }
  2077. | _ ->
  2078. change_expr e { fexpr with eexpr = TTypeExpr decl } (field_name f) None true
  2079. )
  2080. | TField(fexpr, f) when is_dynamic e fexpr (f) ->
  2081. change_expr e (run fexpr) (field_name f) None true
  2082. | TCall(
  2083. { eexpr = TField(_, FStatic({ cl_path = ([], "Reflect") }, { cf_name = "field" })) } ,
  2084. [obj; { eexpr = TConst(TString(field)) }]
  2085. ) ->
  2086. change_expr (mk_field_access gen obj field obj.epos) (run obj) field None false
  2087. | TCall(
  2088. { eexpr = TField(_, FStatic({ cl_path = ([], "Reflect") }, { cf_name = "setField" } )) },
  2089. [obj; { eexpr = TConst(TString(field)) }; evalue]
  2090. ) ->
  2091. change_expr (mk_field_access gen obj field obj.epos) (run obj) field (Some (run evalue)) false
  2092. | TBinop(OpAssign, ({eexpr = TField(fexpr, f)}), evalue) when is_dynamic e fexpr (f) ->
  2093. change_expr e (run fexpr) (field_name f) (Some (run evalue)) true
  2094. | TBinop(OpAssign, { eexpr = TField(fexpr, f) }, evalue) ->
  2095. (match field_access_esp gen fexpr.etype (f) with
  2096. | FClassField(_,_,_,cf,false,t,_) when (try PMap.find cf.cf_name gen.gbase_class_fields == cf with Not_found -> false) ->
  2097. change_expr e (run fexpr) (field_name f) (Some (run evalue)) true
  2098. | _ -> Type.map_expr run e
  2099. )
  2100. (* #if debug *)
  2101. | TBinop(OpAssignOp op, ({eexpr = TField(fexpr, f)}), evalue) when is_dynamic e fexpr (f) -> assert false (* this case shouldn't happen *)
  2102. | TUnop(Increment, _, ({eexpr = TField( ( { eexpr=TLocal(local) } as fexpr ), f)}))
  2103. | TUnop(Decrement, _, ({eexpr = TField( ( { eexpr=TLocal(local) } as fexpr ), f)})) when is_dynamic e fexpr (f) -> assert false (* this case shouldn't happen *)
  2104. (* #end *)
  2105. | TCall( ({ eexpr = TField(fexpr, f) }), params ) when is_dynamic e fexpr (f) ->
  2106. call_expr e (run fexpr) (field_name f) (List.map run params)
  2107. | _ -> Type.map_expr run e
  2108. in run
  2109. (*
  2110. this function will already configure with the abstract implementation, and also will create the needed class fields to
  2111. enable reflection on platforms that don't support reflection.
  2112. this means it will create the following class methods:
  2113. - getField(field, isStatic) - gets the value of the field. isStatic
  2114. - setField -
  2115. -
  2116. *)
  2117. let configure_generate_classes gen optimize (runtime_getset_field:texpr->texpr->string->texpr option->texpr) (runtime_call_expr:texpr->texpr->string->texpr list->texpr) =
  2118. ()
  2119. let configure gen (mapping_func:texpr->texpr) =
  2120. let map e = Some(mapping_func e) in
  2121. gen.gexpr_filters#add ~name:"dynamic_field_access" ~priority:(PCustom(priority)) map
  2122. let configure_as_synf gen (mapping_func:texpr->texpr) =
  2123. let map e = Some(mapping_func e) in
  2124. gen.gexpr_filters#add ~name:"dynamic_field_access" ~priority:(PCustom(priority_as_synf)) map
  2125. end;;
  2126. (* ******************************************* *)
  2127. (* Dynamic TArray Handling *)
  2128. (* ******************************************* *)
  2129. (*
  2130. In some languages you cannot overload the [] operator,
  2131. so we need to decide what is kept as TArray and what gets mapped.
  2132. - in order to do this you must ensure that
  2133. depends on:
  2134. (syntax) must run before expression/statment normalization because it may generate complex expressions
  2135. (ok) must run before binop transformations because it may generate some untreated binop ops
  2136. (ok) must run before dynamic field access is transformed into reflection
  2137. *)
  2138. module TArrayTransform =
  2139. struct
  2140. let name = "dyn_tarray"
  2141. let priority = solve_deps name [DBefore DynamicOperators.priority; DBefore DynamicFieldAccess.priority]
  2142. let priority_as_synf = solve_deps name [DBefore DynamicOperators.priority_as_synf; DBefore DynamicFieldAccess.priority_as_synf]
  2143. (* should change signature: tarray expr -> binop operation -> should change? *)
  2144. let default_implementation gen (should_change:texpr->Ast.binop option->bool) (get_fun:string) (set_fun:string) =
  2145. let basic = gen.gcon.basic in
  2146. let mk_get e e1 e2 =
  2147. let efield = mk_field_access gen e1 get_fun e.epos in
  2148. { e with eexpr = TCall(efield, [e2]) }
  2149. in
  2150. let mk_set e e1 e2 evalue =
  2151. let efield = mk_field_access gen e1 set_fun e.epos in
  2152. { e with eexpr = TCall(efield, [e2; evalue]) }
  2153. in
  2154. let rec run e =
  2155. match e.eexpr with
  2156. | TArray(e1, e2) ->
  2157. (* e1 should always be a var; no need to map there *)
  2158. if should_change e None then mk_get e (run e1) (run e2) else Type.map_expr run e
  2159. | TBinop (Ast.OpAssign, ({ eexpr = TArray(e1a,e2a) } as earray), evalue) when should_change earray (Some Ast.OpAssign) ->
  2160. mk_set e (run e1a) (run e2a) (run evalue)
  2161. | TBinop (Ast.OpAssignOp op,({ eexpr = TArray(e1a,e2a) } as earray) , evalue) when should_change earray (Some (Ast.OpAssignOp op)) ->
  2162. (* cache all arguments in vars so they don't get executed twice *)
  2163. (* let ensure_local gen block name e = *)
  2164. let block = ref [] in
  2165. let arr_local = ensure_local gen block "array" (run e1a) in
  2166. let idx_local = ensure_local gen block "index" (run e2a) in
  2167. block := (mk_set e arr_local idx_local ( { e with eexpr=TBinop(op, mk_get earray arr_local idx_local, run evalue) } )) :: !block;
  2168. { e with eexpr = TBlock (List.rev !block) }
  2169. | TUnop(op, flag, ({ eexpr = TArray(e1a, e2a) } as earray)) ->
  2170. if should_change earray None && match op with | Not | Neg -> false | _ -> true then begin
  2171. let block = ref [] in
  2172. let actual_t = match op with
  2173. | Ast.Increment | Ast.Decrement -> (match follow earray.etype with
  2174. | TInst _ | TAbstract _ | TEnum _ -> earray.etype
  2175. | _ -> basic.tfloat)
  2176. | Ast.Not -> basic.tbool
  2177. | _ -> basic.tint
  2178. in
  2179. let val_v = mk_temp gen "arrVal" actual_t in
  2180. let ret_v = mk_temp gen "arrRet" actual_t in
  2181. let arr_local = ensure_local gen block "arr" (run e1a) in
  2182. let idx_local = ensure_local gen block "arrIndex" (run e2a) in
  2183. let val_local = { earray with eexpr = TLocal(val_v) } in
  2184. let ret_local = { earray with eexpr = TLocal(ret_v) } in
  2185. (* var idx = 1; var val = x._get(idx); var ret = val++; x._set(idx, val); ret; *)
  2186. block := { eexpr = TVar(val_v, Some(mk_get earray arr_local idx_local)); (* var val = x._get(idx) *)
  2187. etype = gen.gcon.basic.tvoid;
  2188. epos = e2a.epos
  2189. } :: !block;
  2190. block := { eexpr = TVar(ret_v, Some { e with eexpr = TUnop(op, flag, val_local) }); (* var ret = val++ *)
  2191. etype = gen.gcon.basic.tvoid;
  2192. epos = e2a.epos
  2193. } :: !block;
  2194. block := (mk_set e arr_local idx_local val_local) (*x._set(idx,val)*) :: !block;
  2195. block := ret_local :: !block;
  2196. { e with eexpr = TBlock (List.rev !block) }
  2197. end else
  2198. Type.map_expr run e
  2199. | _ -> Type.map_expr run e
  2200. in run
  2201. let configure gen (mapping_func:texpr->texpr) =
  2202. let map e = Some(mapping_func e) in
  2203. gen.gexpr_filters#add ~name:"dyn_tarray" ~priority:(PCustom priority) map
  2204. let configure_as_synf gen (mapping_func:texpr->texpr) =
  2205. let map e = Some(mapping_func e) in
  2206. gen.gexpr_filters#add ~name:"dyn_tarray" ~priority:(PCustom priority_as_synf) map
  2207. end;;
  2208. (* ******************************************* *)
  2209. (* Try / Catch + throw native types handling *)
  2210. (* ******************************************* *)
  2211. (*
  2212. Some languages/vm's do not support throwing any kind of value. For them, only
  2213. special kinds of objects can be thrown. Because of this, we must wrap some throw
  2214. statements with an expression, and also we must unwrap it on the catch() phase, and
  2215. maybe manually test with Std.is()
  2216. dependencies:
  2217. must run before dynamic field access (?) TODO review
  2218. It's a syntax filter, as it alters types (throw wrapper)
  2219. *)
  2220. module TryCatchWrapper =
  2221. struct
  2222. let priority = solve_deps "try_catch" [DBefore DynamicFieldAccess.priority]
  2223. (*
  2224. should_wrap : does the type should be wrapped? This of course works on the reverse way, so it tells us if the type should be unwrapped as well
  2225. wrap_throw : the wrapper for throw (throw expr->expr inside throw->returning wrapped expression)
  2226. unwrap_expr : the other way around : given the catch var (maybe will need casting to wrapper_type) , return the unwrap expr
  2227. rethrow_expr : how to rethrow ane exception in the platform
  2228. catchall_type : the class used for catchall (e:Dynamic)
  2229. wrapper_type : the wrapper type, so we can test if exception is of type 'wrapper'
  2230. catch_map : maps the catch expression to include some intialization code (e.g. setting up Stack.exceptionStack)
  2231. *)
  2232. let traverse gen (should_wrap:t->bool) (wrap_throw:texpr->texpr->texpr) (unwrap_expr:tvar->pos->texpr) (rethrow_expr:texpr->texpr) (catchall_type:t) (wrapper_type:t) (catch_map:tvar->texpr->texpr) =
  2233. let rec run e =
  2234. match e.eexpr with
  2235. | TThrow texpr when should_wrap texpr.etype -> wrap_throw e (run texpr)
  2236. | TTry (ttry, catches) ->
  2237. let nowrap_catches, must_wrap_catches, catchall = List.fold_left (fun (nowrap_catches, must_wrap_catches, catchall) (v, catch) ->
  2238. (* first we'll see if the type is Dynamic (catchall) *)
  2239. match follow v.v_type with
  2240. | TDynamic _ ->
  2241. assert (is_none catchall);
  2242. (nowrap_catches, must_wrap_catches, Some(v,run catch))
  2243. (* see if we should unwrap it *)
  2244. | _ when should_wrap (follow v.v_type) ->
  2245. (nowrap_catches, (v,run catch) :: must_wrap_catches, catchall)
  2246. | _ ->
  2247. ( (v,catch_map v (run catch)) :: nowrap_catches, must_wrap_catches, catchall )
  2248. ) ([], [], None) catches
  2249. in
  2250. (*
  2251. 1st catch all nowrap "the easy way"
  2252. 2nd see if there are any must_wrap or catchall. If there is,
  2253. do a catchall first with a temp var.
  2254. then get catchall var (as dynamic) (or create one), and declare it = catchall exception
  2255. then test if it is of type wrapper_type. If it is, unwrap it
  2256. then start doing Std.is() tests for each catch type
  2257. if there is a catchall in the end, end with it. If there isn't, rethrow
  2258. *)
  2259. let dyn_catch = match (catchall, must_wrap_catches) with
  2260. | Some (v,c), _
  2261. | _, (v, c) :: _ ->
  2262. let pos = c.epos in
  2263. let temp_var = mk_temp gen "catchallException" catchall_type in
  2264. let temp_local = { eexpr=TLocal(temp_var); etype = temp_var.v_type; epos = pos } in
  2265. let catchall_var = (*match catchall with
  2266. | None -> *) mk_temp gen "catchall" t_dynamic
  2267. (*| Some (v,_) -> v*)
  2268. in
  2269. let catchall_decl = { eexpr = TVar(catchall_var, Some(temp_local)); etype=gen.gcon.basic.tvoid; epos = pos } in
  2270. let catchall_local = { eexpr = TLocal(catchall_var); etype = t_dynamic; epos = pos } in
  2271. (* if it is of type wrapper_type, unwrap it *)
  2272. let std_is = mk_static_field_access (get_cl (get_type gen ([],"Std"))) "is" (TFun(["v",false,t_dynamic;"cl",false,mt_to_t (get_type gen ([], "Class")) [t_dynamic]],gen.gcon.basic.tbool)) pos in
  2273. let mk_std_is t pos = { eexpr = TCall(std_is, [catchall_local; mk_mt_access (t_to_mt t) pos]); etype = gen.gcon.basic.tbool; epos = pos } in
  2274. let if_is_wrapper_expr = { eexpr = TIf(mk_std_is wrapper_type pos,
  2275. { eexpr = TBinop(OpAssign, catchall_local, unwrap_expr temp_var pos); etype = t_dynamic; epos = pos }
  2276. , None); etype = gen.gcon.basic.tvoid; epos = pos } in
  2277. let rec loop must_wrap_catches = match must_wrap_catches with
  2278. | (vcatch,catch) :: tl ->
  2279. { eexpr = TIf(mk_std_is vcatch.v_type catch.epos,
  2280. { eexpr = TBlock({ eexpr=TVar(vcatch, Some(mk_cast vcatch.v_type catchall_local)); etype=gen.gcon.basic.tvoid; epos=catch.epos } :: [catch] ); etype = catch.etype; epos = catch.epos },
  2281. Some (loop tl));
  2282. etype = catch.etype; epos = catch.epos }
  2283. | [] ->
  2284. match catchall with
  2285. | Some (v,s) ->
  2286. Type.concat { eexpr = TVar(v, Some(catchall_local)); etype = gen.gcon.basic.tvoid; epos = pos } s
  2287. | None ->
  2288. mk_block (rethrow_expr temp_local)
  2289. in
  2290. [ ( temp_var, catch_map temp_var { e with eexpr = TBlock([ catchall_decl; if_is_wrapper_expr; loop must_wrap_catches ]) } ) ]
  2291. | _ ->
  2292. []
  2293. in
  2294. { e with eexpr = TTry(run ttry, (List.rev nowrap_catches) @ dyn_catch) }
  2295. | _ -> Type.map_expr run e
  2296. in
  2297. run
  2298. let configure gen (mapping_func:texpr->texpr) =
  2299. let map e = Some(mapping_func e) in
  2300. gen.gsyntax_filters#add ~name:"try_catch" ~priority:(PCustom priority) map
  2301. end;;
  2302. let fun_args = List.map (function | (v,s) -> (v.v_name, (match s with | None -> false | Some _ -> true), v.v_type))
  2303. (* ******************************************* *)
  2304. (* Closures To Class *)
  2305. (* ******************************************* *)
  2306. (*
  2307. This is a very important filter. It will take all anonymous functions from the AST, will search for all captured variables, and will create a class
  2308. that implements an abstract interface for calling functions. This is very important for targets that don't support anonymous functions to work correctly.
  2309. Also it is possible to implement some strategies to avoid value type boxing, such as NaN tagging or double/object arguments. All this will be abstracted away
  2310. from this interface.
  2311. dependencies:
  2312. must run after dynamic field access, because of conflicting ways to deal with invokeField
  2313. (module filter) must run after OverloadingCtor so we can also change the dynamic function expressions
  2314. uses TArray expressions for array. TODO see interaction
  2315. uses TThrow expressions.
  2316. *)
  2317. module ClosuresToClass =
  2318. struct
  2319. let name = "closures_to_class"
  2320. let priority = solve_deps name [ DAfter DynamicFieldAccess.priority ]
  2321. let priority_as_synf = solve_deps name [ DAfter DynamicFieldAccess.priority_as_synf ]
  2322. type closures_ctx =
  2323. {
  2324. fgen : generator_ctx;
  2325. mutable func_class : tclass;
  2326. (*
  2327. this is what will actually turn the function into class field.
  2328. The standard implementation by default will already take care of creating the class, and setting the captured variables.
  2329. It will also return the super arguments to be called
  2330. *)
  2331. mutable closure_to_classfield : tfunc->t->pos->tclass_field * (texpr list);
  2332. (*
  2333. when a dynamic function call is made, we need to convert it as if it were calling the dynamic function interface.
  2334. TCall expr -> new TCall expr
  2335. *)
  2336. mutable dynamic_fun_call : texpr->texpr;
  2337. (*
  2338. called once so the implementation can make one of a time initializations in the base class
  2339. for all functions
  2340. *)
  2341. mutable initialize_base_class : tclass->unit;
  2342. (*
  2343. Base classfields are the class fields for the abstract implementation of either the Function implementation,
  2344. or the invokeField implementation for the classes
  2345. They will either try to call the right function or will fail with
  2346. (tclass - subject (so we know the type of this)) -> is_function_base -> additional arguments for each function (at the beginning) -> list of the abstract implementation class fields
  2347. *)
  2348. mutable get_base_classfields_for : tclass->bool->(unit->(tvar * tconstant option) list)->tclass_field list;
  2349. (*
  2350. This is a more complex version of get_base_classfields_for.
  2351. It's meant to provide a toolchain so we can easily create classes that extend Function
  2352. and add more functionality on top of it.
  2353. arguments:
  2354. tclass -> subject (so we know the type of this)
  2355. bool -> is it a function type
  2356. ( int -> (int->t->tconstant option->texpr) -> ( (tvar * tconstant option) list * texpr) )
  2357. int -> current arity of the function whose member will be mapped; -1 for dynamic function. It is guaranteed that dynamic function will be called last
  2358. t -> the return type of the function
  2359. (int->t->tconstant option->texpr) -> api to get exprs that unwrap arguments correctly
  2360. int -> argument wanted to unwrap
  2361. t -> solicited type
  2362. tconstant option -> map to this default value if null
  2363. returns a texpr that tells how the default
  2364. should return a list with additional arguments (only works if is_function_base = true)
  2365. and the underlying function expression
  2366. *)
  2367. mutable map_base_classfields : tclass->bool->( int -> t -> (tvar list) -> (int->t->tconstant option->texpr) -> ( (tvar * tconstant option) list * texpr) )->tclass_field list;
  2368. mutable transform_closure : texpr->texpr->string->texpr;
  2369. }
  2370. (*
  2371. the default implementation will take 3 transformation functions:
  2372. * one that will transform closures that are not called immediately (instance.myFunc).
  2373. normally on this case it's best to have a runtime handler that will take the instance, the function and call its invokeField when invoked
  2374. * one that will actually handle the anonymous functions themselves.
  2375. * one that will transform calling a dynamic function. So for example, dynFunc(arg1, arg2) might turn into dynFunc.apply2(arg1, arg2);
  2376. ( suspended ) * an option to match papplied functions
  2377. * handling parameterized anonymous function declaration (optional - tparam_anon_decl and tparam_anon_acc)
  2378. *)
  2379. let rec cleanup_delegate e = match e.eexpr with
  2380. | TParenthesis e | TMeta(_,e)
  2381. | TCast(e,_) -> cleanup_delegate e
  2382. | _ -> e
  2383. let funct gen t = match follow (run_follow gen t) with
  2384. | TFun(args,ret) -> args,ret
  2385. | _ -> raise Not_found
  2386. let mk_conversion_fun gen e =
  2387. let args, ret = funct gen e.etype in
  2388. let tf_args = List.map (fun (n,o,t) -> alloc_var n t,None) args in
  2389. let block, local = match e.eexpr with
  2390. | TLocal v ->
  2391. v.v_capture <- true;
  2392. [],e
  2393. | _ ->
  2394. let tmp = mk_temp gen "delegate_conv" e.etype in
  2395. tmp.v_capture <- true;
  2396. [{ eexpr = TVar(tmp,Some e); etype = gen.gcon.basic.tvoid; epos = e.epos }], mk_local tmp e.epos
  2397. in
  2398. let body = {
  2399. eexpr = TCall(local, List.map (fun (v,_) -> mk_local v e.epos) tf_args);
  2400. etype = ret;
  2401. epos = e.epos;
  2402. } in
  2403. let body = if not (is_void ret) then
  2404. { body with eexpr = TReturn( Some body ) }
  2405. else
  2406. body
  2407. in
  2408. let body = {
  2409. eexpr = TBlock(block @ [body]);
  2410. etype = body.etype;
  2411. epos = body.epos;
  2412. } in
  2413. {
  2414. tf_args = tf_args;
  2415. tf_expr = body;
  2416. tf_type = ret;
  2417. }
  2418. let traverse gen ?tparam_anon_decl ?tparam_anon_acc (transform_closure:texpr->texpr->string->texpr) (handle_anon_func:texpr->tfunc->t option->texpr) (dynamic_func_call:texpr->texpr) e =
  2419. let rec run e =
  2420. match e.eexpr with
  2421. | TCast({ eexpr = TCall({ eexpr = TLocal{ v_name = "__delegate__" } } as local, [del] ) } as e2, _) ->
  2422. let e2 = { e2 with etype = e.etype } in
  2423. let replace_delegate ex =
  2424. { e with eexpr = TCast({ e2 with eexpr = TCall(local, [ex]) }, None) }
  2425. in
  2426. (* found a delegate; let's see if it's a closure or not *)
  2427. let clean = cleanup_delegate del in
  2428. (match clean.eexpr with
  2429. | TField( ef, (FClosure _ as f)) | TField( ef, (FStatic _ as f)) ->
  2430. (* a closure; let's leave this unchanged for FilterClosures to handle it *)
  2431. replace_delegate { clean with eexpr = TField( run ef, f ) }
  2432. | TFunction tf ->
  2433. (* handle like we'd handle a normal function, but create an unchanged closure field for it *)
  2434. let ret = handle_anon_func clean { tf with tf_expr = run tf.tf_expr } (Some e.etype) in
  2435. replace_delegate ret
  2436. | _ -> try
  2437. let tf = mk_conversion_fun gen del in
  2438. let ret = handle_anon_func del { tf with tf_expr = run tf.tf_expr } (Some e.etype) in
  2439. replace_delegate ret
  2440. with Not_found ->
  2441. gen.gcon.error "This delegate construct is unsupported" e.epos;
  2442. replace_delegate (run clean))
  2443. (* parameterized functions handling *)
  2444. | TVar(vv, ve) -> (match tparam_anon_decl with
  2445. | None -> Type.map_expr run e
  2446. | Some tparam_anon_decl ->
  2447. (match (vv, ve) with
  2448. | ({ v_extra = Some( _ :: _, _) } as v), Some ({ eexpr = TFunction tf } as f)
  2449. | ({ v_extra = Some( _ :: _, _) } as v), Some { eexpr = TArrayDecl([{ eexpr = TFunction tf } as f]) } -> (* captured transformation *)
  2450. ignore(tparam_anon_decl v f { tf with tf_expr = run tf.tf_expr });
  2451. { e with eexpr = TBlock([]) }
  2452. | _ ->
  2453. Type.map_expr run { e with eexpr = TVar(vv, ve) })
  2454. )
  2455. | TLocal ({ v_extra = Some( _ :: _, _) } as v)
  2456. | TArray ({ eexpr = TLocal ({ v_extra = Some( _ :: _, _) } as v) }, _) -> (* captured transformation *)
  2457. (match tparam_anon_acc with
  2458. | None -> Type.map_expr run e
  2459. | Some tparam_anon_acc -> tparam_anon_acc v e)
  2460. | TCall( { eexpr = TField(_, FEnum _) }, _ ) ->
  2461. Type.map_expr run e
  2462. (* if a TClosure is being call immediately, there's no need to convert it to a TClosure *)
  2463. | TCall(( { eexpr = TField(ecl,f) } as e1), params) ->
  2464. (* check to see if called field is known and if it is a MethNormal (only MethNormal fields can be called directly) *)
  2465. (* let name = field_name f in *)
  2466. (match field_access_esp gen (gen.greal_type ecl.etype) f with
  2467. | FClassField(_,_,_,cf,_,_,_) ->
  2468. (match cf.cf_kind with
  2469. | Method MethNormal
  2470. | Method MethInline ->
  2471. { e with eexpr = TCall({ e1 with eexpr = TField(run ecl, f) }, List.map run params) }
  2472. | _ ->
  2473. match gen.gfollow#run_f e1.etype with
  2474. | TFun _ ->
  2475. dynamic_func_call { e with eexpr = TCall(run e1, List.map run params) }
  2476. | _ ->
  2477. let i = ref 0 in
  2478. let t = TFun(List.map (fun e -> incr i; "arg" ^ (string_of_int !i), false, e.etype) params, e.etype) in
  2479. dynamic_func_call { e with eexpr = TCall( mk_cast t (run e1), List.map run params ) }
  2480. )
  2481. (* | FNotFound ->
  2482. { e with eexpr = TCall({ e1 with eexpr = TField(run ecl, f) }, List.map run params) }
  2483. (* expressions by now may have generated invalid expressions *) *)
  2484. | _ ->
  2485. match gen.gfollow#run_f e1.etype with
  2486. | TFun _ ->
  2487. dynamic_func_call { e with eexpr = TCall(run e1, List.map run params) }
  2488. | _ ->
  2489. let i = ref 0 in
  2490. let t = TFun(List.map (fun e -> incr i; "arg" ^ (string_of_int !i), false, e.etype) params, e.etype) in
  2491. dynamic_func_call { e with eexpr = TCall( mk_cast t (run e1), List.map run params ) }
  2492. )
  2493. | TField(ecl, FClosure (_,cf)) ->
  2494. transform_closure e (run ecl) cf.cf_name
  2495. | TFunction tf ->
  2496. handle_anon_func e { tf with tf_expr = run tf.tf_expr } None
  2497. | TCall({ eexpr = TConst(TSuper) }, _) ->
  2498. Type.map_expr run e
  2499. | TCall({ eexpr = TLocal(v) }, args) when String.get v.v_name 0 = '_' && Hashtbl.mem gen.gspecial_vars v.v_name ->
  2500. Type.map_expr run e
  2501. | TCall(tc,params) ->
  2502. let i = ref 0 in
  2503. let may_cast = match gen.gfollow#run_f tc.etype with
  2504. | TFun _ -> fun e -> e
  2505. | _ ->
  2506. let t = TFun(List.map (fun e ->
  2507. incr i;
  2508. ("p" ^ (string_of_int !i), false, e.etype)
  2509. ) params, e.etype)
  2510. in
  2511. fun e -> mk_cast t e
  2512. in
  2513. dynamic_func_call { e with eexpr = TCall(run (may_cast tc), List.map run params) }
  2514. | _ -> Type.map_expr run e
  2515. in
  2516. (match e.eexpr with
  2517. | TFunction(tf) -> Type.map_expr run e
  2518. | _ -> run e)
  2519. let rec get_type_params acc t =
  2520. match t with
  2521. | TInst(( { cl_kind = KTypeParameter _ } as cl), []) ->
  2522. if List.memq cl acc then acc else cl :: acc
  2523. | TFun (params,tret) ->
  2524. List.fold_left get_type_params acc ( tret :: List.map (fun (_,_,t) -> t) params )
  2525. | TDynamic t ->
  2526. (match t with | TDynamic _ -> acc | _ -> get_type_params acc t)
  2527. | TAbstract ({ a_impl = Some _ } as a, pl) ->
  2528. get_type_params acc ( Codegen.Abstract.get_underlying_type a pl)
  2529. | TAnon a ->
  2530. PMap.fold (fun cf acc -> get_type_params acc cf.cf_type) a.a_fields acc
  2531. | TType(_, [])
  2532. | TAbstract (_, [])
  2533. | TInst(_, [])
  2534. | TEnum(_, []) ->
  2535. acc
  2536. | TType(_, params)
  2537. | TAbstract(_, params)
  2538. | TEnum(_, params)
  2539. | TInst(_, params) ->
  2540. List.fold_left get_type_params acc params
  2541. | TMono r -> (match !r with
  2542. | Some t -> get_type_params acc t
  2543. | None -> acc)
  2544. | _ -> get_type_params acc (follow_once t)
  2545. let get_captured expr =
  2546. let ret = Hashtbl.create 1 in
  2547. let ignored = Hashtbl.create 0 in
  2548. let params = ref [] in
  2549. let check_params t = params := get_type_params !params t in
  2550. let rec traverse expr =
  2551. match expr.eexpr with
  2552. | TFor (v, _, _) ->
  2553. Hashtbl.add ignored v.v_id v;
  2554. check_params v.v_type;
  2555. Type.iter traverse expr
  2556. | TFunction(tf) ->
  2557. List.iter (fun (v,_) -> check_params v.v_type; Hashtbl.add ignored v.v_id v) tf.tf_args;
  2558. check_params tf.tf_type;
  2559. Type.iter traverse expr
  2560. | TVar (v, opt) ->
  2561. (match v.v_extra with
  2562. | Some(_ :: _, _) -> ()
  2563. | _ ->
  2564. check_params v.v_type);
  2565. Hashtbl.add ignored v.v_id v;
  2566. ignore(Option.map traverse opt)
  2567. | TLocal { v_extra = Some( (_ :: _ ),_) } ->
  2568. ()
  2569. | TLocal(( { v_capture = true } ) as v) ->
  2570. (if not (Hashtbl.mem ignored v.v_id || Hashtbl.mem ret v.v_id) then begin check_params v.v_type; Hashtbl.replace ret v.v_id expr end);
  2571. | _ -> Type.iter traverse expr
  2572. in traverse expr;
  2573. ret, !params
  2574. (*
  2575. OPTIMIZEME:
  2576. Take off from Codegen the code that wraps captured variables,
  2577. traverse through all variables, looking for their use (just like local_usage)
  2578. three possible outcomes for captured variables:
  2579. - become a function member variable <- best performance.
  2580. Will not work on functions that can be created more than once (functions inside a loop or functions inside functions)
  2581. The function will have to be created on top of the block, so its variables can be filled in instead of being declared
  2582. - single-element array - the most compatible way, though also creates a slight overhead.
  2583. - we'll have some labels for captured variables:
  2584. - used in loop
  2585. *)
  2586. (*
  2587. The default implementation will impose a naming convention:
  2588. invoke(arity)_(o for returning object/d for returning double) when arity < max_arity
  2589. invoke_dynamic_(o/d) when arity > max_arity
  2590. This means that it also imposes that the dynamic function return types may only be Dynamic or Float, and all other basic types must be converted to/from it.
  2591. *)
  2592. let default_implementation ft parent_func_class (* e.g. new haxe.lang.ClassClosure *) =
  2593. let gen = ft.fgen in
  2594. ft.initialize_base_class parent_func_class;
  2595. let cfs = ft.get_base_classfields_for parent_func_class true (fun () -> []) in
  2596. List.iter (fun cf ->
  2597. (if cf.cf_name = "new" then parent_func_class.cl_constructor <- Some cf else
  2598. parent_func_class.cl_fields <- PMap.add cf.cf_name cf parent_func_class.cl_fields
  2599. )
  2600. ) cfs;
  2601. parent_func_class.cl_ordered_fields <- (List.filter (fun cf -> cf.cf_name <> "new") cfs) @ parent_func_class.cl_ordered_fields;
  2602. ft.func_class <- parent_func_class;
  2603. let handle_anon_func fexpr tfunc delegate_type : texpr * (tclass * texpr list) =
  2604. (* get all captured variables it uses *)
  2605. let captured_ht, tparams = get_captured fexpr in
  2606. let captured = Hashtbl.fold (fun _ e acc -> e :: acc) captured_ht [] in
  2607. (*let cltypes = List.map (fun cl -> (snd cl.cl_path, TInst(map_param cl, []) )) tparams in*)
  2608. let cltypes = List.map (fun cl -> (snd cl.cl_path, TInst(cl, []) )) tparams in
  2609. (* create a new class that extends abstract function class, with a ctor implementation that will setup all captured variables *)
  2610. let cfield = match ft.fgen.gcurrent_classfield with
  2611. | None -> "Anon"
  2612. | Some cf -> cf.cf_name
  2613. in
  2614. let cur_line = Lexer.get_error_line fexpr.epos in
  2615. let path = (fst ft.fgen.gcurrent_path, Printf.sprintf "%s_%s_%d__Fun" (snd ft.fgen.gcurrent_path) cfield cur_line) in
  2616. let cls = mk_class (get ft.fgen.gcurrent_class).cl_module path tfunc.tf_expr.epos in
  2617. cls.cl_module <- (get ft.fgen.gcurrent_class).cl_module;
  2618. cls.cl_types <- cltypes;
  2619. let mk_this v pos =
  2620. {
  2621. (mk_field_access gen { eexpr = TConst TThis; etype = TInst(cls, List.map snd cls.cl_types); epos = pos } v.v_name pos)
  2622. with etype = v.v_type
  2623. }
  2624. in
  2625. let mk_this_assign v pos =
  2626. {
  2627. eexpr = TBinop(OpAssign, mk_this v pos, { eexpr = TLocal(v); etype = v.v_type; epos = pos });
  2628. etype = v.v_type;
  2629. epos = pos
  2630. } in
  2631. (* mk_class_field name t public pos kind params *)
  2632. let ctor_args, ctor_sig, ctor_exprs = List.fold_left (fun (ctor_args, ctor_sig, ctor_exprs) lexpr ->
  2633. match lexpr.eexpr with
  2634. | TLocal(v) ->
  2635. let cf = mk_class_field v.v_name v.v_type false lexpr.epos (Var({ v_read = AccNormal; v_write = AccNormal; })) [] in
  2636. cls.cl_fields <- PMap.add v.v_name cf cls.cl_fields;
  2637. cls.cl_ordered_fields <- cf :: cls.cl_ordered_fields;
  2638. let ctor_v = alloc_var v.v_name v.v_type in
  2639. ((ctor_v, None) :: ctor_args, (v.v_name, false, v.v_type) :: ctor_sig, (mk_this_assign v cls.cl_pos) :: ctor_exprs)
  2640. | _ -> assert false
  2641. ) ([],[],[]) captured in
  2642. (* change all captured variables to this.capturedVariable *)
  2643. let rec change_captured e =
  2644. match e.eexpr with
  2645. | TLocal( ({ v_capture = true }) as v ) when Hashtbl.mem captured_ht v.v_id ->
  2646. mk_this v e.epos
  2647. | _ -> Type.map_expr change_captured e
  2648. in
  2649. let func_expr = change_captured tfunc.tf_expr in
  2650. let invokecf, invoke_field, super_args = match delegate_type with
  2651. | None -> (* no delegate *)
  2652. let ifield, sa = ft.closure_to_classfield { tfunc with tf_expr = func_expr } fexpr.etype fexpr.epos in
  2653. ifield,ifield,sa
  2654. | Some _ ->
  2655. let pos = cls.cl_pos in
  2656. let cf = mk_class_field "Delegate" (TFun(fun_args tfunc.tf_args, tfunc.tf_type)) true pos (Method MethNormal) [] in
  2657. cf.cf_expr <- Some { fexpr with eexpr = TFunction { tfunc with tf_expr = func_expr }; };
  2658. cf.cf_meta <- (Meta.Final,[],pos) :: cf.cf_meta;
  2659. cls.cl_ordered_fields <- cf :: cls.cl_ordered_fields;
  2660. cls.cl_fields <- PMap.add cf.cf_name cf cls.cl_fields;
  2661. (* invoke function body: call Delegate function *)
  2662. let ibody = {
  2663. eexpr = TCall({
  2664. eexpr = TField({
  2665. eexpr = TConst TThis;
  2666. etype = TInst(cls, List.map snd cls.cl_types);
  2667. epos = pos;
  2668. }, FInstance(cls, cf));
  2669. etype = cf.cf_type;
  2670. epos = pos;
  2671. }, List.map (fun (v,_) -> mk_local v pos) tfunc.tf_args);
  2672. etype = tfunc.tf_type;
  2673. epos = pos
  2674. } in
  2675. let ibody = if not (is_void tfunc.tf_type) then
  2676. { ibody with eexpr = TReturn( Some ibody ) }
  2677. else
  2678. ibody
  2679. in
  2680. let ifield, sa = ft.closure_to_classfield { tfunc with tf_expr = ibody } fexpr.etype fexpr.epos in
  2681. cf,ifield,sa
  2682. in
  2683. (* create the constructor *)
  2684. (* todo properly abstract how type var is set *)
  2685. cls.cl_super <- Some(parent_func_class, []);
  2686. let pos = cls.cl_pos in
  2687. let super_call =
  2688. {
  2689. eexpr = TCall({ eexpr = TConst(TSuper); etype = TInst(parent_func_class,[]); epos = pos }, super_args);
  2690. etype = ft.fgen.gcon.basic.tvoid;
  2691. epos = pos;
  2692. } in
  2693. let ctor_type = (TFun(ctor_sig, ft.fgen.gcon.basic.tvoid)) in
  2694. let ctor = mk_class_field "new" ctor_type true cls.cl_pos (Method(MethNormal)) [] in
  2695. ctor.cf_expr <- Some(
  2696. {
  2697. eexpr = TFunction(
  2698. {
  2699. tf_args = ctor_args;
  2700. tf_type = ft.fgen.gcon.basic.tvoid;
  2701. tf_expr = { eexpr = TBlock(super_call :: ctor_exprs); etype = ft.fgen.gcon.basic.tvoid; epos = cls.cl_pos }
  2702. });
  2703. etype = ctor_type;
  2704. epos = cls.cl_pos;
  2705. });
  2706. cls.cl_constructor <- Some(ctor);
  2707. (* add invoke function to the class *)
  2708. cls.cl_ordered_fields <- invoke_field :: cls.cl_ordered_fields;
  2709. cls.cl_fields <- PMap.add invoke_field.cf_name invoke_field cls.cl_fields;
  2710. cls.cl_overrides <- invoke_field :: cls.cl_overrides;
  2711. (* add this class to the module with gadd_to_module *)
  2712. ft.fgen.gadd_to_module (TClassDecl(cls)) priority;
  2713. (* if there are no captured variables, we can create a cache so subsequent calls don't need to create a new function *)
  2714. let expr, clscapt =
  2715. match captured, tparams with
  2716. | [], [] ->
  2717. let cache_var = ft.fgen.gmk_internal_name "hx" "current" in
  2718. let cache_cf = mk_class_field cache_var (TInst(cls,[])) false func_expr.epos (Var({ v_read = AccNormal; v_write = AccNormal })) [] in
  2719. cls.cl_ordered_statics <- cache_cf :: cls.cl_ordered_statics;
  2720. cls.cl_statics <- PMap.add cache_var cache_cf cls.cl_statics;
  2721. (* if (FuncClass.hx_current != null) FuncClass.hx_current; else (FuncClass.hx_current = new FuncClass()); *)
  2722. (* let mk_static_field_access cl field fieldt pos = *)
  2723. let hx_current = mk_static_field_access cls cache_var (TInst(cls,[])) func_expr.epos in
  2724. let pos = func_expr.epos in
  2725. { fexpr with
  2726. eexpr = TIf(
  2727. {
  2728. eexpr = TBinop(OpNotEq, hx_current, null (TInst(cls,[])) pos);
  2729. etype = ft.fgen.gcon.basic.tbool;
  2730. epos = pos;
  2731. },
  2732. hx_current,
  2733. Some(
  2734. {
  2735. eexpr = TBinop(OpAssign, hx_current, { fexpr with eexpr = TNew(cls, [], captured) });
  2736. etype = (TInst(cls,[]));
  2737. epos = pos;
  2738. }))
  2739. }, (cls,captured)
  2740. | _ ->
  2741. (* change the expression so it will be a new "added class" ( captured variables arguments ) *)
  2742. { fexpr with eexpr = TNew(cls, List.map (fun cl -> TInst(cl,[])) tparams, List.rev captured) }, (cls,captured)
  2743. in
  2744. match delegate_type with
  2745. | None ->
  2746. expr,clscapt
  2747. | Some _ ->
  2748. {
  2749. eexpr = TField(expr, FClosure(Some cls,invokecf));
  2750. etype = invokecf.cf_type;
  2751. epos = cls.cl_pos
  2752. }, clscapt
  2753. in
  2754. let tvar_to_cdecl = Hashtbl.create 0 in
  2755. traverse
  2756. ft.fgen
  2757. ~tparam_anon_decl:(fun v e fn ->
  2758. let _, info = handle_anon_func e fn None in
  2759. Hashtbl.add tvar_to_cdecl v.v_id info
  2760. )
  2761. ~tparam_anon_acc:(fun v e -> try
  2762. let cls, captured = Hashtbl.find tvar_to_cdecl v.v_id in
  2763. let types = match v.v_extra with
  2764. | Some(t,_) -> t
  2765. | _ -> assert false
  2766. in
  2767. let monos = List.map (fun _ -> mk_mono()) types in
  2768. let vt = match follow v.v_type with
  2769. | TInst(_, [v]) -> v
  2770. | v -> v
  2771. in
  2772. let et = match follow e.etype with
  2773. | TInst(_, [v]) -> v
  2774. | v -> v
  2775. in
  2776. let original = apply_params types monos vt in
  2777. unify et original;
  2778. let monos = List.map (fun t -> apply_params types (List.map (fun _ -> t_dynamic) types) t) monos in
  2779. let same_cl t1 t2 = match follow t1, follow t2 with
  2780. | TInst(c,_), TInst(c2,_) -> c == c2
  2781. | _ -> false
  2782. in
  2783. let passoc = List.map2 (fun (_,t) m -> t,m) types monos in
  2784. let cltparams = List.map (fun (_,t) ->
  2785. try
  2786. snd (List.find (fun (t2,_) -> same_cl t t2) passoc)
  2787. with | Not_found -> t) cls.cl_types
  2788. in
  2789. { e with eexpr = TNew(cls, cltparams, captured) }
  2790. with
  2791. | Not_found ->
  2792. gen.gcon.warning "This expression may be invalid" e.epos;
  2793. e
  2794. | Unify_error el ->
  2795. List.iter (fun el -> gen.gcon.warning (Typecore.unify_error_msg (print_context()) el) e.epos) el;
  2796. gen.gcon.warning "This expression may be invalid" e.epos;
  2797. e
  2798. )
  2799. (* (transform_closure:texpr->texpr->string->texpr) (handle_anon_func:texpr->tfunc->texpr) (dynamic_func_call:texpr->texpr->texpr list->texpr) *)
  2800. ft.transform_closure
  2801. (fun e f delegate_type -> fst (handle_anon_func e f delegate_type))
  2802. ft.dynamic_fun_call
  2803. (* (dynamic_func_call:texpr->texpr->texpr list->texpr) *)
  2804. let configure gen (mapping_func:texpr->texpr) =
  2805. let map e = Some(mapping_func e) in
  2806. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority) map
  2807. let configure_as_synf gen (mapping_func:texpr->texpr) =
  2808. let map e = Some(mapping_func e) in
  2809. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority_as_synf) map
  2810. (*
  2811. this submodule will provide the default implementation for the C# and Java targets.
  2812. it will have two return types: double and dynamic, and
  2813. *)
  2814. module DoubleAndDynamicClosureImpl =
  2815. struct
  2816. let get_ctx gen max_arity =
  2817. let basic = gen.gcon.basic in
  2818. let func_args_i i =
  2819. let rec loop i (acc) =
  2820. if i = 0 then (acc) else begin
  2821. let vfloat = alloc_var (gen.gmk_internal_name "fn" ("float" ^ string_of_int i)) basic.tfloat in
  2822. let vdyn = alloc_var (gen.gmk_internal_name "fn" ("dyn" ^ string_of_int i)) t_dynamic in
  2823. loop (i - 1) ((vfloat, None) :: (vdyn, None) :: acc)
  2824. end
  2825. in
  2826. loop i []
  2827. in
  2828. let args_real_to_func args =
  2829. let arity = List.length args in
  2830. if arity >= max_arity then
  2831. [ alloc_var (gen.gmk_internal_name "fn" "dynargs") (basic.tarray t_dynamic), None ]
  2832. else func_args_i arity
  2833. in
  2834. let func_sig_i i =
  2835. let rec loop i acc =
  2836. if i = 0 then acc else begin
  2837. let vfloat = gen.gmk_internal_name "fn" ("float" ^ string_of_int i) in
  2838. let vdyn = gen.gmk_internal_name "fn" ("dyn" ^ string_of_int i) in
  2839. loop (i - 1) ( (vfloat,false,basic.tfloat) :: (vdyn,false,t_dynamic) :: acc )
  2840. end
  2841. in
  2842. loop i []
  2843. in
  2844. let args_real_to_func_sig args =
  2845. let arity = List.length args in
  2846. if arity >= max_arity then
  2847. [gen.gmk_internal_name "fn" "dynargs", false, basic.tarray t_dynamic]
  2848. else begin
  2849. func_sig_i arity
  2850. end
  2851. in
  2852. let rettype_real_to_func t = match run_follow gen t with
  2853. | TType({ t_path = [],"Null" }, _) ->
  2854. 0,t_dynamic
  2855. | _ when like_float t ->
  2856. (1, basic.tfloat)
  2857. | _ ->
  2858. (0, t_dynamic)
  2859. in
  2860. let args_real_to_func_call el (pos:Ast.pos) =
  2861. if List.length el >= max_arity then
  2862. [{ eexpr = TArrayDecl el; etype = basic.tarray t_dynamic; epos = pos }]
  2863. else begin
  2864. List.fold_left (fun acc e ->
  2865. if like_float (gen.greal_type e.etype) then
  2866. ( e :: undefined e.epos :: acc )
  2867. else
  2868. ( null basic.tfloat e.epos :: e :: acc )
  2869. ) ([]) (List.rev el)
  2870. end
  2871. in
  2872. let const_type c def =
  2873. match c with
  2874. | TString _ -> basic.tstring | TInt _ -> basic.tint
  2875. | TFloat _ -> basic.tfloat | TBool _ -> basic.tbool
  2876. | _ -> def
  2877. in
  2878. let get_args_func args changed_args pos =
  2879. let arity = List.length args in
  2880. let mk_const const elocal t =
  2881. match const with
  2882. | None -> mk_cast t elocal
  2883. | Some const ->
  2884. { eexpr = TIf(
  2885. { elocal with eexpr = TBinop(Ast.OpEq, elocal, null elocal.etype elocal.epos); etype = basic.tbool },
  2886. { elocal with eexpr = TConst(const); etype = const_type const t },
  2887. Some ( mk_cast t elocal )
  2888. ); etype = t; epos = elocal.epos }
  2889. in
  2890. if arity >= max_arity then begin
  2891. let varray = match changed_args with | [v,_] -> v | _ -> assert false in
  2892. let varray_local = mk_local varray pos in
  2893. let mk_varray i = { eexpr = TArray(varray_local, { eexpr = TConst(TInt(Int32.of_int i)); etype = basic.tint; epos = pos }); etype = t_dynamic; epos = pos } in
  2894. snd (List.fold_left (fun (count,acc) (v,const) ->
  2895. (count + 1,
  2896. {
  2897. eexpr = TVar(v, Some(mk_const const ( mk_varray count ) v.v_type));
  2898. etype = basic.tvoid;
  2899. epos = pos;
  2900. } :: acc)
  2901. ) (0,[]) args)
  2902. end else begin
  2903. let _, dyn_args, float_args = List.fold_left (fun (count,fargs, dargs) arg ->
  2904. if count land 1 = 0 then
  2905. (count + 1, fargs, arg :: dargs)
  2906. else
  2907. (count + 1, arg :: fargs, dargs)
  2908. ) (1,[],[]) (List.rev changed_args) in
  2909. let rec loop acc args fargs dargs =
  2910. match args, fargs, dargs with
  2911. | [], [], [] -> acc
  2912. | (v,const) :: args, (vf,_) :: fargs, (vd,_) :: dargs ->
  2913. let acc = { eexpr = TVar(v, Some(
  2914. {
  2915. eexpr = TIf(
  2916. { eexpr = TBinop(Ast.OpEq, mk_local vd pos, undefined pos); etype = basic.tbool; epos = pos },
  2917. mk_cast v.v_type (mk_local vf pos),
  2918. Some ( mk_const const (mk_local vd pos) v.v_type )
  2919. );
  2920. etype = v.v_type;
  2921. epos = pos
  2922. } )); etype = basic.tvoid; epos = pos } :: acc in
  2923. loop acc args fargs dargs
  2924. | _ -> assert false
  2925. in
  2926. loop [] args float_args dyn_args
  2927. end
  2928. in
  2929. let closure_to_classfield tfunc old_sig pos =
  2930. (* change function signature *)
  2931. let old_args = tfunc.tf_args in
  2932. let changed_args = args_real_to_func old_args in
  2933. (*
  2934. FIXME properly handle int64 cases, which will break here (because of inference to int)
  2935. UPDATE: the fix will be that Int64 won't be a typedef to Float/Int
  2936. *)
  2937. let changed_sig, arity, type_number, changed_sig_ret, is_void, is_dynamic_func = match follow old_sig with
  2938. | TFun(_sig, ret) ->
  2939. let type_n, ret_t = rettype_real_to_func ret in
  2940. let arity = List.length _sig in
  2941. let is_dynamic_func = arity >= max_arity in
  2942. let ret_t = if is_dynamic_func then t_dynamic else ret_t in
  2943. (TFun(args_real_to_func_sig _sig, ret_t), arity, type_n, ret_t, is_void ret, is_dynamic_func)
  2944. | _ -> (print_endline (s_type (print_context()) (follow old_sig) )); assert false
  2945. in
  2946. let tf_expr = if is_void then begin
  2947. let rec map e =
  2948. match e.eexpr with
  2949. | TReturn None -> { e with eexpr = TReturn (Some (null t_dynamic e.epos)) }
  2950. | _ -> Type.map_expr map e
  2951. in
  2952. let e = mk_block (map tfunc.tf_expr) in
  2953. match e.eexpr with
  2954. | TBlock(bl) ->
  2955. { e with eexpr = TBlock(bl @ [{ eexpr = TReturn (Some (null t_dynamic e.epos)); etype = t_dynamic; epos = e.epos }]) }
  2956. | _ -> assert false
  2957. end else tfunc.tf_expr in
  2958. let changed_sig_ret = if is_dynamic_func then t_dynamic else changed_sig_ret in
  2959. (* get real arguments on top of function body *)
  2960. let get_args = get_args_func tfunc.tf_args changed_args pos in
  2961. (*
  2962. FIXME HACK: in order to be able to run the filters that have already ran for this piece of code,
  2963. we will cheat and run it as if it was the whole code
  2964. We could just make ClosuresToClass run before TArrayTransform, but we cannot because of the
  2965. dependency between ClosuresToClass (after DynamicFieldAccess, and before TArrayTransform)
  2966. maybe a way to solve this would be to add an "until" field to run_from
  2967. *)
  2968. let real_get_args = gen.gexpr_filters#run_f { eexpr = TBlock(get_args); etype = basic.tvoid; epos = pos } in
  2969. let func_expr = Type.concat real_get_args tf_expr in
  2970. (* set invoke function *)
  2971. (* todo properly abstract how naming for invoke is made *)
  2972. let invoke_name = if is_dynamic_func then "invokeDynamic" else ("invoke" ^ (string_of_int arity) ^ (if type_number = 0 then "_o" else "_f")) in
  2973. let invoke_name = gen.gmk_internal_name "hx" invoke_name in
  2974. let invoke_field = mk_class_field invoke_name changed_sig false func_expr.epos (Method(MethNormal)) [] in
  2975. let invoke_fun =
  2976. {
  2977. eexpr = TFunction(
  2978. {
  2979. tf_args = changed_args;
  2980. tf_type = changed_sig_ret;
  2981. tf_expr = func_expr;
  2982. });
  2983. etype = changed_sig;
  2984. epos = func_expr.epos;
  2985. } in
  2986. invoke_field.cf_expr <- Some(invoke_fun);
  2987. (invoke_field, [
  2988. { eexpr = TConst(TInt( Int32.of_int arity )); etype = gen.gcon.basic.tint; epos = pos };
  2989. { eexpr = TConst(TInt( Int32.of_int type_number )); etype = gen.gcon.basic.tint; epos = pos };
  2990. ])
  2991. in
  2992. let dynamic_fun_call call_expr =
  2993. let tc, params = match call_expr.eexpr with
  2994. | TCall(tc, params) -> (tc, params)
  2995. | _ -> assert false
  2996. in
  2997. let postfix, ret_t =
  2998. if like_float (gen.greal_type call_expr.etype) then
  2999. "_f", gen.gcon.basic.tfloat
  3000. else
  3001. "_o", t_dynamic
  3002. in
  3003. let params_len = List.length params in
  3004. let ret_t = if params_len >= max_arity then t_dynamic else ret_t in
  3005. let invoke_fun = if params_len >= max_arity then "invokeDynamic" else "invoke" ^ (string_of_int params_len) ^ postfix in
  3006. let invoke_fun = gen.gmk_internal_name "hx" invoke_fun in
  3007. let fun_t = match follow tc.etype with
  3008. | TFun(_sig, _) ->
  3009. TFun(args_real_to_func_sig _sig, ret_t)
  3010. | _ ->
  3011. let i = ref 0 in
  3012. let _sig = List.map (fun p -> let name = "arg" ^ (string_of_int !i) in incr i; (name,false,p.etype) ) params in
  3013. TFun(args_real_to_func_sig _sig, ret_t)
  3014. in
  3015. let may_cast = match follow call_expr.etype with
  3016. | TEnum({ e_path = ([], "Void")}, [])
  3017. | TAbstract ({ a_path = ([], "Void") },[]) -> (fun e -> e)
  3018. | _ -> mk_cast call_expr.etype
  3019. in
  3020. may_cast
  3021. {
  3022. eexpr = TCall(
  3023. { (mk_field_access gen { tc with etype = gen.greal_type tc.etype } invoke_fun tc.epos) with etype = fun_t },
  3024. args_real_to_func_call params call_expr.epos
  3025. );
  3026. etype = ret_t;
  3027. epos = call_expr.epos
  3028. }
  3029. in
  3030. let iname is_function i is_float =
  3031. let postfix = if is_float then "_f" else "_o" in
  3032. gen.gmk_internal_name "hx" ("invoke" ^ (if not is_function then "Field" else "") ^ string_of_int i) ^ postfix
  3033. in
  3034. let map_base_classfields cl is_function map_fn =
  3035. let pos = cl.cl_pos in
  3036. let this_t = TInst(cl,List.map snd cl.cl_types) in
  3037. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  3038. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  3039. let mk_invoke_i i is_float =
  3040. let cf = mk_class_field (iname is_function i is_float) (TFun(func_sig_i i, if is_float then basic.tfloat else t_dynamic)) false pos (Method MethNormal) [] in
  3041. cf
  3042. in
  3043. let type_name = gen.gmk_internal_name "fn" "type" in
  3044. let dynamic_arg = alloc_var (gen.gmk_internal_name "fn" "dynargs") (basic.tarray t_dynamic) in
  3045. let mk_invoke_complete_i i is_float =
  3046. (* let arity = i in *)
  3047. let args = func_args_i i in
  3048. (* api fn *)
  3049. (* only cast if needed *)
  3050. let mk_cast tto efrom = gen.ghandle_cast (gen.greal_type tto) (gen.greal_type efrom.etype) efrom in
  3051. let api i t const =
  3052. let vf, _ = List.nth args (i * 2) in
  3053. let vo, _ = List.nth args (i * 2 + 1) in
  3054. let needs_cast, is_float = match t, like_float t with
  3055. | TInst({ cl_path = ([], "Float") }, []), _
  3056. | TAbstract({ a_path = ([], "Float") },[]), _ -> false, true
  3057. | _, true -> true, true
  3058. | _ -> false,false
  3059. in
  3060. let olocal = mk_local vo pos in
  3061. let flocal = mk_local vf pos in
  3062. let get_from_obj e = match const with
  3063. | None -> mk_cast t e
  3064. | Some tc ->
  3065. {
  3066. eexpr = TIf(
  3067. { eexpr = TBinop(Ast.OpEq, olocal, null t_dynamic pos); etype = basic.tbool; epos = pos } ,
  3068. { eexpr = TConst(tc); etype = t; epos = pos },
  3069. Some (mk_cast t e)
  3070. );
  3071. etype = t;
  3072. epos = pos;
  3073. }
  3074. in
  3075. {
  3076. eexpr = TIf(
  3077. { eexpr = TBinop(Ast.OpEq, olocal, undefined pos); etype = basic.tbool; epos = pos },
  3078. (if needs_cast then mk_cast t flocal else flocal),
  3079. Some ( get_from_obj olocal )
  3080. );
  3081. etype = t;
  3082. epos = pos
  3083. }
  3084. in
  3085. (* end of api fn *)
  3086. let ret = if is_float then basic.tfloat else t_dynamic in
  3087. let added_args, fn_expr = map_fn i ret (List.map fst args) api in
  3088. let args = added_args @ args in
  3089. let t = TFun(fun_args args, ret) in
  3090. let tfunction =
  3091. {
  3092. eexpr = TFunction({
  3093. tf_args = args;
  3094. tf_type = ret;
  3095. tf_expr =
  3096. mk_block fn_expr
  3097. });
  3098. etype = t;
  3099. epos = pos;
  3100. }
  3101. in
  3102. let cf = mk_invoke_i i is_float in
  3103. cf.cf_expr <- Some tfunction;
  3104. cf
  3105. in
  3106. let rec loop i cfs =
  3107. if i < 0 then cfs else begin
  3108. (*let mk_invoke_complete_i i is_float =*)
  3109. (mk_invoke_complete_i i false) :: (mk_invoke_complete_i i true) :: (loop (i-1) cfs)
  3110. end
  3111. in
  3112. let cfs = loop max_arity [] in
  3113. let added_s_args, switch =
  3114. let api i t const =
  3115. match i with
  3116. | -1 ->
  3117. mk_local dynamic_arg pos
  3118. | _ ->
  3119. mk_cast t {
  3120. eexpr = TArray(
  3121. mk_local dynamic_arg pos,
  3122. { eexpr = TConst(TInt(Int32.of_int i)); etype = basic.tint; epos = pos });
  3123. etype = t;
  3124. epos = pos;
  3125. }
  3126. in
  3127. map_fn (-1) t_dynamic [dynamic_arg] api
  3128. in
  3129. let args = added_s_args @ [dynamic_arg, None] in
  3130. let dyn_t = TFun(fun_args args, t_dynamic) in
  3131. let dyn_cf = mk_class_field (gen.gmk_internal_name "hx" "invokeDynamic") dyn_t false pos (Method MethNormal) [] in
  3132. dyn_cf.cf_expr <-
  3133. Some {
  3134. eexpr = TFunction({
  3135. tf_args = args;
  3136. tf_type = t_dynamic;
  3137. tf_expr = mk_block switch
  3138. });
  3139. etype = dyn_t;
  3140. epos = pos;
  3141. };
  3142. let additional_cfs = if is_function then begin
  3143. let new_t = TFun(["arity", false, basic.tint; "type", false, basic.tint],basic.tvoid) in
  3144. let new_cf = mk_class_field "new" (new_t) true pos (Method MethNormal) [] in
  3145. let v_arity, v_type = alloc_var "arity" basic.tint, alloc_var "type" basic.tint in
  3146. let mk_assign v field = { eexpr = TBinop(Ast.OpAssign, mk_this field v.v_type, mk_local v pos); etype = v.v_type; epos = pos } in
  3147. let arity_name = gen.gmk_internal_name "hx" "arity" in
  3148. new_cf.cf_expr <-
  3149. Some {
  3150. eexpr = TFunction({
  3151. tf_args = [v_arity, None; v_type, None];
  3152. tf_type = basic.tvoid;
  3153. tf_expr =
  3154. {
  3155. eexpr = TBlock([
  3156. mk_assign v_type type_name;
  3157. mk_assign v_arity arity_name
  3158. ]);
  3159. etype = basic.tvoid;
  3160. epos = pos;
  3161. }
  3162. });
  3163. etype = new_t;
  3164. epos = pos;
  3165. }
  3166. ;
  3167. [
  3168. new_cf;
  3169. mk_class_field type_name basic.tint true pos (Var { v_read = AccNormal; v_write = AccNormal }) [];
  3170. mk_class_field arity_name basic.tint true pos (Var { v_read = AccNormal; v_write = AccNormal }) [];
  3171. ]
  3172. end else [] in
  3173. dyn_cf :: (additional_cfs @ cfs)
  3174. in
  3175. (* maybe another param for prefix *)
  3176. let get_base_classfields_for cl is_function mk_additional_args =
  3177. let pos = cl.cl_pos in
  3178. let this_t = TInst(cl,List.map snd cl.cl_types) in
  3179. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  3180. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  3181. let rec mk_dyn_call arity api =
  3182. let zero = { eexpr = TConst(TFloat("0.0")); etype = basic.tfloat; epos = pos } in
  3183. let rec loop i acc =
  3184. if i = 0 then acc else begin
  3185. let arr = api (i-1) t_dynamic None in
  3186. loop (i - 1) (zero :: arr :: acc)
  3187. end
  3188. in
  3189. loop arity ([])
  3190. in
  3191. let mk_invoke_switch i (api:(int->t->tconstant option->texpr)) =
  3192. let t = TFun(func_sig_i i,t_dynamic) in
  3193. (* case i: return this.invokeX_o(0, 0, 0, 0, 0, ... arg[0], args[1]....); *)
  3194. ( [{ eexpr = TConst(TInt(Int32.of_int i)); etype = basic.tint; epos = pos }],
  3195. {
  3196. eexpr = TReturn(Some( {
  3197. eexpr = TCall(mk_this (iname is_function i false) t, mk_dyn_call i api);
  3198. etype = t_dynamic;
  3199. epos = pos;
  3200. } ));
  3201. etype = t_dynamic;
  3202. epos = pos;
  3203. } )
  3204. in
  3205. let cl_t = TInst(cl,List.map snd cl.cl_types) in
  3206. let this = { eexpr = TConst(TThis); etype = cl_t; epos = pos } in
  3207. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  3208. let mk_int i = { eexpr = TConst(TInt ( Int32.of_int i)); etype = basic.tint; epos = pos } in
  3209. let mk_string s = { eexpr = TConst(TString s); etype = basic.tstring; epos = pos } in
  3210. (*
  3211. if it is the Function class, the base class fields will be
  3212. * hx::invokeX_d|o (where X is from 0 to max_arity) (args)
  3213. {
  3214. if (this.type == 0|1) return invokeX_o|d(args); else throw "Invalid number of arguments."
  3215. }
  3216. hx::invokeDynamic, which will work in the same way
  3217. new(arity, type)
  3218. {
  3219. if (type != 0 && type != 1) throw "Invalid type";
  3220. this.arity = arity;
  3221. this.type = type;
  3222. }
  3223. *)
  3224. let type_name = gen.gmk_internal_name "fn" "type" in
  3225. let mk_expr i is_float vars =
  3226. let name = if is_function then "invoke" else "invokeField" in
  3227. let look_ahead = alloc_var "lookAhead" basic.tbool in
  3228. let add_args = if not is_function then mk_additional_args() else [] in
  3229. let vars = if not is_function then (List.map fst add_args) @ (look_ahead :: vars) else vars in
  3230. let call_expr =
  3231. let call_t = TFun(List.map (fun v -> (v.v_name, false, v.v_type)) vars, if is_float then t_dynamic else basic.tfloat) in
  3232. {
  3233. eexpr = TCall(mk_this (gen.gmk_internal_name "hx" (name ^ (string_of_int i) ^ (if is_float then "_o" else "_f"))) call_t, List.map (fun v -> if v.v_id = look_ahead.v_id then ( { eexpr = TConst(TBool false); etype = basic.tbool; epos = pos } ) else mk_local v pos) vars );
  3234. etype = if is_float then t_dynamic else basic.tfloat;
  3235. epos = pos
  3236. }
  3237. in
  3238. (*let call_expr = if is_float then mk_cast basic.tfloat call_expr else call_expr in*)
  3239. let if_cond = if is_function then
  3240. { eexpr=TBinop(Ast.OpNotEq, mk_this type_name basic.tint, mk_int (if is_float then 0 else 1) ); etype = basic.tbool; epos = pos }
  3241. else
  3242. mk_local look_ahead pos
  3243. in
  3244. let if_expr = if is_function then
  3245. {
  3246. eexpr = TIf(if_cond,
  3247. { eexpr = TThrow(mk_string "Wrong number of arguments"); etype = basic.tstring; epos = pos },
  3248. Some( { eexpr = TReturn( Some( call_expr ) ); etype = call_expr.etype; epos = pos } )
  3249. );
  3250. etype = t_dynamic;
  3251. epos = pos;
  3252. }
  3253. else
  3254. {
  3255. eexpr = TIf(if_cond,
  3256. { eexpr = TReturn( Some( call_expr ) ); etype = call_expr.etype; epos = pos },
  3257. Some( { eexpr = TThrow(mk_string "Field not found or wrong number of arguments"); etype = basic.tstring; epos = pos } )
  3258. );
  3259. etype = t_dynamic;
  3260. epos = pos;
  3261. }
  3262. in
  3263. let args = if not is_function then (mk_additional_args()) @ [look_ahead, None] else [] in
  3264. (args, if_expr)
  3265. in
  3266. let arities_processed = Hashtbl.create 10 in
  3267. let max_arity = ref 0 in
  3268. let rec loop_cases api arity acc =
  3269. if arity < 0 then acc else
  3270. loop_cases api (arity - 1) (mk_invoke_switch arity api :: acc)
  3271. in
  3272. (* let rec loop goes here *)
  3273. let map_fn cur_arity fun_ret_type vars (api:(int->t->tconstant option->texpr)) =
  3274. let is_float = like_float fun_ret_type in
  3275. match cur_arity with
  3276. | -1 ->
  3277. let dynargs = api (-1) (t_dynamic) None in
  3278. let switch_cond = mk_field_access gen dynargs "length" pos in
  3279. let switch_cond = {
  3280. eexpr = TIf(
  3281. { eexpr = TBinop(Ast.OpEq, dynargs, null dynargs.etype pos); etype = basic.tbool; epos = pos; },
  3282. { eexpr = TConst(TInt(Int32.zero)); etype = basic.tint; epos = pos },
  3283. Some switch_cond);
  3284. etype = basic.tint;
  3285. epos = pos;
  3286. } in
  3287. let switch =
  3288. {
  3289. eexpr = TSwitch( switch_cond,
  3290. loop_cases api !max_arity [],
  3291. Some({ eexpr = TThrow(mk_string "Too many arguments"); etype = basic.tvoid; epos = pos; }) );
  3292. etype = basic.tvoid;
  3293. epos = pos;
  3294. } in
  3295. ( (if not is_function then mk_additional_args () else []), switch )
  3296. | _ ->
  3297. if not (Hashtbl.mem arities_processed cur_arity) then begin
  3298. Hashtbl.add arities_processed cur_arity true;
  3299. if cur_arity > !max_arity then max_arity := cur_arity
  3300. end;
  3301. mk_expr cur_arity is_float vars
  3302. in
  3303. map_base_classfields cl is_function map_fn
  3304. in
  3305. let initialize_base_class cl =
  3306. ()
  3307. in
  3308. {
  3309. fgen = gen;
  3310. func_class = null_class;
  3311. closure_to_classfield = closure_to_classfield;
  3312. dynamic_fun_call = dynamic_fun_call;
  3313. (*
  3314. called once so the implementation can make one of a time initializations in the base class
  3315. for all functions
  3316. *)
  3317. initialize_base_class = initialize_base_class;
  3318. (*
  3319. Base classfields are the class fields for the abstract implementation of either the Function implementation,
  3320. or the invokeField implementation for the classes
  3321. They will either try to call the right function or will fail with
  3322. (tclass - subject (so we know the type of this)) -> is_function_base -> list of the abstract implementation class fields
  3323. *)
  3324. get_base_classfields_for = get_base_classfields_for;
  3325. map_base_classfields = map_base_classfields;
  3326. (*
  3327. for now we won't deal with the closures.
  3328. They can be dealt with the module ReflectionCFs,
  3329. or a custom implementation
  3330. *)
  3331. transform_closure = (fun tclosure texpr str -> tclosure);
  3332. }
  3333. end;;
  3334. end;;
  3335. (* ******************************************* *)
  3336. (* Type Parameters *)
  3337. (* ******************************************* *)
  3338. (*
  3339. This module will handle type parameters. There are lots of changes we need to do to correctly support type parameters:
  3340. traverse will:
  3341. V Detect when parameterized function calls are made
  3342. * Detect when a parameterized class instance is being cast to another parameter
  3343. * Change new<> parameterized function calls
  3344. *
  3345. extras:
  3346. * On languages that support "real" type parameters, a Cast function is provided that will convert from a <Dynamic> to the requested type.
  3347. This cast will call createEmpty with the correct type, and then set each variable to the new form. Some types will be handled specially, namely the Native Array.
  3348. Other implementations may be delegated to the runtime.
  3349. * parameterized classes will implement a new interface (with only a Cast<> function added to it), so we can access the <Dynamic> type parameter for them. Also any reference to <Dynamic> will be replaced by a reference to this interface. (also on TTypeExpr - Std.is())
  3350. * Type parameter renaming to avoid name clash
  3351. * Detect type parameter casting and call Cast<> instead
  3352. for java:
  3353. * for specially assigned classes, parameters will be replaced by _d and _i versions of parameterized functions. This will only work for parameterized classes, not functions.
  3354. dependencies:
  3355. must run after casts are detected. This will be ensured at CastDetect module.
  3356. *)
  3357. module TypeParams =
  3358. struct
  3359. let name = "type_params"
  3360. let priority = max_dep -. 20.
  3361. (* this function will receive the original function argument, the applied function argument and the original function parameters. *)
  3362. (* from this info, it will infer the applied tparams for the function *)
  3363. (* this function is used by CastDetection module *)
  3364. let infer_params gen pos (original_args:((string * bool * t) list * t)) (applied_args:((string * bool * t) list * t)) (params:(string * t) list) calls_parameters_explicitly : tparams =
  3365. match params with
  3366. | [] -> []
  3367. | _ ->
  3368. let args_list args = (if not calls_parameters_explicitly then t_dynamic else snd args) :: (List.map (fun (n,o,t) -> t) (fst args)) in
  3369. let monos = List.map (fun _ -> mk_mono()) params in
  3370. let original = args_list (get_fun (apply_params params monos (TFun(fst original_args,snd original_args)))) in
  3371. let applied = args_list applied_args in
  3372. (try
  3373. List.iter2 (fun a o ->
  3374. unify a o
  3375. (* type_eq EqStrict a o *)
  3376. ) applied original
  3377. (* unify applied original *)
  3378. with | Unify_error el ->
  3379. (* List.iter (fun el -> gen.gcon.warning (Typecore.unify_error_msg (print_context()) el) pos) el; *)
  3380. gen.gcon.warning ("This expression may be invalid") pos
  3381. | Invalid_argument("List.map2") ->
  3382. gen.gcon.warning ("This expression may be invalid") pos
  3383. );
  3384. List.map (fun t ->
  3385. match follow t with
  3386. | TMono _ -> t_empty
  3387. | t -> t
  3388. ) monos
  3389. (* ******************************************* *)
  3390. (* Real Type Parameters Module *)
  3391. (* ******************************************* *)
  3392. (*
  3393. This submodule is by now specially made for the .NET platform. There might be other targets that will
  3394. make use of this, but it IS very specific.
  3395. On the .NET platform, generics are real specialized classes that are JIT compiled. For this reason, we cannot
  3396. cast from one type parameter to another. Also there is no common type for the type parameters, so for example
  3397. an instance of type Array<Int> will return false for instance is Array<object> .
  3398. So we need to:
  3399. 1. create a common interface (without type parameters) (e.g. "Array") which will only contain a __Cast<> function, which will cast from one type into another
  3400. 2. Implement the __Cast function. This part is a little hard, as we must identify all type parameter-dependent fields contained in the class and convert them.
  3401. In most cases the conversion will just be to call .__Cast<>() on the instances, or just a simple cast. But when the instance is a @:nativegen type, there will be no .__Cast
  3402. function, and we will need to deal with this case either at compile-time (added handlers - specially for NativeArray), or at runtime (adding new runtime handlers)
  3403. 3. traverse the AST looking for casts involving type parameters, and replace them with .__Cast<>() calls. If type is @:nativegen, throw a warning. If really casting from one type parameter to another on a @:nativegen context, throw an error.
  3404. special literals:
  3405. it will use the special literal __typehandle__ that the target must implement in order to run this. This literal is a way to get the typehandle of e.g. the type parameters,
  3406. so we can compare them. In C# it's the equivalent of typeof(T).TypeHandle (TypeHandle compare is faster than System.Type.Equals())
  3407. dependencies:
  3408. (module filter) Interface creation must run AFTER enums are converted into classes, otherwise there is no way to tell parameterized enums to implement an interface
  3409. Must run AFTER CastDetect. This will be ensured per CastDetect
  3410. *)
  3411. module RealTypeParams =
  3412. struct
  3413. let name = "real_type_params"
  3414. let priority = priority
  3415. let cast_field_name = "cast"
  3416. let rec has_type_params t =
  3417. match follow t with
  3418. | TInst( { cl_kind = KTypeParameter _ }, _) -> true
  3419. | TAbstract(_, params)
  3420. | TEnum(_, params)
  3421. | TInst(_, params) -> List.fold_left (fun acc t -> acc || has_type_params t) false params
  3422. | _ -> false
  3423. let is_hxgeneric = function
  3424. | TClassDecl(cl) ->
  3425. not (Meta.has Meta.NativeGeneric cl.cl_meta)
  3426. | TEnumDecl(e) ->
  3427. not (Meta.has Meta.NativeGeneric e.e_meta)
  3428. | TTypeDecl(t) ->
  3429. not (Meta.has Meta.NativeGeneric t.t_meta)
  3430. | TAbstractDecl a ->
  3431. not (Meta.has Meta.NativeGeneric a.a_meta)
  3432. let rec set_hxgeneric gen mds isfirst md =
  3433. let path = t_path md in
  3434. if List.exists (fun m -> path = t_path m) mds then begin
  3435. if isfirst then
  3436. None (* we still can't determine *)
  3437. else
  3438. Some true (* if we're in second pass and still can't determine, it's because it can be hxgeneric *)
  3439. end else begin
  3440. let has_unresolved = ref false in
  3441. let is_false v =
  3442. match v with
  3443. | Some false -> true
  3444. | None -> has_unresolved := true; false
  3445. | Some true -> false
  3446. in
  3447. let mds = md :: mds in
  3448. match md with
  3449. | TClassDecl(cl) ->
  3450. (* first see if any meta is present (already processed) *)
  3451. if Meta.has Meta.NativeGeneric cl.cl_meta then
  3452. Some false
  3453. else if Meta.has Meta.HaxeGeneric cl.cl_meta then
  3454. Some true
  3455. else if not (is_hxgen md) then
  3456. (cl.cl_meta <- (Meta.NativeGeneric, [], cl.cl_pos) :: cl.cl_meta;
  3457. Some false)
  3458. else begin
  3459. (*
  3460. if it's not present, see if any superclass is nativegeneric.
  3461. nativegeneric is inherited, while hxgeneric can be later changed to nativegeneric
  3462. *)
  3463. (* on the first pass, our job is to find any evidence that makes it not be hxgeneric. Otherwise it will be hxgeneric *)
  3464. match cl.cl_super with
  3465. | Some (c,_) when is_false (set_hxgeneric gen mds isfirst (TClassDecl c)) ->
  3466. cl.cl_meta <- (Meta.NativeGeneric, [], cl.cl_pos) :: cl.cl_meta;
  3467. Some false
  3468. | _ ->
  3469. (* see if it's a generic class *)
  3470. match cl.cl_types with
  3471. | [] ->
  3472. (* if it's not, then it will be hxgeneric *)
  3473. cl.cl_meta <- (Meta.HaxeGeneric, [], cl.cl_pos) :: cl.cl_meta;
  3474. Some true
  3475. | _ ->
  3476. (* if it is, loop through all fields + statics and look for non-hxgeneric
  3477. generic classes that have KTypeParameter as params *)
  3478. let rec loop cfs =
  3479. match cfs with
  3480. | [] -> false
  3481. | cf :: cfs ->
  3482. let t = follow (gen.greal_type cf.cf_type) in
  3483. match t with
  3484. | TInst( { cl_kind = KTypeParameter _ }, _ ) -> loop cfs
  3485. | TInst(cl,p) when has_type_params t && is_false (set_hxgeneric gen mds isfirst (TClassDecl cl)) ->
  3486. if not (Hashtbl.mem gen.gtparam_cast cl.cl_path) then true else loop cfs
  3487. | TEnum(e,p) when has_type_params t && is_false (set_hxgeneric gen mds isfirst (TEnumDecl e)) ->
  3488. if not (Hashtbl.mem gen.gtparam_cast e.e_path) then true else loop cfs
  3489. | _ -> loop cfs (* TAbstracts / Dynamics can't be generic *)
  3490. in
  3491. if loop cl.cl_ordered_fields then begin
  3492. cl.cl_meta <- (Meta.NativeGeneric, [], cl.cl_pos) :: cl.cl_meta;
  3493. Some false
  3494. end else if isfirst && !has_unresolved then
  3495. None
  3496. else begin
  3497. cl.cl_meta <- (Meta.HaxeGeneric, [], cl.cl_pos) :: cl.cl_meta;
  3498. Some true
  3499. end
  3500. end
  3501. | TEnumDecl e ->
  3502. if Meta.has Meta.NativeGeneric e.e_meta then
  3503. Some false
  3504. else if Meta.has Meta.HaxeGeneric e.e_meta then
  3505. Some true
  3506. else if not (is_hxgen (TEnumDecl e)) then begin
  3507. e.e_meta <- (Meta.NativeGeneric, [], e.e_pos) :: e.e_meta;
  3508. Some false
  3509. end else begin
  3510. (* if enum is not generic, then it's hxgeneric *)
  3511. match e.e_types with
  3512. | [] ->
  3513. e.e_meta <- (Meta.HaxeGeneric, [], e.e_pos) :: e.e_meta;
  3514. Some true
  3515. | _ ->
  3516. let rec loop efs =
  3517. match efs with
  3518. | [] -> false
  3519. | ef :: efs ->
  3520. let t = follow (gen.greal_type ef.ef_type) in
  3521. match t with
  3522. | TFun(args, _) ->
  3523. if List.exists (fun (n,o,t) ->
  3524. let t = follow t in
  3525. match t with
  3526. | TInst( { cl_kind = KTypeParameter _ }, _ ) ->
  3527. false
  3528. | TInst(cl,p) when has_type_params t && is_false (set_hxgeneric gen mds isfirst (TClassDecl cl)) ->
  3529. not (Hashtbl.mem gen.gtparam_cast cl.cl_path)
  3530. | TEnum(e,p) when has_type_params t && is_false (set_hxgeneric gen mds isfirst (TEnumDecl e)) ->
  3531. not (Hashtbl.mem gen.gtparam_cast e.e_path)
  3532. | _ -> false
  3533. ) args then
  3534. true
  3535. else
  3536. loop efs
  3537. | _ -> loop efs
  3538. in
  3539. let efs = PMap.fold (fun ef acc -> ef :: acc) e.e_constrs [] in
  3540. if loop efs then begin
  3541. e.e_meta <- (Meta.NativeGeneric, [], e.e_pos) :: e.e_meta;
  3542. Some false
  3543. end else if isfirst && !has_unresolved then
  3544. None
  3545. else begin
  3546. e.e_meta <- (Meta.HaxeGeneric, [], e.e_pos) :: e.e_meta;
  3547. Some true
  3548. end
  3549. end
  3550. | _ -> assert false
  3551. end
  3552. let set_hxgeneric gen md =
  3553. match set_hxgeneric gen [] true md with
  3554. | None ->
  3555. get (set_hxgeneric gen [] false md)
  3556. | Some v -> v
  3557. let params_has_tparams params =
  3558. List.fold_left (fun acc t -> acc || has_type_params t) false params
  3559. (* ******************************************* *)
  3560. (* RealTypeParamsModf *)
  3561. (* ******************************************* *)
  3562. (*
  3563. This is the module filter of Real Type Parameters. It will traverse through all types and look for hxgeneric classes (only classes).
  3564. When found, a parameterless interface will be created and associated via the "ifaces" Hashtbl to the original class.
  3565. Also a "cast" function will be automatically generated which will handle unsafe downcasts to more specific type parameters (necessary for serialization)
  3566. dependencies:
  3567. Anything that may create hxgeneric classes must run before it.
  3568. Should run before ReflectionCFs (this dependency will be added to ReflectionCFs), so the added interfaces also get to be real IHxObject's
  3569. *)
  3570. module RealTypeParamsModf =
  3571. struct
  3572. let name = "real_type_params_modf"
  3573. let priority = solve_deps name []
  3574. let rec get_fields gen cl params_cl params_cf acc =
  3575. let fields = List.fold_left (fun acc cf ->
  3576. match follow (gen.greal_type (gen.gfollow#run_f (cf.cf_type))) with
  3577. | TInst(cli, ((_ :: _) as p)) when (not (is_hxgeneric (TClassDecl cli))) && params_has_tparams p ->
  3578. (cf, apply_params cl.cl_types params_cl cf.cf_type, apply_params cl.cl_types params_cf cf.cf_type) :: acc
  3579. | TEnum(e, ((_ :: _) as p)) when not (is_hxgeneric (TEnumDecl e)) && params_has_tparams p ->
  3580. (cf, apply_params cl.cl_types params_cl cf.cf_type, apply_params cl.cl_types params_cf cf.cf_type) :: acc
  3581. | _ -> acc
  3582. ) [] cl.cl_ordered_fields in
  3583. match cl.cl_super with
  3584. | Some(cs, tls) ->
  3585. get_fields gen cs (List.map (apply_params cl.cl_types params_cl) tls) (List.map (apply_params cl.cl_types params_cf) tls) (fields @ acc)
  3586. | None -> (fields @ acc)
  3587. (* overrides all needed cast functions from super classes / interfaces to call the new cast function *)
  3588. let create_stub_casts gen cl cast_cfield =
  3589. (* go through superclasses and interfaces *)
  3590. let p = cl.cl_pos in
  3591. let this = { eexpr = TConst TThis; etype = (TInst(cl, List.map snd cl.cl_types)); epos = p } in
  3592. let rec loop cls tls level reverse_params =
  3593. if (level <> 0 || cls.cl_interface) && tls <> [] && is_hxgeneric (TClassDecl cls) then begin
  3594. let cparams = List.map (fun (s,t) -> (s, TInst (map_param (get_cl_t t), []))) cls.cl_types in
  3595. let name = String.concat "_" ((fst cls.cl_path) @ [snd cls.cl_path; cast_field_name]) in
  3596. if not (PMap.mem name cl.cl_fields) then begin
  3597. let reverse_params = List.map (apply_params cls.cl_types (List.map snd cparams)) reverse_params in
  3598. let cfield = mk_class_field name (TFun([], t_dynamic)) false cl.cl_pos (Method MethNormal) cparams in
  3599. let field = { eexpr = TField(this, FInstance(cl,cast_cfield)); etype = apply_params cast_cfield.cf_params reverse_params cast_cfield.cf_type; epos = p } in
  3600. let call =
  3601. {
  3602. eexpr = TCall(field, []);
  3603. etype = t_dynamic;
  3604. epos = p;
  3605. } in
  3606. let call = gen.gparam_func_call call field reverse_params [] in
  3607. let delay () =
  3608. cfield.cf_expr <-
  3609. Some {
  3610. eexpr = TFunction(
  3611. {
  3612. tf_args = [];
  3613. tf_type = t_dynamic;
  3614. tf_expr =
  3615. {
  3616. eexpr = TReturn( Some call );
  3617. etype = t_dynamic;
  3618. epos = p;
  3619. }
  3620. });
  3621. etype = cfield.cf_type;
  3622. epos = p;
  3623. }
  3624. in
  3625. gen.gafter_filters_ended <- delay :: gen.gafter_filters_ended; (* do not let filters alter this expression content *)
  3626. cl.cl_ordered_fields <- cfield :: cl.cl_ordered_fields;
  3627. cl.cl_fields <- PMap.add cfield.cf_name cfield cl.cl_fields;
  3628. if level <> 0 then cl.cl_overrides <- cfield :: cl.cl_overrides
  3629. end
  3630. end;
  3631. let get_reverse super supertl =
  3632. let kv = List.map2 (fun (_,tparam) applied -> (follow applied, follow tparam)) super.cl_types supertl in
  3633. List.map (fun t ->
  3634. try
  3635. List.assq (follow t) kv
  3636. with | Not_found -> t
  3637. ) reverse_params
  3638. in
  3639. (match cls.cl_super with
  3640. | None -> ()
  3641. | Some(super, supertl) ->
  3642. loop super supertl (level + 1) (get_reverse super supertl));
  3643. List.iter (fun (iface, ifacetl) ->
  3644. loop iface ifacetl level (get_reverse iface ifacetl)
  3645. ) cls.cl_implements
  3646. in
  3647. loop cl (List.map snd cl.cl_types) 0 (List.map snd cl.cl_types)
  3648. (*
  3649. Creates a cast classfield, with the desired name
  3650. Will also look for previous cast() definitions and override them, to reflect the current type and fields
  3651. FIXME: this function still doesn't support generics that extend generics, and are cast as one of its subclasses. This needs to be taken care, by
  3652. looking at previous superclasses and whenever a generic class is found, its cast argument must be overriden. the toughest part is to know how to type
  3653. the current type correctly.
  3654. *)
  3655. let create_cast_cfield gen cl name =
  3656. let basic = gen.gcon.basic in
  3657. let cparams = List.map (fun (s,t) -> (s, TInst (map_param (get_cl_t t), []))) cl.cl_types in
  3658. let cfield = mk_class_field name (TFun([], t_dynamic)) false cl.cl_pos (Method MethNormal) cparams in
  3659. let params = List.map snd cparams in
  3660. let fields = get_fields gen cl (List.map snd cl.cl_types) params [] in
  3661. (* now create the contents of the function *)
  3662. (*
  3663. it will look something like:
  3664. if (typeof(T) == typeof(T2)) return this;
  3665. var new_me = new CurrentClass<T2>(EmptyInstnace);
  3666. for (field in Reflect.fields(this))
  3667. {
  3668. switch(field)
  3669. {
  3670. case "aNativeArray":
  3671. var newArray = new NativeArray(this.aNativeArray.Length);
  3672. default:
  3673. Reflect.setField(new_me, field, Reflect.field(this, field));
  3674. }
  3675. }
  3676. *)
  3677. let new_t = TInst(cl, params) in
  3678. let pos = cl.cl_pos in
  3679. let new_me_var = alloc_var "new_me" new_t in
  3680. let local_new_me = { eexpr = TLocal(new_me_var); etype = new_t; epos = pos } in
  3681. let this = { eexpr = TConst(TThis); etype = (TInst(cl, List.map snd cl.cl_types)); epos = pos } in
  3682. let field_var = alloc_var "field" gen.gcon.basic.tstring in
  3683. let local_field = { eexpr = TLocal(field_var); etype = field_var.v_type; epos = pos } in
  3684. let get_path t =
  3685. match follow t with
  3686. | TInst(cl,_) -> cl.cl_path
  3687. | TEnum(e,_) -> e.e_path
  3688. | TAbstract(a,_) -> a.a_path
  3689. | TMono _
  3690. | TDynamic _ -> ([], "Dynamic")
  3691. | _ -> assert false
  3692. in
  3693. (* this will take all fields that were *)
  3694. let fields_to_cases fields =
  3695. List.map (fun (cf, t_cl, t_cf) ->
  3696. let this_field = { eexpr = TField(this, FInstance(cl, cf)); etype = t_cl; epos = pos } in
  3697. let expr =
  3698. {
  3699. eexpr = TBinop(OpAssign, { eexpr = TField(local_new_me, FInstance(cl, cf) ); etype = t_cf; epos = pos },
  3700. try (Hashtbl.find gen.gtparam_cast (get_path t_cf)) this_field t_cf with | Not_found -> (* if not found tparam cast, it shouldn't be a valid hxgeneric *) assert false
  3701. );
  3702. etype = t_cf;
  3703. epos = pos;
  3704. } in
  3705. ([{ eexpr = TConst(TString(cf.cf_name)); etype = gen.gcon.basic.tstring; epos = pos }], expr)
  3706. ) fields
  3707. in
  3708. let mk_typehandle =
  3709. let thandle = alloc_var "__typeof__" t_dynamic in
  3710. (fun cl -> { eexpr = TCall(mk_local thandle pos, [ mk_classtype_access cl pos ]); etype = t_dynamic; epos = pos })
  3711. in
  3712. let mk_eq cl1 cl2 =
  3713. { eexpr = TBinop(Ast.OpEq, mk_typehandle cl1, mk_typehandle cl2); etype = basic.tbool; epos = pos }
  3714. in
  3715. let rec mk_typehandle_cond thisparams cfparams =
  3716. match thisparams, cfparams with
  3717. | TInst(cl_this,[]) :: [], TInst(cl_cf,[]) :: [] ->
  3718. mk_eq cl_this cl_cf
  3719. | TInst(cl_this,[]) :: hd, TInst(cl_cf,[]) :: hd2 ->
  3720. { eexpr = TBinop(Ast.OpBoolAnd, mk_eq cl_this cl_cf, mk_typehandle_cond hd hd2); etype = basic.tbool; epos = pos }
  3721. | v :: hd, v2 :: hd2 ->
  3722. (match follow v, follow v2 with
  3723. | (TInst(cl1,[]) as v), (TInst(cl2,[]) as v2) ->
  3724. mk_typehandle_cond (v :: hd) (v2 :: hd2)
  3725. | _ ->
  3726. assert false
  3727. )
  3728. | _ -> assert false
  3729. in
  3730. let ref_fields = gen.gtools.r_fields true this in
  3731. let fn =
  3732. {
  3733. tf_args = [];
  3734. tf_type = t_dynamic;
  3735. tf_expr =
  3736. {
  3737. eexpr = TBlock([
  3738. (* if (typeof(T) == typeof(T2)) return this *)
  3739. {
  3740. eexpr = TIf(
  3741. mk_typehandle_cond (List.map snd cl.cl_types) params,
  3742. mk_return this,
  3743. None);
  3744. etype = basic.tvoid;
  3745. epos = pos;
  3746. };
  3747. (* var new_me = /*special create empty with tparams construct*/ *)
  3748. { eexpr = TVar(new_me_var, Some(
  3749. gen.gtools.rf_create_empty cl params pos
  3750. )); etype = gen.gcon.basic.tvoid; epos = pos };
  3751. { eexpr = TFor( (* for (field in Reflect.fields(this)) *)
  3752. field_var,
  3753. mk_iterator_access gen gen.gcon.basic.tstring ref_fields,
  3754. (* { *)
  3755. (* switch(field) *)
  3756. {
  3757. eexpr = TSwitch(local_field, fields_to_cases fields, Some(
  3758. (* default: Reflect.setField(new_me, field, Reflect.field(this, field)) *)
  3759. gen.gtools.r_set_field (gen.gcon.basic.tvoid) local_new_me local_field (gen.gtools.r_field false t_dynamic this local_field)
  3760. ));
  3761. etype = t_dynamic;
  3762. epos = pos;
  3763. }
  3764. (* } *)
  3765. ); etype = t_dynamic; epos = pos };
  3766. (* return new_me *)
  3767. mk_return (mk_local new_me_var pos)
  3768. ]);
  3769. etype = t_dynamic;
  3770. epos = pos;
  3771. };
  3772. }
  3773. in
  3774. cfield.cf_expr <- Some( { eexpr = TFunction(fn); etype = cfield.cf_type; epos = pos } );
  3775. cfield
  3776. let create_static_cast_cf gen iface cf =
  3777. let p = iface.cl_pos in
  3778. let basic = gen.gcon.basic in
  3779. let cparams = List.map (fun (s,t) -> ("To_" ^ s, TInst (map_param (get_cl_t t), []))) cf.cf_params in
  3780. let me_type = TInst(iface,[]) in
  3781. let cfield = mk_class_field "__hx_cast" (TFun(["me",false,me_type], t_dynamic)) false iface.cl_pos (Method MethNormal) (cparams) in
  3782. let params = List.map snd cparams in
  3783. let me = alloc_var "me" me_type in
  3784. let field = { eexpr = TField(mk_local me p, FInstance(iface,cf)); etype = apply_params cf.cf_params params cf.cf_type; epos = p } in
  3785. let call =
  3786. {
  3787. eexpr = TCall(field, []);
  3788. etype = t_dynamic;
  3789. epos = p;
  3790. } in
  3791. let call = gen.gparam_func_call call field params [] in
  3792. (* since object.someCall<ExplicitParameterDefinition>() isn't allowed on Haxe, we need to directly apply the params and delay this call *)
  3793. let delay () =
  3794. cfield.cf_expr <-
  3795. Some {
  3796. eexpr = TFunction(
  3797. {
  3798. tf_args = [me,None];
  3799. tf_type = t_dynamic;
  3800. tf_expr =
  3801. {
  3802. eexpr = TReturn( Some
  3803. {
  3804. eexpr = TIf(
  3805. { eexpr = TBinop(Ast.OpNotEq, mk_local me p, null me.v_type p); etype = basic.tbool; epos = p },
  3806. call,
  3807. Some( null me.v_type p )
  3808. );
  3809. etype = t_dynamic;
  3810. epos = p;
  3811. });
  3812. etype = basic.tvoid;
  3813. epos = p;
  3814. }
  3815. });
  3816. etype = cfield.cf_type;
  3817. epos = p;
  3818. }
  3819. in
  3820. cfield, delay
  3821. let get_cast_name cl = String.concat "_" ((fst cl.cl_path) @ [snd cl.cl_path; cast_field_name]) (* explicitly define it *)
  3822. let default_implementation gen ifaces base_generic =
  3823. let add_iface cl =
  3824. gen.gadd_to_module (TClassDecl cl) (max_dep);
  3825. in
  3826. let implement_stub_cast cthis iface tl =
  3827. let name = get_cast_name iface in
  3828. if not (PMap.mem name cthis.cl_fields) then begin
  3829. let cparams = List.map (fun (s,t) -> ("To_" ^ s, TInst(map_param (get_cl_t t), []))) iface.cl_types in
  3830. let field = mk_class_field name (TFun([],t_dynamic)) false iface.cl_pos (Method MethNormal) cparams in
  3831. let this = { eexpr = TConst TThis; etype = TInst(cthis, List.map snd cthis.cl_types); epos = cthis.cl_pos } in
  3832. field.cf_expr <- Some {
  3833. etype = TFun([],t_dynamic);
  3834. epos = this.epos;
  3835. eexpr = TFunction {
  3836. tf_type = t_dynamic;
  3837. tf_args = [];
  3838. tf_expr = mk_block { this with
  3839. eexpr = TReturn (Some this)
  3840. }
  3841. }
  3842. };
  3843. cthis.cl_ordered_fields <- field :: cthis.cl_ordered_fields;
  3844. cthis.cl_fields <- PMap.add name field cthis.cl_fields
  3845. end
  3846. in
  3847. let rec run md =
  3848. match md with
  3849. | TClassDecl ({ cl_extern = false; cl_types = [] } as cl) ->
  3850. (* see if we're implementing any generic interface *)
  3851. let rec check (iface,tl) =
  3852. if tl <> [] && set_hxgeneric gen (TClassDecl iface) then
  3853. (* implement cast stub *)
  3854. implement_stub_cast cl iface tl;
  3855. List.iter (fun (s,stl) -> check (s, List.map (apply_params iface.cl_types tl) stl)) iface.cl_implements;
  3856. in
  3857. List.iter (check) cl.cl_implements;
  3858. md
  3859. | TClassDecl ({ cl_extern = false; cl_types = hd :: tl } as cl) when set_hxgeneric gen md ->
  3860. let iface = mk_class cl.cl_module cl.cl_path cl.cl_pos in
  3861. iface.cl_array_access <- Option.map (apply_params (cl.cl_types) (List.map (fun _ -> t_dynamic) cl.cl_types)) cl.cl_array_access;
  3862. iface.cl_module <- cl.cl_module;
  3863. iface.cl_meta <- (Meta.HxGen, [], cl.cl_pos) :: iface.cl_meta;
  3864. Hashtbl.add ifaces cl.cl_path iface;
  3865. iface.cl_implements <- (base_generic, []) :: iface.cl_implements;
  3866. iface.cl_interface <- true;
  3867. cl.cl_implements <- (iface, []) :: cl.cl_implements;
  3868. let name = get_cast_name cl in
  3869. let cast_cf = create_cast_cfield gen cl name in
  3870. if not cl.cl_interface then create_stub_casts gen cl cast_cf;
  3871. let rec loop c = match c.cl_super with
  3872. | None -> ()
  3873. | Some(sup,_) -> try
  3874. let siface = Hashtbl.find ifaces sup.cl_path in
  3875. iface.cl_implements <- (siface,[]) :: iface.cl_implements;
  3876. ()
  3877. with | Not_found -> loop sup
  3878. in
  3879. loop cl;
  3880. (if not cl.cl_interface then cl.cl_ordered_fields <- cast_cf :: cl.cl_ordered_fields);
  3881. let iface_cf = mk_class_field name cast_cf.cf_type false cast_cf.cf_pos (Method MethNormal) cast_cf.cf_params in
  3882. let cast_static_cf, delay = create_static_cast_cf gen iface iface_cf in
  3883. cl.cl_ordered_statics <- cast_static_cf :: cl.cl_ordered_statics;
  3884. cl.cl_statics <- PMap.add cast_static_cf.cf_name cast_static_cf cl.cl_statics;
  3885. gen.gafter_filters_ended <- delay :: gen.gafter_filters_ended; (* do not let filters alter this expression content *)
  3886. iface_cf.cf_type <- cast_cf.cf_type;
  3887. iface.cl_fields <- PMap.add name iface_cf iface.cl_fields;
  3888. iface.cl_ordered_fields <- [iface_cf];
  3889. add_iface iface;
  3890. md
  3891. | TTypeDecl _ | TAbstractDecl _ -> md
  3892. | TEnumDecl _ ->
  3893. ignore (set_hxgeneric gen md);
  3894. md
  3895. | _ -> ignore (set_hxgeneric gen md); md
  3896. in
  3897. run
  3898. let configure gen mapping_func =
  3899. let map e = Some(mapping_func e) in
  3900. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  3901. end;;
  3902. (* create a common interface without type parameters and only a __Cast<> function *)
  3903. let default_implementation gen (dyn_tparam_cast:texpr->t->texpr) ifaces =
  3904. let change_expr e cl iface params =
  3905. let field = mk_static_field_access_infer cl "__hx_cast" e.epos params in
  3906. let elist = [mk_cast (TInst(iface,[])) e] in
  3907. let call = { eexpr = TCall(field, elist); etype = t_dynamic; epos = e.epos } in
  3908. gen.gparam_func_call call field params elist
  3909. in
  3910. let rec run e =
  3911. match e.eexpr with
  3912. | TCast(cast_expr, _) ->
  3913. (* see if casting to a native generic class *)
  3914. let t = gen.greal_type e.etype in
  3915. let unifies =
  3916. let ctype = gen.greal_type cast_expr.etype in
  3917. match follow ctype with
  3918. | TInst(cl,_) -> (try
  3919. unify ctype t;
  3920. true
  3921. with | Unify_error el ->
  3922. false)
  3923. | _ -> false
  3924. in
  3925. let unifies = unifies && not (PMap.mem "cs_safe_casts" gen.gcon.defines) in
  3926. (match follow t with
  3927. | TInst(cl, p1 :: pl) when is_hxgeneric (TClassDecl cl) && not unifies ->
  3928. let iface = Hashtbl.find ifaces cl.cl_path in
  3929. mk_cast e.etype (change_expr (Type.map_expr run cast_expr) cl iface (p1 :: pl))
  3930. | _ -> Type.map_expr run e
  3931. )
  3932. | _ -> Type.map_expr run e
  3933. in
  3934. run
  3935. let configure gen traverse =
  3936. gen.ghas_tparam_cast_handler <- true;
  3937. let map e = Some(traverse e) in
  3938. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  3939. let default_config gen (dyn_tparam_cast:texpr->t->texpr) ifaces base_generic =
  3940. configure gen (default_implementation gen dyn_tparam_cast ifaces);
  3941. RealTypeParamsModf.configure gen (RealTypeParamsModf.default_implementation gen ifaces base_generic)
  3942. end;;
  3943. (* ******************************************* *)
  3944. (* Rename Type Parameters *)
  3945. (* ******************************************* *)
  3946. (*
  3947. This module should run after everything is already applied,
  3948. it will look for possible type parameter name clashing and change the classes names to a
  3949. dependencies:
  3950. should run after everything is already applied. There's no configure on this module, only 'run'.
  3951. *)
  3952. module RenameTypeParameters =
  3953. struct
  3954. let name = "rename_type_parameters"
  3955. let run gen =
  3956. let i = ref 0 in
  3957. let found_types = ref PMap.empty in
  3958. let check_type name on_changed =
  3959. let rec loop name =
  3960. incr i;
  3961. let changed_name = (name ^ (string_of_int !i)) in
  3962. if PMap.mem changed_name !found_types then loop name else changed_name
  3963. in
  3964. if PMap.mem name !found_types then begin
  3965. let new_name = loop name in
  3966. found_types := PMap.add new_name true !found_types;
  3967. on_changed new_name
  3968. end else found_types := PMap.add name true !found_types
  3969. in
  3970. let get_cls t =
  3971. match follow t with
  3972. | TInst(cl,_) -> cl
  3973. | _ -> assert false
  3974. in
  3975. let iter_types (_,t) =
  3976. let cls = get_cls t in
  3977. check_type (snd cls.cl_path) (fun name -> cls.cl_path <- (fst cls.cl_path, name))
  3978. in
  3979. List.iter (function
  3980. | TClassDecl cl ->
  3981. i := 0;
  3982. found_types := PMap.empty;
  3983. List.iter iter_types cl.cl_types;
  3984. let cur_found_types = !found_types in
  3985. List.iter (fun cf ->
  3986. found_types := cur_found_types;
  3987. List.iter iter_types cf.cf_params
  3988. ) (cl.cl_ordered_fields @ cl.cl_ordered_statics)
  3989. | TEnumDecl ( ({ e_types = hd :: tl }) ) ->
  3990. i := 0;
  3991. found_types := PMap.empty;
  3992. List.iter iter_types (hd :: tl)
  3993. | TAbstractDecl { a_types = hd :: tl } ->
  3994. i := 0;
  3995. found_types := PMap.empty;
  3996. List.iter iter_types (hd :: tl)
  3997. | _ -> ()
  3998. ) gen.gcon.types
  3999. end;;
  4000. let configure gen (param_func_call:texpr->texpr->tparams->texpr list->texpr) =
  4001. (*let map e = Some(mapping_func e) in
  4002. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority) map*)
  4003. gen.gparam_func_call <- param_func_call
  4004. end;;
  4005. (**************************************************************************************************************************)
  4006. (* SYNTAX FILTERS *)
  4007. (**************************************************************************************************************************)
  4008. (* ******************************************* *)
  4009. (* Expression Unwrap *)
  4010. (* ******************************************* *)
  4011. (*
  4012. This is the most important module for source-code based targets. It will follow a convention of what's an expression and what's a statement,
  4013. and will unwrap statements where expressions are expected, and vice-versa.
  4014. It should be one of the first syntax filters to be applied. As a consequence, it's applied after all filters that add code to the AST, and by being
  4015. the first of the syntax filters, it will also have the AST retain most of the meaning of normal Haxe code. So it's easier to detect cases which are
  4016. side-effects free, for example
  4017. Any target can make use of this, but there is one requirement: The target must accept null to be set to any kind of variable. For example,
  4018. var i:Int = null; must be accepted. The best way to deal with this is to (like it's done in C#) make null equal to "default(Type)"
  4019. dependencies:
  4020. While it's best for Expression Unwrap to delay its execution as much as possible, since theoretically any
  4021. filter can return an expression that needs to be unwrapped, it is also desirable for ExpresionUnwrap to have
  4022. the AST as close as possible as Haxe's, so it can make some correct predictions (for example, so it can
  4023. more accurately know what can be side-effects-free and what can't).
  4024. This way, it will run slightly after the Normal priority, so if you don't say that a syntax filter must run
  4025. before Expression Unwrap, it will run after it.
  4026. TODO : While statement must become do / while, with the actual block inside an if for the condition, and else for 'break'
  4027. *)
  4028. module ExpressionUnwrap =
  4029. struct
  4030. let name = "expression_unwrap"
  4031. (* priority: first syntax filter *)
  4032. let priority = -10.0
  4033. (*
  4034. We always need to rely on Blocks to be able to unwrap expressions correctly.
  4035. So the the standard traverse will always be based on blocks.
  4036. Normal block statements, like for(), while(), if(), ... will be mk_block'ed so there is always a block inside of them.
  4037. At the block level, we'll define an "add_statement" function, which will allow the current expression to
  4038. add statements to the block. This statement may or may not contain statements as expressions, so the texpr will be evaluated recursively before being added.
  4039. - traverse will always evaluate TBlocks
  4040. - for each texpr in a TBlock list,
  4041. check shallow type
  4042. if type is Statement or Both when it has problematic expression (var problematic_expr = count_problematic_expressions),
  4043. if we can eagerly call unwrap_statement on the whole expression (try_call_unwrap_statement), use the return expression
  4044. else
  4045. check expr_type of each underlying type (with expr_stat_map)
  4046. if it has ExprWithStatement or Statement,
  4047. call problematic_expression_unwrap in it
  4048. problematic_expr--
  4049. else if problematic_expr == 0, just add the unchanged expression
  4050. else if NoSideEffects and doesn't have short-circuit, just add the unchanged expression
  4051. else call problematic_expression_unwrap in it
  4052. if type is Expression, check if there are statements or Both inside.
  4053. if there are, problematic_expression_unwrap in it
  4054. aftewards, use on_expr_as_statement to get it
  4055. helpers:
  4056. try_call_unwrap_statement: (returns texpr option)
  4057. if underlying statement is TBinop(OpAssign/OpAssignOp), or TVar, with the right side being a Statement or a short circuit op, we can call apply_assign.
  4058. apply_assign:
  4059. if is TVar, first declare the tvar with default expression = null;
  4060. will receive the left and right side of the assignment; right-side must be Statement
  4061. see if right side is a short-circuit operation, call short_circuit_op_unwrap
  4062. else see eexpr of the right side
  4063. if it's void, just add the statement with add_statement, and set the right side as null;
  4064. if not, it will have a block inside. set the left side = to the last expression on each block inside. add_statement for it.
  4065. short_circuit_op_unwrap: x() && (1 + {var x = 0; x + 1;} == 2) && z()
  4066. -> var x = x();
  4067. var y = false;
  4068. var z = false;
  4069. if (x) //for &&, neg for ||
  4070. {
  4071. var temp = null;
  4072. {
  4073. var x = 0;
  4074. temp = x + 1;
  4075. }
  4076. y = (1 + temp) == 2;
  4077. if (y)
  4078. {
  4079. z = z();
  4080. }
  4081. }
  4082. expects to receive a texpr with TBinop(OpBoolAnd/OpBoolOr)
  4083. will traverse the AST while there is a TBinop(OpBoolAnd/OpBoolOr) as a right-side expr, and declare new temp vars in the for each found.
  4084. will collect the return value, a mapped expr with all exprs as TLocal of the temp vars created
  4085. problematic_expression_unwrap:
  4086. check expr_kind:
  4087. if it is NoSideEffects and not short-circuit, leave it there
  4088. if it is ExprWithStatement and not short-circuit, call Type.map_expr problematic_expression_unwrap
  4089. if it is Statement or Expression or short-circuit expr, call add_assign for this expression
  4090. add_assign:
  4091. see if the type is void. If it is, just add_statement the expression argument, and return a null value
  4092. else create a new variable, set TVar with Some() with the expression argument, add TVar with add_statement, and return the TLocal of this expression.
  4093. map_problematic_expr:
  4094. call expr_stat_map on statement with problematic_expression_unwrap
  4095. types:
  4096. type shallow_expr_type = | Statement | Expression | Both (* shallow expression classification. Both means that they can be either Statements as Expressions *)
  4097. type expr_kind = | NormalExpr | ExprNoSideEffects (* -> short-circuit is considered side-effects *) | ExprWithStatement | Statement
  4098. evaluates an expression (as in not a statement) type. If it is ExprWithStatement or Statement, it means it contains errors
  4099. functions:
  4100. shallow_expr_type (expr:texpr) : shallow_expr_type
  4101. expr_kind (expr:texpr) : expr_kind
  4102. deeply evaluates an expression type
  4103. expr_stat_map (fn:texpr->texpr) (expr:texpr) : texpr
  4104. it will traverse the AST looking for places where an expression is expected, and map the value according to fn
  4105. aggregate_expr_type (is_side_effects_free:bool) (children:expr_type list) : expr_type
  4106. helper function to deal with expr_type aggregation (e.g. an Expression + a Statement as a children, is a ExprWithStatement)
  4107. check_statement_in_expression (expr:texpr) : texpr option :
  4108. will check
  4109. *)
  4110. type shallow_expr_type = | Statement | Expression of texpr | Both of texpr (* shallow expression classification. Both means that they can be either Statements as Expressions *)
  4111. type expr_kind = | KNormalExpr | KNoSideEffects (* -> short-circuit is considered side-effects *) | KExprWithStatement | KStatement
  4112. let rec no_paren e =
  4113. match e.eexpr with
  4114. | TParenthesis e -> no_paren e
  4115. | _ -> e
  4116. (* must be called in a statement. Will execute fn whenever an expression (not statement) is expected *)
  4117. let rec expr_stat_map fn (expr:texpr) =
  4118. match (no_paren expr).eexpr with
  4119. | TBinop ( (Ast.OpAssign as op), left_e, right_e )
  4120. | TBinop ( (Ast.OpAssignOp _ as op), left_e, right_e ) ->
  4121. { expr with eexpr = TBinop(op, fn left_e, fn right_e) }
  4122. | TParenthesis _ -> assert false
  4123. | TCall(left_e, params) ->
  4124. { expr with eexpr = TCall(fn left_e, List.map fn params) }
  4125. | TNew(cl, tparams, params) ->
  4126. { expr with eexpr = TNew(cl, tparams, List.map fn params) }
  4127. | TVar(v,eopt) ->
  4128. { expr with eexpr = TVar(v, Option.map fn eopt) }
  4129. | TFor (v,cond,block) ->
  4130. { expr with eexpr = TFor(v, fn cond, block) }
  4131. | TIf(cond,eif,eelse) ->
  4132. { expr with eexpr = TIf(fn cond, eif, eelse) }
  4133. | TWhile(cond, block, flag) ->
  4134. { expr with eexpr = TWhile(fn cond, block, flag) }
  4135. | TSwitch(cond, el_block_l, default) ->
  4136. { expr with eexpr = TSwitch( fn cond, List.map (fun (el,block) -> (List.map fn el, block)) el_block_l, default ) }
  4137. (* | TMatch(cond, enum, cases, default) ->
  4138. { expr with eexpr = TMatch(fn cond, enum, cases, default) } *)
  4139. | TReturn(eopt) ->
  4140. { expr with eexpr = TReturn(Option.map fn eopt) }
  4141. | TThrow (texpr) ->
  4142. { expr with eexpr = TThrow(fn texpr) }
  4143. | TBreak
  4144. | TContinue
  4145. | TTry _
  4146. | TUnop (Ast.Increment, _, _)
  4147. | TUnop (Ast.Decrement, _, _) (* unop is a special case because the haxe compiler won't let us generate complex expressions with Increment/Decrement *)
  4148. | TBlock _ -> expr (* there is no expected expression here. Only statements *)
  4149. | TMeta(m,e) ->
  4150. { expr with eexpr = TMeta(m,expr_stat_map fn e) }
  4151. | _ -> assert false (* we only expect valid statements here. other expressions aren't valid statements *)
  4152. let is_expr = function | Expression _ -> true | _ -> false
  4153. let aggregate_expr_type map_fn side_effects_free children =
  4154. let rec loop acc children =
  4155. match children with
  4156. | [] -> acc
  4157. | hd :: children ->
  4158. match acc, map_fn hd with
  4159. | _, KExprWithStatement
  4160. | _, KStatement
  4161. | KExprWithStatement, _
  4162. | KStatement, _ -> KExprWithStatement
  4163. | KNormalExpr, KNoSideEffects
  4164. | KNoSideEffects, KNormalExpr
  4165. | KNormalExpr, KNormalExpr -> loop KNormalExpr children
  4166. | KNoSideEffects, KNoSideEffects -> loop KNoSideEffects children
  4167. in
  4168. loop (if side_effects_free then KNoSideEffects else KNormalExpr) children
  4169. (* statements: *)
  4170. (* Error CS0201: Only assignment, call, increment, *)
  4171. (* decrement, and new object expressions can be used as a *)
  4172. (* statement (CS0201). *)
  4173. let rec shallow_expr_type expr : shallow_expr_type =
  4174. match expr.eexpr with
  4175. | TCall _ when not (is_void expr.etype) -> Both expr
  4176. | TNew _
  4177. | TUnop (Ast.Increment, _, _)
  4178. | TUnop (Ast.Decrement, _, _)
  4179. | TBinop (Ast.OpAssign, _, _)
  4180. | TBinop (Ast.OpAssignOp _, _, _) -> Both expr
  4181. | TIf (cond, eif, Some(eelse)) -> (match aggregate_expr_type expr_kind true [cond;eif;eelse] with
  4182. | KExprWithStatement -> Statement
  4183. | _ -> Both expr)
  4184. | TConst _
  4185. | TLocal _
  4186. | TArray _
  4187. | TBinop _
  4188. | TField _
  4189. | TEnumParameter _
  4190. | TTypeExpr _
  4191. | TObjectDecl _
  4192. | TArrayDecl _
  4193. | TFunction _
  4194. | TCast _
  4195. | TUnop _ -> Expression (expr)
  4196. | TParenthesis p | TMeta(_,p) -> shallow_expr_type p
  4197. | TBlock ([e]) -> shallow_expr_type e
  4198. | TCall _
  4199. | TVar _
  4200. | TBlock _
  4201. | TFor _
  4202. | TWhile _
  4203. | TSwitch _
  4204. | TPatMatch _
  4205. | TTry _
  4206. | TReturn _
  4207. | TBreak
  4208. | TContinue
  4209. | TIf _
  4210. | TThrow _ -> Statement
  4211. and expr_kind expr =
  4212. match shallow_expr_type expr with
  4213. | Statement -> KStatement
  4214. | Both expr | Expression expr ->
  4215. let aggregate = aggregate_expr_type expr_kind in
  4216. match expr.eexpr with
  4217. | TConst _
  4218. | TLocal _
  4219. | TFunction _
  4220. | TTypeExpr _ ->
  4221. KNoSideEffects
  4222. | TCall (ecall, params) ->
  4223. aggregate false (ecall :: params)
  4224. | TNew (_,_,params) ->
  4225. aggregate false params
  4226. | TUnop (Increment,_,e)
  4227. | TUnop (Decrement,_,e) ->
  4228. aggregate false [e]
  4229. | TUnop (_,_,e) ->
  4230. aggregate true [e]
  4231. | TBinop (Ast.OpBoolAnd, e1, e2)
  4232. | TBinop (Ast.OpBoolOr, e1, e2) -> (* TODO: should OpBool never be side-effects free? *)
  4233. aggregate true [e1;e2]
  4234. | TBinop (Ast.OpAssign, e1, e2)
  4235. | TBinop (Ast.OpAssignOp _, e1, e2) ->
  4236. aggregate false [e1;e2]
  4237. | TBinop (_, e1, e2) ->
  4238. aggregate true [e1;e2]
  4239. | TIf (cond, eif, Some(eelse)) -> (match aggregate true [cond;eif;eelse] with
  4240. | KExprWithStatement -> KStatement
  4241. | k -> k)
  4242. | TArray (e1,e2) ->
  4243. aggregate true [e1;e2]
  4244. | TParenthesis e
  4245. | TMeta(_,e)
  4246. | TField (e,_) ->
  4247. aggregate true [e]
  4248. | TArrayDecl (el) ->
  4249. aggregate true el
  4250. | TObjectDecl (sel) ->
  4251. aggregate true (List.map snd sel)
  4252. | TCast (e,_) ->
  4253. aggregate true [e]
  4254. | _ -> trace (debug_expr expr); assert false (* should have been read as Statement by shallow_expr_type *)
  4255. let is_side_effects_free e =
  4256. match expr_kind e with | KNoSideEffects -> true | _ -> false
  4257. let get_kinds (statement:texpr) =
  4258. let kinds = ref [] in
  4259. ignore (expr_stat_map (fun e ->
  4260. kinds := (expr_kind e) :: !kinds;
  4261. e
  4262. ) statement);
  4263. List.rev !kinds
  4264. let has_problematic_expressions (kinds:expr_kind list) =
  4265. let rec loop kinds =
  4266. match kinds with
  4267. | [] -> false
  4268. | KStatement :: _
  4269. | KExprWithStatement :: _ -> true
  4270. | _ :: tl -> loop tl
  4271. in
  4272. loop kinds
  4273. let count_problematic_expressions (statement:texpr) =
  4274. let count = ref 0 in
  4275. ignore (expr_stat_map (fun e ->
  4276. (match expr_kind e with
  4277. | KStatement | KExprWithStatement -> incr count
  4278. | _ -> ()
  4279. );
  4280. e
  4281. ) statement);
  4282. !count
  4283. let apply_assign_block assign_fun elist =
  4284. let rec assign acc elist =
  4285. match elist with
  4286. | [] -> acc
  4287. | last :: [] ->
  4288. (assign_fun last) :: acc
  4289. | hd :: tl ->
  4290. assign (hd :: acc) tl
  4291. in
  4292. List.rev (assign [] elist)
  4293. let mk_get_block assign_fun e =
  4294. match e.eexpr with
  4295. | TBlock [] -> e
  4296. | TBlock (el) ->
  4297. { e with eexpr = TBlock(apply_assign_block assign_fun el) }
  4298. | _ ->
  4299. { e with eexpr = TBlock([ assign_fun e ]) }
  4300. let add_assign gen add_statement expr =
  4301. match expr.eexpr, follow expr.etype with
  4302. | _, TEnum({ e_path = ([],"Void") },[])
  4303. | _, TAbstract ({ a_path = ([],"Void") },[])
  4304. | TThrow _, _ ->
  4305. add_statement expr;
  4306. null expr.etype expr.epos
  4307. | _ ->
  4308. let var = mk_temp gen "stmt" expr.etype in
  4309. let tvars = { expr with eexpr = TVar(var,Some(expr)) } in
  4310. let local = { expr with eexpr = TLocal(var) } in
  4311. add_statement tvars;
  4312. local
  4313. (* requirement: right must be a statement *)
  4314. let rec apply_assign assign_fun right =
  4315. match right.eexpr with
  4316. | TBlock el ->
  4317. { right with eexpr = TBlock(apply_assign_block assign_fun el) }
  4318. | TSwitch (cond, elblock_l, default) ->
  4319. { right with eexpr = TSwitch(cond, List.map (fun (el,block) -> (el, mk_get_block assign_fun block)) elblock_l, Option.map (mk_get_block assign_fun) default) }
  4320. (* | TMatch (cond, ep, il_vlo_e_l, default) ->
  4321. { right with eexpr = TMatch(cond, ep, List.map (fun (il,vlo,e) -> (il,vlo,mk_get_block assign_fun e)) il_vlo_e_l, Option.map (mk_get_block assign_fun) default) } *)
  4322. | TTry (block, catches) ->
  4323. { right with eexpr = TTry(mk_get_block assign_fun block, List.map (fun (v,block) -> (v,mk_get_block assign_fun block) ) catches) }
  4324. | TIf (cond,eif,eelse) ->
  4325. { right with eexpr = TIf(cond, mk_get_block assign_fun eif, Option.map (mk_get_block assign_fun) eelse) }
  4326. | TThrow _
  4327. | TWhile _
  4328. | TFor _
  4329. | TReturn _
  4330. | TBreak
  4331. | TContinue -> right
  4332. | TParenthesis p | TMeta(_,p) ->
  4333. apply_assign assign_fun p
  4334. | _ ->
  4335. match follow right.etype with
  4336. | TEnum( { e_path = ([], "Void") }, [] )
  4337. | TAbstract ({ a_path = ([], "Void") },[]) ->
  4338. right
  4339. | _ -> trace (debug_expr right); assert false (* a statement is required *)
  4340. let short_circuit_op_unwrap gen add_statement expr :texpr =
  4341. let do_not expr =
  4342. { expr with eexpr = TUnop(Ast.Not, Ast.Prefix, expr) }
  4343. in
  4344. (* loop will always return its own TBlock, and the mapped expression *)
  4345. let rec loop acc expr =
  4346. match expr.eexpr with
  4347. | TBinop ( (Ast.OpBoolAnd as op), left, right) ->
  4348. let var = mk_temp gen "boolv" right.etype in
  4349. let tvars = { right with eexpr = TVar(var, Some( { right with eexpr = TConst(TBool false); etype = gen.gcon.basic.tbool } )); etype = gen.gcon.basic.tvoid } in
  4350. let local = { right with eexpr = TLocal(var) } in
  4351. let mapped_left, ret_acc = loop ( (local, { right with eexpr = TBinop(Ast.OpAssign, local, right) } ) :: acc) left in
  4352. add_statement tvars;
  4353. ({ expr with eexpr = TBinop(op, mapped_left, local) }, ret_acc)
  4354. (* we only accept OpBoolOr when it's the first to be evaluated *)
  4355. | TBinop ( (Ast.OpBoolOr as op), left, right) when acc = [] ->
  4356. let left = match left.eexpr with
  4357. | TLocal _ | TConst _ -> left
  4358. | _ -> add_assign gen add_statement left
  4359. in
  4360. let var = mk_temp gen "boolv" right.etype in
  4361. let tvars = { right with eexpr = TVar(var, Some( { right with eexpr = TConst(TBool false); etype = gen.gcon.basic.tbool } )); etype = gen.gcon.basic.tvoid } in
  4362. let local = { right with eexpr = TLocal(var) } in
  4363. add_statement tvars;
  4364. ({ expr with eexpr = TBinop(op, left, local) }, [ do_not left, { right with eexpr = TBinop(Ast.OpAssign, local, right) } ])
  4365. | _ when acc = [] -> assert false
  4366. | _ ->
  4367. let var = mk_temp gen "boolv" expr.etype in
  4368. let tvars = { expr with eexpr = TVar(var, Some( { expr with etype = gen.gcon.basic.tbool } )); etype = gen.gcon.basic.tvoid } in
  4369. let local = { expr with eexpr = TLocal(var) } in
  4370. let last_local = ref local in
  4371. let acc = List.map (fun (local, assign) ->
  4372. let l = !last_local in
  4373. last_local := local;
  4374. (l, assign)
  4375. ) acc in
  4376. add_statement tvars;
  4377. (local, acc)
  4378. in
  4379. let mapped_expr, local_assign_list = loop [] expr in
  4380. let rec loop local_assign_list : texpr =
  4381. match local_assign_list with
  4382. | [local, assign] ->
  4383. { eexpr = TIf(local, assign, None); etype = gen.gcon.basic.tvoid; epos = assign.epos }
  4384. | (local, assign) :: tl ->
  4385. { eexpr = TIf(local,
  4386. {
  4387. eexpr = TBlock ( assign :: [loop tl] );
  4388. etype = gen.gcon.basic.tvoid;
  4389. epos = assign.epos;
  4390. },
  4391. None); etype = gen.gcon.basic.tvoid; epos = assign.epos }
  4392. | [] -> assert false
  4393. in
  4394. add_statement (loop local_assign_list);
  4395. mapped_expr
  4396. (* there are two short_circuit fuctions as I'm still testing the best way to do it *)
  4397. (*let short_circuit_op_unwrap gen add_statement expr :texpr =
  4398. let block = ref [] in
  4399. let rec short_circuit_op_unwrap is_first last_block expr =
  4400. match expr.eexpr with
  4401. | TBinop ( (Ast.OpBoolAnd as op), left, right)
  4402. | TBinop ( (Ast.OpBoolOr as op), left, right) ->
  4403. let var = mk_temp gen "boolv" left.etype in
  4404. let tvars = { left with eexpr = TVar([var, if is_first then Some(left) else Some( { left with eexpr = TConst(TBool false) } )]); etype = gen.gcon.basic.tvoid } in
  4405. let local = { left with eexpr = TLocal(var) } in
  4406. if not is_first then begin
  4407. last_block := !last_block @ [ { left with eexpr = TBinop(Ast.OpAssign, local, left) } ]
  4408. end;
  4409. add_statement tvars;
  4410. let local_op = match op with | Ast.OpBoolAnd -> local | Ast.OpBoolOr -> { local with eexpr = TUnop(Ast.Not, Ast.Prefix, local) } | _ -> assert false in
  4411. let new_block = ref [] in
  4412. let new_right = short_circuit_op_unwrap false new_block right in
  4413. last_block := !last_block @ [ { expr with eexpr = TIf(local_op, { right with eexpr = TBlock(!new_block) }, None) } ];
  4414. { expr with eexpr = TBinop(op, local, new_right) }
  4415. | _ when is_first -> assert false
  4416. | _ ->
  4417. let var = mk_temp gen "boolv" expr.etype in
  4418. let tvars = { expr with eexpr = TVar([var, Some ( { expr with eexpr = TConst(TBool false) } ) ]); etype = gen.gcon.basic.tvoid } in
  4419. let local = { expr with eexpr = TLocal(var) } in
  4420. last_block := !last_block @ [ { expr with eexpr = TBinop(Ast.OpAssign, local, expr) } ];
  4421. add_statement tvars;
  4422. local
  4423. in
  4424. let mapped_expr = short_circuit_op_unwrap true block expr in
  4425. add_statement { eexpr = TBlock(!block); etype = gen.gcon.basic.tvoid; epos = expr.epos };
  4426. mapped_expr*)
  4427. let twhile_with_condition_statement gen add_statement twhile cond e1 flag =
  4428. (* when a TWhile is found with a problematic condition *)
  4429. let basic = gen.gcon.basic in
  4430. let block = if flag = Ast.NormalWhile then
  4431. { e1 with eexpr = TIf(cond, e1, Some({ e1 with eexpr = TBreak; etype = basic.tvoid })) }
  4432. else
  4433. Type.concat e1 { e1 with
  4434. eexpr = TIf({
  4435. eexpr = TUnop(Ast.Not, Ast.Prefix, mk_paren cond);
  4436. etype = basic.tbool;
  4437. epos = cond.epos
  4438. }, { e1 with eexpr = TBreak; etype = basic.tvoid }, None);
  4439. etype = basic.tvoid
  4440. }
  4441. in
  4442. add_statement { twhile with
  4443. eexpr = TWhile(
  4444. { eexpr = TConst(TBool true); etype = basic.tbool; epos = cond.epos },
  4445. block,
  4446. Ast.DoWhile
  4447. );
  4448. }
  4449. let try_call_unwrap_statement gen problematic_expression_unwrap (add_statement:texpr->unit) (expr:texpr) : texpr option =
  4450. let check_left left =
  4451. match expr_kind left with
  4452. | KExprWithStatement ->
  4453. problematic_expression_unwrap add_statement left KExprWithStatement
  4454. | KStatement -> assert false (* doesn't make sense a KStatement as a left side expression *)
  4455. | _ -> left
  4456. in
  4457. let handle_assign op left right =
  4458. let left = check_left left in
  4459. Some (apply_assign (fun e -> { e with eexpr = TBinop(op, left, if is_void left.etype then e else gen.ghandle_cast left.etype e.etype e) }) right )
  4460. in
  4461. let handle_return e =
  4462. Some( apply_assign (fun e ->
  4463. match e.eexpr with
  4464. | TThrow _ -> e
  4465. | _ when is_void e.etype ->
  4466. { e with eexpr = TBlock([e; { e with eexpr = TReturn None }]) }
  4467. | _ ->
  4468. { e with eexpr = TReturn( Some e ) }
  4469. ) e )
  4470. in
  4471. let is_problematic_if right =
  4472. match expr_kind right with
  4473. | KStatement | KExprWithStatement -> true
  4474. | _ -> false
  4475. in
  4476. match expr.eexpr with
  4477. | TBinop((Ast.OpAssign as op),left,right)
  4478. | TBinop((Ast.OpAssignOp _ as op),left,right) when shallow_expr_type right = Statement ->
  4479. handle_assign op left right
  4480. | TReturn( Some right ) when shallow_expr_type right = Statement ->
  4481. handle_return right
  4482. | TBinop((Ast.OpAssign as op),left, ({ eexpr = TBinop(Ast.OpBoolAnd,_,_) } as right) )
  4483. | TBinop((Ast.OpAssign as op),left,({ eexpr = TBinop(Ast.OpBoolOr,_,_) } as right))
  4484. | TBinop((Ast.OpAssignOp _ as op),left,({ eexpr = TBinop(Ast.OpBoolAnd,_,_) } as right) )
  4485. | TBinop((Ast.OpAssignOp _ as op),left,({ eexpr = TBinop(Ast.OpBoolOr,_,_) } as right) ) ->
  4486. let right = short_circuit_op_unwrap gen add_statement right in
  4487. Some { expr with eexpr = TBinop(op, check_left left, right) }
  4488. | TVar(v,Some({ eexpr = TBinop(Ast.OpBoolAnd,_,_) } as right))
  4489. | TVar(v,Some({ eexpr = TBinop(Ast.OpBoolOr,_,_) } as right)) ->
  4490. let right = short_circuit_op_unwrap gen add_statement right in
  4491. Some { expr with eexpr = TVar(v, Some(right)) }
  4492. | TVar(v,Some(right)) when shallow_expr_type right = Statement ->
  4493. add_statement ({ expr with eexpr = TVar(v, Some(null right.etype right.epos)) });
  4494. handle_assign Ast.OpAssign { expr with eexpr = TLocal(v); etype = v.v_type } right
  4495. (* TIf handling *)
  4496. | TBinop((Ast.OpAssign as op),left, ({ eexpr = TIf _ } as right))
  4497. | TBinop((Ast.OpAssignOp _ as op),left,({ eexpr = TIf _ } as right)) when is_problematic_if right ->
  4498. handle_assign op left right
  4499. | TVar(v,Some({ eexpr = TIf _ } as right)) when is_problematic_if right ->
  4500. add_statement ({ expr with eexpr = TVar(v, Some(null right.etype right.epos)) });
  4501. handle_assign Ast.OpAssign { expr with eexpr = TLocal(v); etype = v.v_type } right
  4502. | TWhile(cond, e1, flag) when is_problematic_if cond ->
  4503. twhile_with_condition_statement gen add_statement expr cond e1 flag;
  4504. Some (null expr.etype expr.epos)
  4505. | _ -> None
  4506. let traverse gen (on_expr_as_statement:texpr->texpr option) =
  4507. let add_assign = add_assign gen in
  4508. let problematic_expression_unwrap add_statement expr e_type =
  4509. let rec problematic_expression_unwrap is_first expr e_type =
  4510. match e_type, expr.eexpr with
  4511. | _, TBinop(Ast.OpBoolAnd, _, _)
  4512. | _, TBinop(Ast.OpBoolOr, _, _) -> add_assign add_statement expr (* add_assign so try_call_unwrap_expr *)
  4513. | KNoSideEffects, _ -> expr
  4514. | KStatement, _
  4515. | KNormalExpr, _ -> add_assign add_statement expr
  4516. | KExprWithStatement, TCall _
  4517. | KExprWithStatement, TNew _
  4518. | KExprWithStatement, TBinop (Ast.OpAssign,_,_)
  4519. | KExprWithStatement, TBinop (Ast.OpAssignOp _,_,_)
  4520. | KExprWithStatement, TUnop (Ast.Increment,_,_) (* all of these may have side-effects, so they must also be add_assign'ed . is_first avoids infinite loop *)
  4521. | KExprWithStatement, TUnop (Ast.Decrement,_,_) when not is_first -> add_assign add_statement expr
  4522. (* bugfix: Type.map_expr doesn't guarantee the correct order of execution *)
  4523. | KExprWithStatement, TBinop(op,e1,e2) ->
  4524. let e1 = problematic_expression_unwrap false e1 (expr_kind e1) in
  4525. let e2 = problematic_expression_unwrap false e2 (expr_kind e2) in
  4526. { expr with eexpr = TBinop(op, e1, e2) }
  4527. | KExprWithStatement, TArray(e1,e2) ->
  4528. let e1 = problematic_expression_unwrap false e1 (expr_kind e1) in
  4529. let e2 = problematic_expression_unwrap false e2 (expr_kind e2) in
  4530. { expr with eexpr = TArray(e1, e2) }
  4531. (* bugfix: calls should not be transformed into closure calls *)
  4532. | KExprWithStatement, TCall(( { eexpr = TField (ef_left, f) } as ef ), eargs) ->
  4533. { expr with eexpr = TCall(
  4534. { ef with eexpr = TField(problematic_expression_unwrap false ef_left (expr_kind ef_left), f) },
  4535. List.map (fun e -> problematic_expression_unwrap false e (expr_kind e)) eargs)
  4536. }
  4537. | KExprWithStatement, _ -> Type.map_expr (fun e -> problematic_expression_unwrap false e (expr_kind e)) expr
  4538. in
  4539. problematic_expression_unwrap true expr e_type
  4540. in
  4541. let rec traverse e =
  4542. match e.eexpr with
  4543. | TBlock el ->
  4544. let new_block = ref [] in
  4545. let rec process_statement e =
  4546. let e = no_paren e in
  4547. match e.eexpr, shallow_expr_type e with
  4548. | TCall( { eexpr = TLocal v } as elocal, elist ), _ when String.get v.v_name 0 = '_' && Hashtbl.mem gen.gspecial_vars v.v_name ->
  4549. new_block := { e with eexpr = TCall( elocal, List.map (fun e ->
  4550. match e.eexpr with
  4551. | TBlock _ -> traverse e
  4552. | _ -> e
  4553. ) elist ) } :: !new_block
  4554. | _, Statement | _, Both _ ->
  4555. let e = match e.eexpr with | TReturn (Some ({ eexpr = TThrow _ } as ethrow)) -> ethrow | _ -> e in
  4556. let kinds = get_kinds e in
  4557. if has_problematic_expressions kinds then begin
  4558. match try_call_unwrap_statement gen problematic_expression_unwrap add_statement e with
  4559. | Some { eexpr = TConst(TNull) } (* no op *)
  4560. | Some { eexpr = TBlock [] } -> ()
  4561. | Some e ->
  4562. if has_problematic_expressions (get_kinds e) then begin
  4563. process_statement e
  4564. end else
  4565. new_block := (traverse e) :: !new_block
  4566. | None ->
  4567. (
  4568. let acc = ref kinds in
  4569. let new_e = expr_stat_map (fun e ->
  4570. match !acc with
  4571. | hd :: tl ->
  4572. acc := tl;
  4573. if has_problematic_expressions (hd :: tl) then begin
  4574. problematic_expression_unwrap add_statement e hd
  4575. end else
  4576. e
  4577. | [] -> assert false
  4578. ) e in
  4579. new_block := (traverse new_e) :: !new_block
  4580. )
  4581. end else begin new_block := (traverse e) :: !new_block end
  4582. | _, Expression e ->
  4583. match on_expr_as_statement e with
  4584. | None -> ()
  4585. | Some e -> process_statement e
  4586. and add_statement expr =
  4587. process_statement expr
  4588. in
  4589. List.iter (process_statement) el;
  4590. let block = List.rev !new_block in
  4591. { e with eexpr = TBlock(block) }
  4592. | TTry (block, catches) ->
  4593. { e with eexpr = TTry(traverse (mk_block block), List.map (fun (v,block) -> (v, traverse (mk_block block))) catches) }
  4594. (* | TMatch (cond,ep,il_vol_e_l,default) ->
  4595. { e with eexpr = TMatch(cond,ep,List.map (fun (il,vol,e) -> (il,vol,traverse (mk_block e))) il_vol_e_l, Option.map (fun e -> traverse (mk_block e)) default) } *)
  4596. | TSwitch (cond,el_e_l, default) ->
  4597. { e with eexpr = TSwitch(cond, List.map (fun (el,e) -> (el, traverse (mk_block e))) el_e_l, Option.map (fun e -> traverse (mk_block e)) default) }
  4598. | TWhile (cond,block,flag) ->
  4599. {e with eexpr = TWhile(cond,traverse (mk_block block), flag) }
  4600. | TIf (cond, eif, eelse) ->
  4601. { e with eexpr = TIf(cond, traverse (mk_block eif), Option.map (fun e -> traverse (mk_block e)) eelse) }
  4602. | TFor (v,it,block) ->
  4603. { e with eexpr = TFor(v,it, traverse (mk_block block)) }
  4604. | TFunction (tfunc) ->
  4605. { e with eexpr = TFunction({ tfunc with tf_expr = traverse (mk_block tfunc.tf_expr) }) }
  4606. | _ -> e (* if expression doesn't have a block, we will exit *)
  4607. in
  4608. traverse
  4609. let configure gen (mapping_func:texpr->texpr) =
  4610. let map e = Some(mapping_func e) in
  4611. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  4612. end;;
  4613. (* ******************************************* *)
  4614. (* Casts detection v2 *)
  4615. (* ******************************************* *)
  4616. (*
  4617. Will detect implicit casts and add TCast for them. Since everything is already followed by follow_all, typedefs are considered a new type altogether
  4618. Types shouldn't be cast if:
  4619. * When an instance is being coerced to a superclass or to an implemented interface
  4620. * When anything is being coerced to Dynamic
  4621. edit:
  4622. As a matter of performance, we will also run the type parameters casts in here. Otherwise the exact same computation would have to be performed twice,
  4623. with maybe even some loss of information
  4624. * TAnon / TDynamic will call
  4625. * Type parameter handling will be abstracted
  4626. dependencies:
  4627. Must run before ExpressionUnwrap
  4628. *)
  4629. module CastDetect =
  4630. struct
  4631. let name = "cast_detect_2"
  4632. let priority = solve_deps name [DBefore TypeParams.priority; DBefore ExpressionUnwrap.priority]
  4633. (* ******************************************* *)
  4634. (* ReturnCast *)
  4635. (* ******************************************* *)
  4636. (*
  4637. Cast detection for return types can't be done at CastDetect time, since we need an
  4638. unwrapped expression to make sure we catch all return cast detections. So this module
  4639. is specifically to deal with that, and is configured automatically by CastDetect
  4640. dependencies:
  4641. *)
  4642. module ReturnCast =
  4643. struct
  4644. let name = "return_cast"
  4645. let priority = solve_deps name [DAfter priority; DAfter ExpressionUnwrap.priority]
  4646. let default_implementation gen =
  4647. let rec extract_expr e = match e.eexpr with
  4648. | TParenthesis e
  4649. | TMeta (_,e)
  4650. | TCast(e,_) -> extract_expr e
  4651. | _ -> e
  4652. in
  4653. let current_ret_type = ref None in
  4654. let handle e tto tfrom = gen.ghandle_cast (gen.greal_type tto) (gen.greal_type tfrom) e in
  4655. let in_value = ref false in
  4656. let rec run e =
  4657. let was_in_value = !in_value in
  4658. in_value := true;
  4659. match e.eexpr with
  4660. | TReturn (eopt) ->
  4661. (* a return must be inside a function *)
  4662. let ret_type = match !current_ret_type with | Some(s) -> s | None -> gen.gcon.error "Invalid return outside function declaration." e.epos; assert false in
  4663. (match eopt with
  4664. | None when not (is_void ret_type) ->
  4665. { e with eexpr = TReturn( Some(null ret_type e.epos)) }
  4666. | None -> e
  4667. | Some eret ->
  4668. { e with eexpr = TReturn( Some(handle (run eret) ret_type eret.etype ) ) })
  4669. | TFunction(tfunc) ->
  4670. let last_ret = !current_ret_type in
  4671. current_ret_type := Some(tfunc.tf_type);
  4672. let ret = Type.map_expr run e in
  4673. current_ret_type := last_ret;
  4674. ret
  4675. | TBlock el ->
  4676. { e with eexpr = TBlock ( List.map (fun e -> in_value := false; run e) el ) }
  4677. | TBinop ( (Ast.OpAssign as op),e1,e2)
  4678. | TBinop ( (Ast.OpAssignOp _ as op),e1,e2) when was_in_value ->
  4679. let e1 = extract_expr (run e1) in
  4680. let r = { e with eexpr = TBinop(op, e1, handle (run e2) e1.etype e2.etype); etype = e1.etype } in
  4681. handle r e.etype e1.etype
  4682. | TBinop ( (Ast.OpAssign as op),({ eexpr = TField(tf, f) } as e1), e2 )
  4683. | TBinop ( (Ast.OpAssignOp _ as op),({ eexpr = TField(tf, f) } as e1), e2 ) ->
  4684. (match field_access_esp gen (gen.greal_type tf.etype) (f) with
  4685. | FClassField(cl,params,_,_,is_static,actual_t,_) ->
  4686. let actual_t = if is_static then actual_t else apply_params cl.cl_types params actual_t in
  4687. let e1 = extract_expr (run e1) in
  4688. { e with eexpr = TBinop(op, e1, handle (run e2) actual_t e2.etype); etype = e1.etype }
  4689. | _ ->
  4690. let e1 = extract_expr (run e1) in
  4691. { e with eexpr = TBinop(op, e1, handle (run e2) e1.etype e2.etype); etype = e1.etype }
  4692. )
  4693. | TBinop ( (Ast.OpAssign as op),e1,e2)
  4694. | TBinop ( (Ast.OpAssignOp _ as op),e1,e2) ->
  4695. let e1 = extract_expr (run e1) in
  4696. { e with eexpr = TBinop(op, e1, handle (run e2) e1.etype e2.etype); etype = e1.etype }
  4697. | _ -> Type.map_expr run e
  4698. in
  4699. run
  4700. let configure gen =
  4701. let map e = Some(default_implementation gen e) in
  4702. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  4703. end;;
  4704. let get_args t = match follow t with
  4705. | TFun(args,ret) -> args,ret
  4706. | _ -> trace (debug_type t); assert false
  4707. let s_path (pack,n) = (String.concat "." (pack @ [n]))
  4708. (*
  4709. Since this function is applied under native-context only, the type paraters will already be changed
  4710. *)
  4711. let map_cls gen also_implements fn super =
  4712. let rec loop c tl =
  4713. if c == super then
  4714. fn c tl
  4715. else (match c.cl_super with
  4716. | None -> false
  4717. | Some (cs,tls) ->
  4718. let tls = gen.greal_type_param (TClassDecl cs) tls in
  4719. loop cs (List.map (apply_params c.cl_types tl) tls)
  4720. ) || (if also_implements then List.exists (fun (cs,tls) ->
  4721. loop cs (List.map (apply_params c.cl_types tl) tls)
  4722. ) c.cl_implements else false)
  4723. in
  4724. loop
  4725. let follow_dyn t = match follow t with
  4726. | TMono _ | TLazy _ -> t_dynamic
  4727. | t -> t
  4728. (*
  4729. this has a slight change from the type.ml version, in which it doesn't
  4730. change a TMono into the other parameter
  4731. *)
  4732. let rec type_eq gen param a b =
  4733. if a == b then
  4734. ()
  4735. else match follow_dyn (gen.greal_type a) , follow_dyn (gen.greal_type b) with
  4736. | TEnum (e1,tl1) , TEnum (e2,tl2) ->
  4737. if e1 != e2 && not (param = EqCoreType && e1.e_path = e2.e_path) then Type.error [cannot_unify a b];
  4738. List.iter2 (type_eq gen param) tl1 tl2
  4739. | TAbstract (a1,tl1) , TAbstract (a2,tl2) ->
  4740. if a1 != a2 && not (param = EqCoreType && a1.a_path = a2.a_path) then Type.error [cannot_unify a b];
  4741. List.iter2 (type_eq gen param) tl1 tl2
  4742. | TInst (c1,tl1) , TInst (c2,tl2) ->
  4743. if c1 != c2 && not (param = EqCoreType && c1.cl_path = c2.cl_path) && (match c1.cl_kind, c2.cl_kind with KExpr _, KExpr _ -> false | _ -> true) then Type.error [cannot_unify a b];
  4744. List.iter2 (type_eq gen param) tl1 tl2
  4745. | TFun (l1,r1) , TFun (l2,r2) when List.length l1 = List.length l2 ->
  4746. (try
  4747. type_eq gen param r1 r2;
  4748. List.iter2 (fun (n,o1,t1) (_,o2,t2) ->
  4749. if o1 <> o2 then Type.error [Not_matching_optional n];
  4750. type_eq gen param t1 t2
  4751. ) l1 l2
  4752. with
  4753. Unify_error l -> Type.error (cannot_unify a b :: l))
  4754. | TDynamic a , TDynamic b ->
  4755. type_eq gen param a b
  4756. | TAnon a1, TAnon a2 ->
  4757. (try
  4758. PMap.iter (fun n f1 ->
  4759. try
  4760. let f2 = PMap.find n a2.a_fields in
  4761. if f1.cf_kind <> f2.cf_kind && (param = EqStrict || param = EqCoreType || not (unify_kind f1.cf_kind f2.cf_kind)) then Type.error [invalid_kind n f1.cf_kind f2.cf_kind];
  4762. try
  4763. type_eq gen param f1.cf_type f2.cf_type
  4764. with
  4765. Unify_error l -> Type.error (invalid_field n :: l)
  4766. with
  4767. Not_found ->
  4768. if is_closed a2 then Type.error [has_no_field b n];
  4769. if not (link (ref None) b f1.cf_type) then Type.error [cannot_unify a b];
  4770. a2.a_fields <- PMap.add n f1 a2.a_fields
  4771. ) a1.a_fields;
  4772. PMap.iter (fun n f2 ->
  4773. if not (PMap.mem n a1.a_fields) then begin
  4774. if is_closed a1 then Type.error [has_no_field a n];
  4775. if not (link (ref None) a f2.cf_type) then Type.error [cannot_unify a b];
  4776. a1.a_fields <- PMap.add n f2 a1.a_fields
  4777. end;
  4778. ) a2.a_fields;
  4779. with
  4780. Unify_error l -> Type.error (cannot_unify a b :: l))
  4781. | _ , _ ->
  4782. if b == t_dynamic && (param = EqRightDynamic || param = EqBothDynamic) then
  4783. ()
  4784. else if a == t_dynamic && param = EqBothDynamic then
  4785. ()
  4786. else
  4787. Type.error [cannot_unify a b]
  4788. let type_iseq gen a b =
  4789. try
  4790. type_eq gen EqStrict a b;
  4791. true
  4792. with
  4793. Unify_error _ -> false
  4794. (* will return true if both arguments are compatible. If it's not the case, a runtime error is very likely *)
  4795. let is_cl_related gen cl tl super superl =
  4796. let is_cl_related cl tl super superl = map_cls gen (gen.guse_tp_constraints || (match cl.cl_kind,super.cl_kind with KTypeParameter _, _ | _,KTypeParameter _ -> false | _ -> true)) (fun _ _ -> true) super cl tl in
  4797. is_cl_related cl tl super superl || is_cl_related super superl cl tl
  4798. let rec is_unsafe_cast gen to_t from_t =
  4799. match (follow to_t, follow from_t) with
  4800. | TInst(cl_to, to_params), TInst(cl_from, from_params) ->
  4801. not (is_cl_related gen cl_from from_params cl_to to_params)
  4802. | TEnum(e_to, _), TEnum(e_from, _) ->
  4803. e_to.e_path <> e_from.e_path
  4804. | TFun _, TFun _ ->
  4805. (* functions are never unsafe cast by default. This behavior might be changed *)
  4806. (* with a later AST pass which will run through TFun to TFun casts *)
  4807. false
  4808. | TMono _, _
  4809. | _, TMono _
  4810. | TDynamic _, _
  4811. | _, TDynamic _ ->
  4812. false
  4813. | TAnon _, _
  4814. | _, TAnon _ ->
  4815. (* anonymous are never unsafe also. *)
  4816. (* Though they will generate a cast, so if this cast is unneeded it's better to avoid them by tweaking gen.greal_type *)
  4817. false
  4818. | TAbstract _, _
  4819. | _, TAbstract _ ->
  4820. (try
  4821. unify from_t to_t;
  4822. false
  4823. with | Unify_error _ ->
  4824. try
  4825. unify to_t from_t; (* still not unsafe *)
  4826. false
  4827. with | Unify_error _ ->
  4828. true)
  4829. | _ -> true
  4830. let do_unsafe_cast gen from_t to_t e =
  4831. let t_path t =
  4832. match t with
  4833. | TInst(cl, _) -> cl.cl_path
  4834. | TEnum(e, _) -> e.e_path
  4835. | TType(t, _) -> t.t_path
  4836. | TAbstract(a, _) -> a.a_path
  4837. | TDynamic _ -> ([], "Dynamic")
  4838. | _ -> raise Not_found
  4839. in
  4840. let do_default () =
  4841. gen.gon_unsafe_cast to_t e.etype e.epos;
  4842. mk_cast to_t (mk_cast t_dynamic e)
  4843. in
  4844. (* TODO: there really should be a better way to write that *)
  4845. try
  4846. if (Hashtbl.find gen.gsupported_conversions (t_path from_t)) from_t to_t then
  4847. mk_cast to_t e
  4848. else
  4849. do_default()
  4850. with
  4851. | Not_found ->
  4852. try
  4853. if (Hashtbl.find gen.gsupported_conversions (t_path to_t)) from_t to_t then
  4854. mk_cast to_t e
  4855. else
  4856. do_default()
  4857. with
  4858. | Not_found -> do_default()
  4859. (* ****************************** *)
  4860. (* cast handler *)
  4861. (* decides if a cast should be emitted, given a from and a to type *)
  4862. (*
  4863. this function is like a mini unify, without e.g. subtyping, which makes sense
  4864. at the backend level, since most probably Anons and TInst will have a different representation there
  4865. *)
  4866. let rec handle_cast gen e real_to_t real_from_t =
  4867. let do_unsafe_cast () = do_unsafe_cast gen real_from_t real_to_t { e with etype = real_from_t } in
  4868. let to_t, from_t = real_to_t, real_from_t in
  4869. let mk_cast t e =
  4870. match e.eexpr with
  4871. (* TThrow is always typed as Dynamic, we just need to type it accordingly *)
  4872. | TThrow _ -> { e with etype = t }
  4873. | _ -> mk_cast t e
  4874. in
  4875. let e = { e with etype = real_from_t } in
  4876. if try fast_eq real_to_t real_from_t with Invalid_argument("List.for_all2") -> false then e else
  4877. match real_to_t, real_from_t with
  4878. (* string is the only type that can be implicitly converted from any other *)
  4879. | TInst( { cl_path = ([], "String") }, []), _ ->
  4880. mk_cast to_t e
  4881. | TInst(cl_to, params_to), TInst(cl_from, params_from) ->
  4882. let ret = ref None in
  4883. (*
  4884. this is a little confusing:
  4885. we are here mapping classes until we have the same to and from classes, applying the type parameters in each step, so we can
  4886. compare the type parameters;
  4887. If a class is found - meaning that the cl_from can be converted without a cast into cl_to,
  4888. we still need to check their type parameters.
  4889. *)
  4890. ignore (map_cls gen (gen.guse_tp_constraints || (match cl_from.cl_kind,cl_to.cl_kind with KTypeParameter _, _ | _,KTypeParameter _ -> false | _ -> true)) (fun _ tl ->
  4891. try
  4892. (* type found, checking type parameters *)
  4893. List.iter2 (type_eq gen EqStrict) tl params_to;
  4894. ret := Some e;
  4895. true
  4896. with | Unify_error _ ->
  4897. (* type parameters need casting *)
  4898. if gen.ghas_tparam_cast_handler then begin
  4899. (*
  4900. if we are already handling type parameter casts on other part of code (e.g. RealTypeParameters),
  4901. we'll just make a cast to indicate that this place needs type parameter-involved casting
  4902. *)
  4903. ret := Some (mk_cast to_t e);
  4904. true
  4905. end else
  4906. (*
  4907. if not, we're going to check if we only need a simple cast,
  4908. or if we need to first cast into the dynamic version of it
  4909. *)
  4910. try
  4911. List.iter2 (type_eq gen EqRightDynamic) tl params_to;
  4912. ret := Some (mk_cast to_t e);
  4913. true
  4914. with | Unify_error _ ->
  4915. ret := Some (mk_cast to_t (mk_cast (TInst(cl_to, List.map (fun _ -> t_dynamic) params_to)) e));
  4916. true
  4917. ) cl_to cl_from params_from);
  4918. if is_some !ret then
  4919. get !ret
  4920. else if is_cl_related gen cl_from params_from cl_to params_to then
  4921. mk_cast to_t e
  4922. else
  4923. (* potential unsafe cast *)
  4924. (do_unsafe_cast ())
  4925. | TMono _, TMono _
  4926. | TMono _, TDynamic _
  4927. | TDynamic _, TDynamic _
  4928. | TDynamic _, TMono _ ->
  4929. e
  4930. | TMono _, _
  4931. | TDynamic _, _
  4932. | TAnon _, _ when gen.gneeds_box real_from_t ->
  4933. mk_cast to_t e
  4934. | TMono _, _
  4935. | TDynamic _, _ -> e
  4936. | _, TMono _
  4937. | _, TDynamic _ -> mk_cast to_t e
  4938. | TAnon (a_to), TAnon (a_from) ->
  4939. if a_to == a_from then
  4940. e
  4941. else if type_iseq gen to_t from_t then (* FIXME apply unify correctly *)
  4942. e
  4943. else
  4944. mk_cast to_t e
  4945. | _, TAnon(anon) -> (try
  4946. let p2 = match !(anon.a_status) with
  4947. | Statics c -> TInst(c,List.map (fun _ -> t_dynamic) c.cl_types)
  4948. | EnumStatics e -> TEnum(e, List.map (fun _ -> t_dynamic) e.e_types)
  4949. | AbstractStatics a -> TAbstract(a, List.map (fun _ -> t_dynamic) a.a_types)
  4950. | _ -> raise Not_found
  4951. in
  4952. let tclass = match get_type gen ([],"Class") with
  4953. | TAbstractDecl(a) -> a
  4954. | _ -> assert false in
  4955. handle_cast gen e real_to_t (gen.greal_type (TAbstract(tclass, [p2])))
  4956. with | Not_found ->
  4957. mk_cast to_t e)
  4958. | TAbstract (a_to, _), TAbstract(a_from, _) when a_to == a_from ->
  4959. e
  4960. | TAbstract _, TInst({ cl_kind = KTypeParameter _ }, _)
  4961. | TInst({ cl_kind = KTypeParameter _ }, _), TAbstract _ ->
  4962. do_unsafe_cast()
  4963. | TAbstract _, _
  4964. | _, TAbstract _ ->
  4965. (try
  4966. unify from_t to_t;
  4967. mk_cast to_t e
  4968. with | Unify_error _ ->
  4969. try
  4970. unify to_t from_t;
  4971. mk_cast to_t e
  4972. with | Unify_error _ ->
  4973. do_unsafe_cast())
  4974. | TEnum(e_to, []), TEnum(e_from, []) ->
  4975. if e_to == e_from then
  4976. e
  4977. else
  4978. (* potential unsafe cast *)
  4979. (do_unsafe_cast ())
  4980. | TEnum(e_to, params_to), TEnum(e_from, params_from) when e_to.e_path = e_from.e_path ->
  4981. (try
  4982. List.iter2 (type_eq gen (if gen.gallow_tp_dynamic_conversion then EqRightDynamic else EqStrict)) params_from params_to;
  4983. e
  4984. with
  4985. | Unify_error _ -> do_unsafe_cast ()
  4986. )
  4987. | TEnum(en, params_to), TInst(cl, params_from)
  4988. | TInst(cl, params_to), TEnum(en, params_from) ->
  4989. (* this is here for max compatibility with EnumsToClass module *)
  4990. if en.e_path = cl.cl_path && en.e_extern then begin
  4991. (try
  4992. List.iter2 (type_eq gen (if gen.gallow_tp_dynamic_conversion then EqRightDynamic else EqStrict)) params_from params_to;
  4993. e
  4994. with
  4995. | Invalid_argument("List.iter2") ->
  4996. (*
  4997. this is a hack for RealTypeParams. Since there is no way at this stage to know if the class is the actual
  4998. EnumsToClass derived from the enum, we need to imply from possible ArgumentErrors (because of RealTypeParams interfaces),
  4999. that they would only happen if they were a RealTypeParams created interface
  5000. *)
  5001. e
  5002. | Unify_error _ -> do_unsafe_cast ()
  5003. )
  5004. end else
  5005. do_unsafe_cast ()
  5006. | TType(t_to, params_to), TType(t_from, params_from) when t_to == t_from ->
  5007. if gen.gspecial_needs_cast real_to_t real_from_t then
  5008. (try
  5009. List.iter2 (type_eq gen (if gen.gallow_tp_dynamic_conversion then EqRightDynamic else EqStrict)) params_from params_to;
  5010. e
  5011. with
  5012. | Unify_error _ -> do_unsafe_cast ()
  5013. )
  5014. else
  5015. e
  5016. | TType(t_to, _), TType(t_from,_) ->
  5017. if gen.gspecial_needs_cast real_to_t real_from_t then
  5018. mk_cast to_t e
  5019. else
  5020. e
  5021. | TType _, _ when gen.gspecial_needs_cast real_to_t real_from_t ->
  5022. mk_cast to_t e
  5023. | _, TType _ when gen.gspecial_needs_cast real_to_t real_from_t ->
  5024. mk_cast to_t e
  5025. (*| TType(t_to, _), TType(t_from, _) ->
  5026. if t_to.t_path = t_from.t_path then
  5027. e
  5028. else if is_unsafe_cast gen real_to_t real_from_t then (* is_unsafe_cast will already follow both *)
  5029. (do_unsafe_cast ())
  5030. else
  5031. mk_cast to_t e*)
  5032. | TType _, _
  5033. | _, TType _ ->
  5034. if is_unsafe_cast gen real_to_t real_from_t then (* is_unsafe_cast will already follow both *)
  5035. (do_unsafe_cast ())
  5036. else
  5037. mk_cast to_t e
  5038. | TAnon anon, _ ->
  5039. if PMap.is_empty anon.a_fields then
  5040. e
  5041. else
  5042. mk_cast to_t e
  5043. | TFun(args, ret), TFun(args2, ret2) ->
  5044. let get_args = List.map (fun (_,_,t) -> t) in
  5045. (try List.iter2 (type_eq gen (EqBothDynamic)) (ret :: get_args args) (ret2 :: get_args args2); e with | Unify_error _ | Invalid_argument("List.iter2") -> mk_cast to_t e)
  5046. | _, _ ->
  5047. do_unsafe_cast ()
  5048. (* end of cast handler *)
  5049. (* ******************* *)
  5050. let is_static_overload c name =
  5051. match c.cl_super with
  5052. | None -> false
  5053. | Some (sup,_) ->
  5054. let rec loop c =
  5055. (PMap.mem name c.cl_statics) || (match c.cl_super with
  5056. | None -> false
  5057. | Some (sup,_) -> loop sup)
  5058. in
  5059. loop sup
  5060. let does_unify a b =
  5061. try
  5062. unify a b;
  5063. true
  5064. with | Unify_error _ -> false
  5065. (* this is a workaround for issue #1743, as FInstance() is returning the incorrect classfield *)
  5066. let select_overload gen applied_f overloads types params =
  5067. let rec check_arg arglist elist =
  5068. match arglist, elist with
  5069. | [], [] -> true (* it is valid *)
  5070. | (_,_,t) :: arglist, (_,_,et) :: elist when Type.type_iseq et t ->
  5071. check_arg arglist elist
  5072. | _ -> false
  5073. in
  5074. match follow applied_f with
  5075. | TFun _ ->
  5076. replace_mono applied_f;
  5077. let args, _ = get_fun applied_f in
  5078. let elist = List.rev args in
  5079. let rec check_overload overloads =
  5080. match overloads with
  5081. | (t, cf) :: overloads ->
  5082. let cft = apply_params types params t in
  5083. let cft = monomorphs cf.cf_params cft in
  5084. let args, _ = get_fun cft in
  5085. if check_arg (List.rev args) elist then
  5086. cf,t,false
  5087. else if overloads = [] then
  5088. cf,t,true (* no compatible overload was found *)
  5089. else
  5090. check_overload overloads
  5091. | [] -> assert false
  5092. in
  5093. check_overload overloads
  5094. | _ -> match overloads with (* issue #1742 *)
  5095. | (t,cf) :: [] -> cf,t,true
  5096. | (t,cf) :: _ -> cf,t,false
  5097. | _ -> assert false
  5098. let choose_ctor gen cl tparams etl maybe_empty_t p =
  5099. let ctor, sup, stl = OverloadingConstructor.cur_ctor cl tparams in
  5100. (* get returned stl, with Dynamic as t_empty *)
  5101. let rec get_changed_stl c tl =
  5102. if c == sup then
  5103. tl
  5104. else match c.cl_super with
  5105. | None -> stl
  5106. | Some(sup,stl) -> get_changed_stl sup (List.map (apply_params c.cl_types tl) stl)
  5107. in
  5108. let ret_tparams = List.map (fun t -> match follow t with
  5109. | TDynamic _ | TMono _ -> t_empty
  5110. | _ -> t) tparams in
  5111. let ret_stl = get_changed_stl cl ret_tparams in
  5112. let ctors = ctor :: ctor.cf_overloads in
  5113. List.iter replace_mono etl;
  5114. (* first filter out or select outright maybe_empty *)
  5115. let ctors, is_overload = match etl, maybe_empty_t with
  5116. | [t], Some empty_t ->
  5117. let count = ref 0 in
  5118. let is_empty_call = Type.type_iseq t empty_t in
  5119. let ret = List.filter (fun cf -> match follow cf.cf_type with
  5120. (* | TFun([_,_,t],_) -> incr count; true *)
  5121. | TFun([_,_,t],_) -> replace_mono t; incr count; is_empty_call = (Type.type_iseq t empty_t)
  5122. | _ -> false) ctors in
  5123. ret, !count > 1
  5124. | _ ->
  5125. let len = List.length etl in
  5126. let ret = List.filter (fun cf -> List.length (fst (get_fun cf.cf_type)) = len) ctors in
  5127. ret, (match ret with | _ :: [] -> false | _ -> true)
  5128. in
  5129. let rec check_arg arglist elist =
  5130. match arglist, elist with
  5131. | [], [] -> true
  5132. | (_,_,t) :: arglist, et :: elist -> (try
  5133. unify et t;
  5134. check_arg arglist elist
  5135. with | Unify_error el ->
  5136. (* List.iter (fun el -> gen.gcon.warning (Typecore.unify_error_msg (print_context()) el) p) el; *)
  5137. false)
  5138. | _ -> false
  5139. in
  5140. let rec check_cf cf =
  5141. let t = apply_params sup.cl_types stl cf.cf_type in
  5142. replace_mono t;
  5143. let args, _ = get_fun t in
  5144. check_arg args etl
  5145. in
  5146. is_overload, List.find check_cf ctors, sup, ret_stl
  5147. (*
  5148. Type parameter handling
  5149. It will detect if/what type parameters were used, and call the cast handler
  5150. It will handle both TCall(TField) and TCall by receiving a texpr option field: e
  5151. Also it will transform the type parameters with greal_type_param and make
  5152. handle_impossible_tparam - should cases where the type parameter is impossible to be determined from the called parameters be Dynamic?
  5153. e.g. static function test<T>():T {}
  5154. *)
  5155. (* match e.eexpr with | TCall( ({ eexpr = TField(ef, f) }) as e1, elist ) -> *)
  5156. let handle_type_parameter gen e e1 ef ~clean_ef ~overloads_cast_to_base f elist calls_parameters_explicitly =
  5157. (* the ONLY way to know if this call has parameters is to analyze the calling field. *)
  5158. (* To make matters a little worse, on both C# and Java only in some special cases that type parameters will be used *)
  5159. (* Namely, when using reflection type parameters are useless, of course. This also includes anonymous types *)
  5160. (* this will have to be handled by gparam_func_call *)
  5161. let return_var efield =
  5162. match e with
  5163. | None ->
  5164. efield
  5165. | Some ecall ->
  5166. match follow efield.etype with
  5167. | TFun(_,ret) ->
  5168. (* closures will be handled by the closure handler. So we will just hint what's the expected type *)
  5169. (* FIXME: should closures have also its arguments cast correctly? In the current implementation I think not. TO_REVIEW *)
  5170. handle_cast gen { ecall with eexpr = TCall(efield, elist) } (gen.greal_type ecall.etype) ret
  5171. | _ ->
  5172. { ecall with eexpr = TCall(efield, elist) }
  5173. in
  5174. let real_type = gen.greal_type ef.etype in
  5175. (* this part was rewritten at roughly r6477 in order to correctly support overloads *)
  5176. (match field_access_esp gen real_type (f) with
  5177. | FClassField (cl, params, _, cf, is_static, actual_t, declared_t) when e <> None && (cf.cf_kind = Method MethNormal || cf.cf_kind = Method MethInline) ->
  5178. (* C# target changes params with a real_type function *)
  5179. let params = match follow clean_ef.etype with
  5180. | TInst(_,params) -> params
  5181. | _ -> params in
  5182. let ecall = get e in
  5183. let ef = ref ef in
  5184. let is_overload = cf.cf_overloads <> [] || Meta.has Meta.Overload cf.cf_meta || (is_static && is_static_overload cl (field_name f)) in
  5185. let cf, actual_t, error = match is_overload with
  5186. | false ->
  5187. (* since actual_t from FClassField already applies greal_type, we're using the get_overloads helper to get this info *)
  5188. cf,declared_t,false
  5189. | true ->
  5190. let (cf, actual_t, error), is_static = match f with
  5191. | FInstance(c,cf) | FClosure(Some c,cf) ->
  5192. (* get from overloads *)
  5193. (* FIXME: this is a workaround for issue #1743 . Uncomment this code after it was solved *)
  5194. (* let t, cf = List.find (fun (t,cf2) -> cf == cf2) (Typeload.get_overloads cl (field_name f)) in *)
  5195. (* cf, t, false *)
  5196. select_overload gen e1.etype (Typeload.get_overloads cl (field_name f)) cl.cl_types params, false
  5197. | FStatic(c,f) ->
  5198. (* workaround for issue #1743 *)
  5199. (* f,f.cf_type, false *)
  5200. select_overload gen e1.etype ((f.cf_type,f) :: List.map (fun f -> f.cf_type,f) f.cf_overloads) [] [], true
  5201. | _ ->
  5202. gen.gcon.warning "Overloaded classfield typed as anonymous" ecall.epos;
  5203. (cf, actual_t, true), true
  5204. in
  5205. if not (is_static || error) then match find_first_declared_field gen cl ~exact_field:{ cf with cf_type = actual_t } cf.cf_name with
  5206. | Some(_,actual_t,_,_,declared_cl,tl,tlch) ->
  5207. if declared_cl != cl && overloads_cast_to_base then begin
  5208. let pos = (!ef).epos in
  5209. ef := {
  5210. eexpr = TCall(
  5211. { eexpr = TLocal(alloc_var "__as__" t_dynamic); etype = t_dynamic; epos = pos },
  5212. [!ef]);
  5213. etype = TInst(declared_cl,List.map (apply_params cl.cl_types params) tl);
  5214. epos = pos
  5215. }
  5216. end;
  5217. cf,actual_t,false
  5218. | None ->
  5219. gen.gcon.warning "Cannot find matching overload" ecall.epos;
  5220. cf, actual_t, true
  5221. else
  5222. cf,actual_t,error
  5223. in
  5224. let error = error || (match follow actual_t with | TFun _ -> false | _ -> true) in
  5225. if error then (* if error, ignore arguments *)
  5226. if is_void ecall.etype then
  5227. { ecall with eexpr = TCall({ e1 with eexpr = TField(!ef, f) }, elist ) }
  5228. else
  5229. mk_cast ecall.etype { ecall with eexpr = TCall({ e1 with eexpr = TField(!ef, f) }, elist ) }
  5230. else begin
  5231. (* infer arguments *)
  5232. (* let called_t = TFun(List.map (fun e -> "arg",false,e.etype) elist, ecall.etype) in *)
  5233. let called_t = match follow e1.etype with | TFun _ -> e1.etype | _ -> TFun(List.map (fun e -> "arg",false,e.etype) elist, ecall.etype) in (* workaround for issue #1742 *)
  5234. let fparams = TypeParams.infer_params gen ecall.epos (get_fun (apply_params cl.cl_types params actual_t)) (get_fun called_t) cf.cf_params calls_parameters_explicitly in
  5235. (* get what the backend actually sees *)
  5236. (* actual field's function *)
  5237. let actual_t = get_real_fun gen actual_t in
  5238. let real_params = gen.greal_type_param (TClassDecl cl) params in
  5239. let function_t = apply_params cl.cl_types real_params actual_t in
  5240. let real_fparams = if calls_parameters_explicitly then
  5241. gen.greal_type_param (TClassDecl cl) fparams
  5242. else
  5243. gen.greal_type_param (TClassDecl cl) (TypeParams.infer_params gen ecall.epos (get_fun function_t) (get_fun (get_real_fun gen called_t)) cf.cf_params calls_parameters_explicitly) in
  5244. let function_t = get_real_fun gen (apply_params cf.cf_params real_fparams function_t) in
  5245. let args_ft, ret_ft = get_fun function_t in
  5246. (* applied function *)
  5247. let applied = elist in
  5248. (* check types list *)
  5249. let new_ecall, elist = try
  5250. let elist = List.map2 (fun applied (_,_,funct) ->
  5251. match is_overload, applied.eexpr with
  5252. | true, TConst TNull ->
  5253. mk_cast (gen.greal_type funct) applied
  5254. | true, _ -> (* when not (type_iseq gen (gen.greal_type applied.etype) funct) -> *)
  5255. let ret = handle_cast gen applied (funct) (gen.greal_type applied.etype) in
  5256. (match ret.eexpr with
  5257. | TCast _ -> ret
  5258. | _ -> mk_cast (funct) ret)
  5259. | _ ->
  5260. handle_cast gen applied (funct) (gen.greal_type applied.etype)
  5261. ) applied args_ft in
  5262. { ecall with
  5263. eexpr = TCall(
  5264. { e1 with eexpr = TField(!ef, f) },
  5265. elist);
  5266. }, elist
  5267. with | Invalid_argument("List.map2") ->
  5268. gen.gcon.warning ("This expression may be invalid" ) ecall.epos;
  5269. { ecall with eexpr = TCall({ e1 with eexpr = TField(!ef, f) }, elist) }, elist
  5270. in
  5271. let new_ecall = if fparams <> [] then gen.gparam_func_call new_ecall { e1 with eexpr = TField(!ef, f) } fparams elist else new_ecall in
  5272. handle_cast gen new_ecall (gen.greal_type ecall.etype) (gen.greal_type ret_ft)
  5273. end
  5274. | FClassField (cl,params,_,{ cf_kind = (Method MethDynamic | Var _) },_,actual_t,_) ->
  5275. (* if it's a var, we will just try to apply the class parameters that have been changed with greal_type_param *)
  5276. let t = apply_params cl.cl_types (gen.greal_type_param (TClassDecl cl) params) (gen.greal_type actual_t) in
  5277. return_var (handle_cast gen { e1 with eexpr = TField(ef, f) } (gen.greal_type e1.etype) (gen.greal_type t))
  5278. | FClassField (cl,params,_,cf,_,actual_t,_) ->
  5279. return_var (handle_cast gen { e1 with eexpr = TField({ ef with etype = t_dynamic }, f) } e1.etype t_dynamic) (* force dynamic and cast back to needed type *)
  5280. | FEnumField (en, efield, true) ->
  5281. let ecall = match e with | None -> trace (field_name f); trace efield.ef_name; gen.gcon.error "This field should be called immediately" ef.epos; assert false | Some ecall -> ecall in
  5282. (match en.e_types with
  5283. (*
  5284. | [] ->
  5285. let args, ret = get_args (efield.ef_type) in
  5286. let ef = { ef with eexpr = TTypeExpr( TEnumDecl en ); etype = TEnum(en, []) } in
  5287. handle_cast gen { ecall with eexpr = TCall({ e1 with eexpr = TField(ef, FEnum(en, efield)) }, List.map2 (fun param (_,_,t) -> handle_cast gen param (gen.greal_type t) (gen.greal_type param.etype)) elist args) } (gen.greal_type ecall.etype) (gen.greal_type ret)
  5288. *)
  5289. | _ ->
  5290. let pt = match e with | None -> real_type | Some _ -> snd (get_fun e1.etype) in
  5291. let _params = match follow pt with | TEnum(_, p) -> p | _ -> gen.gcon.warning (debug_expr e1) e1.epos; assert false in
  5292. let args, ret = get_args efield.ef_type in
  5293. let actual_t = TFun(List.map (fun (n,o,t) -> (n,o,gen.greal_type t)) args, gen.greal_type ret) in
  5294. (*
  5295. because of differences on how <Dynamic> is handled on the platforms, this is a hack to be able to
  5296. correctly use class field type parameters with RealTypeParams
  5297. *)
  5298. let cf_params = List.map (fun t -> match follow t with | TDynamic _ -> t_empty | _ -> t) _params in
  5299. (* params are inverted *)
  5300. let cf_params = List.rev cf_params in
  5301. let t = apply_params en.e_types (gen.greal_type_param (TEnumDecl en) cf_params) actual_t in
  5302. let t = apply_params efield.ef_params (List.map (fun _ -> t_dynamic) efield.ef_params) t in
  5303. let args, ret = get_args t in
  5304. let elist = List.map2 (fun param (_,_,t) -> handle_cast gen (param) (gen.greal_type t) (gen.greal_type param.etype)) elist args in
  5305. let e1 = { e1 with eexpr = TField({ ef with eexpr = TTypeExpr( TEnumDecl en ); etype = TEnum(en, _params) }, FEnum(en, efield) ) } in
  5306. let new_ecall = gen.gparam_func_call ecall e1 _params elist in
  5307. handle_cast gen new_ecall (gen.greal_type ecall.etype) (gen.greal_type ret)
  5308. )
  5309. | FEnumField _ when is_some e -> assert false
  5310. | FEnumField (en,efield,_) ->
  5311. return_var { e1 with eexpr = TField({ ef with eexpr = TTypeExpr( TEnumDecl en ); },FEnum(en,efield)) }
  5312. (* no target by date will uses this.so this code may not be correct at all *)
  5313. | FAnonField cf ->
  5314. let t = gen.greal_type cf.cf_type in
  5315. return_var (handle_cast gen { e1 with eexpr = TField(ef, f) } (gen.greal_type e1.etype) t)
  5316. | FNotFound
  5317. | FDynamicField _ ->
  5318. if is_some e then
  5319. return_var { e1 with eexpr = TField(ef, f) }
  5320. else
  5321. return_var (handle_cast gen { e1 with eexpr = TField({ ef with etype = t_dynamic }, f) } e1.etype t_dynamic) (* force dynamic and cast back to needed type *)
  5322. )
  5323. (* end of type parameter handling *)
  5324. (* ****************************** *)
  5325. (** overloads_cast_to_base argument will cast overloaded function types to the class that declared it. **)
  5326. (** This is necessary for C#, and if true, will require the target to implement __as__, as a `quicker` form of casting **)
  5327. let default_implementation gen ?(native_string_cast = true) ?(overloads_cast_to_base = false) maybe_empty_t calls_parameters_explicitly =
  5328. let handle e t1 t2 = handle_cast gen e (gen.greal_type t1) (gen.greal_type t2) in
  5329. let in_value = ref false in
  5330. let rec run ?(just_type = false) e =
  5331. let handle = if not just_type then handle else fun e t1 t2 -> { e with etype = gen.greal_type t2 } in
  5332. let was_in_value = !in_value in
  5333. in_value := true;
  5334. match e.eexpr with
  5335. | TConst ( TInt _ | TFloat _ | TBool _ ) ->
  5336. (* take off any Null<> that it may have *)
  5337. { e with etype = follow (run_follow gen e.etype) }
  5338. | TCast( { eexpr = TCall( { eexpr = TLocal { v_name = "__delegate__" } } as local, [del] ) } as e2, _) ->
  5339. { e with eexpr = TCast({ e2 with eexpr = TCall(local, [Type.map_expr run del]) }, None) }
  5340. | TBinop ( (Ast.OpAssign | Ast.OpAssignOp _ as op), e1, e2 ) ->
  5341. { e with eexpr = TBinop(op, run ~just_type:true e1, run e2) }
  5342. | TField(ef, f) ->
  5343. handle_type_parameter gen None e (run ef) ~clean_ef:ef ~overloads_cast_to_base:overloads_cast_to_base f [] calls_parameters_explicitly
  5344. | TArrayDecl el ->
  5345. let et = e.etype in
  5346. let base_type = match follow et with
  5347. | TInst({ cl_path = ([], "Array") } as cl, bt) -> gen.greal_type_param (TClassDecl cl) bt
  5348. | _ -> assert false
  5349. in
  5350. let base_type = List.hd base_type in
  5351. { e with eexpr = TArrayDecl( List.map (fun e -> handle (run e) base_type e.etype) el ); etype = et }
  5352. | TCall( ({ eexpr = TLocal v } as local), params ) when String.get v.v_name 0 = '_' && String.get v.v_name 1 = '_' && Hashtbl.mem gen.gspecial_vars v.v_name ->
  5353. { e with eexpr = TCall(local, List.map (fun e -> (match e.eexpr with TBlock _ -> in_value := false | _ -> ()); run e) params) }
  5354. | TCall( ({ eexpr = TField(ef, f) }) as e1, elist ) ->
  5355. handle_type_parameter gen (Some e) (e1) (run ef) ~clean_ef:ef ~overloads_cast_to_base:overloads_cast_to_base f (List.map run elist) calls_parameters_explicitly
  5356. (* the TNew and TSuper code was modified at r6497 *)
  5357. | TCall( { eexpr = TConst TSuper } as ef, eparams ) ->
  5358. let cl, tparams = match follow ef.etype with
  5359. | TInst(cl,p) -> cl, p
  5360. | _ -> assert false in
  5361. (try
  5362. let is_overload, cf, sup, stl = choose_ctor gen cl tparams (List.map (fun e -> e.etype) eparams) maybe_empty_t e.epos in
  5363. let handle e t1 t2 =
  5364. if is_overload then
  5365. let ret = handle e t1 t2 in
  5366. match ret.eexpr with
  5367. | TCast _ -> ret
  5368. | _ -> mk_cast (gen.greal_type t1) e
  5369. else
  5370. handle e t1 t2
  5371. in
  5372. let stl = gen.greal_type_param (TClassDecl sup) stl in
  5373. let args, _ = get_fun (apply_params sup.cl_types stl cf.cf_type) in
  5374. let eparams = List.map2 (fun e (_,_,t) ->
  5375. handle (run e) t e.etype
  5376. ) eparams args in
  5377. { e with eexpr = TCall(ef, eparams) }
  5378. with | Not_found ->
  5379. gen.gcon.warning "No overload found for this constructor call" e.epos;
  5380. { e with eexpr = TCall(ef, List.map run eparams) })
  5381. | TCall (ef, eparams) ->
  5382. (match ef.etype with
  5383. | TFun(p, ret) ->
  5384. handle ({ e with eexpr = TCall(run ef, List.map2 (fun param (_,_,t) -> handle (run param) t param.etype) eparams p) }) e.etype ret
  5385. | _ -> Type.map_expr run e
  5386. )
  5387. (* the TNew and TSuper code was modified at r6497 *)
  5388. | TNew ({ cl_kind = KTypeParameter _ }, _, _) ->
  5389. Type.map_expr run e
  5390. | TNew (cl, tparams, eparams) -> (try
  5391. let is_overload, cf, sup, stl = choose_ctor gen cl tparams (List.map (fun e -> e.etype) eparams) maybe_empty_t e.epos in
  5392. let handle e t1 t2 =
  5393. if true then
  5394. let ret = handle e t1 t2 in
  5395. match ret.eexpr with
  5396. | TCast _ -> ret
  5397. | _ -> mk_cast (gen.greal_type t1) e
  5398. else
  5399. handle e t1 t2
  5400. in
  5401. let stl = gen.greal_type_param (TClassDecl sup) stl in
  5402. let args, _ = get_fun (apply_params sup.cl_types stl cf.cf_type) in
  5403. let eparams = List.map2 (fun e (_,_,t) ->
  5404. handle (run e) t e.etype
  5405. ) eparams args in
  5406. { e with eexpr = TNew(cl, tparams, eparams) }
  5407. with | Not_found ->
  5408. gen.gcon.warning "No overload found for this constructor call" e.epos;
  5409. { e with eexpr = TNew(cl, tparams, List.map run eparams) })
  5410. | TArray(arr, idx) ->
  5411. let arr_etype = match follow arr.etype with
  5412. | (TInst _ as t) -> t
  5413. | TAbstract ({ a_impl = Some _ } as a, pl) ->
  5414. follow (Codegen.Abstract.get_underlying_type a pl)
  5415. | t -> t in
  5416. let idx = match gen.greal_type idx.etype with
  5417. | TAbstract({ a_path = [],"Int" },_) -> run idx
  5418. | _ -> match handle (run idx) gen.gcon.basic.tint (gen.greal_type idx.etype) with
  5419. | ({ eexpr = TCast _ } as idx) -> idx
  5420. | idx -> mk_cast gen.gcon.basic.tint idx
  5421. in
  5422. let e = { e with eexpr = TArray(run arr, idx) } in
  5423. (* get underlying class (if it's a class *)
  5424. (match arr_etype with
  5425. | TInst(cl, params) ->
  5426. (* see if it implements ArrayAccess *)
  5427. (match cl.cl_array_access with
  5428. | None -> e
  5429. | Some t ->
  5430. (* if it does, apply current parameters (and change them) *)
  5431. (* let real_t = apply_params_internal (List.map (gen.greal_type_param (TClassDecl cl))) cl params t in *)
  5432. let param = apply_params cl.cl_types (gen.greal_type_param (TClassDecl cl) params) t in
  5433. let real_t = apply_params cl.cl_types params param in
  5434. (* see if it needs a cast *)
  5435. handle (e) (gen.greal_type e.etype) (gen.greal_type real_t)
  5436. )
  5437. | _ -> Type.map_expr run e)
  5438. | TVar (v, eopt) ->
  5439. { e with eexpr = TVar (v, match eopt with
  5440. | None -> eopt
  5441. | Some e -> Some( handle (run e) v.v_type e.etype ))
  5442. }
  5443. (* FIXME deal with in_value when using other statements that may not have a TBlock wrapped on them *)
  5444. | TIf (econd, ethen, Some(eelse)) when was_in_value ->
  5445. { e with eexpr = TIf (handle (run econd) gen.gcon.basic.tbool econd.etype, handle (run ethen) e.etype ethen.etype, Some( handle (run eelse) e.etype eelse.etype ) ) }
  5446. | TIf (econd, ethen, eelse) ->
  5447. { e with eexpr = TIf (handle (run econd) gen.gcon.basic.tbool econd.etype, (in_value := false; run (mk_block ethen)), Option.map (fun e -> in_value := false; run (mk_block e)) eelse) }
  5448. | TWhile (econd, e1, flag) ->
  5449. { e with eexpr = TWhile (handle (run econd) gen.gcon.basic.tbool econd.etype, (in_value := false; run (mk_block e1)), flag) }
  5450. | TSwitch (cond, el_e_l, edef) ->
  5451. { e with eexpr = TSwitch(run cond, List.map (fun (el,e) -> (List.map run el, (in_value := false; run (mk_block e)))) el_e_l, Option.map (fun e -> in_value := false; run (mk_block e)) edef) }
  5452. (* | TMatch (cond, en, il_vl_e_l, edef) ->
  5453. { e with eexpr = TMatch(run cond, en, List.map (fun (il, vl, e) -> (il, vl, run (mk_block e))) il_vl_e_l, Option.map (fun e -> run (mk_block e)) edef) } *)
  5454. | TFor (v,cond,e1) ->
  5455. { e with eexpr = TFor(v, run cond, (in_value := false; run (mk_block e1))) }
  5456. | TTry (e, ve_l) ->
  5457. { e with eexpr = TTry((in_value := false; run (mk_block e)), List.map (fun (v,e) -> in_value := false; (v, run (mk_block e))) ve_l) }
  5458. | TBlock el ->
  5459. let i = ref 0 in
  5460. let len = List.length el in
  5461. { e with eexpr = TBlock ( List.map (fun e ->
  5462. incr i;
  5463. if !i <> len || not was_in_value then
  5464. in_value := false;
  5465. run e
  5466. ) el ) }
  5467. | TCast (expr, md) when is_void (follow e.etype) ->
  5468. run expr
  5469. | TCast (expr, md) ->
  5470. let rec get_null e =
  5471. match e.eexpr with
  5472. | TConst TNull -> Some e
  5473. | TParenthesis e | TMeta(_,e) -> get_null e
  5474. | _ -> None
  5475. in
  5476. (match get_null expr with
  5477. | Some enull ->
  5478. if gen.gcon.platform = Cs then
  5479. { enull with etype = gen.greal_type e.etype }
  5480. else
  5481. mk_cast (gen.greal_type e.etype) enull
  5482. | _ ->
  5483. let last_unsafe = gen.gon_unsafe_cast in
  5484. gen.gon_unsafe_cast <- (fun t t2 pos -> ());
  5485. let ret = handle (run expr) e.etype expr.etype in
  5486. gen.gon_unsafe_cast <- last_unsafe;
  5487. match ret.eexpr with
  5488. | TCast _ -> ret
  5489. | _ -> { e with eexpr = TCast(ret,md); etype = gen.greal_type e.etype }
  5490. )
  5491. (*| TCast _ ->
  5492. (* if there is already a cast, we should skip this cast check *)
  5493. Type.map_expr run e*)
  5494. | TFunction f ->
  5495. in_value := false;
  5496. Type.map_expr run e
  5497. | _ -> Type.map_expr run e
  5498. in
  5499. run
  5500. let configure gen (mapping_func:texpr->texpr) =
  5501. gen.ghandle_cast <- (fun tto tfrom expr -> handle_cast gen expr (gen.greal_type tto) (gen.greal_type tfrom));
  5502. let map e = Some(mapping_func e) in
  5503. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map;
  5504. ReturnCast.configure gen
  5505. end;;
  5506. (* ******************************************* *)
  5507. (* Reflection-enabling Class fields *)
  5508. (* ******************************************* *)
  5509. (*
  5510. This is the most hardcore codegen part of the code. There's much to improve so this code can be more readable, but at least it's running correctly right now! This will be improved. (TODO)
  5511. This module will create class fields that enable reflection for targets that have a slow or inexistent reflection abilities. Because of the similarity
  5512. of strategies between what should have been different modules, they are all unified in this reflection-enabling class fields.
  5513. They include:
  5514. * Get(isStatic, throwErrors, isCheck) / Set fields . Remember to allow implements Dynamic also.
  5515. * Invoke fields(isStatic) -> You need to configure how many invoke_field fields there will be. + invokeDynamic
  5516. * Has field -> parameter in get field that returns __undefined__ if it doesn't exist.
  5517. * GetType -> return the current Class<> / Enum<>
  5518. * Fields(isStatic) -> returns all the fields / static fields. Remember to allow implements Dynamic also
  5519. * Create(arguments array), CreateEmpty - calls new() or create empty
  5520. * getInstanceFields / getClassFields -> show even function fields, everything!
  5521. * deleteField -> only for implements Dynamic
  5522. for enums:
  5523. * createEnum -> invokeField for classes
  5524. * createEnumIndex -> use invokeField as well, and use numbers e.g. "0", "1", "2" .... For this, use "@:alias" metadata
  5525. * getEnumConstructs -> fields()
  5526. need to be solved outside:
  5527. * getEnumName
  5528. * enumIndex
  5529. *
  5530. need to be solved by haxe code:
  5531. * enumParameters -> for (field in Reflect.fields(enum)) arr.push(Reflect.field(enum, field))
  5532. Standard:
  5533. if a class contains a @:$enum metadata, it's treated as a converted enum to class
  5534. Optimizations:
  5535. * if optimize is true, all fields will be hashed by the same hashing function as neko (31 bits int : always positive). Every function that expects a string for the field will expect also an int, for the hash
  5536. a string (which is nullable for compile-time hashes) + an int.
  5537. At compile-time, a collision will throw an error (like neko).
  5538. At runtime, a collision will make a negative int. Negative ints will always resolve to a special Hash<> field which takes a string.
  5539. * if optimize is true, Reflect.field/setField will be replaced by either the runtime version (with already hashed string), either by the own .Field()/.SetField() HxObject's version,
  5540. if the type is detected to already be hxgen
  5541. * TODO: if for() optimization for arrays is disabled, we can replace for(field in Reflect.fields(obj)) to:
  5542. for (field in ( (Std.is(obj, HxObject) ? ((HxObject)obj).Fields() : Reflect.fields(obj)) )) // no array copying . for further optimization this could be guaranteed to return
  5543. the already hashed fields.
  5544. Mappings:
  5545. * if create Dynamic class is true, TObjectDecl will be mapped to new DynamicClass(fields, [hashedFields], values)
  5546. *
  5547. dependencies:
  5548. There is no big dependency from this target. Though it should be a syntax filter, mainly one of the first so most expression generation has already been done,
  5549. while the AST has its meaning close to haxe's.
  5550. Should run before InitFunction so it detects variables containing expressions as "always-execute" expressions, even when using CreateEmpty
  5551. * Must run before switch() syntax changes
  5552. *)
  5553. open ClosuresToClass;;
  5554. module ReflectionCFs =
  5555. struct
  5556. let name = "reflection_cfs"
  5557. type rcf_ctx =
  5558. {
  5559. rcf_gen : generator_ctx;
  5560. rcf_ft : ClosuresToClass.closures_ctx;
  5561. rcf_optimize : bool;
  5562. mutable rcf_float_special_case : bool;
  5563. mutable rcf_object_iface : tclass;
  5564. mutable rcf_create_getsetinvoke_fields : bool;
  5565. (* should we create the get type (get Class)? *)
  5566. mutable rcf_create_get_type : bool;
  5567. (* should we handle implements dynamic? *)
  5568. mutable rcf_handle_impl_dynamic : bool;
  5569. (*
  5570. create_dyn_overloading_ctor :
  5571. when creating the implements dynamic code, we can also create a special constructor for
  5572. the actual DynamicObject class, which will receive all its <implements Dynamic> fields from the code outside.
  5573. Note that this will only work on targets that support overloading contrstuctors, as any class that extends
  5574. our DynamicObject will have an empty super() call
  5575. *)
  5576. mutable rcf_create_dyn_ctor : bool;
  5577. mutable rcf_max_func_arity : int;
  5578. (*
  5579. the hash lookup function. can be an inlined expr or simply a function call.
  5580. its only needed features is that it should return the index of the key if found, and the
  5581. complement of the index of where it should be inserted if not found (Ints).
  5582. hash->hash_array->returning expression
  5583. *)
  5584. mutable rcf_hash_function : texpr->texpr->texpr;
  5585. mutable rcf_lookup_function : texpr->texpr;
  5586. (*
  5587. class_cl is the real class for Class<> instances.
  5588. In the current implementation, due to some targets' limitations, (in particular, Java),
  5589. we have to use an empty object so we can access its virtual mehtods.
  5590. FIXME find a better way to create Class<> objects in a performant way
  5591. *)
  5592. mutable rcf_class_cl : tclass option;
  5593. (*
  5594. Also about the Class<> type, should we crate all classes eagerly?
  5595. If false, it means that we should have a way at runtime to create the class when needed by
  5596. Type.resolveClass/Enum
  5597. *)
  5598. mutable rcf_class_eager_creation : bool;
  5599. rcf_hash_fields : (int, string) Hashtbl.t;
  5600. (*
  5601. main expr -> field expr -> field string -> possible hash int (if optimize) -> possible set expr -> should_throw_exceptions -> changed expression
  5602. Changes a get / set field to the runtime resolution function
  5603. *)
  5604. mutable rcf_on_getset_field : texpr->texpr->string->int32 option->texpr option->bool->texpr;
  5605. mutable rcf_on_call_field : texpr->texpr->string->int32 option->texpr list->texpr;
  5606. mutable rcf_handle_statics : bool;
  5607. }
  5608. let new_ctx gen ft object_iface optimize dynamic_getset_field dynamic_call_field hash_function lookup_function handle_statics =
  5609. {
  5610. rcf_gen = gen;
  5611. rcf_ft = ft;
  5612. rcf_optimize = optimize;
  5613. rcf_float_special_case = true;
  5614. rcf_object_iface = object_iface;
  5615. rcf_create_getsetinvoke_fields = true;
  5616. rcf_create_get_type = true;
  5617. rcf_handle_impl_dynamic = true;
  5618. rcf_create_dyn_ctor = true;
  5619. rcf_max_func_arity = 10;
  5620. rcf_hash_function = hash_function;
  5621. rcf_lookup_function = lookup_function;
  5622. rcf_class_cl = None;
  5623. rcf_class_eager_creation = false;
  5624. rcf_hash_fields = Hashtbl.create 100;
  5625. rcf_on_getset_field = dynamic_getset_field;
  5626. rcf_on_call_field = dynamic_call_field;
  5627. rcf_handle_statics = handle_statics;
  5628. }
  5629. (*
  5630. methods as a bool option is a little laziness of my part.
  5631. None means that methods are included with normal fields;
  5632. Some(true) means collect only methods
  5633. Some(false) means collect only fields (and MethDynamic fields)
  5634. *)
  5635. let collect_fields cl (methods : bool option) (statics : bool option) =
  5636. let collected = Hashtbl.create 0 in
  5637. let collect cf acc =
  5638. if Meta.has Meta.CompilerGenerated cf.cf_meta || Meta.has Meta.SkipReflection cf.cf_meta then
  5639. acc
  5640. else match methods, cf.cf_kind with
  5641. | None, _ when not (Hashtbl.mem collected cf.cf_name) -> Hashtbl.add collected cf.cf_name true; ([cf.cf_name], cf) :: acc
  5642. | Some true, Method MethDynamic -> acc
  5643. | Some true, Method _ when not (Hashtbl.mem collected cf.cf_name) -> Hashtbl.add collected cf.cf_name true; ([cf.cf_name], cf) :: acc
  5644. | Some false, Method MethDynamic
  5645. | Some false, Var _ when not (Hashtbl.mem collected cf.cf_name) -> Hashtbl.add collected cf.cf_name true; ([cf.cf_name], cf) :: acc
  5646. | _ -> acc
  5647. in
  5648. let collect_cfs cfs acc =
  5649. let rec loop cfs acc =
  5650. match cfs with
  5651. | [] -> acc
  5652. | hd :: tl -> loop tl (collect hd acc)
  5653. in
  5654. loop cfs acc
  5655. in
  5656. let rec loop cl acc =
  5657. let acc = match statics with
  5658. | None -> collect_cfs cl.cl_ordered_fields (collect_cfs cl.cl_ordered_statics acc)
  5659. | Some true -> collect_cfs cl.cl_ordered_statics acc
  5660. | Some false -> collect_cfs cl.cl_ordered_fields acc
  5661. in
  5662. match cl.cl_super with
  5663. | None -> acc
  5664. | Some(cl,_) ->
  5665. if not (is_hxgen (TClassDecl cl)) then loop cl acc else acc
  5666. in
  5667. loop cl []
  5668. let hash f =
  5669. let h = ref 0 in
  5670. for i = 0 to String.length f - 1 do
  5671. h := !h * 223 + int_of_char (String.unsafe_get f i);
  5672. done;
  5673. if Sys.word_size = 64 then Int32.to_int (Int32.shift_right (Int32.shift_left (Int32.of_int !h) 1) 1) else !h
  5674. let hash_field ctx f pos =
  5675. let h = hash f in
  5676. (try
  5677. let f2 = Hashtbl.find ctx.rcf_hash_fields h in
  5678. if f <> f2 then ctx.rcf_gen.gcon.error ("Field conflict between " ^ f ^ " and " ^ f2) pos
  5679. with Not_found ->
  5680. Hashtbl.add ctx.rcf_hash_fields h f);
  5681. h
  5682. (* ( tf_args, switch_var ) *)
  5683. let field_type_args ctx pos =
  5684. match ctx.rcf_optimize with
  5685. | true ->
  5686. let field_name, field_hash = alloc_var "field" ctx.rcf_gen.gcon.basic.tstring, alloc_var "hash" ctx.rcf_gen.gcon.basic.tint in
  5687. [field_name, None; field_hash, None], field_hash
  5688. | false ->
  5689. let field_name = alloc_var "field" ctx.rcf_gen.gcon.basic.tstring in
  5690. [field_name, None], field_name
  5691. let hash_field_i32 ctx pos field_name =
  5692. let i = hash_field ctx field_name pos in
  5693. let i = Int32.of_int (i) in
  5694. if i < Int32.zero then
  5695. Int32.logor (Int32.logand i (Int32.of_int 0x3FFFFFFF)) (Int32.shift_left Int32.one 30)
  5696. else i
  5697. let switch_case ctx pos field_name =
  5698. match ctx.rcf_optimize with
  5699. | true ->
  5700. let i = hash_field_i32 ctx pos field_name in
  5701. { eexpr = TConst(TInt(i)); etype = ctx.rcf_gen.gcon.basic.tint; epos = pos }
  5702. | false ->
  5703. { eexpr = TConst(TString(field_name)); etype = ctx.rcf_gen.gcon.basic.tstring; epos = pos }
  5704. (*
  5705. Will implement getField / setField which will follow the following rule:
  5706. function getField(field, isStatic, throwErrors, isCheck, handleProperty, isFirst):Dynamic
  5707. {
  5708. if (isStatic)
  5709. {
  5710. switch(field)
  5711. {
  5712. case "aStaticField": return ThisClass.aStaticField;
  5713. case "aDynamicField": return ThisClass.aDynamicField;
  5714. default:
  5715. if (isFirst) return getField_d(field, isStatic, throwErrors, handleProperty, false);
  5716. if(throwErrors) throw "Field not found"; else if (isCheck) return __undefined__ else return null;
  5717. }
  5718. } else {
  5719. switch(field)
  5720. {
  5721. case "aNormalField": return this.aNormalField;
  5722. case "aBoolField": return this.aBoolField;
  5723. case "aDoubleField": return this.aDoubleField;
  5724. default: return getField_d(field, isStatic, throwErrors, isCheck);
  5725. }
  5726. }
  5727. }
  5728. function getField_d(field, isStatic, throwErrors, handleProperty, isFirst):Float
  5729. {
  5730. if (isStatic)
  5731. {
  5732. switch(field)
  5733. {
  5734. case "aDynamicField": return cast ThisClass.aDynamicField;
  5735. default: if (throwErrors) throw "Field not found"; else return null;
  5736. }
  5737. }
  5738. etc...
  5739. }
  5740. function setField(field, value, isStatic):Dynamic {}
  5741. function setField_d(field, value:Float, isStatic):Float {}
  5742. *)
  5743. let call_super ctx fn_args ret_t cf cl this_t pos =
  5744. {
  5745. eexpr = TCall({
  5746. eexpr = TField({ eexpr = TConst(TSuper); etype = this_t; epos = pos }, FInstance(cl,cf));
  5747. etype = TFun(fun_args fn_args, ret_t);
  5748. epos = pos;
  5749. }, List.map (fun (v,_) -> mk_local v pos) fn_args);
  5750. etype = ret_t;
  5751. epos = pos;
  5752. }
  5753. let mk_string ctx str pos =
  5754. { eexpr = TConst(TString(str)); etype = ctx.rcf_gen.gcon.basic.tstring; epos = pos }
  5755. let mk_int ctx i pos =
  5756. { eexpr = TConst(TInt(Int32.of_int i)); etype = ctx.rcf_gen.gcon.basic.tint; epos = pos }
  5757. let mk_bool ctx b pos =
  5758. { eexpr = TConst(TBool(b)); etype = ctx.rcf_gen.gcon.basic.tbool; epos = pos }
  5759. let mk_throw ctx str pos = { eexpr = TThrow (mk_string ctx str pos); etype = ctx.rcf_gen.gcon.basic.tvoid; epos = pos }
  5760. let enumerate_dynamic_fields ctx cl when_found =
  5761. let gen = ctx.rcf_gen in
  5762. let basic = gen.gcon.basic in
  5763. let pos = cl.cl_pos in
  5764. let mk_for arr =
  5765. let t = if ctx.rcf_optimize then basic.tint else basic.tstring in
  5766. let convert_str e = if ctx.rcf_optimize then ctx.rcf_lookup_function e else e in
  5767. let var = mk_temp gen "field" t in
  5768. {
  5769. eexpr = TFor(var, mk_iterator_access gen t arr, mk_block (when_found (convert_str (mk_local var pos))));
  5770. etype = basic.tvoid;
  5771. epos = pos;
  5772. }
  5773. in
  5774. let this_t = TInst(cl, List.map snd cl.cl_types) in
  5775. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  5776. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  5777. if ctx.rcf_optimize then
  5778. [
  5779. mk_for (mk_this (gen.gmk_internal_name "hx" "hashes") (basic.tarray basic.tint));
  5780. mk_for (mk_this (gen.gmk_internal_name "hx" "hashes_f") (basic.tarray basic.tint));
  5781. ] else [
  5782. mk_for (mk_this (gen.gmk_internal_name "hx" "hashes") (basic.tarray basic.tstring));
  5783. mk_for (mk_this (gen.gmk_internal_name "hx" "hashes_f") (basic.tarray basic.tstring));
  5784. ]
  5785. (* *********************
  5786. Dynamic lookup
  5787. *********************
  5788. This is the behavior of standard <implements Dynamic> classes. It will replace the error throwing
  5789. if a field doesn't exists when looking it up.
  5790. In order for it to work, an implementation for hash_function must be created.
  5791. hash_function is the function to be called/inlined that will allow us to lookup the hash into a sorted array of hashes.
  5792. A binary search or linear search algorithm may be implemented. The only need is that if not found, the NegBits of
  5793. the place where it should be inserted must be returned.
  5794. *)
  5795. let abstract_dyn_lookup_implementation ctx this hash_local may_value is_float pos =
  5796. let gen = ctx.rcf_gen in
  5797. let basic = gen.gcon.basic in
  5798. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  5799. let a_t = if ctx.rcf_optimize then basic.tint else basic.tstring in
  5800. let hx_hashes = mk_this (gen.gmk_internal_name "hx" "hashes") (basic.tarray a_t) in
  5801. let hx_hashes_f = mk_this (gen.gmk_internal_name "hx" "hashes_f") (basic.tarray a_t) in
  5802. let hx_dynamics = mk_this (gen.gmk_internal_name "hx" "dynamics") (basic.tarray t_empty) in
  5803. let hx_dynamics_f = mk_this (gen.gmk_internal_name "hx" "dynamics_f") (basic.tarray basic.tfloat) in
  5804. let res = alloc_var "res" basic.tint in
  5805. let fst_hash, snd_hash, fst_dynamics, snd_dynamics =
  5806. if is_float then hx_hashes_f, hx_hashes, hx_dynamics_f, hx_dynamics else hx_hashes, hx_hashes_f, hx_dynamics, hx_dynamics_f
  5807. in
  5808. let res_local = mk_local res pos in
  5809. let gte = {
  5810. eexpr = TBinop(Ast.OpGte, res_local, { eexpr = TConst(TInt(Int32.zero)); etype = basic.tint; epos = pos });
  5811. etype = basic.tbool;
  5812. epos = pos;
  5813. } in
  5814. let get_array_t t = match follow t with | TInst({ cl_path = ([],"Array") },[arrtype]) -> arrtype | _ -> assert false in
  5815. let mk_tarray arr idx =
  5816. let t = get_array_t arr.etype in
  5817. {
  5818. eexpr = TArray(arr, idx);
  5819. etype = t;
  5820. epos = pos;
  5821. }
  5822. in
  5823. let ret_t = if is_float then basic.tfloat else t_dynamic in
  5824. match may_value with
  5825. | None ->
  5826. (*
  5827. var res = lookup(this.__hx_hashes/f, hash);
  5828. if (res < 0)
  5829. {
  5830. res = lookup(this.__hx_hashes_f/_, hash);
  5831. if(res < 0)
  5832. return null;
  5833. else
  5834. return __hx_dynamics_f[res];
  5835. } else {
  5836. return __hx_dynamics[res];
  5837. }
  5838. *)
  5839. let block =
  5840. [
  5841. { eexpr = TVar(res, Some(ctx.rcf_hash_function hash_local fst_hash)); etype = basic.tvoid; epos = pos };
  5842. { eexpr = TIf(gte, mk_return (mk_tarray fst_dynamics res_local), Some({
  5843. eexpr = TBlock(
  5844. [
  5845. { eexpr = TBinop(Ast.OpAssign, res_local, ctx.rcf_hash_function hash_local snd_hash); etype = basic.tint; epos = pos };
  5846. { eexpr = TIf(gte, mk_return (mk_tarray snd_dynamics res_local), None); etype = ret_t; epos = pos }
  5847. ]);
  5848. etype = ret_t;
  5849. epos = pos;
  5850. })); etype = ret_t; epos = pos }
  5851. ] in
  5852. block
  5853. | Some value_local ->
  5854. (*
  5855. //if is not float:
  5856. //if (isNumber(value_local)) return this.__hx_setField_f(field, getNumber(value_local), false(not static));
  5857. var res = lookup(this.__hx_hashes/f, hash);
  5858. if (res >= 0)
  5859. {
  5860. return __hx_dynamics/f[res] = value_local;
  5861. } else {
  5862. res = lookup(this.__hx_hashes_f/_, hash);
  5863. if (res >= 0)
  5864. {
  5865. __hx_dynamics_f/_.splice(res,1);
  5866. __hx_hashes_f/_.splice(res,1);
  5867. }
  5868. }
  5869. __hx_hashses/_f.insert(~res, hash);
  5870. __hx_dynamics/_f.insert(~res, value_local);
  5871. return value_local;
  5872. *)
  5873. let mk_splice arr at_pos = {
  5874. eexpr = TCall(
  5875. mk_field_access gen arr "splice" pos,
  5876. [at_pos; { eexpr = TConst(TInt Int32.one); etype = basic.tint; epos = pos }]
  5877. );
  5878. etype = arr.etype;
  5879. epos = pos
  5880. } in
  5881. let mk_insert arr at_pos value = {
  5882. eexpr = TCall(
  5883. mk_field_access gen arr "insert" pos,
  5884. [at_pos; value]);
  5885. etype = basic.tvoid;
  5886. epos = pos
  5887. } in
  5888. let neg_res = { eexpr = TUnop(Ast.NegBits, Ast.Prefix, res_local); etype = basic.tint; epos = pos } in
  5889. let res2 = alloc_var "res2" basic.tint in
  5890. let res2_local = mk_local res2 pos in
  5891. let gte2 = {
  5892. eexpr = TBinop(Ast.OpGte, res2_local, { eexpr = TConst(TInt(Int32.zero)); etype = basic.tint; epos = pos });
  5893. etype = basic.tbool;
  5894. epos = pos;
  5895. } in
  5896. let block =
  5897. [
  5898. { eexpr = TVar(res, Some(ctx.rcf_hash_function hash_local fst_hash)); etype = basic.tvoid; epos = pos };
  5899. {
  5900. eexpr = TIf(gte,
  5901. mk_return { eexpr = TBinop(Ast.OpAssign, mk_tarray fst_dynamics res_local, value_local); etype = value_local.etype; epos = pos },
  5902. Some({ eexpr = TBlock([
  5903. { eexpr = TVar( res2, Some(ctx.rcf_hash_function hash_local snd_hash)); etype = basic.tvoid; epos = pos };
  5904. {
  5905. eexpr = TIf(gte2, { eexpr = TBlock([
  5906. mk_splice snd_hash res2_local;
  5907. mk_splice snd_dynamics res2_local
  5908. ]); etype = t_dynamic; epos = pos }, None);
  5909. etype = t_dynamic;
  5910. epos = pos;
  5911. }
  5912. ]); etype = t_dynamic; epos = pos }));
  5913. etype = t_dynamic;
  5914. epos = pos;
  5915. };
  5916. mk_insert fst_hash neg_res hash_local;
  5917. mk_insert fst_dynamics neg_res value_local;
  5918. mk_return value_local
  5919. ] in
  5920. block
  5921. let get_delete_field ctx cl is_dynamic =
  5922. let pos = cl.cl_pos in
  5923. let this_t = TInst(cl, List.map snd cl.cl_types) in
  5924. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  5925. let gen = ctx.rcf_gen in
  5926. let basic = gen.gcon.basic in
  5927. let tf_args, switch_var = field_type_args ctx pos in
  5928. let local_switch_var = mk_local switch_var pos in
  5929. let fun_type = TFun(fun_args tf_args,basic.tbool) in
  5930. let cf = mk_class_field (gen.gmk_internal_name "hx" "deleteField") fun_type false pos (Method MethNormal) [] in
  5931. let body = if is_dynamic then begin
  5932. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  5933. let a_t = if ctx.rcf_optimize then basic.tint else basic.tstring in
  5934. let hx_hashes = mk_this (gen.gmk_internal_name "hx" "hashes") (basic.tarray a_t) in
  5935. let hx_hashes_f = mk_this (gen.gmk_internal_name "hx" "hashes_f") (basic.tarray a_t) in
  5936. let hx_dynamics = mk_this (gen.gmk_internal_name "hx" "dynamics") (basic.tarray t_empty) in
  5937. let hx_dynamics_f = mk_this (gen.gmk_internal_name "hx" "dynamics_f") (basic.tarray basic.tfloat) in
  5938. let res = alloc_var "res" basic.tint in
  5939. let res_local = mk_local res pos in
  5940. let gte = {
  5941. eexpr = TBinop(Ast.OpGte, res_local, { eexpr = TConst(TInt(Int32.zero)); etype = basic.tint; epos = pos });
  5942. etype = basic.tbool;
  5943. epos = pos;
  5944. } in
  5945. let mk_splice arr at_pos = {
  5946. eexpr = TCall(
  5947. mk_field_access gen arr "splice" pos,
  5948. [at_pos; { eexpr = TConst(TInt Int32.one); etype = basic.tint; epos = pos }]
  5949. );
  5950. etype = arr.etype;
  5951. epos = pos
  5952. } in
  5953. (*
  5954. var res = lookup(this.__hx_hashes, hash);
  5955. if (res >= 0)
  5956. {
  5957. __hx_dynamics.splice(res,1);
  5958. __hx_hashes.splice(res,1);
  5959. return true;
  5960. } else {
  5961. res = lookup(this.__hx_hashes_f, hash);
  5962. if (res >= 0)
  5963. {
  5964. __hx_dynamics_f.splice(res,1);
  5965. __hx_hashes_f.splice(res,1);
  5966. return true;
  5967. }
  5968. }
  5969. return false;
  5970. *)
  5971. [
  5972. { eexpr = TVar(res,Some(ctx.rcf_hash_function local_switch_var hx_hashes)); etype = basic.tvoid; epos = pos };
  5973. {
  5974. eexpr = TIf(gte, { eexpr = TBlock([
  5975. mk_splice hx_hashes res_local;
  5976. mk_splice hx_dynamics res_local;
  5977. mk_return { eexpr = TConst(TBool true); etype = basic.tbool; epos = pos }
  5978. ]); etype = t_dynamic; epos = pos }, Some({ eexpr = TBlock([
  5979. { eexpr = TBinop(Ast.OpAssign, res_local, ctx.rcf_hash_function local_switch_var hx_hashes_f); etype = basic.tint; epos = pos };
  5980. { eexpr = TIf(gte, { eexpr = TBlock([
  5981. mk_splice hx_hashes_f res_local;
  5982. mk_splice hx_dynamics_f res_local;
  5983. mk_return { eexpr = TConst(TBool true); etype = basic.tbool; epos = pos }
  5984. ]); etype = t_dynamic; epos = pos }, None); etype = t_dynamic; epos = pos }
  5985. ]); etype = t_dynamic; epos = pos }));
  5986. etype = t_dynamic;
  5987. epos = pos;
  5988. };
  5989. mk_return { eexpr = TConst(TBool false); etype = basic.tbool; epos = pos }
  5990. ]
  5991. end else
  5992. [
  5993. mk_return { eexpr = TConst(TBool false); etype = basic.tbool; epos = pos }
  5994. ] in
  5995. (* create function *)
  5996. let fn =
  5997. {
  5998. tf_args = tf_args;
  5999. tf_type = basic.tbool;
  6000. tf_expr = { eexpr = TBlock(body); etype = t_dynamic; epos = pos }
  6001. } in
  6002. cf.cf_expr <- Some({ eexpr = TFunction(fn); etype = fun_type; epos = pos });
  6003. cf
  6004. let rec is_first_dynamic cl =
  6005. match cl.cl_super with
  6006. | Some(cl,_) ->
  6007. if is_some cl.cl_dynamic then false else is_first_dynamic cl
  6008. | None -> true
  6009. let is_override cl = match cl.cl_super with
  6010. | Some (cl, _) when is_hxgen (TClassDecl cl) -> true
  6011. | _ -> false
  6012. let get_args t = match follow t with
  6013. | TFun(args,ret) -> args,ret
  6014. | _ -> assert false
  6015. (* WARNING: this will only work if overloading contructors is possible on target language *)
  6016. let implement_dynamic_object_ctor ctx cl =
  6017. let rec is_side_effects_free e =
  6018. match e.eexpr with
  6019. | TConst _
  6020. | TLocal _
  6021. | TFunction _
  6022. | TTypeExpr _ ->
  6023. true
  6024. | TNew(clnew,[],params) when clnew == cl ->
  6025. List.for_all is_side_effects_free params
  6026. | TUnop(Increment,_,_)
  6027. | TUnop(Decrement,_,_)
  6028. | TBinop(OpAssign,_,_)
  6029. | TBinop(OpAssignOp _,_,_) ->
  6030. false
  6031. | TUnop(_,_,e) ->
  6032. is_side_effects_free e
  6033. | TArray(e1,e2)
  6034. | TBinop(_,e1,e2) ->
  6035. is_side_effects_free e1 && is_side_effects_free e2
  6036. | TIf(cond,e1,Some e2) ->
  6037. is_side_effects_free cond && is_side_effects_free e1 && is_side_effects_free e2
  6038. | TField(e,_)
  6039. | TParenthesis e | TMeta(_,e) -> is_side_effects_free e
  6040. | TArrayDecl el -> List.for_all is_side_effects_free el
  6041. | TCast(e,_) -> is_side_effects_free e
  6042. | _ -> false
  6043. in
  6044. let pos = cl.cl_pos in
  6045. let gen = ctx.rcf_gen in
  6046. let basic = gen.gcon.basic in
  6047. let hasht = if ctx.rcf_optimize then basic.tint else basic.tstring in
  6048. let fields =
  6049. [
  6050. gen.gmk_internal_name "hx" "hashes", basic.tarray hasht;
  6051. gen.gmk_internal_name "hx" "dynamics", basic.tarray t_empty;
  6052. gen.gmk_internal_name "hx" "hashes_f", basic.tarray hasht;
  6053. gen.gmk_internal_name "hx" "dynamics_f", basic.tarray basic.tfloat;
  6054. ] in
  6055. let tf_args = List.map (fun (name, t) ->
  6056. alloc_var name t, None
  6057. ) fields in
  6058. let this = { eexpr = TConst TThis; etype = TInst(cl, List.map snd cl.cl_types); epos = pos } in
  6059. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  6060. let fun_t = TFun(fun_args tf_args,basic.tvoid) in
  6061. let ctor = mk_class_field "new" fun_t true pos (Method MethNormal) [] in
  6062. ctor.cf_expr <- Some(
  6063. {
  6064. eexpr = TFunction({
  6065. tf_args = tf_args;
  6066. tf_type = basic.tvoid;
  6067. tf_expr =
  6068. {
  6069. eexpr = TBlock(List.map (fun (v,_) ->
  6070. { eexpr = TBinop(Ast.OpAssign, mk_this v.v_name v.v_type, mk_local v pos); etype = v.v_type; epos = pos }
  6071. ) tf_args);
  6072. etype = basic.tvoid;
  6073. epos = pos
  6074. }
  6075. });
  6076. etype = fun_t;
  6077. epos = pos
  6078. });
  6079. add_constructor cl ctor;
  6080. (* default ctor also *)
  6081. let ctor = mk_class_field "new" (TFun([],basic.tvoid)) false pos (Method MethNormal) [] in
  6082. ctor.cf_expr <- Some {
  6083. eexpr = TFunction {
  6084. tf_type = basic.tvoid;
  6085. tf_args = [];
  6086. tf_expr = {
  6087. eexpr = TBlock(List.map (fun (f,t) ->
  6088. { eexpr = TBinop(Ast.OpAssign, mk_this f t,{ eexpr = TArrayDecl([]); etype = t; epos = pos; }); etype = t; epos = pos }
  6089. ) fields);
  6090. etype = basic.tvoid;
  6091. epos = pos;
  6092. }
  6093. };
  6094. etype = ctor.cf_type;
  6095. epos = pos;
  6096. };
  6097. add_constructor cl ctor;
  6098. (* and finally we will return a function that transforms a TObjectDecl into a new DynamicObject() call *)
  6099. let rec loop objdecl acc acc_f =
  6100. match objdecl with
  6101. | [] -> acc,acc_f
  6102. | (name,expr) :: tl ->
  6103. let real_t = gen.greal_type expr.etype in
  6104. match follow expr.etype with
  6105. | TInst ( { cl_path = ["haxe"], "Int64" }, [] ) ->
  6106. loop tl ((name, gen.ghandle_cast t_dynamic real_t expr) :: acc) acc_f
  6107. | _ ->
  6108. if like_float real_t then
  6109. loop tl acc ((name, gen.ghandle_cast basic.tfloat real_t expr) :: acc_f)
  6110. else
  6111. loop tl ((name, gen.ghandle_cast t_dynamic real_t expr) :: acc) acc_f
  6112. in
  6113. let may_hash_field s =
  6114. if ctx.rcf_optimize then begin
  6115. (* let hash_field ctx f pos = *)
  6116. { eexpr = TConst(TInt (hash_field_i32 ctx pos s)); etype = basic.tint; epos = pos }
  6117. end else begin
  6118. { eexpr = TConst(TString s); etype = basic.tstring; epos = pos }
  6119. end
  6120. in
  6121. let do_objdecl e objdecl =
  6122. let exprs_before = ref [] in
  6123. let rec change_exprs decl acc = match decl with
  6124. | (name,expr) :: tl ->
  6125. if is_side_effects_free expr then
  6126. change_exprs tl ((name,expr) :: acc)
  6127. else begin
  6128. let var = mk_temp gen "odecl" expr.etype in
  6129. exprs_before := { eexpr = TVar(var,Some expr); etype = basic.tvoid; epos = expr.epos } :: !exprs_before;
  6130. change_exprs tl ((name,mk_local var expr.epos) :: acc)
  6131. end
  6132. | [] -> acc
  6133. in
  6134. let objdecl = change_exprs objdecl [] in
  6135. let odecl, odecl_f = loop objdecl [] [] in
  6136. let changed_expr = List.map (fun (s,e) -> (may_hash_field s,e)) in
  6137. let odecl, odecl_f = changed_expr odecl, changed_expr odecl_f in
  6138. let sort_fn (e1,_) (e2,_) =
  6139. match e1.eexpr, e2.eexpr with
  6140. | TConst(TInt i1), TConst(TInt i2) -> compare i1 i2
  6141. | TConst(TString s1), TConst(TString s2) -> compare s1 s2
  6142. | _ -> assert false
  6143. in
  6144. let odecl, odecl_f = List.sort sort_fn odecl, List.sort sort_fn odecl_f in
  6145. let mk_arrdecl el t = { eexpr = TArrayDecl(el); etype = t; epos = pos } in
  6146. let ret = {
  6147. e with eexpr = TNew(cl,[],
  6148. [
  6149. mk_arrdecl (List.map fst odecl) (basic.tarray hasht);
  6150. mk_arrdecl (List.map snd odecl) (basic.tarray t_empty);
  6151. mk_arrdecl (List.map fst odecl_f) (basic.tarray hasht);
  6152. mk_arrdecl (List.map snd odecl_f) (basic.tarray basic.tfloat)
  6153. ]);
  6154. } in
  6155. match !exprs_before with
  6156. | [] -> ret
  6157. | block ->
  6158. {
  6159. eexpr = TBlock(List.rev block @ [ret]);
  6160. etype = ret.etype;
  6161. epos = ret.epos;
  6162. }
  6163. in
  6164. do_objdecl
  6165. let implement_dynamics ctx cl =
  6166. let pos = cl.cl_pos in
  6167. let is_override = is_override cl in
  6168. if is_some cl.cl_dynamic then begin
  6169. if is_first_dynamic cl then begin
  6170. (*
  6171. * add hx_hashes, hx_hashes_f, hx_dynamics, hx_dynamics_f to class
  6172. * implement hx_deleteField
  6173. *)
  6174. let gen = ctx.rcf_gen in
  6175. let basic = gen.gcon.basic in
  6176. let hasht = if ctx.rcf_optimize then basic.tint else basic.tstring in
  6177. let new_fields =
  6178. [
  6179. mk_class_field (gen.gmk_internal_name "hx" "hashes") (basic.tarray hasht) false pos (Var { v_read = AccNormal; v_write = AccNormal }) [];
  6180. mk_class_field (gen.gmk_internal_name "hx" "dynamics") (basic.tarray t_empty) false pos (Var { v_read = AccNormal; v_write = AccNormal }) [];
  6181. mk_class_field (gen.gmk_internal_name "hx" "hashes_f") (basic.tarray hasht) false pos (Var { v_read = AccNormal; v_write = AccNormal }) [];
  6182. mk_class_field (gen.gmk_internal_name "hx" "dynamics_f") (basic.tarray basic.tfloat) false pos (Var { v_read = AccNormal; v_write = AccNormal }) [];
  6183. ] in
  6184. (if cl.cl_path <> (["haxe"; "lang"], "DynamicObject") then
  6185. List.iter (fun cf -> cf.cf_expr <- Some { eexpr = TArrayDecl([]); etype = cf.cf_type; epos = cf.cf_pos }) new_fields
  6186. );
  6187. let delete = get_delete_field ctx cl true in
  6188. List.iter (fun cf ->
  6189. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields
  6190. ) (delete :: new_fields);
  6191. (*
  6192. let rec last_ctor cl =
  6193. match cl.cl_constructor with
  6194. | None -> (match cl.cl_super with | None -> None | Some (cl,_) -> last_ctor cl)
  6195. | Some c -> Some c
  6196. in
  6197. *)
  6198. (*
  6199. in order for the next to work, we need to execute our script before InitFunction, so the expressions inside the variables are initialized by the constructor
  6200. *)
  6201. (*
  6202. Now we need to add their initialization.
  6203. This will consist of different parts:
  6204. Check if there are constructors. If not, create one and add initialization to it (calling super, ok)
  6205. If there are, add as first statement (or second if there is a super() call in the first)
  6206. If class has @:$DynamicObject meta, also create another new() class with its parameters as constructor arguments
  6207. *)
  6208. List.iter (fun cf ->
  6209. cf.cf_expr <- Some({ eexpr = TArrayDecl([]); etype = cf.cf_type; epos = cf.cf_pos })
  6210. ) new_fields;
  6211. cl.cl_ordered_fields <- cl.cl_ordered_fields @ (delete :: new_fields);
  6212. if is_override then cl.cl_overrides <- delete :: cl.cl_overrides
  6213. end
  6214. end else if not is_override then begin
  6215. let delete = get_delete_field ctx cl false in
  6216. cl.cl_ordered_fields <- cl.cl_ordered_fields @ [delete];
  6217. cl.cl_fields <- PMap.add delete.cf_name delete cl.cl_fields
  6218. end
  6219. let implement_create_empty ctx cl =
  6220. let gen = ctx.rcf_gen in
  6221. let basic = gen.gcon.basic in
  6222. let pos = cl.cl_pos in
  6223. let is_override = is_override cl in
  6224. let tparams = List.map (fun _ -> t_empty) cl.cl_types in
  6225. let create =
  6226. let arr = alloc_var "arr" (basic.tarray t_dynamic) in
  6227. let tf_args = [ arr, None ] in
  6228. let t = TFun(fun_args tf_args, t_dynamic) in
  6229. let cf = mk_class_field (gen.gmk_internal_name "hx" "create") t false pos (Method MethNormal) [] in
  6230. let i = ref 0 in
  6231. let arr_local = mk_local arr pos in
  6232. let ctor = if is_some cl.cl_constructor then cl.cl_constructor else get_last_ctor cl in
  6233. let params = match ctor with
  6234. | None -> []
  6235. | Some ctor ->
  6236. List.map (fun (n,_,t) ->
  6237. let old = !i in
  6238. incr i;
  6239. {
  6240. eexpr = TArray(arr_local, { eexpr = TConst(TInt (Int32.of_int old)); etype = basic.tint; epos = pos } );
  6241. etype = t_dynamic;
  6242. epos = pos
  6243. }
  6244. ) ( fst ( get_fun ctor.cf_type ) )
  6245. in
  6246. let expr = mk_return {
  6247. eexpr = TNew(cl, tparams, params);
  6248. etype = TInst(cl, tparams);
  6249. epos = pos
  6250. } in
  6251. let fn = {
  6252. eexpr = TFunction({
  6253. tf_args = tf_args;
  6254. tf_type = t_dynamic;
  6255. tf_expr = mk_block expr
  6256. });
  6257. etype = t;
  6258. epos = pos
  6259. } in
  6260. cf.cf_expr <- Some fn;
  6261. cf
  6262. in
  6263. let create_empty =
  6264. let t = TFun([],t_dynamic) in
  6265. let cf = mk_class_field (gen.gmk_internal_name "hx" "createEmpty") t false pos (Method MethNormal) [] in
  6266. let fn = {
  6267. eexpr = TFunction({
  6268. tf_args = [];
  6269. tf_type = t_dynamic;
  6270. tf_expr = mk_block (mk_return ( gen.gtools.rf_create_empty cl tparams pos ))
  6271. });
  6272. etype = t;
  6273. epos = pos
  6274. } in
  6275. cf.cf_expr <- Some fn;
  6276. cf
  6277. in
  6278. (* if rcf_handle_statics is false, there is no reason to make createEmpty/create not be static *)
  6279. if ctx.rcf_handle_statics then begin
  6280. cl.cl_ordered_fields <- cl.cl_ordered_fields @ [create_empty; create];
  6281. cl.cl_fields <- PMap.add create_empty.cf_name create_empty cl.cl_fields;
  6282. cl.cl_fields <- PMap.add create.cf_name create cl.cl_fields;
  6283. if is_override then begin
  6284. cl.cl_overrides <- create_empty :: create :: cl.cl_overrides
  6285. end
  6286. end else begin
  6287. cl.cl_ordered_statics <- cl.cl_ordered_statics @ [create_empty; create];
  6288. cl.cl_statics <- PMap.add create_empty.cf_name create_empty cl.cl_statics;
  6289. cl.cl_statics <- PMap.add create.cf_name create cl.cl_statics
  6290. end
  6291. (*
  6292. Implements:
  6293. __hx_lookupField(field:String, throwErrors:Bool, isCheck:Bool, handleProperties:Bool, isFirst:Bool):Dynamic
  6294. __hx_lookupField_f(field:String, throwErrors:Bool, handleProperties:Bool, isFirst:Bool):Float
  6295. __hx_lookupSetField(field:String, value:Dynamic, handleProperties:Bool, isFirst:Bool):Dynamic;
  6296. __hx_lookupSetField(field:String, value:Float, handleProperties:Bool, isFirst:Bool):Float;
  6297. *)
  6298. let implement_final_lookup ctx cl =
  6299. let gen = ctx.rcf_gen in
  6300. let basic = gen.gcon.basic in
  6301. let pos = cl.cl_pos in
  6302. let is_override = is_override cl in
  6303. let this = { eexpr = TConst(TThis); etype = TInst(cl, List.map snd cl.cl_types); epos = pos } in
  6304. (*
  6305. this function will create the class fields and call callback for each version
  6306. callback : is_float fields_args switch_var throw_errors_option is_check_option value_option : texpr list
  6307. *)
  6308. let create_cfs is_dynamic callback =
  6309. let create_cf is_float is_set =
  6310. let name = gen.gmk_internal_name "hx" ( (if is_set then "lookupSetField" else "lookupField") ^ (if is_float then "_f" else "") ) in
  6311. let field_args, switch_var = field_type_args ctx pos in
  6312. let ret_t = if is_float then basic.tfloat else t_dynamic in
  6313. let tf_args, throw_errors_opt =
  6314. if is_set then
  6315. field_args, None
  6316. else
  6317. let v = alloc_var "throwErrors" basic.tbool in
  6318. field_args @ [v,None], Some v
  6319. in
  6320. let tf_args, is_check_opt =
  6321. if is_set || is_float then
  6322. tf_args, None
  6323. else
  6324. let v = alloc_var "isCheck" basic.tbool in
  6325. tf_args @ [v,None], Some v
  6326. in
  6327. let tf_args, value_opt =
  6328. if not is_set then
  6329. tf_args, None
  6330. else
  6331. let v = alloc_var "value" ret_t in
  6332. field_args @ [v,None], Some v
  6333. in
  6334. let fun_t = TFun(fun_args tf_args, ret_t) in
  6335. let cf = mk_class_field name fun_t false pos (Method MethNormal) [] in
  6336. let block = callback is_float field_args switch_var throw_errors_opt is_check_opt value_opt in
  6337. let block = if not is_set then let tl = begin
  6338. let throw_errors_local = mk_local (get throw_errors_opt) pos in
  6339. let mk_check_throw msg =
  6340. {
  6341. eexpr = TIf(throw_errors_local, mk_throw ctx msg pos, Some (mk_return (null ret_t pos)));
  6342. etype = ret_t;
  6343. epos = pos
  6344. } in
  6345. let mk_may_check_throw msg = if is_dynamic then mk_return (null ret_t pos) else mk_check_throw msg in
  6346. if is_float then begin
  6347. [
  6348. mk_may_check_throw "Field not found or incompatible field type.";
  6349. ]
  6350. end else begin
  6351. let undefined = alloc_var "__undefined__" t_dynamic in
  6352. let undefined_local = mk_local undefined pos in
  6353. let is_check_local = mk_local (get is_check_opt) pos in
  6354. [
  6355. {
  6356. eexpr = TIf(is_check_local, mk_return undefined_local, Some( mk_may_check_throw "Field not found." ));
  6357. etype = ret_t;
  6358. epos = pos;
  6359. }
  6360. ]
  6361. end
  6362. end in block @ tl else block in
  6363. cf.cf_expr <- Some(
  6364. {
  6365. eexpr = TFunction({
  6366. tf_args = tf_args;
  6367. tf_type = ret_t;
  6368. tf_expr = { eexpr = TBlock(block); etype = ret_t; epos = pos }
  6369. });
  6370. etype = fun_t;
  6371. epos = pos
  6372. }
  6373. );
  6374. cf
  6375. in
  6376. let cfs =
  6377. [
  6378. create_cf false false;
  6379. create_cf true false;
  6380. create_cf false true;
  6381. create_cf true true
  6382. ] in
  6383. cl.cl_ordered_fields <- cl.cl_ordered_fields @ cfs;
  6384. List.iter (fun cf ->
  6385. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields;
  6386. if is_override then cl.cl_overrides <- cf :: cl.cl_overrides
  6387. ) cfs
  6388. in
  6389. if is_some cl.cl_dynamic then begin
  6390. (* let abstract_dyn_lookup_implementation ctx this hash_local may_value is_float pos = *)
  6391. (* callback : is_float fields_args switch_var throw_errors_option is_check_option value_option : texpr list *)
  6392. if is_first_dynamic cl then
  6393. create_cfs true (fun is_float fields_args switch_var _ _ value_opt ->
  6394. abstract_dyn_lookup_implementation ctx this (mk_local switch_var pos) (Option.map (fun v -> mk_local v pos) value_opt) is_float pos
  6395. )
  6396. end else if not is_override then begin
  6397. create_cfs false (fun is_float fields_args switch_var _ _ value_opt ->
  6398. match value_opt with
  6399. | None -> (* is not set *)
  6400. []
  6401. | Some _ -> (* is set *)
  6402. if is_float then
  6403. [ mk_throw ctx "Cannot access field for writing or incompatible type." pos ]
  6404. else
  6405. [ mk_throw ctx "Cannot access field for writing." pos ]
  6406. )
  6407. end
  6408. (* *)
  6409. let implement_get_set ctx cl =
  6410. let gen = ctx.rcf_gen in
  6411. let mk_cfield is_set is_float =
  6412. let pos = cl.cl_pos in
  6413. let basic = ctx.rcf_gen.gcon.basic in
  6414. let tf_args, switch_var = field_type_args ctx pos in
  6415. let field_args = tf_args in
  6416. let local_switch_var = { eexpr = TLocal(switch_var); etype = switch_var.v_type; epos = pos } in
  6417. let is_static = alloc_var "isStatic" basic.tbool in
  6418. let is_static_local = { eexpr = TLocal(is_static); etype = basic.tbool; epos = pos } in
  6419. let handle_prop = alloc_var "handleProperties" basic.tbool in
  6420. let handle_prop_local = mk_local handle_prop pos in
  6421. let this = { eexpr = TConst TThis; etype = TInst(cl, List.map snd cl.cl_types); epos = pos } in
  6422. let mk_this_call_raw name fun_t params =
  6423. { eexpr = TCall( { (mk_field_access gen this name pos) with etype = fun_t; }, params ); etype = snd (get_args fun_t); epos = pos }
  6424. in
  6425. let tf_args = if ctx.rcf_handle_statics then tf_args @ [is_static, None] else tf_args in
  6426. let fun_type = ref (TFun([], basic.tvoid)) in
  6427. let fun_name = ctx.rcf_gen.gmk_internal_name "hx" ( (if is_set then "setField" else "getField") ^ (if is_float then "_f" else "") ) in
  6428. let cfield = mk_class_field fun_name !fun_type false pos (Method MethNormal) [] in
  6429. let maybe_cast e = e in
  6430. let t = TInst(cl, List.map snd cl.cl_types) in
  6431. (* if it's not latest hxgen class -> check super *)
  6432. let mk_do_default args do_default =
  6433. match cl.cl_super with
  6434. | None -> fun () -> maybe_cast (do_default ())
  6435. | Some (super, sparams) when not (is_hxgen (TClassDecl super)) ->
  6436. fun () -> maybe_cast (do_default ())
  6437. | _ ->
  6438. fun () ->
  6439. mk_return {
  6440. eexpr = TCall(
  6441. { eexpr = TField({ eexpr = TConst TSuper; etype = t; epos = pos }, FInstance(cl, cfield)); etype = !fun_type; epos = pos },
  6442. (List.map (fun (v,_) -> mk_local v pos) args) );
  6443. etype = if is_float then basic.tfloat else t_dynamic;
  6444. epos = pos;
  6445. };
  6446. in
  6447. (* if it is set function, there are some different set fields to do *)
  6448. let do_default, do_default_static , do_field, tf_args = if is_set then begin
  6449. let value_var = alloc_var "value" (if is_float then basic.tfloat else t_dynamic) in
  6450. let value_local = { eexpr = TLocal(value_var); etype = value_var.v_type; epos = pos } in
  6451. let tf_args = tf_args @ [value_var,None; handle_prop, None; ] in
  6452. let lookup_name = gen.gmk_internal_name "hx" ("lookupSetField" ^ if is_float then "_f" else "") in
  6453. let do_default =
  6454. fun () ->
  6455. mk_return (mk_this_call_raw lookup_name (TFun(fun_args (field_args @ [value_var,None]),value_var.v_type)) ( List.map (fun (v,_) -> mk_local v pos) field_args @ [ value_local ] ))
  6456. in
  6457. let do_field cf cf_type is_static =
  6458. let get_field ethis = { eexpr = TField (ethis, if is_static then FStatic (cl, cf) else FInstance(cl, cf)); etype = cf_type; epos = pos } in
  6459. let this = if is_static then mk_classtype_access cl pos else { eexpr = TConst(TThis); etype = t; epos = pos } in
  6460. let value_local = if is_float then match follow cf_type with
  6461. | TInst({ cl_kind = KTypeParameter _ }, _) ->
  6462. mk_cast t_dynamic value_local
  6463. | _ ->
  6464. value_local
  6465. else
  6466. value_local
  6467. in
  6468. let ret =
  6469. {
  6470. eexpr = TBlock([
  6471. {
  6472. eexpr = TBinop(Ast.OpAssign,
  6473. get_field this,
  6474. mk_cast cf_type value_local);
  6475. etype = cf_type;
  6476. epos = pos;
  6477. };
  6478. mk_return value_local
  6479. ]);
  6480. etype = cf_type;
  6481. epos = pos;
  6482. } in
  6483. match cf.cf_kind with
  6484. | Var { v_write = AccCall } ->
  6485. let bl =
  6486. [
  6487. mk_this_call_raw ("set_" ^ cf.cf_name) (TFun(["value",false,cf.cf_type], cf.cf_type)) [ value_local ];
  6488. mk_return value_local
  6489. ] in
  6490. if Type.is_extern_field cf then
  6491. { eexpr = TBlock bl; etype = value_local.etype; epos = pos }
  6492. else
  6493. {
  6494. eexpr = TIf(
  6495. handle_prop_local,
  6496. { eexpr = TBlock bl; etype = value_local.etype; epos = pos },
  6497. Some ret);
  6498. etype = value_local.etype;
  6499. epos = pos;
  6500. }
  6501. | _ ->
  6502. ret
  6503. in
  6504. (mk_do_default tf_args do_default, do_default, do_field, tf_args)
  6505. end else begin
  6506. (* (field, isStatic, throwErrors, isCheck):Dynamic *)
  6507. let throw_errors = alloc_var "throwErrors" basic.tbool in
  6508. let throw_errors_local = mk_local throw_errors pos in
  6509. let do_default, tf_args = if not is_float then begin
  6510. let is_check = alloc_var "isCheck" basic.tbool in
  6511. let is_check_local = mk_local is_check pos in
  6512. let tf_args = tf_args @ [ throw_errors,None; ] in
  6513. (* default: if (isCheck) return __undefined__ else if(throwErrors) throw "Field not found"; else return null; *)
  6514. let lookup_name = gen.gmk_internal_name "hx" "lookupField" in
  6515. let do_default =
  6516. fun () ->
  6517. mk_return (mk_this_call_raw lookup_name (TFun(fun_args (field_args @ [throw_errors,None;is_check,None; ]),t_dynamic)) ( List.map (fun (v,_) -> mk_local v pos) field_args @ [ throw_errors_local; is_check_local; ] ))
  6518. in
  6519. (do_default, tf_args @ [ is_check,None; handle_prop,None; ])
  6520. end else begin
  6521. let tf_args = tf_args @ [ throw_errors,None; ] in
  6522. let lookup_name = gen.gmk_internal_name "hx" "lookupField_f" in
  6523. let do_default =
  6524. fun () ->
  6525. mk_return (mk_this_call_raw lookup_name (TFun(fun_args (field_args @ [throw_errors,None; ]),basic.tfloat)) ( List.map (fun (v,_) -> mk_local v pos) field_args @ [ throw_errors_local; ] ))
  6526. in
  6527. (do_default, tf_args @ [ handle_prop,None; ])
  6528. end in
  6529. let get_field cf cf_type ethis cl name =
  6530. match cf.cf_kind with
  6531. | Var { v_read = AccCall } when Type.is_extern_field cf ->
  6532. mk_return (mk_this_call_raw ("get_" ^ cf.cf_name) (TFun(["value",false,cf.cf_type], cf.cf_type)) [ ])
  6533. | Var { v_read = AccCall } ->
  6534. {
  6535. eexpr = TIf(
  6536. handle_prop_local,
  6537. mk_return (mk_this_call_raw ("get_" ^ cf.cf_name) (TFun(["value",false,cf.cf_type], cf.cf_type)) [ ]),
  6538. Some { eexpr = TField (ethis, FInstance(cl, cf)); etype = cf_type; epos = pos }
  6539. );
  6540. etype = cf_type;
  6541. epos = pos;
  6542. }
  6543. | Var _
  6544. | Method MethDynamic -> { eexpr = TField (ethis, FInstance(cl,cf)); etype = cf_type; epos = pos }
  6545. | _ ->
  6546. { eexpr = TField (this, FClosure(Some cl, cf)); etype = cf_type; epos = pos }
  6547. in
  6548. let do_field cf cf_type static =
  6549. let this = if static then mk_classtype_access cl pos else { eexpr = TConst(TThis); etype = t; epos = pos } in
  6550. match is_float, follow cf_type with
  6551. | true, TInst( { cl_kind = KTypeParameter _ }, _ ) ->
  6552. mk_return (mk_cast basic.tfloat (mk_cast t_dynamic (get_field cf cf_type this cl cf.cf_name)))
  6553. | _ ->
  6554. mk_return (maybe_cast (get_field cf cf_type this cl cf.cf_name ))
  6555. in
  6556. (mk_do_default tf_args do_default, do_default, do_field, tf_args)
  6557. end in
  6558. let get_fields static =
  6559. let ret = collect_fields cl ( if is_float || is_set then Some (false) else None ) (Some static) in
  6560. let ret = if is_set then List.filter (fun (_,cf) ->
  6561. match cf.cf_kind with
  6562. (* | Var { v_write = AccNever } -> false *)
  6563. | _ -> not (Meta.has Meta.ReadOnly cf.cf_meta)) ret
  6564. else
  6565. List.filter (fun (_,cf) ->
  6566. match cf.cf_kind with
  6567. (* | Var { v_read = AccNever } -> false *)
  6568. | _ -> true) ret in
  6569. if is_float then
  6570. List.filter (fun (_,cf) -> (* TODO: maybe really apply_params in cf.cf_type. The benefits would be limited, though *)
  6571. match follow (ctx.rcf_gen.greal_type (ctx.rcf_gen.gfollow#run_f cf.cf_type)) with
  6572. | TDynamic _ | TMono _
  6573. | TInst ({ cl_kind = KTypeParameter _ }, _) -> true
  6574. | t when like_float t -> true
  6575. | _ -> false
  6576. ) ret
  6577. else
  6578. (* dynamic will always contain all references *)
  6579. ret
  6580. in
  6581. (* now we have do_default, do_field and tf_args *)
  6582. (* so create the switch expr *)
  6583. fun_type := TFun(List.map (fun (v,_) -> (v.v_name, false, v.v_type)) tf_args, if is_float then basic.tfloat else t_dynamic );
  6584. let has_fields = ref false in
  6585. let mk_switch static =
  6586. let fields = get_fields static in
  6587. let fields = List.filter (fun (_, cf) -> match is_set, cf.cf_kind with
  6588. | true, Var { v_write = AccCall } -> true
  6589. | false, Var { v_read = AccCall } -> true
  6590. | _ -> not (Type.is_extern_field cf)) fields
  6591. in
  6592. (if fields <> [] then has_fields := true);
  6593. let cases = List.map (fun (names, cf) ->
  6594. (if names = [] then assert false);
  6595. (List.map (switch_case ctx pos) names, do_field cf cf.cf_type static)
  6596. ) fields in
  6597. let default = Some(if static then do_default_static() else do_default()) in
  6598. { eexpr = TSwitch(local_switch_var, cases, default); etype = basic.tvoid; epos = pos }
  6599. in
  6600. let content = if ctx.rcf_handle_statics then
  6601. mk_block { eexpr = TIf(is_static_local, mk_switch true, Some(mk_switch false)); etype = basic.tvoid; epos = pos }
  6602. else
  6603. mk_block (mk_switch false)
  6604. in
  6605. let is_override = match cl.cl_super with
  6606. | Some (cl, _) when is_hxgen (TClassDecl cl) -> true
  6607. | _ -> false
  6608. in
  6609. if !has_fields || (not is_override) then begin
  6610. let func =
  6611. {
  6612. tf_args = tf_args;
  6613. tf_type = if is_float then basic.tfloat else t_dynamic;
  6614. tf_expr = content;
  6615. } in
  6616. let func = { eexpr = TFunction(func); etype = !fun_type; epos = pos } in
  6617. cfield.cf_type <- !fun_type;
  6618. cfield.cf_expr <- Some func;
  6619. cl.cl_ordered_fields <- cl.cl_ordered_fields @ [cfield];
  6620. cl.cl_fields <- PMap.add fun_name cfield cl.cl_fields;
  6621. (if is_override then cl.cl_overrides <- cfield :: cl.cl_overrides)
  6622. end else ()
  6623. in
  6624. (if ctx.rcf_float_special_case then mk_cfield true true);
  6625. mk_cfield true false;
  6626. mk_cfield false false;
  6627. (if ctx.rcf_float_special_case then mk_cfield false true)
  6628. let mk_field_access_r ctx pos local field is_float is_static throw_errors set_option =
  6629. let is_set = is_some set_option in
  6630. let gen = ctx.rcf_gen in
  6631. let basic = gen.gcon.basic in
  6632. let fun_name = ctx.rcf_gen.gmk_internal_name "hx" ( (if is_set then "setField" else "getField") ^ (if is_float then "_f" else "") ) in
  6633. let tf_args, _ = field_type_args ctx pos in
  6634. let tf_args, args = fun_args tf_args, field in
  6635. let rett = if is_float then basic.tfloat else t_dynamic in
  6636. let tf_args, args = if ctx.rcf_handle_statics then tf_args @ [ "isStatic", false, basic.tbool ], args @ [is_static] else tf_args, args in
  6637. let tf_args, args = if is_set then tf_args @ [ "setVal", false, rett ], args @ [get set_option] else tf_args, args in
  6638. let tf_args, args = tf_args @ [ "throwErrors",false,basic.tbool ], args @ [throw_errors] in
  6639. let tf_args, args = if is_set || is_float then tf_args, args else tf_args @ [ "isCheck", false, basic.tbool ], args @ [{ eexpr = TConst(TBool false); etype = basic.tbool; epos = pos }] in
  6640. let tf_args, args = tf_args @ [ "handleProperties",false,basic.tbool; ], args @ [ mk_bool ctx false pos; ] in
  6641. {
  6642. eexpr = TCall(
  6643. { (mk_field_access gen local fun_name pos) with etype = TFun(tf_args, rett) },
  6644. args);
  6645. etype = rett;
  6646. epos = pos;
  6647. }
  6648. let implement_fields ctx cl =
  6649. (*
  6650. implement two kinds of fields get:
  6651. classFields
  6652. generic 'fields': receives a parameter isInstance
  6653. will receive an Array<String> and start pushing the fields into it.
  6654. //add all common fields
  6655. if(isInstance)
  6656. {
  6657. //add methods
  6658. } else {
  6659. super.fields(isInstance, array);
  6660. }
  6661. *)
  6662. let gen = ctx.rcf_gen in
  6663. let basic = gen.gcon.basic in
  6664. let pos = cl.cl_pos in
  6665. (*
  6666. let rec has_no_dynamic cl =
  6667. if is_some cl.cl_dynamic then
  6668. false
  6669. else match cl.cl_super with
  6670. | None -> true
  6671. | Some(cl,_) -> has_no_dynamic cl
  6672. in
  6673. *)
  6674. (* Type.getClassFields() *)
  6675. if ctx.rcf_handle_statics then begin
  6676. let name = gen.gmk_internal_name "hx" "classFields" in
  6677. let v_base_arr = alloc_var "baseArr" (basic.tarray basic.tstring) in
  6678. let base_arr = mk_local v_base_arr pos in
  6679. let tf_args = [v_base_arr,None] in
  6680. let t = TFun(fun_args tf_args, basic.tvoid) in
  6681. let cf = mk_class_field name t false pos (Method MethNormal) [] in
  6682. cl.cl_ordered_fields <- cl.cl_ordered_fields @ [cf];
  6683. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields;
  6684. (if is_override cl then cl.cl_overrides <- cf :: cl.cl_overrides);
  6685. (*
  6686. var newarr = ["field1", "field2"] ...;
  6687. *)
  6688. let fields = collect_fields cl None (Some true) in
  6689. let mk_push value =
  6690. { eexpr = TCall({ (mk_field_access gen base_arr "push" pos) with etype = TFun(["x", false, basic.tstring], basic.tint) }, [value] ); etype = basic.tint; epos = pos }
  6691. in
  6692. let new_arr_contents =
  6693. {
  6694. eexpr = TBlock(
  6695. List.map (fun (_,cf) -> mk_push { eexpr = TConst(TString(cf.cf_name)); etype = basic.tstring; epos = pos }) fields
  6696. );
  6697. etype = basic.tvoid;
  6698. epos = pos
  6699. } in
  6700. let expr = new_arr_contents in
  6701. let fn =
  6702. {
  6703. tf_args = tf_args;
  6704. tf_type = basic.tvoid;
  6705. tf_expr = mk_block expr
  6706. } in
  6707. cf.cf_expr <- Some { eexpr = TFunction(fn); etype = t; epos = pos }
  6708. end;
  6709. let fields =
  6710. (*
  6711. function __hx_fields(baseArr:Array<String>, isInstanceFields:Bool)
  6712. {
  6713. //add all variable fields
  6714. //then:
  6715. if (isInstanceFields)
  6716. {
  6717. //add all method fields as well
  6718. } else {
  6719. super.__hx_fields(baseArr, isInstanceFields);
  6720. }
  6721. }
  6722. *)
  6723. let name = gen.gmk_internal_name "hx" "getFields" in
  6724. let v_base_arr, v_is_inst = alloc_var "baseArr" (basic.tarray basic.tstring), alloc_var "isInstanceFields" basic.tbool in
  6725. let base_arr, is_inst = mk_local v_base_arr pos, mk_local v_is_inst pos in
  6726. let tf_args = (v_base_arr,None) :: (if ctx.rcf_handle_statics then [v_is_inst, None] else []) in
  6727. let t = TFun(fun_args tf_args, basic.tvoid) in
  6728. let cf = mk_class_field name t false pos (Method MethNormal) [] in
  6729. let mk_push value =
  6730. { eexpr = TCall({ (mk_field_access gen base_arr "push" pos) with etype = TFun(["x", false, basic.tstring], basic.tint); }, [value] ); etype = basic.tint; epos = pos }
  6731. in
  6732. let has_value = ref false in
  6733. let map_fields =
  6734. List.map (fun (_,cf) ->
  6735. match cf.cf_kind with
  6736. | Var _
  6737. | Method MethDynamic when not (List.memq cf cl.cl_overrides) ->
  6738. has_value := true;
  6739. mk_push { eexpr = TConst(TString(cf.cf_name)); etype = basic.tstring; epos = pos }
  6740. | _ -> null basic.tvoid pos
  6741. )
  6742. in
  6743. (*
  6744. if it is first_dynamic, then we need to enumerate the dynamic fields
  6745. *)
  6746. let if_not_inst = if is_some cl.cl_dynamic && is_first_dynamic cl then begin
  6747. has_value := true;
  6748. Some (enumerate_dynamic_fields ctx cl mk_push)
  6749. end else
  6750. None
  6751. in
  6752. let if_not_inst = if is_override cl then
  6753. Some(
  6754. {
  6755. eexpr = TBlock(
  6756. (if is_some if_not_inst then get if_not_inst else []) @
  6757. [{
  6758. eexpr = TCall(
  6759. { eexpr = TField({ eexpr = TConst TSuper; etype = TInst(cl, List.map snd cl.cl_types); epos = pos }, FInstance(cl, cf)); etype = t; epos = pos },
  6760. base_arr :: (if ctx.rcf_handle_statics then [is_inst] else [])
  6761. );
  6762. etype = basic.tvoid;
  6763. epos = pos
  6764. }]
  6765. );
  6766. etype = basic.tvoid;
  6767. epos = pos
  6768. }
  6769. ) else if is_some if_not_inst then
  6770. Some({ eexpr = TBlock(get if_not_inst); etype = basic.tvoid; epos = pos })
  6771. else
  6772. None
  6773. in
  6774. let expr_contents = map_fields (collect_fields cl (Some false) (Some false)) in
  6775. let expr_contents = if ctx.rcf_handle_statics then
  6776. expr_contents @
  6777. [ {
  6778. eexpr = TIf(is_inst,
  6779. { eexpr = TBlock( map_fields (collect_fields cl (Some true) (Some false)) ); etype = basic.tvoid; epos = pos },
  6780. if_not_inst
  6781. );
  6782. etype = basic.tvoid;
  6783. epos = pos
  6784. } ]
  6785. else
  6786. expr_contents @ (if is_some if_not_inst then [ get if_not_inst ] else [])
  6787. in
  6788. let expr =
  6789. {
  6790. eexpr = TBlock( expr_contents );
  6791. etype = basic.tvoid;
  6792. epos = pos;
  6793. } in
  6794. let fn =
  6795. {
  6796. tf_args = tf_args;
  6797. tf_type = basic.tvoid;
  6798. tf_expr = expr
  6799. } in
  6800. (if !has_value || (not (is_override cl)) then begin
  6801. cl.cl_ordered_fields <- cl.cl_ordered_fields @ [cf];
  6802. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields;
  6803. (if is_override cl then cl.cl_overrides <- cf :: cl.cl_overrides)
  6804. end);
  6805. cf.cf_expr <- Some { eexpr = TFunction(fn); etype = t; epos = pos }
  6806. in
  6807. ignore fields
  6808. let implement_class_methods ctx cl =
  6809. ctx.rcf_class_cl <- Some cl;
  6810. let pos = cl.cl_pos in
  6811. let gen = ctx.rcf_gen in
  6812. let basic = gen.gcon.basic in
  6813. (*
  6814. fields -> redirected to classFields
  6815. getField -> redirected to getField with isStatic true
  6816. setField -> isStatic true
  6817. invokeField -> isStatic true
  6818. getClass -> null
  6819. create -> proxy
  6820. createEmpty -> proxy
  6821. *)
  6822. let is_override = is_override cl in
  6823. let name = "classProxy" in
  6824. let t = (TInst(ctx.rcf_object_iface,[])) in
  6825. (* let cf = mk_class_field name t false pos (Var { v_read = AccNormal; v_write = AccNormal }) [] in *)
  6826. let register_cf cf override =
  6827. cl.cl_ordered_fields <- cf :: cl.cl_ordered_fields;
  6828. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields;
  6829. if override then cl.cl_overrides <- cf :: cl.cl_overrides
  6830. in
  6831. (* register_cf cf false; *)
  6832. let this_t = TInst(cl, List.map snd cl.cl_types) in
  6833. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  6834. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  6835. let proxy = mk_this name t in
  6836. (*let ctor =
  6837. let cls = alloc_var "cls" t in
  6838. let tf_args = [cls, None] in
  6839. let t = TFun(fun_args tf_args, basic.tvoid) in
  6840. let cf = mk_class_field "new" t true pos (Method MethNormal) [] in
  6841. cf.cf_expr <- Some({
  6842. eexpr = TFunction({
  6843. tf_args = tf_args;
  6844. tf_type = basic.tvoid;
  6845. tf_expr = mk_block {
  6846. eexpr = TBinop(Ast.OpAssign, proxy, mk_local cls pos);
  6847. etype = cls.v_type;
  6848. epos = pos;
  6849. }
  6850. });
  6851. etype = t;
  6852. epos = pos;
  6853. });
  6854. cf
  6855. in
  6856. register_cf ctor false;*)
  6857. (* setting it as DynamicObject makes getClass return null *)
  6858. let get_class =
  6859. cl.cl_meta <- (Meta.DynamicObject, [], pos) :: cl.cl_meta
  6860. in
  6861. ignore get_class;
  6862. (* fields -> if isInstanceField, redir the method. If not, return classFields *)
  6863. let fields =
  6864. let name = gen.gmk_internal_name "hx" "getFields" in
  6865. let v_base_arr, v_is_inst = alloc_var "baseArr" (basic.tarray basic.tstring), alloc_var "isInstanceFields" basic.tbool in
  6866. let base_arr, is_inst = mk_local v_base_arr pos, mk_local v_is_inst pos in
  6867. let tf_args = [ v_base_arr,None; v_is_inst, None ] in
  6868. let t = TFun(fun_args tf_args, basic.tvoid) in
  6869. let cf = mk_class_field name t false pos (Method MethNormal) [] in
  6870. cf.cf_expr <- Some({
  6871. eexpr = TFunction({
  6872. tf_args = tf_args;
  6873. tf_type = basic.tvoid;
  6874. tf_expr = mk_block {
  6875. eexpr = TIf(is_inst,
  6876. { eexpr = TCall( { (mk_field_access gen proxy name pos) with etype = t }, [base_arr;is_inst]); etype = basic.tvoid; epos = pos },
  6877. Some { eexpr = TCall(mk_this (gen.gmk_internal_name "hx" "classFields") (TFun(["baseArr",false,basic.tarray basic.tstring], basic.tvoid)), [base_arr]); etype = basic.tvoid; epos = pos });
  6878. etype = basic.tvoid;
  6879. epos = pos
  6880. }
  6881. });
  6882. etype = t;
  6883. epos = pos;
  6884. });
  6885. cf
  6886. in
  6887. register_cf fields (is_override);
  6888. let do_proxy field tf_args ret is_static_argnum =
  6889. let field = gen.gmk_internal_name "hx" field in
  6890. let t = TFun(fun_args tf_args, ret) in
  6891. let cf = mk_class_field field t false pos (Method MethNormal) [] in
  6892. let is_void = is_void ret in
  6893. let may_return e = if is_void then mk_block e else mk_block (mk_return e) in
  6894. let i = ref 0 in
  6895. cf.cf_expr <- Some({
  6896. eexpr = TFunction({
  6897. tf_args = tf_args;
  6898. tf_type = ret;
  6899. tf_expr = may_return {
  6900. eexpr = TCall(
  6901. { (mk_field_access gen proxy field pos) with etype = t },
  6902. List.map (fun (v,_) ->
  6903. let lasti = !i in
  6904. incr i;
  6905. if lasti = is_static_argnum then
  6906. { eexpr = TConst(TBool true); etype = basic.tbool; epos = pos }
  6907. else
  6908. mk_local v pos
  6909. ) tf_args);
  6910. etype = ret;
  6911. epos = pos
  6912. }
  6913. });
  6914. etype = t;
  6915. epos = pos;
  6916. });
  6917. cf
  6918. in
  6919. (* getClassFields -> redir *)
  6920. register_cf (do_proxy "classFields" [ alloc_var "baseArr" (basic.tarray basic.tstring), None ] basic.tvoid (-1)) true;
  6921. (*register_cf (do_proxy "classFields" [ alloc_var "baseArr" (basic.tarray basic.tstring), None ] basic.tvoid (-1)) true;*)
  6922. let fst_args, _ = field_type_args ctx pos in
  6923. let fst_args_len = List.length fst_args in
  6924. (* getField -> redir the method with static = true *)
  6925. (* setField -> redir the methods with static = true *)
  6926. (if ctx.rcf_float_special_case then
  6927. register_cf (do_proxy "getField_f" (fst_args @ [ alloc_var "isStatic" basic.tbool, None; alloc_var "throwErrors" basic.tbool, None ]) basic.tfloat fst_args_len) true;
  6928. register_cf (do_proxy "setField_f" (fst_args @ [ alloc_var "isStatic" basic.tbool, None; alloc_var "value" basic.tfloat, None ]) basic.tfloat fst_args_len) true
  6929. );
  6930. register_cf (do_proxy "getField" (fst_args @ [ alloc_var "isStatic" basic.tbool, None; alloc_var "throwErrors" basic.tbool, None; alloc_var "isCheck" basic.tbool, None; alloc_var "handleProperties" basic.tbool,None; ]) t_dynamic fst_args_len) true;
  6931. register_cf (do_proxy "setField" (fst_args @ [ alloc_var "isStatic" basic.tbool, None; alloc_var "value" t_dynamic, None; alloc_var "handleProperties" basic.tbool,None; ]) t_dynamic fst_args_len) true;
  6932. (* invokeField -> redir the method with static = true *)
  6933. register_cf (do_proxy "invokeField" (fst_args @ [ alloc_var "isStatic" basic.tbool, None; alloc_var "dynArgs" (basic.tarray t_dynamic), None ]) t_dynamic fst_args_len) true;
  6934. (* create / createEmpty -> redir the method *)
  6935. register_cf (do_proxy "create" [ alloc_var "arr" (basic.tarray t_dynamic), None ] t_dynamic (-1)) true;
  6936. register_cf (do_proxy "createEmpty" [ ] t_dynamic (-1)) true
  6937. let implement_get_class ctx cl =
  6938. (*
  6939. if it is DynamicObject, return null;
  6940. if it is not, just do the following:
  6941. if (typehandle(this.class) == typehandle(MyClass))
  6942. return (MyClass.__hx_class != null ? MyClass.__hx_class : MyClass.__hx_class = create_empty(MyClass));
  6943. return MyClass.__hx_class = haxe.lang.Runtime.getClass(MyClass);
  6944. implement both on static and non-static contexts. This way we can call without references.
  6945. *)
  6946. let gen = ctx.rcf_gen in
  6947. let basic = gen.gcon.basic in
  6948. let pos = cl.cl_pos in
  6949. let tclass = get_cl ( (Hashtbl.find gen.gtypes ([],"Class")) ) in
  6950. let cls = TInst(tclass, [ TInst(cl, List.map (fun _ -> t_dynamic) cl.cl_types) ]) in
  6951. let cls_dyn = TInst(tclass, [t_dynamic]) in
  6952. let expr, static_cfs =
  6953. if Meta.has Meta.DynamicObject cl.cl_meta then
  6954. mk_return (null t_dynamic pos), []
  6955. else
  6956. let cache_name = (gen.gmk_internal_name "hx" "class") in
  6957. let cache = mk_class_field cache_name cls false pos (Var { v_read = AccNormal; v_write = AccNormal }) [] in
  6958. cl.cl_ordered_statics <- cl.cl_ordered_statics @ [ cache ];
  6959. cl.cl_statics <- PMap.add cache_name cache cl.cl_statics;
  6960. let cache_access = mk_static_field_access cl cache_name cls pos in
  6961. let create_expr = {
  6962. eexpr = TNew(get ctx.rcf_class_cl, [], [gen.gtools.rf_create_empty cl (List.map (fun _ -> t_dynamic) cl.cl_types) pos]);
  6963. etype = cls;
  6964. epos = pos
  6965. } in
  6966. (if ctx.rcf_class_eager_creation then cache.cf_expr <- Some(create_expr));
  6967. let expr = if ctx.rcf_class_eager_creation then
  6968. mk_return cache_access
  6969. else
  6970. mk_return {
  6971. eexpr = TIf(
  6972. { eexpr = TBinop(Ast.OpNotEq, cache_access, null cls pos); etype = basic.tbool; epos = pos },
  6973. cache_access,
  6974. Some({ eexpr = TBinop(Ast.OpAssign, cache_access, create_expr); etype = cls; epos = pos })
  6975. );
  6976. etype = cls;
  6977. epos = pos
  6978. }
  6979. in
  6980. expr, []
  6981. in
  6982. let func =
  6983. {
  6984. eexpr = TFunction({
  6985. tf_args = [];
  6986. tf_type = cls_dyn;
  6987. tf_expr = expr
  6988. });
  6989. etype = TFun([],cls_dyn);
  6990. epos = pos
  6991. } in
  6992. let get_cl_static = mk_class_field (gen.gmk_internal_name "hx" "getClassStatic") (TFun([],cls_dyn)) false pos (Method MethNormal) [] in
  6993. let get_cl = mk_class_field (gen.gmk_internal_name "hx" "getClass") (TFun([],cls_dyn)) false pos (Method MethNormal) [] in
  6994. get_cl_static.cf_expr <- Some func;
  6995. get_cl.cf_expr <- Some func;
  6996. let all_f = [get_cl] in
  6997. cl.cl_ordered_fields <- cl.cl_ordered_fields @ all_f;
  6998. List.iter (fun cf -> cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields) all_f;
  6999. let all_f = get_cl_static :: static_cfs in
  7000. cl.cl_ordered_statics <- cl.cl_ordered_statics @ all_f;
  7001. List.iter (fun cf -> cl.cl_statics <- PMap.add cf.cf_name cf cl.cl_statics) all_f;
  7002. if is_override cl then cl.cl_overrides <- get_cl :: cl.cl_overrides
  7003. let implement_invokeField ctx ~slow_invoke cl =
  7004. (*
  7005. There are two ways to implement an haxe reflection-enabled class:
  7006. When we extend a non-hxgen class, and when we extend the base HxObject class.
  7007. Because of the added boiler plate we'd add every time we extend a non-hxgen class to implement a big IHxObject
  7008. interface, we'll handle the cases differently when implementing each interface.
  7009. At the IHxObject interface, there's only invokeDynamic(field, args[]), while at the HxObject class there are
  7010. the other, more optimized methods, that follow the Function class interface.
  7011. Since this will only be called by the Closure class, this conversion can be properly dealt with later.
  7012. TODO: create the faster version. By now only invokeDynamic will be implemented
  7013. *)
  7014. let gen = ctx.rcf_gen in
  7015. let basic = gen.gcon.basic in
  7016. let pos = cl.cl_pos in
  7017. let has_method = ref false in
  7018. let is_override = ref false in
  7019. let rec extends_hxobject cl =
  7020. match cl.cl_super with
  7021. | None -> true
  7022. | Some (cl,_) when is_hxgen (TClassDecl cl) -> is_override := true; extends_hxobject cl
  7023. | _ -> false
  7024. in
  7025. let field_args, switch_var = field_type_args ctx cl.cl_pos in
  7026. let field_args_exprs = List.map (fun (v,_) -> mk_local v pos) field_args in
  7027. let is_static = alloc_var "isStatic" basic.tbool in
  7028. let dynamic_arg = alloc_var "dynargs" (basic.tarray t_dynamic) in
  7029. let all_args = field_args @ (if ctx.rcf_handle_statics then [ is_static,None; dynamic_arg,None ] else [ dynamic_arg, None ] ) in
  7030. let fun_t = TFun(fun_args all_args, t_dynamic) in
  7031. let this_t = TInst(cl, List.map snd cl.cl_types) in
  7032. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  7033. let apply_object cf = apply_params cf.cf_params (List.map (fun _ -> t_dynamic) cf.cf_params) cf.cf_type in
  7034. let mk_this_call_raw name fun_t params =
  7035. { eexpr = TCall( { (mk_field_access gen this name pos) with etype = fun_t }, params ); etype = snd (get_args fun_t); epos = pos }
  7036. in
  7037. let mk_this_call cf params =
  7038. let t = apply_object cf in
  7039. (* the return type transformation into Dynamic *)
  7040. (* is meant to avoid return-type casting after functions with *)
  7041. (* type parameters are properly inferred at TypeParams.infer_params *)
  7042. (* e.g. function getArray<T : SomeType>(t:T):Array<T>; after infer_params, *)
  7043. (* T will be inferred as SomeType, but the returned type will still be typed *)
  7044. (* as Array<Dynamic> *)
  7045. let args, ret = get_args t in
  7046. let ret = match follow ret with
  7047. | TEnum({ e_path = ([], "Void") }, [])
  7048. | TAbstract ({ a_path = ([], "Void") },[]) -> ret
  7049. | _ -> ret
  7050. in
  7051. mk_this_call_raw cf.cf_name (TFun(args, ret)) params
  7052. in
  7053. let mk_static_call cf params =
  7054. let t = apply_object cf in
  7055. let _, ret = get_fun (follow t) in
  7056. { eexpr = TCall( mk_static_field_access cl cf.cf_name t pos, params ); etype = ret; epos = pos }
  7057. in
  7058. let extends_hxobject = extends_hxobject cl in
  7059. ignore extends_hxobject;
  7060. (* creates a dynamicInvoke of the class fields listed here *)
  7061. (*
  7062. function dynamicInvoke(field, isStatic, dynargs)
  7063. {
  7064. switch(field)
  7065. {
  7066. case "a": this.a(dynargs[0], dynargs[1], dynargs[2]...);
  7067. default: super.dynamicInvoke //or this.getField(field).invokeField(dynargs)
  7068. }
  7069. }
  7070. *)
  7071. let dyn_fun = mk_class_field (ctx.rcf_gen.gmk_internal_name "hx" "invokeField") fun_t false cl.cl_pos (Method MethNormal) [] in
  7072. let mk_switch_dyn cfs static old =
  7073. (* mk_class_field name t public pos kind params = *)
  7074. let get_case (names,cf) =
  7075. has_method := true;
  7076. let i = ref 0 in
  7077. let dyn_arg_local = mk_local dynamic_arg pos in
  7078. let cases = List.map (switch_case ctx pos) names in
  7079. (cases,
  7080. { eexpr = TReturn(Some ( (if static then mk_static_call else mk_this_call) cf (List.map (fun (name,_,t) ->
  7081. let ret = { eexpr = TArray(dyn_arg_local, mk_int ctx !i pos); etype = t_dynamic; epos = pos } in
  7082. incr i;
  7083. ret
  7084. ) (fst (get_args (cf.cf_type))) ) ));
  7085. etype = basic.tvoid;
  7086. epos = pos
  7087. }
  7088. )
  7089. in
  7090. let cfs = List.filter (fun (_,cf) -> match cf.cf_kind with
  7091. | Method _ -> if List.memq cf cl.cl_overrides then false else true
  7092. | _ -> true) cfs
  7093. in
  7094. let cases = List.map get_case cfs in
  7095. let cases = match old with
  7096. | [] -> cases
  7097. | _ ->
  7098. let ncases = List.map (fun cf -> switch_case ctx pos cf.cf_name) old in
  7099. ( ncases, mk_return ((get slow_invoke) this (mk_local (fst (List.hd field_args)) pos) (mk_local dynamic_arg pos)) ) :: cases
  7100. in
  7101. let default = if !is_override && not(static) then
  7102. (* let call_super ctx fn_args ret_t fn_name this_t pos = *)
  7103. { eexpr = TReturn(Some (call_super ctx all_args t_dynamic dyn_fun cl this_t pos) ); etype = basic.tvoid; epos = pos }
  7104. (*else if ctx.rcf_create_getsetinvoke_fields then (* we always need to run create_getset before *)
  7105. let get_field_name = gen.gmk_internal_name "hx" "getField" in
  7106. { eexpr = TReturn( Some (mk_this_call (PMap.find get_field_name cl.cl_fields) [mk_local dynamic_arg pos] ) ); etype = basic.tvoid; epos = pos }*)
  7107. else (
  7108. (*let field = (gen.gtools.r_field false (TInst(ctx.rcf_ft.func_class,[])) this (mk_local (fst (List.hd all_args)) pos)) in*)
  7109. (* let mk_field_access ctx pos local field is_float is_static throw_errors set_option = *)
  7110. let field = mk_field_access_r ctx pos this field_args_exprs false {eexpr = TConst(TBool static); etype = basic.tbool; epos = pos} { eexpr = TConst(TBool true); etype = basic.tbool; epos = pos } None in
  7111. let field = mk_cast (TInst(ctx.rcf_ft.func_class,[])) field in
  7112. mk_return {
  7113. eexpr = TCall(
  7114. mk_field_access gen field (gen.gmk_internal_name "hx" "invokeDynamic") pos,
  7115. [mk_local dynamic_arg pos]);
  7116. etype = t_dynamic;
  7117. epos = pos
  7118. } )
  7119. in
  7120. {
  7121. eexpr = TSwitch(mk_local switch_var pos, cases, Some default);
  7122. etype = basic.tvoid;
  7123. epos = pos;
  7124. }
  7125. in
  7126. let contents =
  7127. let statics = collect_fields cl (Some true) (Some true) in
  7128. let nonstatics = collect_fields cl (Some true) (Some false) in
  7129. let old_nonstatics = ref [] in
  7130. let nonstatics = match slow_invoke with
  7131. | None -> nonstatics
  7132. | Some _ ->
  7133. List.filter (fun (n,cf) ->
  7134. let is_old = not (PMap.mem cf.cf_name cl.cl_fields) || List.memq cf cl.cl_overrides in
  7135. (if is_old then old_nonstatics := cf :: !old_nonstatics);
  7136. not is_old
  7137. ) nonstatics
  7138. in
  7139. if ctx.rcf_handle_statics then
  7140. {
  7141. eexpr = TIf(mk_local is_static pos, mk_switch_dyn statics true [], Some(mk_switch_dyn nonstatics false !old_nonstatics));
  7142. etype = basic.tvoid;
  7143. epos = pos;
  7144. } else
  7145. mk_switch_dyn nonstatics false !old_nonstatics
  7146. in
  7147. dyn_fun.cf_expr <- Some
  7148. {
  7149. eexpr = TFunction(
  7150. {
  7151. tf_args = all_args;
  7152. tf_type = t_dynamic;
  7153. tf_expr = mk_block contents;
  7154. });
  7155. etype = TFun(fun_args all_args, t_dynamic);
  7156. epos = pos;
  7157. };
  7158. if !is_override && not (!has_method) then () else begin
  7159. cl.cl_ordered_fields <- cl.cl_ordered_fields @ [dyn_fun];
  7160. cl.cl_fields <- PMap.add dyn_fun.cf_name dyn_fun cl.cl_fields;
  7161. (if !is_override then cl.cl_overrides <- dyn_fun :: cl.cl_overrides)
  7162. end
  7163. let implement_varargs_cl ctx cl =
  7164. let pos = cl.cl_pos in
  7165. let gen = ctx.rcf_gen in
  7166. let basic = gen.gcon.basic in
  7167. let this_t = TInst(cl, List.map snd cl.cl_types) in
  7168. let this = { eexpr = TConst(TThis); etype = this_t ; epos = pos } in
  7169. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  7170. let invokedyn = gen.gmk_internal_name "hx" "invokeDynamic" in
  7171. let idyn_t = TFun([gen.gmk_internal_name "fn" "dynargs", false, basic.tarray t_dynamic], t_dynamic) in
  7172. let this_idyn = mk_this invokedyn idyn_t in
  7173. let map_fn arity ret vars api =
  7174. let rec loop i acc =
  7175. if i < 0 then
  7176. acc
  7177. else
  7178. let obj = api i t_dynamic None in
  7179. loop (i - 1) (obj :: acc)
  7180. in
  7181. let call_arg = if arity = (-1) then
  7182. api (-1) t_dynamic None
  7183. else if arity = 0 then
  7184. null (basic.tarray t_empty) pos
  7185. else
  7186. { eexpr = TArrayDecl(loop (arity - 1) []); etype = basic.tarray t_empty; epos = pos }
  7187. in
  7188. let expr = {
  7189. eexpr = TCall(
  7190. this_idyn,
  7191. [ call_arg ]
  7192. );
  7193. etype = t_dynamic;
  7194. epos = pos
  7195. } in
  7196. let expr = if like_float ret && not (like_int ret) then mk_cast ret expr else expr in
  7197. [], mk_return expr
  7198. in
  7199. let all_cfs = List.filter (fun cf -> cf.cf_name <> "new" && cf.cf_name <> (invokedyn) && match cf.cf_kind with Method _ -> true | _ -> false) (ctx.rcf_ft.map_base_classfields cl true map_fn) in
  7200. cl.cl_ordered_fields <- cl.cl_ordered_fields @ all_cfs;
  7201. List.iter (fun cf ->
  7202. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields
  7203. ) all_cfs;
  7204. List.iter (fun cf ->
  7205. cl.cl_overrides <- cf :: cl.cl_overrides
  7206. ) cl.cl_ordered_fields
  7207. let implement_closure_cl ctx cl =
  7208. let pos = cl.cl_pos in
  7209. let gen = ctx.rcf_gen in
  7210. let basic = gen.gcon.basic in
  7211. let field_args, _ = field_type_args ctx pos in
  7212. let obj_arg = alloc_var "target" (TInst(ctx.rcf_object_iface, [])) in
  7213. let this_t = TInst(cl, List.map snd cl.cl_types) in
  7214. let this = { eexpr = TConst(TThis); etype = this_t ; epos = pos } in
  7215. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  7216. let tf_args = field_args @ [obj_arg, None] in
  7217. let cfs, ctor_body = List.fold_left (fun (acc_cf,acc_expr) (v,_) ->
  7218. let cf = mk_class_field v.v_name v.v_type false pos (Var { v_read = AccNormal; v_write = AccNormal } ) [] in
  7219. let expr = { eexpr = TBinop(Ast.OpAssign, mk_this v.v_name v.v_type, mk_local v pos); etype = v.v_type; epos = pos } in
  7220. (cf :: acc_cf, expr :: acc_expr)
  7221. ) ([], []) tf_args in
  7222. let map_fn arity ret vars api =
  7223. let this_obj = mk_this "target" (TInst(ctx.rcf_object_iface, [])) in
  7224. let rec loop i acc =
  7225. if i < 0 then
  7226. acc
  7227. else
  7228. let obj = api i t_dynamic None in
  7229. loop (i - 1) (obj :: acc)
  7230. in
  7231. let call_arg = if arity = (-1) then
  7232. api (-1) t_dynamic None
  7233. else if arity = 0 then
  7234. null (basic.tarray t_empty) pos
  7235. else
  7236. { eexpr = TArrayDecl(loop (arity - 1) []); etype = basic.tarray t_empty; epos = pos }
  7237. in
  7238. let expr = {
  7239. eexpr = TCall(
  7240. mk_field_access gen this_obj (gen.gmk_internal_name "hx" "invokeField") pos,
  7241. (List.map (fun (v,_) -> mk_this v.v_name v.v_type) field_args) @
  7242. (if ctx.rcf_handle_statics then
  7243. [ { eexpr = TConst(TBool false); etype = basic.tbool; epos = pos }; call_arg ]
  7244. else
  7245. [ call_arg ]
  7246. )
  7247. );
  7248. etype = t_dynamic;
  7249. epos = pos
  7250. } in
  7251. let expr = if like_float ret && not (like_int ret) then mk_cast ret expr else expr in
  7252. [], mk_return expr
  7253. in
  7254. let all_cfs = List.filter (fun cf -> cf.cf_name <> "new" && match cf.cf_kind with Method _ -> true | _ -> false) (ctx.rcf_ft.map_base_classfields cl true map_fn) in
  7255. List.iter (fun cf ->
  7256. cl.cl_overrides <- cf :: cl.cl_overrides
  7257. ) all_cfs;
  7258. let all_cfs = cfs @ all_cfs in
  7259. cl.cl_ordered_fields <- cl.cl_ordered_fields @ all_cfs;
  7260. List.iter (fun cf ->
  7261. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields
  7262. ) all_cfs;
  7263. let ctor_t = TFun(fun_args tf_args, basic.tvoid) in
  7264. let ctor_cf = mk_class_field "new" ctor_t true pos (Method MethNormal) [] in
  7265. ctor_cf.cf_expr <- Some {
  7266. eexpr = TFunction({
  7267. tf_args = tf_args;
  7268. tf_type = basic.tvoid;
  7269. tf_expr = { eexpr = TBlock({
  7270. eexpr = TCall({ eexpr = TConst(TSuper); etype = TInst(cl,[]); epos = pos }, [mk_int ctx (-1) pos; mk_int ctx (-1) pos]);
  7271. etype = basic.tvoid;
  7272. epos = pos
  7273. } :: ctor_body); etype = basic.tvoid; epos = pos }
  7274. });
  7275. etype = ctor_t;
  7276. epos = pos
  7277. };
  7278. cl.cl_constructor <- Some ctor_cf;
  7279. let closure_fun eclosure e field is_static =
  7280. let f = { eexpr = TConst(TString field); etype = basic.tstring; epos = eclosure.epos } in
  7281. let args = if ctx.rcf_optimize then [ f; { eexpr = TConst(TInt (hash_field_i32 ctx eclosure.epos field)); etype = basic.tint; epos = eclosure.epos } ] else [ f ] in
  7282. let args = args @ [ mk_cast (TInst(ctx.rcf_object_iface, [])) e ] in
  7283. { eclosure with eexpr = TNew(cl,[],args) }
  7284. in
  7285. closure_fun
  7286. let get_closure_func ctx closure_cl =
  7287. let gen = ctx.rcf_gen in
  7288. let basic = gen.gcon.basic in
  7289. let closure_func eclosure e field is_static =
  7290. mk_cast eclosure.etype { eclosure with
  7291. eexpr = TNew(closure_cl, [], [
  7292. e;
  7293. { eexpr = TConst(TString field); etype = basic.tstring; epos = eclosure.epos }
  7294. ] @ (
  7295. if ctx.rcf_optimize then [ { eexpr = TConst(TInt (hash_field_i32 ctx eclosure.epos field)); etype = basic.tint; epos = eclosure.epos } ] else []
  7296. ));
  7297. etype = TInst(closure_cl,[])
  7298. }
  7299. in
  7300. closure_func
  7301. (*
  7302. main expr -> field expr -> field string -> possible set expr -> should_throw_exceptions -> changed expression
  7303. Changes a get / set
  7304. *
  7305. mutable rcf_on_getset_field : texpr->texpr->string->texpr option->bool->texpr;*)
  7306. let configure_dynamic_field_access ctx is_synf =
  7307. let gen = ctx.rcf_gen in
  7308. let is_dynamic expr fexpr field =
  7309. match (field_access_esp gen (gen.greal_type fexpr.etype) field) with
  7310. | FEnumField _
  7311. | FClassField _ -> false
  7312. | _ -> true
  7313. in
  7314. let configure = if is_synf then DynamicFieldAccess.configure_as_synf else DynamicFieldAccess.configure in
  7315. let maybe_hash = if ctx.rcf_optimize then fun str pos -> Some (hash_field_i32 ctx pos str) else fun str pos -> None in
  7316. configure gen (DynamicFieldAccess.abstract_implementation gen is_dynamic
  7317. (fun expr fexpr field set is_unsafe ->
  7318. let hash = maybe_hash field fexpr.epos in
  7319. ctx.rcf_on_getset_field expr fexpr field hash set is_unsafe
  7320. )
  7321. (fun ecall fexpr field call_list ->
  7322. let hash = maybe_hash field fexpr.epos in
  7323. ctx.rcf_on_call_field ecall fexpr field hash call_list
  7324. )
  7325. );
  7326. ()
  7327. let replace_reflection ctx cl =
  7328. let gen = ctx.rcf_gen in
  7329. let pos = cl.cl_pos in
  7330. let this_t = TInst(cl, List.map snd cl.cl_types) in
  7331. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  7332. let last_fields = match cl.cl_super with
  7333. | None -> PMap.empty
  7334. | Some (super,_) -> super.cl_fields
  7335. in
  7336. let new_fields = ref [] in
  7337. let process_cf static cf =
  7338. match cf.cf_kind with
  7339. | Var _ -> ()
  7340. | _ when Meta.has Meta.ReplaceReflection cf.cf_meta ->
  7341. let name = if String.get cf.cf_name 0 = '_' then String.sub cf.cf_name 1 (String.length cf.cf_name - 1) else cf.cf_name in
  7342. let new_name = gen.gmk_internal_name "hx" name in
  7343. let new_cf = mk_class_field new_name cf.cf_type cf.cf_public cf.cf_pos cf.cf_kind cf.cf_params in
  7344. let fn_args, ret = get_fun (follow cf.cf_type) in
  7345. let tf_args = List.map (fun (name,_,t) -> alloc_var name t, None) fn_args in
  7346. let is_void = is_void ret in
  7347. let expr = {
  7348. eexpr = TCall(
  7349. {
  7350. eexpr = (if static then TField(mk_classtype_access cl pos, FStatic(cl, cf)) else TField(this, FInstance(cl, cf)));
  7351. etype = cf.cf_type;
  7352. epos = cf.cf_pos;
  7353. },
  7354. List.map (fun (v,_) -> mk_local v cf.cf_pos) tf_args);
  7355. etype = ret;
  7356. epos = cf.cf_pos
  7357. } in
  7358. let new_f =
  7359. {
  7360. tf_args = tf_args;
  7361. tf_type = ret;
  7362. tf_expr = {
  7363. eexpr = TBlock([if is_void then expr else mk_return expr]);
  7364. etype = ret;
  7365. epos = pos;
  7366. }
  7367. } in
  7368. new_cf.cf_expr <- Some({ eexpr = TFunction(new_f); etype = cf.cf_type; epos = cf.cf_pos});
  7369. new_fields := new_cf :: !new_fields;
  7370. (if static then cl.cl_statics <- PMap.add new_name new_cf cl.cl_statics else cl.cl_fields <- PMap.add new_name new_cf cl.cl_fields);
  7371. if not static && PMap.mem new_name last_fields then cl.cl_overrides <- new_cf :: cl.cl_overrides
  7372. | _ -> ()
  7373. in
  7374. List.iter (process_cf false) cl.cl_ordered_fields;
  7375. cl.cl_ordered_fields <- cl.cl_ordered_fields @ !new_fields;
  7376. new_fields := [];
  7377. List.iter (process_cf true) cl.cl_ordered_statics;
  7378. cl.cl_ordered_statics <- cl.cl_ordered_statics @ !new_fields
  7379. (* ******************************************* *)
  7380. (* UniversalBaseClass *)
  7381. (* ******************************************* *)
  7382. (*
  7383. Sets the universal base class for hxgen types (HxObject / IHxObject)
  7384. dependencies:
  7385. As a rule, it should be one of the last module filters to run so any @:hxgen class created in the process
  7386. -Should- only run after TypeParams.RealTypeParams.Modf, since
  7387. *)
  7388. module UniversalBaseClass =
  7389. struct
  7390. let name = "rcf_universal_base_class"
  7391. let priority = min_dep +. 10.
  7392. let default_implementation gen baseclass baseinterface basedynamic =
  7393. (* baseinterface.cl_meta <- (Meta.BaseInterface, [], baseinterface.cl_pos) :: baseinterface.cl_meta; *)
  7394. let rec run md =
  7395. (if is_hxgen md then
  7396. match md with
  7397. | TClassDecl ( { cl_interface = true } as cl ) when cl.cl_path <> baseclass.cl_path && cl.cl_path <> baseinterface.cl_path && cl.cl_path <> basedynamic.cl_path ->
  7398. cl.cl_implements <- (baseinterface, []) :: cl.cl_implements
  7399. | TClassDecl ({ cl_kind = KAbstractImpl _ } as cl) ->
  7400. (*
  7401. TODO: probably here is not the best place to add @:final to KAbstractImpl, also:
  7402. Doesn't it make sense to add @:final to KAbstractImpls on all platforms?
  7403. *)
  7404. if not (Meta.has Meta.Final cl.cl_meta) then cl.cl_meta <- (Meta.Final, [], cl.cl_pos) :: cl.cl_meta
  7405. | TClassDecl ( { cl_super = None } as cl ) when cl.cl_path <> baseclass.cl_path && cl.cl_path <> baseinterface.cl_path && cl.cl_path <> basedynamic.cl_path ->
  7406. if is_some cl.cl_dynamic then
  7407. cl.cl_super <- Some (basedynamic,[])
  7408. else
  7409. cl.cl_super <- Some (baseclass,[])
  7410. | TClassDecl ( { cl_super = Some(super,_) } as cl ) when cl.cl_path <> baseclass.cl_path && cl.cl_path <> baseinterface.cl_path && not ( is_hxgen (TClassDecl super) ) ->
  7411. cl.cl_implements <- (baseinterface, []) :: cl.cl_implements
  7412. | _ -> ()
  7413. );
  7414. md
  7415. in
  7416. run
  7417. let configure gen mapping_func =
  7418. let map e = Some(mapping_func e) in
  7419. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  7420. let default_config gen baseclass baseinterface basedynamic =
  7421. let impl = (default_implementation gen baseclass baseinterface basedynamic) in
  7422. configure gen impl
  7423. end;;
  7424. (*
  7425. Priority: must run AFTER UniversalBaseClass
  7426. *)
  7427. let priority = solve_deps name [DAfter UniversalBaseClass.priority]
  7428. let configure ?slow_invoke ctx baseinterface =
  7429. let gen = ctx.rcf_gen in
  7430. let run = (fun md -> match md with
  7431. | TClassDecl cl when is_hxgen md && ( not cl.cl_interface || cl.cl_path = baseinterface.cl_path ) && (match cl.cl_kind with KAbstractImpl _ -> false | _ -> true) ->
  7432. (if Meta.has Meta.ReplaceReflection cl.cl_meta then replace_reflection ctx cl);
  7433. (implement_dynamics ctx cl);
  7434. (if not (PMap.mem (gen.gmk_internal_name "hx" "lookupField") cl.cl_fields) then implement_final_lookup ctx cl);
  7435. (if not (PMap.mem (gen.gmk_internal_name "hx" "getField") cl.cl_fields) then implement_get_set ctx cl);
  7436. (if not (PMap.mem (gen.gmk_internal_name "hx" "invokeField") cl.cl_fields) then implement_invokeField ctx ~slow_invoke:slow_invoke cl);
  7437. (if not (PMap.mem (gen.gmk_internal_name "hx" "classFields") cl.cl_fields) then implement_fields ctx cl);
  7438. (if ctx.rcf_handle_statics && not (PMap.mem (gen.gmk_internal_name "hx" "getClassStatic") cl.cl_statics) then implement_get_class ctx cl);
  7439. (if not cl.cl_interface && not (PMap.mem (gen.gmk_internal_name "hx" "create") cl.cl_fields) then implement_create_empty ctx cl);
  7440. None
  7441. | _ -> None)
  7442. in
  7443. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) run
  7444. end;;
  7445. (* ******************************************* *)
  7446. (* Object Declaration Mapper *)
  7447. (* ******************************************* *)
  7448. (*
  7449. A simple Object Declaration Mapper. By default it will be a syntax filter, which only runs
  7450. after
  7451. dependencies:
  7452. *)
  7453. module ObjectDeclMap =
  7454. struct
  7455. let name = "object_decl_map"
  7456. let priority = solve_deps name []
  7457. let traverse gen map_fn =
  7458. let rec run e =
  7459. match e.eexpr with
  7460. | TObjectDecl odecl ->
  7461. let e = Type.map_expr run e in
  7462. (match e.eexpr with | TObjectDecl odecl -> map_fn e odecl | _ -> assert false)
  7463. | _ -> Type.map_expr run e
  7464. in
  7465. run
  7466. let configure gen (mapping_func:texpr->texpr) =
  7467. let map e = Some(mapping_func e) in
  7468. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  7469. end;;
  7470. (* ******************************************* *)
  7471. (* EnumToClass *)
  7472. (* ******************************************* *)
  7473. (*
  7474. For languages that don't support parameterized enums and/or metadata in enums, we need to transform
  7475. enums into normal classes. This is done at the first module pass by creating new classes with the same
  7476. path inside the modules, and removing the actual enum module by setting it as en extern.
  7477. Later, on the last expression pass, it will transform the TMatch codes into TSwitch. it will introduce a new
  7478. dependency, though:
  7479. * The target must create its own strategy to deal with reflection. As it is right now, we will have a base class
  7480. which the class will extend, create @:$IsEnum metadata for the class, and create @:alias() metadatas for the fields,
  7481. with their tag order (as a string) as their alias. If you are using ReflectionCFs, then you don't have to worry
  7482. about that, as it's already generating all information needed by the haxe runtime.
  7483. so they can be
  7484. dependencies:
  7485. The MatchToSwitch part must run after ExprStatementUnwrap as modified expressions might confuse it (not so true anymore)
  7486. *)
  7487. module EnumToClass =
  7488. struct
  7489. let name = "enum_to_class"
  7490. let priority = solve_deps name []
  7491. type t = {
  7492. ec_tbl : (path, tclass) Hashtbl.t;
  7493. }
  7494. let new_t () =
  7495. {
  7496. ec_tbl = Hashtbl.create 10
  7497. }
  7498. (* ******************************************* *)
  7499. (* EnumToClassModf *)
  7500. (* ******************************************* *)
  7501. (*
  7502. The actual Module Filter that will transform the enum into a class
  7503. dependencies:
  7504. Should run before ReflectionCFs, in order to enable proper reflection access.
  7505. Should run before TypeParams.RealTypeParams.RealTypeParamsModf, since generic enums must be first converted to generic classes
  7506. *)
  7507. module EnumToClassModf =
  7508. struct
  7509. let name = "enum_to_class_mod"
  7510. let priority = solve_deps name [DBefore ReflectionCFs.priority; DBefore TypeParams.RealTypeParams.RealTypeParamsModf.priority]
  7511. let pmap_exists fn pmap = try PMap.iter (fun a b -> if fn a b then raise Exit) pmap; false with | Exit -> true
  7512. let has_any_meta en =
  7513. let has_meta meta = List.exists (fun (m,_,_) -> match m with Meta.Custom _ -> true | _ -> false) meta in
  7514. has_meta en.e_meta || pmap_exists (fun _ ef -> has_meta ef.ef_meta) en.e_constrs
  7515. let has_parameters e =
  7516. try
  7517. (PMap.iter (fun _ ef -> match follow ef.ef_type with | TFun _ -> raise Exit | _ -> ()) e.e_constrs);
  7518. false
  7519. with | Exit -> true
  7520. let convert gen t base_class en should_be_hxgen handle_type_params =
  7521. let basic = gen.gcon.basic in
  7522. let pos = en.e_pos in
  7523. (* create the class *)
  7524. let cl = mk_class en.e_module en.e_path pos in
  7525. Hashtbl.add t.ec_tbl en.e_path cl;
  7526. (match Codegen.build_metadata gen.gcon (TEnumDecl en) with
  7527. | Some expr ->
  7528. let cf = mk_class_field "__meta__" expr.etype false expr.epos (Var { v_read = AccNormal; v_write = AccNormal }) [] in
  7529. cf.cf_expr <- Some expr;
  7530. cl.cl_statics <- PMap.add "__meta__" cf cl.cl_statics;
  7531. cl.cl_ordered_statics <- cf :: cl.cl_ordered_statics
  7532. | _ -> ()
  7533. );
  7534. cl.cl_super <- Some(base_class,[]);
  7535. cl.cl_extern <- en.e_extern;
  7536. en.e_extern <- true;
  7537. en.e_meta <- (Meta.Class, [], pos) :: en.e_meta;
  7538. cl.cl_module <- en.e_module;
  7539. cl.cl_meta <- ( Meta.Enum, [], pos ) :: cl.cl_meta;
  7540. let c_types =
  7541. if handle_type_params then
  7542. List.map (fun (s,t) -> (s, TInst (map_param (get_cl_t t), []))) en.e_types
  7543. else
  7544. []
  7545. in
  7546. cl.cl_types <- c_types;
  7547. let i = ref 0 in
  7548. let cfs = List.map (fun name ->
  7549. let ef = PMap.find name en.e_constrs in
  7550. let pos = ef.ef_pos in
  7551. let old_i = !i in
  7552. incr i;
  7553. let cf = match follow ef.ef_type with
  7554. | TFun(params,ret) ->
  7555. let dup_types =
  7556. if handle_type_params then
  7557. List.map (fun (s,t) -> (s, TInst (map_param (get_cl_t t), []))) en.e_types
  7558. else
  7559. []
  7560. in
  7561. let ef_type =
  7562. let fn, types = if handle_type_params then snd, dup_types else (fun _ -> t_dynamic), en.e_types in
  7563. let t = apply_params en.e_types (List.map fn types) ef.ef_type in
  7564. apply_params ef.ef_params (List.map fn ef.ef_params) t
  7565. in
  7566. let params, ret = get_fun ef_type in
  7567. let cf_params = if handle_type_params then dup_types @ ef.ef_params else [] in
  7568. let cf = mk_class_field name ef_type true pos (Method MethNormal) cf_params in
  7569. cf.cf_meta <- [];
  7570. let tf_args = List.map (fun (name,opt,t) -> (alloc_var name t, if opt then Some TNull else None) ) params in
  7571. let arr_decl = { eexpr = TArrayDecl(List.map (fun (v,_) -> mk_local v pos) tf_args); etype = basic.tarray t_empty; epos = pos } in
  7572. let expr = {
  7573. eexpr = TFunction({
  7574. tf_args = tf_args;
  7575. tf_type = ret;
  7576. tf_expr = mk_block ( mk_return { eexpr = TNew(cl,List.map snd dup_types, [mk_int gen old_i pos; arr_decl] ); etype = TInst(cl, List.map snd dup_types); epos = pos } );
  7577. });
  7578. etype = ef_type;
  7579. epos = pos
  7580. } in
  7581. cf.cf_expr <- Some expr;
  7582. cf
  7583. | _ ->
  7584. let actual_t = match follow ef.ef_type with
  7585. | TEnum(e, p) -> TEnum(e, List.map (fun _ -> t_dynamic) p)
  7586. | _ -> assert false
  7587. in
  7588. let cf = mk_class_field name actual_t true pos (Var { v_read = AccNormal; v_write = AccNormal }) [] in
  7589. cf.cf_meta <- [];
  7590. cf.cf_expr <- Some {
  7591. eexpr = TNew(cl, List.map (fun _ -> t_empty) cl.cl_types, [mk_int gen old_i pos; { eexpr = TArrayDecl []; etype = basic.tarray t_empty; epos = pos }]);
  7592. etype = TInst(cl, List.map (fun _ -> t_empty) cl.cl_types);
  7593. epos = pos;
  7594. };
  7595. cf
  7596. in
  7597. cl.cl_statics <- PMap.add cf.cf_name cf cl.cl_statics;
  7598. cf
  7599. ) en.e_names in
  7600. let constructs_cf = mk_class_field "constructs" (basic.tarray basic.tstring) true pos (Var { v_read = AccNormal; v_write = AccNormal }) [] in
  7601. constructs_cf.cf_meta <- [];
  7602. constructs_cf.cf_expr <- Some {
  7603. eexpr = TArrayDecl (List.map (fun s -> { eexpr = TConst(TString s); etype = basic.tstring; epos = pos }) en.e_names);
  7604. etype = basic.tarray basic.tstring;
  7605. epos = pos;
  7606. };
  7607. cl.cl_ordered_statics <- constructs_cf :: cfs @ cl.cl_ordered_statics ;
  7608. cl.cl_statics <- PMap.add "constructs" constructs_cf cl.cl_statics;
  7609. (if should_be_hxgen then
  7610. cl.cl_meta <- (Meta.HxGen,[],cl.cl_pos) :: cl.cl_meta
  7611. else begin
  7612. (* create the constructor *)
  7613. let tf_args = [ alloc_var "index" basic.tint, None; alloc_var "params" (basic.tarray t_empty), None ] in
  7614. let ftype = TFun(fun_args tf_args, basic.tvoid) in
  7615. let ctor = mk_class_field "new" ftype true pos (Method MethNormal) [] in
  7616. let me = TInst(cl, List.map snd cl.cl_types) in
  7617. ctor.cf_expr <-
  7618. Some {
  7619. eexpr = TFunction(
  7620. {
  7621. tf_args = tf_args;
  7622. tf_type = basic.tvoid;
  7623. tf_expr = mk_block {
  7624. eexpr = TCall({ eexpr = TConst TSuper; etype = me; epos = pos }, List.map (fun (v,_) -> mk_local v pos) tf_args);
  7625. etype = basic.tvoid;
  7626. epos = pos;
  7627. }
  7628. });
  7629. etype = ftype;
  7630. epos = pos
  7631. };
  7632. cl.cl_constructor <- Some ctor
  7633. end);
  7634. gen.gadd_to_module (TClassDecl cl) (max_dep);
  7635. TEnumDecl en
  7636. (*
  7637. traverse
  7638. gen - gen context
  7639. convert_all : bool - should we convert all enums? If set, convert_if_has_meta will be ignored.
  7640. convert_if_has_meta : bool - should we convert only if it has meta?
  7641. enum_base_class : tclass - the enum base class.
  7642. should_be_hxgen : bool - should the created enum be hxgen?
  7643. *)
  7644. let traverse gen t convert_all convert_if_has_meta enum_base_class should_be_hxgen handle_tparams =
  7645. let convert e = convert gen t enum_base_class e should_be_hxgen handle_tparams in
  7646. let run md = match md with
  7647. | TEnumDecl e when is_hxgen md ->
  7648. if convert_all then
  7649. convert e
  7650. else if convert_if_has_meta && has_any_meta e then
  7651. convert e
  7652. else if has_parameters e then
  7653. convert e
  7654. else begin
  7655. (* take off the :hxgen meta from it, if there's any *)
  7656. e.e_meta <- List.filter (fun (n,_,_) -> not (n = Meta.HxGen)) e.e_meta;
  7657. md
  7658. end
  7659. | _ -> md
  7660. in
  7661. run
  7662. let configure gen (mapping_func:module_type->module_type) =
  7663. let map md = Some(mapping_func md) in
  7664. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  7665. end;;
  7666. (* ******************************************* *)
  7667. (* EnumToClassExprf *)
  7668. (* ******************************************* *)
  7669. (*
  7670. Enum to class Expression Filter
  7671. will convert TMatch into TSwitch
  7672. dependencies:
  7673. Should run before TArrayTransform, since it generates array access expressions
  7674. *)
  7675. module EnumToClassExprf =
  7676. struct
  7677. let name = "enum_to_class_exprf"
  7678. let priority = solve_deps name [DBefore TArrayTransform.priority]
  7679. let ensure_local gen cond =
  7680. let exprs_before, new_cond = match cond.eexpr with
  7681. | TLocal v ->
  7682. [], cond
  7683. | _ ->
  7684. let v = mk_temp gen "cond" cond.etype in
  7685. [ { eexpr = TVar(v, Some cond); etype = gen.gcon.basic.tvoid; epos = cond.epos } ], mk_local v cond.epos
  7686. in
  7687. exprs_before, new_cond
  7688. let get_index gen cond cls tparams =
  7689. { (mk_field_access gen { cond with etype = TInst(cls, tparams) } "index" cond.epos) with etype = gen.gcon.basic.tint }
  7690. (* stolen from Hugh's hxcpp sources *)
  7691. let tmatch_params_to_vars params =
  7692. (match params with
  7693. | None | Some [] -> []
  7694. | Some l ->
  7695. let n = ref (-1) in
  7696. List.fold_left
  7697. (fun acc v -> incr n; match v with None -> acc | Some v -> (v,!n) :: acc) [] l)
  7698. (* let tmatch_params_to_exprs gen params cond_local =
  7699. let vars = tmatch_params_to_vars params in
  7700. let cond_array = { (mk_field_access gen cond_local "params" cond_local.epos) with etype = gen.gcon.basic.tarray t_empty } in
  7701. let tvars = List.map (fun (v, n) ->
  7702. (v, Some({ eexpr = TArray(cond_array, mk_int gen n cond_array.epos); etype = t_dynamic; epos = cond_array.epos }))
  7703. ) vars in
  7704. match vars with
  7705. | [] ->
  7706. []
  7707. | _ ->
  7708. [ { eexpr = TVar(tvars); etype = gen.gcon.basic.tvoid; epos = cond_local.epos } ]
  7709. *)
  7710. let traverse gen t opt_get_native_enum_tag =
  7711. let rec run e =
  7712. match e.eexpr with
  7713. | TEnumParameter(f, _,i) ->
  7714. let f = run f in
  7715. (* check if en was converted to class *)
  7716. (* if it was, switch on tag field and change cond type *)
  7717. let f = try
  7718. let en, eparams = match follow (gen.gfollow#run_f f.etype) with
  7719. | TEnum(en,p) -> en, p
  7720. | _ -> raise Not_found
  7721. in
  7722. let cl = Hashtbl.find t.ec_tbl en.e_path in
  7723. { f with etype = TInst(cl, eparams) }
  7724. with | Not_found ->
  7725. f
  7726. in
  7727. let cond_array = { (mk_field_access gen f "params" f.epos) with etype = gen.gcon.basic.tarray t_empty } in
  7728. { e with eexpr = TArray(cond_array, mk_int gen i cond_array.epos); }
  7729. | _ -> Type.map_expr run e
  7730. in
  7731. run
  7732. let configure gen (mapping_func:texpr->texpr) =
  7733. let map e = Some(mapping_func e) in
  7734. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority) map
  7735. end;;
  7736. let configure gen opt_get_native_enum_tag convert_all convert_if_has_meta enum_base_class should_be_hxgen handle_tparams =
  7737. let t = new_t () in
  7738. EnumToClassModf.configure gen (EnumToClassModf.traverse gen t convert_all convert_if_has_meta enum_base_class should_be_hxgen handle_tparams);
  7739. EnumToClassExprf.configure gen (EnumToClassExprf.traverse gen t opt_get_native_enum_tag)
  7740. end;;
  7741. (* ******************************************* *)
  7742. (* IteratorsInterface *)
  7743. (* ******************************************* *)
  7744. (*
  7745. This module will handle with Iterators, Iterables and TFor() expressions.
  7746. At first, a module filter will receive a Iterator<T> and Iterable<T> interface, which will be implemented
  7747. if hasNext(), next() or iterator() fields are detected with the correct type.
  7748. At this part a custom function will be called which can adequate the class fields so they are compatible with
  7749. native Iterators as well
  7750. The expression filter part of this module will look for TFor() expressions, and transform like that:
  7751. for (anInt in value.iterator())
  7752. {
  7753. }
  7754. {
  7755. var s:haxe.lang.Iterator<Int> = ExternalFunction.getIterator(value.iterator());
  7756. while (s.hasNext())
  7757. {
  7758. var anInt:Int = s.next();
  7759. }
  7760. }
  7761. dependencies:
  7762. None.
  7763. *)
  7764. module IteratorsInterface =
  7765. struct
  7766. let name = "iterators_interface"
  7767. (* TODO later
  7768. (* ******************************************* *)
  7769. (* IteratorsInterfaceModf *)
  7770. (* ******************************************* *)
  7771. (*
  7772. The module filter for Iterators Interface, which will implement the iterator/iterable interface on each
  7773. class that conforms with the typedefs Iterator<> and Iterable<>
  7774. It's a very simple module and it will rely on cast detection to work correctly. This is so that
  7775. when the
  7776. dependencies:
  7777. Must run at the Module Filters, so cast detection can detect a cast to the interface and we can
  7778. *)
  7779. module IteratorsInterfaceModf =
  7780. struct
  7781. let name = "iterators_interface_modf"
  7782. let conforms_cfs has_next next =
  7783. try (match follow has_next.cf_type with
  7784. | TFun([],ret) when
  7785. (match follow ret with | TEnum({ e_path = ([], "Bool") }, []) -> () | _ -> raise Not_found) ->
  7786. ()
  7787. | _ -> raise Not_found);
  7788. (match follow next.cf_type with
  7789. | TFun([], ret) -> ret
  7790. | _ -> raise Not_found
  7791. )
  7792. let conforms_type_iterator t =
  7793. try match follow t with
  7794. | TInst(cl,params) ->
  7795. let has_next = PMap.find "hasNext" cl.cl_fields in
  7796. let next = PMap.find "next" cl.cl_fields in
  7797. Some (conforms_cfs has_next next)
  7798. | TAnon(anon) ->
  7799. let has_next = PMap.find "hasNext" anon.a_fields in
  7800. let next = PMap.find "next" anon.a_fields in
  7801. Some (conforms_cfs has_next next)
  7802. | _ -> None
  7803. with | Not_found -> None
  7804. let conforms_as_iterable cl =
  7805. try
  7806. let iterator = PMap.find "iterator" cl.cl_fields in
  7807. match follow iterator.cf_type with
  7808. | TFun([], ret) -> conforms_type_iterator ret
  7809. | _ -> None
  7810. with | Not_found -> None
  7811. let conforms_as_iterator cl =
  7812. try
  7813. let has_next = PMap.find "hasNext" cl.cl_fields in
  7814. let next = PMap.find "next" cl.cl_fields in
  7815. Some (conforms_cfs has_next next)
  7816. with | Not_found -> None
  7817. let priority = solve_deps name []
  7818. let traverse gen iterator_iface iterable_iface on_found_iterator on_found_iterable =
  7819. let rec run md =
  7820. match md with
  7821. | TClassDecl cl when not cl.cl_extern && is_hxgen cl ->
  7822. let conforms_iterator = conforms_as_iterator cl in
  7823. let conforms_iterable = conforms_as_iterable cl in
  7824. if is_some conforms_iterator then begin
  7825. let it_t = get conforms_iterator in
  7826. cl.cl_interfaces <- (iterator_iface, [it_t]);
  7827. on_found_iterator cl
  7828. end;
  7829. if is_some conforms_iterable then begin
  7830. let it_t = get conforms_iterable in
  7831. cl.cl_interfaces <- (iterable_iface, [it_t]);
  7832. on_found_iterable cl
  7833. end;
  7834. md
  7835. | _ -> md
  7836. in
  7837. run
  7838. let configure gen (mapping_func:texpr->texpr) =
  7839. let map e = Some(mapping_func e) in
  7840. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority) map
  7841. end;;
  7842. *)
  7843. (* ******************************************* *)
  7844. (* IteratorsInterfaceExprf *)
  7845. (* ******************************************* *)
  7846. (*
  7847. The expression filter for Iterators. Will look for TFor, transform it into
  7848. {
  7849. var iterator = // in expression here
  7850. while (iterator.hasNext())
  7851. {
  7852. var varName = iterator.next();
  7853. }
  7854. }
  7855. dependencies:
  7856. Must run before Dynamic fields access is run
  7857. *)
  7858. module IteratorsInterfaceExprf =
  7859. struct
  7860. let name = "iterators_interface_exprf"
  7861. let priority = solve_deps name [DBefore DynamicFieldAccess.priority]
  7862. let priority_as_synf = solve_deps name [DBefore DynamicFieldAccess.priority_as_synf]
  7863. let mk_access gen v name pos =
  7864. let field_t =
  7865. try match follow v.v_type with
  7866. | TInst(cl, params) ->
  7867. let field = PMap.find name cl.cl_fields in
  7868. apply_params cl.cl_types params field.cf_type
  7869. | TAnon(anon) ->
  7870. let field = PMap.find name anon.a_fields in
  7871. field.cf_type
  7872. | _ -> t_dynamic
  7873. with | Not_found -> t_dynamic
  7874. in
  7875. { (mk_field_access gen (mk_local v pos) name pos) with etype = field_t }
  7876. let traverse gen change_in_expr =
  7877. let basic = gen.gcon.basic in
  7878. let rec run e =
  7879. match e.eexpr with
  7880. | TFor(var, in_expr, block) ->
  7881. let in_expr = change_in_expr (run in_expr) in
  7882. let temp = mk_temp gen "iterator" in_expr.etype in
  7883. let block =
  7884. [
  7885. { eexpr = TVar(temp, Some(in_expr)); etype = basic.tvoid; epos = in_expr.epos };
  7886. {
  7887. eexpr = TWhile(
  7888. { eexpr = TCall(mk_access gen temp "hasNext" in_expr.epos, []); etype = basic.tbool; epos = in_expr.epos },
  7889. Type.concat ({
  7890. eexpr = TVar(var, Some({ eexpr = TCall(mk_access gen temp "next" in_expr.epos, []); etype = var.v_type; epos = in_expr.epos }));
  7891. etype = basic.tvoid;
  7892. epos = in_expr.epos
  7893. }) ( run block ),
  7894. Ast.NormalWhile);
  7895. etype = basic.tvoid;
  7896. epos = e.epos
  7897. }
  7898. ] in
  7899. { eexpr = TBlock(block); etype = e.etype; epos = e.epos }
  7900. | _ -> Type.map_expr run e
  7901. in
  7902. run
  7903. let configure gen (mapping_func:texpr->texpr) =
  7904. let map e = Some(mapping_func e) in
  7905. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority) map
  7906. let configure_as_synf gen (mapping_func:texpr->texpr) =
  7907. let map e = Some(mapping_func e) in
  7908. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority_as_synf) map
  7909. end;;
  7910. let configure gen change_in_expr =
  7911. IteratorsInterfaceExprf.configure gen (IteratorsInterfaceExprf.traverse gen change_in_expr)
  7912. let configure_as_synf gen change_in_expr =
  7913. IteratorsInterfaceExprf.configure_as_synf gen (IteratorsInterfaceExprf.traverse gen change_in_expr)
  7914. end;;
  7915. (* ******************************************* *)
  7916. (* SwitchToIf *)
  7917. (* ******************************************* *)
  7918. (*
  7919. Just a syntax filter which changes switch expressions to if() else if() else if() ...
  7920. It can be also an expression filter
  7921. dependencies:
  7922. *)
  7923. module SwitchToIf =
  7924. struct
  7925. let name = "switch_to_if"
  7926. let priority = solve_deps name []
  7927. let traverse gen (should_convert:texpr->bool) (handle_nullables:bool) =
  7928. let basic = gen.gcon.basic in
  7929. let rec run e =
  7930. match e.eexpr with
  7931. | TSwitch(cond,cases,default) when should_convert e ->
  7932. let cond_etype, should_cache = match handle_nullables, gen.gfollow#run_f cond.etype with
  7933. | true, TType({ t_path = ([], "Null") }, [t]) ->
  7934. let rec take_off_nullable t = match gen.gfollow#run_f t with
  7935. | TType({ t_path = ([], "Null") }, [t]) -> take_off_nullable t
  7936. | _ -> t
  7937. in
  7938. take_off_nullable t, true
  7939. | _, _ -> cond.etype, false
  7940. in
  7941. if should_cache && not (should_convert { e with eexpr = TSwitch({ cond with etype = cond_etype }, cases, default) }) then begin
  7942. { e with eexpr = TSwitch(mk_cast cond_etype (run cond), List.map (fun (cs,e) -> (List.map run cs, run e)) cases, Option.map run default) }
  7943. end else begin
  7944. let local, fst_block = match cond.eexpr, should_cache with
  7945. | TLocal _, false -> cond, []
  7946. | _ ->
  7947. let var = mk_temp gen "switch" cond_etype in
  7948. let cond = run cond in
  7949. let cond = if should_cache then mk_cast cond_etype cond else cond in
  7950. mk_local var cond.epos, [ { eexpr = TVar(var,Some(cond)); etype = basic.tvoid; epos = cond.epos } ]
  7951. in
  7952. let mk_eq cond =
  7953. { eexpr = TBinop(Ast.OpEq, local, cond); etype = basic.tbool; epos = cond.epos }
  7954. in
  7955. let rec mk_many_cond conds =
  7956. match conds with
  7957. | cond :: [] ->
  7958. mk_eq cond
  7959. | cond :: tl ->
  7960. { eexpr = TBinop(Ast.OpBoolOr, mk_eq (run cond), mk_many_cond tl); etype = basic.tbool; epos = cond.epos }
  7961. | [] -> assert false
  7962. in
  7963. let mk_many_cond conds =
  7964. let ret = mk_many_cond conds in
  7965. (*
  7966. this might be considered a hack. But since we're on a syntax filter and
  7967. the condition is guaranteed to not have run twice, we can really run the
  7968. expr filters again for it (so to change e.g. OpEq accordingly
  7969. *)
  7970. gen.gexpr_filters#run_f ret
  7971. in
  7972. let rec loop cases = match cases with
  7973. | (conds,e) :: [] ->
  7974. { eexpr = TIf(mk_many_cond conds, run e, Option.map run default); etype = e.etype; epos = e.epos }
  7975. | (conds,e) :: tl ->
  7976. { eexpr = TIf(mk_many_cond conds, run e, Some(loop tl)); etype = e.etype; epos = e.epos }
  7977. | [] -> match default with
  7978. | None ->
  7979. raise Exit
  7980. | Some d -> run d
  7981. in
  7982. try
  7983. { e with eexpr = TBlock(fst_block @ [loop cases]) }
  7984. with | Exit ->
  7985. { e with eexpr = TBlock [] }
  7986. end
  7987. | _ -> Type.map_expr run e
  7988. in
  7989. run
  7990. let configure gen (mapping_func:texpr->texpr) =
  7991. let map e = Some(mapping_func e) in
  7992. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  7993. end;;
  7994. (* ******************************************* *)
  7995. (* Anonymous Class object handling *)
  7996. (* ******************************************* *)
  7997. (*
  7998. (syntax)
  7999. When we pass a class as an object, in some languages we will need a special construct to be able to
  8000. access its statics as if they were normal object fields. On C# and Java the way found to do that is
  8001. by handling statics reflection also by a normal instance. This also happens in hxcpp and neko, so I
  8002. guess it's a valid practice.
  8003. So if we want to handle the reflection of the static MyClass, here's roughly how it will be done:
  8004. var x = MyClass;
  8005. gets converted into
  8006. Haxe.Lang.Class x = Haxe.Lang.Runtime.GetType(typeof(MyClass).RuntimeHandle);
  8007. which will in turn look in its cache but roughly would do:
  8008. Haxe.Lang.Class x = new Haxe.Lang.Class(new MyClass(EmptyObject.EMPTY));
  8009. This module will of course let the caller choose how this will be implemented. It will just identify all
  8010. uses of class that will require it to be cast as an object.
  8011. dependencies:
  8012. *)
  8013. module ClassInstance =
  8014. struct
  8015. let priority = solve_deps "class_instance" []
  8016. let traverse gen (change_expr:texpr->module_type->texpr) =
  8017. let rec run e =
  8018. match e.eexpr with
  8019. | TCall( ({ eexpr = TLocal(v) } as local), calls ) when String.get v.v_name 0 = '_' && Hashtbl.mem gen.gspecial_vars v.v_name ->
  8020. { e with eexpr = TCall(local, List.map (fun e ->
  8021. match e.eexpr with
  8022. | TTypeExpr _ -> e
  8023. | _ -> run e) calls) }
  8024. | TField({ eexpr = TTypeExpr(mt) }, f) ->
  8025. e
  8026. | TField(ef, f) ->
  8027. (match anon_class ef.etype with
  8028. | None -> Type.map_expr run e
  8029. | Some t ->
  8030. { e with eexpr = TField( { ef with eexpr = TTypeExpr(t) }, f) }
  8031. )
  8032. | TTypeExpr(mt) -> change_expr e mt
  8033. | _ -> Type.map_expr run e
  8034. in
  8035. run
  8036. let configure gen (mapping_func:texpr->texpr) =
  8037. let map e = Some(mapping_func e) in
  8038. gen.gsyntax_filters#add ~name:"class_instance" ~priority:(PCustom priority) map
  8039. end;;
  8040. (* ******************************************* *)
  8041. (* HardNullableSynf *)
  8042. (* ******************************************* *)
  8043. (*
  8044. This module will handle Null<T> types for languages that offer a way of dealing with
  8045. stack-allocated structures or tuples and generics. Essentialy on those targets a Null<T>
  8046. will be a tuple ( 'a * bool ), where bool is whether the value is null or not.
  8047. At first (configure-time), we will modify the follow function so it can follow correctly nested Null<Null<T>>,
  8048. and do not follow Null<T> to its underlying type
  8049. Then we will run a syntax filter, which will look for casts to Null<T> and replace them by
  8050. a call to the new Null<T> creation;
  8051. Also casts from Null<T> to T or direct uses of Null<T> (call, field access, array access, closure)
  8052. will result in the actual value being accessed
  8053. For compatibility with the C# target, HardNullable will accept both Null<T> and haxe.lang.Null<T> types
  8054. dependencies:
  8055. Needs to be run after all cast detection modules
  8056. *)
  8057. module HardNullableSynf =
  8058. struct
  8059. let name = "hard_nullable"
  8060. let priority = solve_deps name [DAfter CastDetect.ReturnCast.priority]
  8061. let rec is_null_t gen t = match gen.greal_type t with
  8062. | TType( { t_path = ([], "Null") }, [of_t])
  8063. | TInst( { cl_path = (["haxe";"lang"], "Null") }, [of_t]) ->
  8064. let rec take_off_null t =
  8065. match is_null_t gen t with | None -> t | Some s -> take_off_null s
  8066. in
  8067. Some (take_off_null of_t)
  8068. | TMono r -> (match !r with | Some t -> is_null_t gen t | None -> None)
  8069. | TLazy f -> is_null_t gen (!f())
  8070. | TType (t, tl) ->
  8071. is_null_t gen (apply_params t.t_types tl t.t_type)
  8072. | _ -> None
  8073. let follow_addon gen t =
  8074. let rec strip_off_nullable t =
  8075. let t = gen.gfollow#run_f t in
  8076. match t with
  8077. (* haxe.lang.Null<haxe.lang.Null<>> wouldn't be a valid construct, so only follow Null<> *)
  8078. | TType ( { t_path = ([], "Null") }, [of_t] ) -> strip_off_nullable of_t
  8079. | _ -> t
  8080. in
  8081. match t with
  8082. | TType( ({ t_path = ([], "Null") } as tdef), [of_t]) ->
  8083. Some( TType(tdef, [ strip_off_nullable of_t ]) )
  8084. | _ -> None
  8085. let traverse gen unwrap_null wrap_val null_to_dynamic has_value opeq_handler handle_opeq handle_cast =
  8086. let handle_unwrap to_t e =
  8087. let e_null_t = get (is_null_t gen e.etype) in
  8088. match gen.greal_type to_t with
  8089. | TDynamic _ | TMono _ | TAnon _ ->
  8090. (match e_null_t with
  8091. | TDynamic _ | TMono _ | TAnon _ ->
  8092. gen.ghandle_cast to_t e_null_t (unwrap_null e)
  8093. | _ -> null_to_dynamic e
  8094. )
  8095. | _ ->
  8096. gen.ghandle_cast to_t e_null_t (unwrap_null e)
  8097. in
  8098. let handle_wrap e t =
  8099. match e.eexpr with
  8100. | TConst(TNull) ->
  8101. wrap_val e t false
  8102. | _ ->
  8103. wrap_val e t true
  8104. in
  8105. let is_null_t = is_null_t gen in
  8106. let cur_block = ref [] in
  8107. let add_tmp v e p =
  8108. cur_block := { eexpr = TVar(v,e); etype = gen.gcon.basic.tvoid; epos = p } :: !cur_block
  8109. in
  8110. let get_local e = match e.eexpr with
  8111. | TLocal _ ->
  8112. e, e
  8113. | _ ->
  8114. let v = mk_temp gen "nulltmp" e.etype in
  8115. add_tmp v (Some (null e.etype e.epos)) e.epos;
  8116. let local = { e with eexpr = TLocal(v) } in
  8117. mk_paren { e with eexpr = TBinop(Ast.OpAssign, local, e) }, local
  8118. in
  8119. let rec run e =
  8120. match e.eexpr with
  8121. | TBlock(bl) ->
  8122. let lst = !cur_block in
  8123. cur_block := [];
  8124. List.iter (fun e ->
  8125. let e = run e in
  8126. cur_block := (e :: !cur_block)
  8127. ) bl;
  8128. let ret = !cur_block in
  8129. cur_block := lst;
  8130. { e with eexpr = TBlock(List.rev ret) }
  8131. | TCast(v, _) ->
  8132. let null_et = is_null_t e.etype in
  8133. let null_vt = is_null_t v.etype in
  8134. (match null_vt, null_et with
  8135. | Some(vt), None ->
  8136. (match v.eexpr with
  8137. (* is there an unnecessary cast to Nullable? *)
  8138. | TCast(v2, _) ->
  8139. run { v with etype = e.etype }
  8140. | _ ->
  8141. handle_unwrap e.etype (run v)
  8142. )
  8143. | None, Some(et) ->
  8144. handle_wrap (run v) et
  8145. | Some(vt), Some(et) when handle_cast ->
  8146. handle_wrap (gen.ghandle_cast et vt (handle_unwrap vt (run v))) et
  8147. | Some(vt), Some(et) when not (type_iseq (run_follow gen vt) (run_follow gen et)) ->
  8148. (* check if has value and convert *)
  8149. let vlocal_fst, vlocal = get_local (run v) in
  8150. {
  8151. eexpr = TIf(
  8152. has_value vlocal_fst,
  8153. handle_wrap (mk_cast et (unwrap_null vlocal)) et,
  8154. Some( handle_wrap (null et e.epos) et ));
  8155. etype = e.etype;
  8156. epos = e.epos
  8157. }
  8158. | _ ->
  8159. Type.map_expr run e
  8160. )
  8161. | TField(ef, field) when is_some (is_null_t ef.etype) ->
  8162. let to_t = get (is_null_t ef.etype) in
  8163. { e with eexpr = TField(handle_unwrap to_t (run ef), field) }
  8164. | TCall(ecall, params) when is_some (is_null_t ecall.etype) ->
  8165. let to_t = get (is_null_t ecall.etype) in
  8166. { e with eexpr = TCall(handle_unwrap to_t (run ecall), List.map run params) }
  8167. | TArray(earray, p) when is_some (is_null_t earray.etype) ->
  8168. let to_t = get (is_null_t earray.etype) in
  8169. { e with eexpr = TArray(handle_unwrap to_t (run earray), p) }
  8170. | TBinop(op, e1, e2) ->
  8171. let e1_t = is_null_t e1.etype in
  8172. let e2_t = is_null_t e2.etype in
  8173. (match op with
  8174. | Ast.OpAssign
  8175. | Ast.OpAssignOp _ ->
  8176. (match e1_t, e2_t with
  8177. | Some t1, Some t2 ->
  8178. (match op with
  8179. | Ast.OpAssign ->
  8180. Type.map_expr run e
  8181. | Ast.OpAssignOp op ->
  8182. (match e1.eexpr with
  8183. | TLocal _ ->
  8184. { e with eexpr = TBinop( Ast.OpAssign, e1, handle_wrap { e with eexpr = TBinop (op, handle_unwrap t1 e1, handle_unwrap t2 (run e2) ) } t1 ) }
  8185. | _ ->
  8186. let v, e1, evars = match e1.eexpr with
  8187. | TField(ef, f) ->
  8188. let v = mk_temp gen "nullbinop" ef.etype in
  8189. v, { e1 with eexpr = TField(mk_local v ef.epos, f) }, ef
  8190. | _ ->
  8191. let v = mk_temp gen "nullbinop" e1.etype in
  8192. v, mk_local v e1.epos, e1
  8193. in
  8194. { e with eexpr = TBlock([
  8195. { eexpr = TVar(v, Some evars); etype = gen.gcon.basic.tvoid; epos = e.epos };
  8196. { e with eexpr = TBinop( Ast.OpAssign, e1, handle_wrap { e with eexpr = TBinop (op, handle_unwrap t1 e1, handle_unwrap t2 (run e2) ) } t1 ) }
  8197. ]) }
  8198. )
  8199. | _ -> assert false
  8200. )
  8201. | _ ->
  8202. Type.map_expr run e (* casts are already dealt with normal CastDetection module *)
  8203. )
  8204. | Ast.OpEq | Ast.OpNotEq when not handle_opeq ->
  8205. Type.map_expr run e
  8206. | Ast.OpEq | Ast.OpNotEq ->
  8207. (match e1.eexpr, e2.eexpr with
  8208. | TConst(TNull), _ when is_some e2_t ->
  8209. let e = has_value (run e2) in
  8210. if op = Ast.OpEq then
  8211. { e with eexpr = TUnop(Ast.Not, Ast.Prefix, e) }
  8212. else
  8213. e
  8214. | _, TConst(TNull) when is_some e1_t ->
  8215. let e = has_value (run e1) in
  8216. if op = Ast.OpEq then
  8217. { e with eexpr = TUnop(Ast.Not, Ast.Prefix, e) }
  8218. else
  8219. e
  8220. | _ when is_some e1_t || is_some e2_t ->
  8221. let e1, e2 =
  8222. if not (is_some e1_t) then
  8223. run e2, handle_wrap (run e1) (get e2_t)
  8224. else if not (is_some e2_t) then
  8225. run e1, handle_wrap (run e2) (get e1_t)
  8226. else
  8227. run e1, run e2
  8228. in
  8229. let e = opeq_handler e1 e2 in
  8230. if op = Ast.OpEq then
  8231. { e with eexpr = TUnop(Ast.Not, Ast.Prefix, e) }
  8232. else
  8233. e
  8234. | _ ->
  8235. Type.map_expr run e
  8236. )
  8237. | _ ->
  8238. let e1 = if is_some e1_t then
  8239. handle_unwrap (get e1_t) (run e1)
  8240. else run e1 in
  8241. let e2 = if is_some e2_t then
  8242. handle_unwrap (get e2_t) (run e2)
  8243. else
  8244. run e2 in
  8245. (* if it is Null<T>, we need to convert the result again to null *)
  8246. let e_t = (is_null_t e.etype) in
  8247. if is_some e_t then
  8248. wrap_val { eexpr = TBinop(op, e1, e2); etype = get e_t; epos = e.epos } (get e_t) true
  8249. else
  8250. { e with eexpr = TBinop(op, e1, e2) }
  8251. )
  8252. (*| TUnop( (Ast.Increment as op)*)
  8253. | _ -> Type.map_expr run e
  8254. in
  8255. let run e = match e.eexpr with
  8256. | TFunction tf ->
  8257. run { e with eexpr = TFunction { tf with tf_expr = mk_block tf.tf_expr } }
  8258. | TBlock _ ->
  8259. run e
  8260. | _ -> match run (mk_block e) with
  8261. | { eexpr = TBlock([e]) } -> e
  8262. | e -> e
  8263. in
  8264. run
  8265. let configure gen (mapping_func:texpr->texpr) =
  8266. gen.gfollow#add ~name:(name ^ "_follow") (follow_addon gen);
  8267. let map e = Some(mapping_func e) in
  8268. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  8269. end;;
  8270. (* ******************************************* *)
  8271. (* ArrayDeclSynf *)
  8272. (* ******************************************* *)
  8273. (*
  8274. A syntax filter that will change array declarations to the actual native array declarations plus
  8275. the haxe array initialization
  8276. dependencies:
  8277. Must run after ObjectDeclMap since it can add TArrayDecl expressions
  8278. *)
  8279. module ArrayDeclSynf =
  8280. struct
  8281. let name = "array_decl_synf"
  8282. let priority = solve_deps name [DAfter ObjectDeclMap.priority]
  8283. let default_implementation gen native_array_cl =
  8284. let rec run e =
  8285. match e.eexpr with
  8286. | TArrayDecl el ->
  8287. let cl, params = match follow e.etype with
  8288. | TInst(({ cl_path = ([], "Array") } as cl), ( _ :: _ as params)) -> cl, params
  8289. | TInst(({ cl_path = ([], "Array") } as cl), []) -> cl, [t_dynamic]
  8290. | _ -> assert false
  8291. in
  8292. let changed_params = gen.greal_type_param (TClassDecl cl) params in
  8293. { e with eexpr = TNew(cl, changed_params, [ { e with eexpr = TArrayDecl(List.map run el); etype = TInst(native_array_cl, changed_params) } ] ); }
  8294. | _ -> Type.map_expr run e
  8295. in
  8296. run
  8297. let configure gen (mapping_func:texpr->texpr) =
  8298. let map e = Some(mapping_func e) in
  8299. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  8300. end;;
  8301. (* ******************************************* *)
  8302. (* SwitchBreakSynf *)
  8303. (* ******************************************* *)
  8304. (*
  8305. In most languages, 'break' is used as a statement also to break from switch statements.
  8306. This generates an incompatibility with haxe code, as we can use break to break from loops from inside a switch
  8307. This script will detect 'breaks' inside switch statements, and will offer the opportunity to change both
  8308. when this pattern is found.
  8309. Some options are possible:
  8310. On languages that support goto, 'break' may mean goto " after the loop ". There also can be special labels for
  8311. loops, so you can write "break label" (javascript, java, d)
  8312. On languages that do not support goto, a custom solution must be enforced
  8313. dependencies:
  8314. Since UnreachableCodeElimination must run before it, and Unreachable should be one of the
  8315. very last filters to run, we will make a fixed value which runs after UnreachableCodeElimination
  8316. (meaning: it's the very last filter)
  8317. *)
  8318. module SwitchBreakSynf =
  8319. struct
  8320. let name = "switch_break_synf"
  8321. let priority = min_dep -. 150.0
  8322. type add_to_block_api = texpr->bool->unit
  8323. let traverse gen (change_loop:texpr->int->add_to_block_api->texpr) (change_break:texpr->int->add_to_block_api->texpr) =
  8324. let in_switch = ref false in
  8325. let cur_block = ref [] in
  8326. let to_add = ref [] in
  8327. let did_found = ref (-1) in
  8328. let api expr before =
  8329. if before then cur_block := expr :: !cur_block else to_add := expr :: !to_add
  8330. in
  8331. let num = ref 0 in
  8332. let cur_num = ref 0 in
  8333. let rec run e =
  8334. match e.eexpr with
  8335. | TFunction _ ->
  8336. let old_num = !num in
  8337. num := 0;
  8338. let ret = Type.map_expr run e in
  8339. num := old_num;
  8340. ret
  8341. | TFor _
  8342. | TWhile _ ->
  8343. let last_switch = !in_switch in
  8344. let last_found = !did_found in
  8345. let last_num = !cur_num in
  8346. in_switch := false;
  8347. incr num;
  8348. cur_num := !num;
  8349. did_found := -1;
  8350. let new_e = Type.map_expr run e in (* assuming that no loop will be found in the condition *)
  8351. let new_e = if !did_found <> -1 then change_loop new_e !did_found api else new_e in
  8352. did_found := last_found;
  8353. in_switch := last_switch;
  8354. cur_num := last_num;
  8355. new_e
  8356. | TSwitch _
  8357. | TPatMatch _ ->
  8358. let last_switch = !in_switch in
  8359. in_switch := true;
  8360. let new_e = Type.map_expr run e in
  8361. in_switch := last_switch;
  8362. new_e
  8363. | TBlock bl ->
  8364. let last_block = !cur_block in
  8365. let last_toadd = !to_add in
  8366. to_add := [];
  8367. cur_block := [];
  8368. List.iter (fun e ->
  8369. let new_e = run e in
  8370. cur_block := new_e :: !cur_block;
  8371. match !to_add with
  8372. | [] -> ()
  8373. | _ -> cur_block := !to_add @ !cur_block; to_add := []
  8374. ) bl;
  8375. let ret = List.rev !cur_block in
  8376. cur_block := last_block;
  8377. to_add := last_toadd;
  8378. { e with eexpr = TBlock(ret) }
  8379. | TBreak ->
  8380. if !in_switch then (did_found := !cur_num; change_break e !cur_num api) else e
  8381. | _ -> Type.map_expr run e
  8382. in
  8383. run
  8384. let configure gen (mapping_func:texpr->texpr) =
  8385. let map e = Some(mapping_func e) in
  8386. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  8387. end;;
  8388. (* ******************************************* *)
  8389. (* Unreachable Code Elimination *)
  8390. (* ******************************************* *)
  8391. (*
  8392. In some source code platforms, the code won't compile if there is Unreachable code, so this filter will take off any unreachable code.
  8393. If the parameter "handle_switch_break" is set to true, it will already add a "break" statement on switch cases when suitable;
  8394. in order to not confuse with while break, it will be a special expression __sbreak__
  8395. If the parameter "handle_not_final_returns" is set to true, it will also add final returns when functions are detected to be lacking of them.
  8396. (Will respect __fallback__ expressions)
  8397. If the parameter "java_mode" is set to true, some additional checks following the java unreachable specs
  8398. (http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21) will be added
  8399. dependencies:
  8400. This must run before SwitchBreakSynf (see SwitchBreakSynf dependecy value)
  8401. This must be the LAST syntax filter to run. It expects ExpressionUnwrap to have run correctly, since this will only work for source-code based targets
  8402. *)
  8403. module UnreachableCodeEliminationSynf =
  8404. struct
  8405. let name = "unreachable_synf"
  8406. let priority = min_dep -. 100.0
  8407. type uexpr_kind =
  8408. | Normal
  8409. | BreaksLoop
  8410. | BreaksFunction
  8411. let aggregate_kind e1 e2 =
  8412. match e1, e2 with
  8413. | Normal, _
  8414. | _, Normal -> Normal
  8415. | BreaksLoop, _
  8416. | _, BreaksLoop -> BreaksLoop
  8417. | BreaksFunction, BreaksFunction -> BreaksFunction
  8418. let aggregate_constant op c1 c2=
  8419. match op, c1, c2 with
  8420. | OpEq, Some v1, Some v2 -> Some (TBool (v1 = v2))
  8421. | OpNotEq, Some v1, Some v2 -> Some (TBool (v1 <> v2))
  8422. | OpBoolOr, Some (TBool v1) , Some (TBool v2) -> Some (TBool (v1 || v2))
  8423. | OpBoolAnd, Some (TBool v1) , Some (TBool v2) -> Some (TBool (v1 && v2))
  8424. | OpAssign, _, Some v2 -> Some v2
  8425. | _ -> None
  8426. let rec get_constant_expr e =
  8427. match e.eexpr with
  8428. | TConst (v) -> Some v
  8429. | TBinop(op, v1, v2) -> aggregate_constant op (get_constant_expr v1) (get_constant_expr v2)
  8430. | TParenthesis(e) | TMeta(_,e) -> get_constant_expr e
  8431. | _ -> None
  8432. let traverse gen should_warn handle_switch_break handle_not_final_returns java_mode =
  8433. let basic = gen.gcon.basic in
  8434. let do_warn =
  8435. if should_warn then gen.gcon.warning "Unreachable code" else (fun pos -> ())
  8436. in
  8437. let return_loop expr kind =
  8438. match kind with
  8439. | Normal | BreaksLoop -> expr, Normal
  8440. | _ -> expr, kind
  8441. in
  8442. let sbreak = alloc_var "__sbreak__" t_dynamic in
  8443. let mk_sbreak = mk_local sbreak in
  8444. let rec has_fallback expr = match expr.eexpr with
  8445. | TBlock(bl) -> (match List.rev bl with
  8446. | { eexpr = TLocal { v_name = "__fallback__" } } :: _ -> true
  8447. | ({ eexpr = TBlock(_) } as bl) :: _ -> has_fallback bl
  8448. | _ -> false)
  8449. | TLocal { v_name = "__fallback__" } -> true
  8450. | _ -> false
  8451. in
  8452. let handle_case = if handle_switch_break then
  8453. (fun (expr,kind) ->
  8454. match kind with
  8455. | Normal when has_fallback expr -> expr
  8456. | Normal -> Type.concat expr (mk_sbreak expr.epos)
  8457. | BreaksLoop | BreaksFunction -> expr
  8458. )
  8459. else
  8460. fst
  8461. in
  8462. let has_break = ref false in
  8463. let rec process_expr expr =
  8464. match expr.eexpr with
  8465. | TReturn _ | TThrow _ -> expr, BreaksFunction
  8466. | TContinue -> expr, BreaksLoop
  8467. | TBreak -> has_break := true; expr, BreaksLoop
  8468. | TCall( { eexpr = TLocal { v_name = "__goto__" } }, _ ) -> expr, BreaksLoop
  8469. | TBlock bl ->
  8470. let new_block = ref [] in
  8471. let is_unreachable = ref false in
  8472. let ret_kind = ref Normal in
  8473. List.iter (fun e ->
  8474. if !is_unreachable then
  8475. do_warn e.epos
  8476. else begin
  8477. let changed_e, kind = process_expr e in
  8478. new_block := changed_e :: !new_block;
  8479. match kind with
  8480. | BreaksLoop | BreaksFunction ->
  8481. ret_kind := kind;
  8482. is_unreachable := true
  8483. | _ -> ()
  8484. end
  8485. ) bl;
  8486. { expr with eexpr = TBlock(List.rev !new_block) }, !ret_kind
  8487. | TFunction tf ->
  8488. let changed, kind = process_expr tf.tf_expr in
  8489. let changed = if handle_not_final_returns && not (is_void tf.tf_type) && kind <> BreaksFunction then
  8490. Type.concat changed { eexpr = TReturn( Some (null tf.tf_type expr.epos) ); etype = basic.tvoid; epos = expr.epos }
  8491. else
  8492. changed
  8493. in
  8494. { expr with eexpr = TFunction({ tf with tf_expr = changed }) }, Normal
  8495. | TFor(var, cond, block) ->
  8496. let last_has_break = !has_break in
  8497. has_break := false;
  8498. let changed_block, _ = process_expr block in
  8499. has_break := last_has_break;
  8500. let expr = { expr with eexpr = TFor(var, cond, changed_block) } in
  8501. return_loop expr Normal
  8502. | TIf(cond, eif, None) ->
  8503. if java_mode then
  8504. match get_constant_expr cond with
  8505. | Some (TBool true) ->
  8506. process_expr eif
  8507. | _ ->
  8508. { expr with eexpr = TIf(cond, fst (process_expr eif), None) }, Normal
  8509. else
  8510. { expr with eexpr = TIf(cond, fst (process_expr eif), None) }, Normal
  8511. | TIf(cond, eif, Some eelse) ->
  8512. let eif, eif_k = process_expr eif in
  8513. let eelse, eelse_k = process_expr eelse in
  8514. let k = aggregate_kind eif_k eelse_k in
  8515. { expr with eexpr = TIf(cond, eif, Some eelse) }, k
  8516. | TWhile(cond, block, flag) ->
  8517. let last_has_break = !has_break in
  8518. has_break := false;
  8519. let block, k = process_expr block in
  8520. if java_mode then
  8521. match get_constant_expr cond, flag, !has_break with
  8522. | Some (TBool true), _, false ->
  8523. has_break := last_has_break;
  8524. { expr with eexpr = TWhile(cond, block, flag) }, BreaksFunction
  8525. | Some (TBool false), NormalWhile, _ ->
  8526. has_break := last_has_break;
  8527. do_warn expr.epos;
  8528. null expr.etype expr.epos, Normal
  8529. | _ ->
  8530. has_break := last_has_break;
  8531. return_loop { expr with eexpr = TWhile(cond,block,flag) } Normal
  8532. else begin
  8533. has_break := last_has_break;
  8534. return_loop { expr with eexpr = TWhile(cond,block,flag) } Normal
  8535. end
  8536. | TSwitch(cond, el_e_l, None) ->
  8537. { expr with eexpr = TSwitch(cond, List.map (fun (el, e) -> (el, handle_case (process_expr e))) el_e_l, None) }, Normal
  8538. | TSwitch(cond, el_e_l, Some def) ->
  8539. let def, k = process_expr def in
  8540. let def = handle_case (def, k) in
  8541. let k = ref k in
  8542. let ret = { expr with eexpr = TSwitch(cond, List.map (fun (el, e) ->
  8543. let e, ek = process_expr e in
  8544. k := aggregate_kind !k ek;
  8545. (el, handle_case (e, ek))
  8546. ) el_e_l, Some def) } in
  8547. ret, !k
  8548. (* | TMatch(cond, ep, il_vopt_e_l, None) ->
  8549. { expr with eexpr = TMatch(cond, ep, List.map (fun (il, vopt, e) -> (il, vopt, handle_case (process_expr e))) il_vopt_e_l, None) }, Normal *)
  8550. (* | TMatch(cond, ep, il_vopt_e_l, Some def) ->
  8551. let def, k = process_expr def in
  8552. let def = handle_case (def, k) in
  8553. let k = ref k in
  8554. let ret = { expr with eexpr = TMatch(cond, ep, List.map (fun (il, vopt, e) ->
  8555. let e, ek = process_expr e in
  8556. k := aggregate_kind !k ek;
  8557. (il, vopt, handle_case (e, ek))
  8558. ) il_vopt_e_l, Some def) } in
  8559. ret, !k *)
  8560. | TTry (e, catches) ->
  8561. let e, k = process_expr e in
  8562. let k = ref k in
  8563. let ret = { expr with eexpr = TTry(e, List.map (fun (v, e) ->
  8564. let e, ek = process_expr e in
  8565. k := aggregate_kind !k ek;
  8566. (v, e)
  8567. ) catches) } in
  8568. ret, !k
  8569. | _ -> expr, Normal
  8570. in
  8571. let run e = fst (process_expr e) in
  8572. run
  8573. let configure gen (mapping_func:texpr->texpr) =
  8574. let map e = Some(mapping_func e) in
  8575. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  8576. end;;
  8577. (* ******************************************* *)
  8578. (* DefaultArguments *)
  8579. (* ******************************************* *)
  8580. (*
  8581. This Module Filter will go through all defined functions in all modules and change them
  8582. so they set all default arguments to be of a Nullable type, and adds the unroll from nullable to
  8583. the not-nullable type in the beginning of the function.
  8584. dependencies:
  8585. It must run before OverloadingCtors, since OverloadingCtors will change optional structures behavior
  8586. *)
  8587. module DefaultArguments =
  8588. struct
  8589. let name = "default_arguments"
  8590. let priority = solve_deps name [ DBefore OverloadingConstructor.priority ]
  8591. let add_opt gen block pos (var,opt) =
  8592. match opt with
  8593. | None | Some TNull -> (var,opt)
  8594. | Some (TString str) ->
  8595. block := Codegen.set_default gen.gcon var (TString str) pos :: !block;
  8596. (var, opt)
  8597. | Some const ->
  8598. let basic = gen.gcon.basic in
  8599. let nullable_var = mk_temp gen var.v_name (basic.tnull var.v_type) in
  8600. let orig_name = var.v_name in
  8601. var.v_name <- nullable_var.v_name;
  8602. nullable_var.v_name <- orig_name;
  8603. let const_t = match const with
  8604. | TString _ -> basic.tstring | TInt _ -> basic.tint | TFloat _ -> basic.tfloat
  8605. | TNull -> var.v_type | TBool _ -> basic.tbool | _ -> assert false
  8606. in
  8607. (* var v = (temp_var == null) ? const : cast temp_var; *)
  8608. block :=
  8609. {
  8610. eexpr = TVar(var, Some(
  8611. {
  8612. eexpr = TIf(
  8613. { eexpr = TBinop(Ast.OpEq, mk_local nullable_var pos, null nullable_var.v_type pos); etype = basic.tbool; epos = pos },
  8614. mk_cast var.v_type { eexpr = TConst(const); etype = const_t; epos = pos },
  8615. Some(mk_cast var.v_type (mk_local nullable_var pos))
  8616. );
  8617. etype = var.v_type;
  8618. epos = pos;
  8619. }));
  8620. etype = basic.tvoid;
  8621. epos = pos;
  8622. } :: !block;
  8623. (nullable_var, opt)
  8624. let rec change_func gen cf =
  8625. List.iter (change_func gen) cf.cf_overloads;
  8626. let is_ctor = cf.cf_name = "new" in
  8627. let basic = gen.gcon.basic in
  8628. match cf.cf_kind, follow cf.cf_type with
  8629. | Var _, _ | Method MethDynamic, _ -> ()
  8630. | _, TFun(args, ret) ->
  8631. let found = ref false in
  8632. let args = ref (List.map (fun (n,opt,t) ->
  8633. (n,opt, if opt then (found := true; basic.tnull t) else t)
  8634. ) args) in
  8635. (match !found, cf.cf_expr with
  8636. | true, Some ({ eexpr = TFunction tf } as texpr) ->
  8637. let block = ref [] in
  8638. let tf_args = List.map (add_opt gen block tf.tf_expr.epos) tf.tf_args in
  8639. let arg_assoc = List.map2 (fun (v,o) (v2,_) -> v,(v2,o) ) tf.tf_args tf_args in
  8640. let rec extract_super e = match e.eexpr with
  8641. | TBlock(({ eexpr = TCall({ eexpr = TConst TSuper }, _) } as e2) :: tl) ->
  8642. e2, tl
  8643. | TBlock(hd :: tl) ->
  8644. let e2, tl2 = extract_super hd in
  8645. e2, tl2 @ tl
  8646. | _ -> raise Not_found
  8647. in
  8648. let block = try
  8649. if not is_ctor then raise Not_found;
  8650. (* issue #2570 *)
  8651. (* check if the class really needs the super as the first statement -
  8652. just to make sure we don't inadvertently break any existing code *)
  8653. let rec check cl =
  8654. if not (is_hxgen (TClassDecl cl)) then
  8655. ()
  8656. else match cl.cl_super with
  8657. | None ->
  8658. raise Not_found
  8659. | Some (cl,_) ->
  8660. check cl
  8661. in
  8662. (match gen.gcurrent_class with
  8663. | Some cl -> check cl
  8664. | _ -> ());
  8665. let super, tl = extract_super tf.tf_expr in
  8666. (match super.eexpr with
  8667. | TCall({ eexpr = TConst TSuper } as e1, args) ->
  8668. (* any super argument will be replaced by an inlined version of the check *)
  8669. let found = ref false in
  8670. let rec replace_args e = match e.eexpr with
  8671. | TLocal(v) -> (try
  8672. let v2,o = List.assq v arg_assoc in
  8673. let o = match o with
  8674. | None -> raise Not_found
  8675. | Some o -> o
  8676. in
  8677. let e = { e with eexpr = TLocal v2; etype = basic.tnull e.etype } in
  8678. let const = mk_cast e.etype { e with eexpr = TConst(o); etype = v.v_type } in
  8679. found := true;
  8680. { e with eexpr = TIf({
  8681. eexpr = TBinop(Ast.OpEq, e, null e.etype e.epos);
  8682. etype = basic.tbool;
  8683. epos = e.epos
  8684. }, const, Some e) }
  8685. with | Not_found -> e)
  8686. | _ -> Type.map_expr replace_args e
  8687. in
  8688. let args = List.map (replace_args) args in
  8689. { tf.tf_expr with eexpr = TBlock((if !found then { super with eexpr = TCall(e1,args) } else super) :: !block @ tl) }
  8690. | _ -> assert false)
  8691. with | Not_found ->
  8692. Type.concat { tf.tf_expr with eexpr = TBlock(!block); etype = basic.tvoid } tf.tf_expr
  8693. in
  8694. args := fun_args tf_args;
  8695. cf.cf_expr <- Some( {texpr with eexpr = TFunction( { tf with
  8696. tf_args = tf_args;
  8697. tf_expr = block
  8698. } ); etype = TFun(!args, ret) } );
  8699. cf.cf_type <- TFun(!args, ret)
  8700. | _ -> ()
  8701. );
  8702. (if !found then cf.cf_type <- TFun(!args, ret))
  8703. | _, _ -> assert false
  8704. let traverse gen =
  8705. let run md = match md with
  8706. | TClassDecl cl ->
  8707. List.iter (change_func gen) cl.cl_ordered_fields;
  8708. List.iter (change_func gen) cl.cl_ordered_statics;
  8709. (match cl.cl_constructor with | None -> () | Some cf -> change_func gen cf);
  8710. md
  8711. | _ -> md
  8712. in
  8713. run
  8714. let configure gen (mapping_func:module_type->module_type) =
  8715. let map md = Some(mapping_func md) in
  8716. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  8717. end;;
  8718. (* ******************************************* *)
  8719. (* Interface Variables Removal Modf *)
  8720. (* ******************************************* *)
  8721. (*
  8722. This module filter will take care of sanitizing interfaces for targets that do not support
  8723. variables declaration in interfaces. By now this will mean that if anything is typed as the interface,
  8724. and a variable access is made, a FNotFound will be returned for the field_access, so
  8725. the field will be only accessible by reflection.
  8726. Speed-wise, ideally it would be best to create getProp/setProp functions in this case and change
  8727. the AST to call them when accessing by interface. (TODO)
  8728. But right now it will be accessed by reflection.
  8729. dependencies:
  8730. *)
  8731. module InterfaceVarsDeleteModf =
  8732. struct
  8733. let name = "interface_vars"
  8734. let priority = solve_deps name []
  8735. let run gen =
  8736. let run md = match md with
  8737. | TClassDecl ( { cl_interface = true } as cl ) ->
  8738. let to_add = ref [] in
  8739. let fields = List.filter (fun cf ->
  8740. match cf.cf_kind with
  8741. | Var vkind ->
  8742. (match vkind.v_read with
  8743. | AccCall ->
  8744. let newcf = mk_class_field ("get_" ^ cf.cf_name) (TFun([],cf.cf_type)) true cf.cf_pos (Method MethNormal) [] in
  8745. to_add := newcf :: !to_add;
  8746. | _ -> ()
  8747. );
  8748. (match vkind.v_write with
  8749. | AccCall ->
  8750. let newcf = mk_class_field ("set_" ^ cf.cf_name) (TFun(["val",false,cf.cf_type],cf.cf_type)) true cf.cf_pos (Method MethNormal) [] in
  8751. to_add := newcf :: !to_add;
  8752. | _ -> ()
  8753. );
  8754. cl.cl_fields <- PMap.remove cf.cf_name cl.cl_fields;
  8755. false
  8756. | _ -> true
  8757. ) cl.cl_ordered_fields in
  8758. cl.cl_ordered_fields <- fields;
  8759. List.iter (fun cf ->
  8760. if not (PMap.mem cf.cf_name cl.cl_fields) then begin
  8761. cl.cl_ordered_fields <- cf :: cl.cl_ordered_fields;
  8762. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields
  8763. end
  8764. ) !to_add;
  8765. md
  8766. | _ -> md
  8767. in
  8768. run
  8769. let configure gen =
  8770. let run = run gen in
  8771. let map md = Some(run md) in
  8772. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  8773. end;;
  8774. (* ******************************************* *)
  8775. (* InterfaceProps *)
  8776. (* ******************************************* *)
  8777. (*
  8778. This module filter will go through all declared properties, and see if they are conforming to a native interface.
  8779. If they are, it will add Meta.Property to it
  8780. dependencies:
  8781. *)
  8782. module InterfaceProps =
  8783. struct
  8784. let name = "interface_props"
  8785. let priority = solve_deps name []
  8786. let run gen =
  8787. let run md = match md with
  8788. | TClassDecl ( { cl_interface = false; cl_extern = false } as cl ) ->
  8789. let vars = List.fold_left (fun acc (iface,_) ->
  8790. if Meta.has Meta.CsNative iface.cl_meta then
  8791. List.filter (fun cf -> match cf.cf_kind with
  8792. | Var { v_read = AccCall } | Var { v_write = AccCall } ->
  8793. true
  8794. | _ -> false
  8795. ) iface.cl_ordered_fields @ acc
  8796. else
  8797. acc
  8798. ) [] cl.cl_implements in
  8799. let vars = List.map (fun cf -> cf.cf_name) vars in
  8800. if vars <> [] then
  8801. List.iter (fun cf -> match cf.cf_kind with
  8802. | Var { v_read = AccCall } | Var { v_write = AccCall } when List.mem cf.cf_name vars ->
  8803. cf.cf_meta <- (Meta.Property, [], Ast.null_pos) :: cf.cf_meta
  8804. | _ -> ()
  8805. ) cl.cl_ordered_fields;
  8806. md
  8807. | _ -> md
  8808. in
  8809. run
  8810. let configure gen =
  8811. let run = run gen in
  8812. let map md = Some(run md) in
  8813. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  8814. end;;
  8815. (* ******************************************* *)
  8816. (* Int Division Synf *)
  8817. (* ******************************************* *)
  8818. (*
  8819. On targets that support int division, this module will force a float division to be performed,
  8820. so compatibility with current haxe targets is ensured.
  8821. If catch_int_div is set to true, though, it will look for casts to int or use of Std.int() to optimize
  8822. this kind of operation.
  8823. dependencies:
  8824. since it depends on nothing, but many modules might generate division expressions,
  8825. it will be one of the last modules to run
  8826. *)
  8827. module IntDivisionSynf =
  8828. struct
  8829. let name = "int_division_synf"
  8830. let priority = solve_deps name [ DAfter ExpressionUnwrap.priority; DAfter ObjectDeclMap.priority; DAfter ArrayDeclSynf.priority ]
  8831. let is_int = like_int
  8832. let default_implementation gen catch_int_div =
  8833. let basic = gen.gcon.basic in
  8834. let rec run e =
  8835. match e.eexpr with
  8836. | TBinop((Ast.OpDiv as op), e1, e2) when is_int e1.etype && is_int e2.etype ->
  8837. { e with eexpr = TBinop(op, mk_cast basic.tfloat (run e1), run e2) }
  8838. | TCall(
  8839. { eexpr = TField(_, FStatic({ cl_path = ([], "Std") }, { cf_name = "int" })) },
  8840. [ ({ eexpr = TBinop((Ast.OpDiv as op), e1, e2) } as ebinop ) ]
  8841. ) when catch_int_div && is_int e1.etype && is_int e2.etype ->
  8842. { ebinop with eexpr = TBinop(op, run e1, run e2); etype = basic.tint }
  8843. | TCast( ({ eexpr = TBinop((Ast.OpDiv as op), e1, e2) } as ebinop ), _ )
  8844. | TCast( ({ eexpr = TBinop(( (Ast.OpAssignOp Ast.OpDiv) as op), e1, e2) } as ebinop ), _ ) when catch_int_div && is_int e1.etype && is_int e2.etype && is_int e.etype ->
  8845. { ebinop with eexpr = TBinop(op, run e1, run e2); etype = basic.tint }
  8846. | _ -> Type.map_expr run e
  8847. in
  8848. run
  8849. let configure gen (mapping_func:texpr->texpr) =
  8850. let map e = Some(mapping_func e) in
  8851. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  8852. end;;
  8853. (* ******************************************* *)
  8854. (* UnnecessaryCastsRemoval *)
  8855. (* ******************************************* *)
  8856. (*
  8857. This module will take care of simplifying unnecessary casts, specially those made by the compiler
  8858. when inlining. Right now, it will only take care of casts used as a statement, which are always useless;
  8859. TODO: Take care of more cases, e.g. when the to and from types are the same
  8860. dependencies:
  8861. This must run after CastDetection, but before ExpressionUnwrap
  8862. *)
  8863. module UnnecessaryCastsRemoval =
  8864. struct
  8865. let name = "casts_removal"
  8866. let priority = solve_deps name [DAfter CastDetect.priority; DBefore ExpressionUnwrap.priority]
  8867. let rec take_off_cast run e =
  8868. match e.eexpr with
  8869. | TCast (c, _) ->
  8870. take_off_cast run c
  8871. | _ -> run e
  8872. let default_implementation gen =
  8873. let rec traverse e =
  8874. match e.eexpr with
  8875. | TBlock bl ->
  8876. let bl = List.map (fun e ->
  8877. take_off_cast traverse e
  8878. ) bl in
  8879. { e with eexpr = TBlock bl }
  8880. | TTry (block, catches) ->
  8881. { e with eexpr = TTry(traverse (mk_block block), List.map (fun (v,block) -> (v, traverse (mk_block block))) catches) }
  8882. (* | TMatch (cond,ep,il_vol_e_l,default) ->
  8883. { e with eexpr = TMatch(cond,ep,List.map (fun (il,vol,e) -> (il,vol,traverse (mk_block e))) il_vol_e_l, Option.map (fun e -> traverse (mk_block e)) default) } *)
  8884. | TSwitch (cond,el_e_l, default) ->
  8885. { e with eexpr = TSwitch(cond, List.map (fun (el,e) -> (el, traverse (mk_block e))) el_e_l, Option.map (fun e -> traverse (mk_block e)) default) }
  8886. | TWhile (cond,block,flag) ->
  8887. {e with eexpr = TWhile(cond,traverse (mk_block block), flag) }
  8888. | TIf (cond, eif, eelse) ->
  8889. { e with eexpr = TIf(cond, traverse (mk_block eif), Option.map (fun e -> traverse (mk_block e)) eelse) }
  8890. | TFor (v,it,block) ->
  8891. { e with eexpr = TFor(v,it, traverse (mk_block block)) }
  8892. | TFunction (tfunc) ->
  8893. { e with eexpr = TFunction({ tfunc with tf_expr = traverse (mk_block tfunc.tf_expr) }) }
  8894. | _ -> e (* if expression doesn't have a block, we will exit *)
  8895. in
  8896. traverse
  8897. let configure gen =
  8898. let map e = Some(default_implementation gen e) in
  8899. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  8900. end;;
  8901. (* ******************************************* *)
  8902. (* OverrideFix *)
  8903. (* ******************************************* *)
  8904. (*
  8905. When DCE is on, sometimes a field is marked as override when it
  8906. really doesn't override anything. This module filter will take care of this.
  8907. dependencies:
  8908. No dependencies
  8909. *)
  8910. module OverrideFix =
  8911. struct
  8912. let name = "override_fix"
  8913. let priority = solve_deps name []
  8914. let default_implementation gen =
  8915. let rec run e =
  8916. match e.eexpr with
  8917. | _ -> Type.map_expr run e
  8918. in
  8919. run
  8920. let configure gen =
  8921. let map md =
  8922. match md with
  8923. | TClassDecl cl ->
  8924. cl.cl_overrides <- List.filter (fun s ->
  8925. let rec loop cl =
  8926. match cl.cl_super with
  8927. | Some (cl,_) when PMap.mem s.cf_name cl.cl_fields -> true
  8928. | Some (cl,_) -> loop cl
  8929. | None -> false
  8930. in
  8931. loop cl
  8932. ) cl.cl_overrides;
  8933. Some md
  8934. | _ -> Some md
  8935. in
  8936. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  8937. end;;
  8938. (* ******************************************* *)
  8939. (* AbstractImplementationFix *)
  8940. (* ******************************************* *)
  8941. (*
  8942. This module filter will map the compiler created classes from abstract
  8943. implementations to valid haxe code, as needed by gencommon
  8944. dependencies:
  8945. No dependencies
  8946. *)
  8947. module AbstractImplementationFix =
  8948. struct
  8949. let name = "abstract_implementation_fix"
  8950. let priority = solve_deps name []
  8951. let default_implementation gen =
  8952. let rec run md =
  8953. match md with
  8954. | TClassDecl ({ cl_kind = KAbstractImpl a } as c) ->
  8955. List.iter (function
  8956. | cf when Meta.has Meta.Impl cf.cf_meta ->
  8957. (* add type parameters to all implementation functions *)
  8958. cf.cf_params <- cf.cf_params @ a.a_types
  8959. | _ -> ()
  8960. ) c.cl_ordered_statics;
  8961. Some md
  8962. | _ -> Some md
  8963. in
  8964. run
  8965. let configure gen =
  8966. let map = default_implementation gen in
  8967. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  8968. end;;
  8969. (* ******************************************* *)
  8970. (* FixOverrides *)
  8971. (* ******************************************* *)
  8972. (*
  8973. Covariant return types, contravariant function arguments and applied type parameters may change
  8974. in a way that expected implementations / overrides aren't recognized as such.
  8975. This filter will fix that.
  8976. dependencies:
  8977. FixOverrides expects that the target platform is able to deal with overloaded functions
  8978. It must run after DefaultArguments, otherwise code added by the default arguments may be invalid
  8979. *)
  8980. module FixOverrides =
  8981. struct
  8982. let name = "fix_overrides"
  8983. let priority = solve_deps name [DAfter DefaultArguments.priority]
  8984. (*
  8985. if the platform allows explicit interface implementation (C#),
  8986. specify a explicit_fn_name function (tclass->string->string)
  8987. Otherwise, it expects the platform to be able to handle covariant return types
  8988. *)
  8989. let run ~explicit_fn_name gen =
  8990. let implement_explicitly = is_some explicit_fn_name in
  8991. let run md = match md with
  8992. | TClassDecl ( { cl_interface = true; cl_extern = false } as c ) ->
  8993. (* overrides can be removed from interfaces *)
  8994. c.cl_ordered_fields <- List.filter (fun f ->
  8995. try
  8996. if Meta.has Meta.Overload f.cf_meta then raise Not_found;
  8997. let f2 = Codegen.find_field c f in
  8998. if f2 == f then raise Not_found;
  8999. c.cl_fields <- PMap.remove f.cf_name c.cl_fields;
  9000. false;
  9001. with Not_found ->
  9002. true
  9003. ) c.cl_ordered_fields;
  9004. md
  9005. | TClassDecl({ cl_extern = false } as c) ->
  9006. let this = { eexpr = TConst TThis; etype = TInst(c,List.map snd c.cl_types); epos = c.cl_pos } in
  9007. (* look through all interfaces, and try to find a type that applies exactly *)
  9008. let rec loop_iface (iface:tclass) itl =
  9009. List.iter (fun (s,stl) -> loop_iface s (List.map (apply_params iface.cl_types itl) stl)) iface.cl_implements;
  9010. let real_itl = gen.greal_type_param (TClassDecl iface) itl in
  9011. let rec loop_f f =
  9012. List.iter loop_f f.cf_overloads;
  9013. let ftype = apply_params iface.cl_types itl f.cf_type in
  9014. let real_ftype = get_real_fun gen (apply_params iface.cl_types real_itl f.cf_type) in
  9015. replace_mono real_ftype;
  9016. let overloads = Typeload.get_overloads c f.cf_name in
  9017. try
  9018. let t2, f2 =
  9019. match overloads with
  9020. | (_, cf) :: _ when Meta.has Meta.Overload cf.cf_meta -> (* overloaded function *)
  9021. (* try to find exact function *)
  9022. List.find (fun (t,f2) ->
  9023. Typeload.same_overload_args ftype t f f2
  9024. ) overloads
  9025. | _ :: _ ->
  9026. (match field_access gen (TInst(c, List.map snd c.cl_types)) f.cf_name with
  9027. | FClassField(_,_,_,f2,false,t,_) -> t,f2 (* if it's not an overload, all functions should have the same signature *)
  9028. | _ -> raise Not_found)
  9029. | [] -> raise Not_found
  9030. in
  9031. replace_mono t2;
  9032. (* if we find a function with the exact type of real_ftype, it means this interface has already been taken care of *)
  9033. if not (type_iseq (get_real_fun gen (apply_params f2.cf_params (List.map snd f.cf_params) t2)) real_ftype) then begin
  9034. (match f.cf_kind with | Method (MethNormal | MethInline) -> () | _ -> raise Not_found);
  9035. let t2 = get_real_fun gen t2 in
  9036. if List.length f.cf_params <> List.length f2.cf_params then raise Not_found;
  9037. replace_mono t2;
  9038. match follow (apply_params f2.cf_params (List.map snd f.cf_params) t2), follow real_ftype with
  9039. | TFun(a1,r1), TFun(a2,r2) when not implement_explicitly && not (type_iseq r1 r2) && Typeload.same_overload_args real_ftype t2 f f2 ->
  9040. (* different return types are the trickiest cases to deal with *)
  9041. (* check for covariant return type *)
  9042. let is_covariant = match follow r1, follow r2 with
  9043. | _, TDynamic _ -> true
  9044. | r1, r2 -> try
  9045. unify r1 r2;
  9046. true
  9047. with | Unify_error _ -> false
  9048. in
  9049. (* we only have to worry about non-covariant issues *)
  9050. if not is_covariant then begin
  9051. (* override return type and cast implemented function *)
  9052. let args, newr = match follow t2, follow (apply_params f.cf_params (List.map snd f2.cf_params) real_ftype) with
  9053. | TFun(a,_), TFun(_,r) -> a,r
  9054. | _ -> assert false
  9055. in
  9056. f2.cf_type <- TFun(args,newr);
  9057. (match f2.cf_expr with
  9058. | Some ({ eexpr = TFunction tf } as e) ->
  9059. f2.cf_expr <- Some { e with eexpr = TFunction { tf with tf_type = newr } }
  9060. | _ -> ())
  9061. end
  9062. | TFun(a1,r1), TFun(a2,r2) ->
  9063. (* just implement a function that will call the main one *)
  9064. let name, is_explicit = match explicit_fn_name with
  9065. | Some fn when not (type_iseq r1 r2) && Typeload.same_overload_args real_ftype t2 f f2 ->
  9066. fn iface itl f.cf_name, true
  9067. | _ -> f.cf_name, false
  9068. in
  9069. let p = f2.cf_pos in
  9070. let newf = mk_class_field name real_ftype true f.cf_pos (Method MethNormal) f.cf_params in
  9071. let vars = List.map (fun (n,_,t) -> alloc_var n t) a2 in
  9072. let args = List.map2 (fun v (_,_,t) -> mk_cast t (mk_local v f2.cf_pos)) vars a1 in
  9073. let field = { eexpr = TField(this, FInstance(c,f2)); etype = TFun(a1,r1); epos = p } in
  9074. let call = { eexpr = TCall(field, args); etype = r1; epos = p } in
  9075. (* let call = gen.gparam_func_call call field (List.map snd f.cf_params) args in *)
  9076. let is_void = is_void r2 in
  9077. newf.cf_expr <- Some {
  9078. eexpr = TFunction({
  9079. tf_args = List.map (fun v -> v,None) vars;
  9080. tf_type = r2;
  9081. tf_expr = (if is_void then call else {
  9082. eexpr = TReturn (Some (mk_cast r2 call));
  9083. etype = r2;
  9084. epos = p
  9085. })
  9086. });
  9087. etype = real_ftype;
  9088. epos = p;
  9089. };
  9090. (* delayed: add to class *)
  9091. let delay () =
  9092. try
  9093. let fm = PMap.find f.cf_name c.cl_fields in
  9094. fm.cf_overloads <- newf :: fm.cf_overloads
  9095. with | Not_found ->
  9096. c.cl_fields <- PMap.add f.cf_name newf c.cl_fields;
  9097. c.cl_ordered_fields <- newf :: c.cl_ordered_fields
  9098. in
  9099. (* gen.gafter_filters_ended <- delay :: gen.gafter_filters_ended *)
  9100. delay();
  9101. | _ -> assert false
  9102. end
  9103. with | Not_found -> ()
  9104. in
  9105. List.iter loop_f iface.cl_ordered_fields
  9106. in
  9107. List.iter (fun (iface,itl) -> loop_iface iface itl) c.cl_implements;
  9108. (* now go through all overrides, *)
  9109. let rec check_f f =
  9110. (* find the first declared field *)
  9111. let is_overload = Meta.has Meta.Overload f.cf_meta in
  9112. let decl = if is_overload then
  9113. find_first_declared_field gen c ~exact_field:f f.cf_name
  9114. else
  9115. find_first_declared_field gen c f.cf_name
  9116. in
  9117. match decl with
  9118. | Some(f2,actual_t,_,t,declared_cl,_,_)
  9119. when not (Typeload.same_overload_args actual_t (get_real_fun gen f.cf_type) f2 f) ->
  9120. if Meta.has Meta.Overload f.cf_meta then begin
  9121. (* if it is overload, create another field with the requested type *)
  9122. let f3 = mk_class_field f.cf_name t f.cf_public f.cf_pos f.cf_kind f.cf_params in
  9123. let p = f.cf_pos in
  9124. let old_args, old_ret = get_fun f.cf_type in
  9125. let args, ret = get_fun t in
  9126. let tf_args = List.map (fun (n,o,t) -> alloc_var n t, None) args in
  9127. f3.cf_expr <- Some {
  9128. eexpr = TFunction({
  9129. tf_args = tf_args;
  9130. tf_type = ret;
  9131. tf_expr = mk_block (mk_return (mk_cast ret {
  9132. eexpr = TCall(
  9133. {
  9134. eexpr = TField(
  9135. { eexpr = TConst TThis; etype = TInst(c, List.map snd c.cl_types); epos = p },
  9136. FInstance(c,f));
  9137. etype = f.cf_type;
  9138. epos = p
  9139. },
  9140. List.map2 (fun (v,_) (_,_,t) -> mk_cast t (mk_local v p)) tf_args old_args);
  9141. etype = old_ret;
  9142. epos = p
  9143. }))
  9144. });
  9145. etype = t;
  9146. epos = p;
  9147. };
  9148. gen.gafter_filters_ended <- ((fun () ->
  9149. f.cf_overloads <- f3 :: f.cf_overloads;
  9150. ) :: gen.gafter_filters_ended);
  9151. f3
  9152. end else begin match f.cf_expr with
  9153. | Some({ eexpr = TFunction(tf) } as e) ->
  9154. (* if it's not overload, just cast the vars *)
  9155. let actual_args, _ = get_fun (get_real_fun gen actual_t) in
  9156. let new_args, vardecl = List.fold_left2 (fun (args,vdecl) (v,_) (_,_,t) ->
  9157. if not (type_iseq (gen.greal_type v.v_type) (gen.greal_type t)) then begin
  9158. let new_var = mk_temp gen v.v_name t in
  9159. (new_var,None) :: args, (v, Some(mk_cast v.v_type (mk_local new_var f.cf_pos))) :: vdecl
  9160. end else
  9161. (v,None) :: args, vdecl
  9162. ) ([],[]) tf.tf_args actual_args in
  9163. if vardecl <> [] then
  9164. f.cf_expr <- Some({ e with
  9165. eexpr = TFunction({ tf with
  9166. tf_args = List.rev new_args;
  9167. tf_expr = Type.concat { eexpr = TBlock(List.map (fun (v,ve) -> { eexpr = TVar(v,ve); etype = gen.gcon.basic.tvoid; epos = e.epos }) vardecl); etype = gen.gcon.basic.tvoid; epos = e.epos } tf.tf_expr
  9168. });
  9169. });
  9170. f
  9171. | _ -> f
  9172. end
  9173. | _ -> f
  9174. in
  9175. if not c.cl_extern then
  9176. c.cl_overrides <- List.map (fun f -> check_f f) c.cl_overrides;
  9177. md
  9178. | _ -> md
  9179. in
  9180. run
  9181. let configure ?explicit_fn_name gen =
  9182. let delay () =
  9183. Hashtbl.clear gen.greal_field_types
  9184. in
  9185. gen.gafter_mod_filters_ended <- delay :: gen.gafter_mod_filters_ended;
  9186. let run = run ~explicit_fn_name:explicit_fn_name gen in
  9187. let map md = Some(run md) in
  9188. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  9189. end;;
  9190. (* ******************************************* *)
  9191. (* Normalize *)
  9192. (* ******************************************* *)
  9193. (*
  9194. - Filters out enum constructor type parameters from the AST; See Issue #1796
  9195. - Filters out monomorphs
  9196. - Filters out all non-whitelisted AST metadata
  9197. dependencies:
  9198. No dependencies; but it still should be one of the first filters to run,
  9199. as it will help normalize the AST
  9200. *)
  9201. module Normalize =
  9202. struct
  9203. let name = "normalize_type"
  9204. let priority = max_dep
  9205. let rec filter_param t = match t with
  9206. | TInst({ cl_kind = KTypeParameter _ } as c,_) when Meta.has Meta.EnumConstructorParam c.cl_meta ->
  9207. t_dynamic
  9208. | TMono r -> (match !r with
  9209. | None -> t_dynamic
  9210. | Some t -> filter_param t)
  9211. | TInst(_,[]) | TEnum(_,[]) | TType(_,[]) | TAbstract(_,[]) -> t
  9212. | TType(t,tl) -> TType(t,List.map filter_param tl)
  9213. | TInst(c,tl) -> TInst(c,List.map filter_param tl)
  9214. | TEnum(e,tl) -> TEnum(e,List.map filter_param tl)
  9215. | TAbstract(a,tl) -> TAbstract(a, List.map filter_param tl)
  9216. | TAnon a ->
  9217. TAnon {
  9218. a_fields = PMap.map (fun f -> { f with cf_type = filter_param f.cf_type }) a.a_fields;
  9219. a_status = a.a_status;
  9220. }
  9221. | TFun(args,ret) -> TFun(List.map (fun (n,o,t) -> (n,o,filter_param t)) args, filter_param ret)
  9222. | TDynamic _ -> t
  9223. | TLazy f -> filter_param (!f())
  9224. let default_implementation gen ~metas =
  9225. let rec run e =
  9226. match e.eexpr with
  9227. | TMeta(entry, e) when not (Hashtbl.mem metas entry) ->
  9228. run e
  9229. | _ ->
  9230. map_expr_type (fun e -> run e) filter_param (fun v -> v.v_type <- filter_param v.v_type; v) e
  9231. in
  9232. run
  9233. let configure gen ~metas =
  9234. let map e = Some(default_implementation gen e ~metas:metas) in
  9235. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority) map
  9236. end;;
  9237. (*
  9238. (* ******************************************* *)
  9239. (* Example *)
  9240. (* ******************************************* *)
  9241. (*
  9242. description
  9243. dependencies:
  9244. *)
  9245. module Example =
  9246. struct
  9247. let name = "example"
  9248. let priority = solve_deps name []
  9249. let default_implementation gen =
  9250. let rec run e =
  9251. match e.eexpr with
  9252. | _ -> Type.map_expr run e
  9253. in
  9254. run
  9255. let configure gen (mapping_func:texpr->texpr) =
  9256. let map e = Some(mapping_func e) in
  9257. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  9258. end;;
  9259. *)