gencommon.ml 402 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132
  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 Unix
  38. open Ast
  39. open Type
  40. open Common
  41. open Option
  42. open Printf
  43. open ExtString
  44. let debug_type_ctor = function
  45. | TMono _ -> "TMono"
  46. | TEnum _ -> "TEnum"
  47. | TInst _ -> "TInst"
  48. | TType _ -> "TType"
  49. | TFun _ -> "TFun"
  50. | TAnon _ -> "TAnon"
  51. | TDynamic _ -> "TDynamic"
  52. | TLazy _ -> "TLazy"
  53. | TAbstract _ -> "TAbstract"
  54. let debug_type = (s_type (print_context()))
  55. let debug_expr = s_expr debug_type
  56. let rec like_float t =
  57. match follow t with
  58. | TAbstract({ a_path = ([], "Float") },[])
  59. | TAbstract({ a_path = ([], "Int") },[]) -> true
  60. | TAbstract({ a_path = (["cs"], "Pointer") },_) -> false
  61. | TAbstract(a, _) -> List.exists (fun t -> like_float t) a.a_from || List.exists (fun t -> like_float t) a.a_to
  62. | _ -> false
  63. let rec like_int t =
  64. match follow t with
  65. | TAbstract({ a_path = ([], "Int") },[]) -> true
  66. | TAbstract({ a_path = (["cs"], "Pointer") },_) -> false
  67. | TAbstract(a, _) -> List.exists (fun t -> like_int t) a.a_from || List.exists (fun t -> like_int t) a.a_to
  68. | _ -> false
  69. let rec like_i64 t =
  70. match follow t with
  71. | TInst({ cl_path = (["cs"], "Int64") },[])
  72. | TAbstract({ a_path = (["cs"], "Int64") },[])
  73. | TInst({ cl_path = (["cs"], "UInt64") },[])
  74. | TInst({ cl_path = (["java"], "Int64") },[])
  75. | TAbstract({ a_path = (["java"], "Int64") },[])
  76. | TInst({ cl_path = (["haxe"], "Int64") },[])
  77. | TAbstract({ a_path = (["haxe"], "Int64") },[]) -> true
  78. | TAbstract(a, _) -> List.exists (fun t -> like_i64 t) a.a_from || List.exists (fun t -> like_i64 t) a.a_to
  79. | _ -> false
  80. let follow_once t =
  81. match t with
  82. | TMono r ->
  83. (match !r with
  84. | Some t -> t
  85. | _ -> t_dynamic (* avoid infinite loop / should be the same in this context *))
  86. | TLazy f ->
  87. !f()
  88. | TType (t,tl) ->
  89. apply_params t.t_params tl t.t_type
  90. | _ -> t
  91. let t_empty = TAnon({ a_fields = PMap.empty; a_status = ref (Closed) })
  92. (* the undefined is a special var that works like null, but can have special meaning *)
  93. let v_undefined = alloc_var "__undefined__" t_dynamic
  94. let undefined pos = { eexpr = TLocal(v_undefined); etype = t_dynamic; epos = pos }
  95. module ExprHashtblHelper =
  96. struct
  97. type hash_texpr_t =
  98. {
  99. hepos : pos;
  100. heexpr : int;
  101. hetype : int;
  102. }
  103. let mk_heexpr = function
  104. | TConst _ -> 0 | TLocal _ -> 1 | TArray _ -> 3 | TBinop _ -> 4 | TField _ -> 5 | TTypeExpr _ -> 7 | TParenthesis _ -> 8 | TObjectDecl _ -> 9
  105. | TArrayDecl _ -> 10 | TCall _ -> 11 | TNew _ -> 12 | TUnop _ -> 13 | TFunction _ -> 14 | TVar _ -> 15 | TBlock _ -> 16 | TFor _ -> 17 | TIf _ -> 18 | TWhile _ -> 19
  106. | TSwitch _ -> 20 (* | TPatMatch _ -> 21 *) | TTry _ -> 22 | TReturn _ -> 23 | TBreak -> 24 | TContinue -> 25 | TThrow _ -> 26 | TCast _ -> 27 | TMeta _ -> 28 | TEnumParameter _ -> 29
  107. let mk_heetype = function
  108. | TMono _ -> 0 | TEnum _ -> 1 | TInst _ -> 2 | TType _ -> 3 | TFun _ -> 4
  109. | TAnon _ -> 5 | TDynamic _ -> 6 | TLazy _ -> 7 | TAbstract _ -> 8
  110. let mk_type e =
  111. {
  112. hepos = e.epos;
  113. heexpr = mk_heexpr e.eexpr;
  114. hetype = mk_heetype e.etype;
  115. }
  116. end;;
  117. let path_of_md_def md_def =
  118. match md_def.m_types with
  119. | [TClassDecl c] -> c.cl_path
  120. | _ -> md_def.m_path
  121. open ExprHashtblHelper;;
  122. (* Expression Hashtbl. This shouldn't be kept indefinately as it's not a weak Hashtbl. *)
  123. module ExprHashtbl = Hashtbl.Make(
  124. struct
  125. type t = Type.texpr
  126. let equal = (==)
  127. let hash t = Hashtbl.hash (mk_type t)
  128. end
  129. );;
  130. (* ******************************************* *)
  131. (* Gen Common
  132. This is the key module for generation of Java and C# sources
  133. In order for both modules to share as much code as possible, some
  134. rules were devised:
  135. - every feature has its own submodule, and may contain the following methods:
  136. - configure
  137. sets all the configuration variables for the module to run. If a module has this method,
  138. it *should* be called once before running any filter
  139. - run_filter ->
  140. runs the filter immediately on the context
  141. - add_filter ->
  142. adds the filter to an expr->expr list. Most filter modules will provide this option so the filter
  143. function can only run once.
  144. - most submodules will have side-effects so the order of operations will matter.
  145. When running configure / add_filter this might be taken care of with the rule-based dispatch system working
  146. underneath, but still there might be some incompatibilities. There will be an effort to document it.
  147. The modules can hint on the order by suffixing their functions with _first or _last.
  148. - any of those methods might have different parameters, that configure how the filter will run.
  149. For example, a simple filter that maps switch() expressions to if () .. else if... might receive
  150. a function that filters what content should be mapped
  151. - Other targets can use those filters on their own code. In order to do that,
  152. a simple configuration step is needed: you need to initialize a generator_ctx type with
  153. Gencommon.new_gen (context:Common.context)
  154. with a generator_ctx context you will be able to add filters to your code, and execute them with
  155. Gencommon.run_filters (gen_context:Gencommon.generator_ctx)
  156. After running the filters, you can run your own generator normally.
  157. (* , or you can run
  158. Gencommon.generate_modules (gen_context:Gencommon.generator_ctx) (extension:string) (module_gen:module_type list->bool)
  159. where module_gen will take a whole module (can be *)
  160. *)
  161. (* ******************************************* *)
  162. (* common helpers *)
  163. (* ******************************************* *)
  164. let assertions = false (* when assertions == true, many assertions will be made to guarantee the quality of the data input *)
  165. let debug_mode = ref false
  166. let trace s = if !debug_mode then print_endline s else ()
  167. let timer name = if !debug_mode then Common.timer name else fun () -> ()
  168. let is_string t = match follow t with | TInst({ cl_path = ([], "String") }, []) -> true | _ -> false
  169. (* helper function for creating Anon types of class / enum modules *)
  170. let anon_of_classtype cl =
  171. TAnon {
  172. a_fields = cl.cl_statics;
  173. a_status = ref (Statics cl)
  174. }
  175. let anon_of_enum e =
  176. TAnon {
  177. a_fields = PMap.empty;
  178. a_status = ref (EnumStatics e)
  179. }
  180. let anon_of_abstract a =
  181. TAnon {
  182. a_fields = PMap.empty;
  183. a_status = ref (AbstractStatics a)
  184. }
  185. let anon_of_mt mt = match mt with
  186. | TClassDecl cl -> anon_of_classtype cl
  187. | TEnumDecl e -> anon_of_enum e
  188. | TAbstractDecl a -> anon_of_abstract a
  189. | _ -> assert false
  190. let anon_class t =
  191. match follow t with
  192. | TAnon anon ->
  193. (match !(anon.a_status) with
  194. | Statics (cl) -> Some(TClassDecl(cl))
  195. | EnumStatics (e) -> Some(TEnumDecl(e))
  196. | AbstractStatics (a) -> Some(TAbstractDecl(a))
  197. | _ -> None)
  198. | _ -> None
  199. let path_s path =
  200. match path with | ([], s) -> s | (p, s) -> (String.concat "." (fst path)) ^ "." ^ (snd path)
  201. let rec t_to_md t = match t with
  202. | TInst (cl,_) -> TClassDecl cl
  203. | TEnum (e,_) -> TEnumDecl e
  204. | TType (t,_) -> TTypeDecl t
  205. | TAbstract (a,_) -> TAbstractDecl a
  206. | TAnon anon ->
  207. (match !(anon.a_status) with
  208. | EnumStatics e -> TEnumDecl e
  209. | Statics cl -> TClassDecl cl
  210. | AbstractStatics a -> TAbstractDecl a
  211. | _ -> assert false)
  212. | TLazy f -> t_to_md (!f())
  213. | TMono r -> (match !r with | Some t -> t_to_md t | None -> assert false)
  214. | _ -> assert false
  215. let get_cl mt = match mt with | TClassDecl cl -> cl | _ -> failwith ("Unexpected module type of '" ^ path_s (t_path mt) ^ "'")
  216. let get_abstract mt = match mt with | TAbstractDecl a -> a | _ -> failwith ("Unexpected module type of '" ^ path_s (t_path mt) ^ "'")
  217. let get_tdef mt = match mt with | TTypeDecl t -> t | _ -> assert false
  218. let mk_mt_access mt pos = { eexpr = TTypeExpr(mt); etype = anon_of_mt mt; epos = pos }
  219. let is_void t = match follow t with
  220. | TAbstract ({ a_path = ([], "Void") },[]) ->
  221. true
  222. | _ -> false
  223. let mk_local var pos = { eexpr = TLocal(var); etype = var.v_type; epos = pos }
  224. (* this function is used by CastDetection module *)
  225. let get_fun t =
  226. match follow t with | TFun(r1,r2) -> (r1,r2) | _ -> (trace (s_type (print_context()) (follow t) )); assert false
  227. let mk_cast t e =
  228. { eexpr = TCast(e, None); etype = t; epos = e.epos }
  229. let mk_classtype_access cl pos =
  230. { eexpr = TTypeExpr(TClassDecl(cl)); etype = anon_of_classtype cl; epos = pos }
  231. let mk_static_field_access_infer cl field pos params =
  232. try
  233. let cf = (PMap.find field cl.cl_statics) in
  234. { 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 }
  235. with | Not_found -> failwith ("Cannot find field " ^ field ^ " in type " ^ (path_s cl.cl_path))
  236. let mk_static_field_access cl field fieldt pos =
  237. { (mk_static_field_access_infer cl field pos []) with etype = fieldt }
  238. (* stolen from Hugh's sources ;-) *)
  239. (* this used to be a class, but there was something in there that crashed ocaml native compiler in windows *)
  240. module SourceWriter =
  241. struct
  242. type source_writer =
  243. {
  244. sw_buf : Buffer.t;
  245. mutable sw_has_content : bool;
  246. mutable sw_indent : string;
  247. mutable sw_indents : string list;
  248. }
  249. let new_source_writer () =
  250. {
  251. sw_buf = Buffer.create 0;
  252. sw_has_content = false;
  253. sw_indent = "";
  254. sw_indents = [];
  255. }
  256. let add_writer w_write w_read = Buffer.add_buffer w_read.sw_buf w_write.sw_buf
  257. let contents w = Buffer.contents w.sw_buf
  258. let len w = Buffer.length w.sw_buf
  259. let write w x =
  260. (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);
  261. let len = (String.length x)-1 in
  262. if len >= 0 && String.get x len = '\n' then begin w.sw_has_content <- false end else w.sw_has_content <- true
  263. let push_indent w = w.sw_indents <- "\t"::w.sw_indents; w.sw_indent <- String.concat "" w.sw_indents
  264. let pop_indent w =
  265. match w.sw_indents with
  266. | h::tail -> w.sw_indents <- tail; w.sw_indent <- String.concat "" w.sw_indents
  267. | [] -> w.sw_indent <- "/*?*/"
  268. let newline w = write w "\n"
  269. let begin_block w = (if w.sw_has_content then newline w); write w "{"; push_indent w; newline w
  270. let end_block w = pop_indent w; (if w.sw_has_content then newline w); write w "}"; newline w
  271. let print w =
  272. (if not w.sw_has_content then begin w.sw_has_content <- true; Buffer.add_string w.sw_buf w.sw_indent end);
  273. bprintf w.sw_buf;
  274. end;;
  275. (* rule_dispatcher's priority *)
  276. type priority =
  277. | PFirst
  278. | PLast
  279. | PZero
  280. | PCustom of float
  281. exception DuplicateName of string
  282. exception NoRulesApplied
  283. let indent = ref []
  284. (* the rule dispatcher is the primary way to deal with distributed "plugins" *)
  285. (* we will define rules that will form a distributed / extensible match system *)
  286. class ['tp, 'ret] rule_dispatcher name ignore_not_found =
  287. object(self)
  288. val tbl = Hashtbl.create 16
  289. val mutable keys = []
  290. val names = Hashtbl.create 16
  291. val mutable temp = 0
  292. method add ?(name : string option) (* name helps debugging *) ?(priority : priority = PZero) (rule : 'tp->'ret option) =
  293. let p = match priority with
  294. | PFirst -> infinity
  295. | PLast -> neg_infinity
  296. | PZero -> 0.0
  297. | PCustom i -> i
  298. in
  299. let q = if not( Hashtbl.mem tbl p ) then begin
  300. let q = Stack.create() in
  301. Hashtbl.add tbl p q;
  302. keys <- p :: keys;
  303. keys <- List.sort (fun x y -> - (compare x y)) keys;
  304. q
  305. end else Hashtbl.find tbl p in
  306. let name = match name with
  307. | None -> temp <- temp + 1; "$_" ^ (string_of_int temp)
  308. | Some s -> s
  309. in
  310. (if Hashtbl.mem names name then raise (DuplicateName(name)));
  311. Hashtbl.add names name q;
  312. Stack.push (name, rule) q
  313. method describe =
  314. Hashtbl.iter (fun s _ -> (trace s)) names;
  315. method remove (name : string) =
  316. if Hashtbl.mem names name then begin
  317. let q = Hashtbl.find names name in
  318. let q_temp = Stack.create () in
  319. Stack.iter (function
  320. | (n, _) when n = name -> ()
  321. | _ as r -> Stack.push r q_temp
  322. ) q;
  323. Stack.clear q;
  324. Stack.iter (fun r -> Stack.push r q) q_temp;
  325. Hashtbl.remove names name;
  326. true
  327. end else false
  328. method run_f tp = get (self#run tp)
  329. method did_run tp = is_some (self#run tp)
  330. method get_list =
  331. let ret = ref [] in
  332. List.iter (fun key ->
  333. let q = Hashtbl.find tbl key in
  334. Stack.iter (fun (_, rule) -> ret := rule :: !ret) q
  335. ) keys;
  336. List.rev !ret
  337. method run_from (priority:float) (tp:'tp) : 'ret option =
  338. let ok = ref ignore_not_found in
  339. let ret = ref None in
  340. indent := "\t" :: !indent;
  341. (try begin
  342. List.iter (fun key ->
  343. if key < priority then begin
  344. let q = Hashtbl.find tbl key in
  345. Stack.iter (fun (n, rule) ->
  346. let t = if !debug_mode then Common.timer ("rule dispatcher rule: " ^ n) else fun () -> () in
  347. let r = rule(tp) in
  348. t();
  349. if is_some r then begin ret := r; raise Exit end
  350. ) q
  351. end
  352. ) keys
  353. end with Exit -> ok := true);
  354. (match !indent with
  355. | [] -> ()
  356. | h::t -> indent := t);
  357. (if not (!ok) then raise NoRulesApplied);
  358. !ret
  359. method run (tp:'tp) : 'ret option =
  360. self#run_from infinity tp
  361. end;;
  362. (* this is a special case where tp = tret and you stack their output as the next's input *)
  363. class ['tp] rule_map_dispatcher name =
  364. object(self)
  365. inherit ['tp, 'tp] rule_dispatcher name true as super
  366. method run_f tp = get (self#run tp)
  367. method run_from (priority:float) (tp:'tp) : 'ret option =
  368. let cur = ref tp in
  369. (try begin
  370. List.iter (fun key ->
  371. if key < priority then begin
  372. let q = Hashtbl.find tbl key in
  373. Stack.iter (fun (n, rule) ->
  374. trace ("running rule " ^ n);
  375. let t = if !debug_mode then Common.timer ("rule map dispatcher rule: " ^ n) else fun () -> () in
  376. let r = rule(!cur) in
  377. t();
  378. if is_some r then begin cur := get r end
  379. ) q
  380. end
  381. ) keys
  382. end with Exit -> ());
  383. Some (!cur)
  384. end;;
  385. type generator_ctx =
  386. {
  387. (* these are the basic context fields. If another target is using this context, *)
  388. (* this is all you need to care about *)
  389. mutable gcon : Common.context;
  390. gclasses : gen_classes;
  391. gtools : gen_tools;
  392. (*
  393. configurable function that receives a desired name and makes it "internal", doing the best
  394. to ensure that it will not be called from outside.
  395. To avoid name clashes between internal names, user must specify two strings: a "namespace" and the name itself
  396. *)
  397. mutable gmk_internal_name : string->string->string;
  398. (*
  399. module filters run before module filters and they should generate valid haxe syntax as a result.
  400. Module filters shouldn't go through the expressions as it adds an unnecessary burden to the GC,
  401. and it can all be done in a single step with gexpr_filters and proper priority selection.
  402. As a convention, Module filters should end their name with Modf, so they aren't mistaken with expression filters
  403. *)
  404. gmodule_filters : (module_type) rule_map_dispatcher;
  405. (*
  406. expression filters are the most common filters to be applied.
  407. They should also generate only valid haxe expressions, so e.g. calls to non-existant methods
  408. should be avoided, although there are some ways around them (like gspecial_methods)
  409. *)
  410. gexpr_filters : (texpr) rule_map_dispatcher;
  411. (*
  412. syntax filters are also expression filters but they no longer require
  413. that the resulting expressions be valid haxe expressions.
  414. They then have no guarantee that either the input expressions or the output one follow the same
  415. rules as normal haxe code.
  416. *)
  417. gsyntax_filters : (texpr) rule_map_dispatcher;
  418. (* these are more advanced features, but they would require a rewrite of targets *)
  419. (* they are just helpers to ditribute functions like "follow" or "type to string" *)
  420. (* so adding a module will already take care of correctly following a certain type of *)
  421. (* variable, for example *)
  422. (* follows the type through typedefs, lazy typing, etc. *)
  423. (* it's the place to put specific rules to handle typedefs, like *)
  424. (* other basic types like UInt *)
  425. gfollow : (t, t) rule_dispatcher;
  426. gtypes : (path, module_type) Hashtbl.t;
  427. (* cast detection helpers / settings *)
  428. (* this is a cache for all field access types *)
  429. 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;
  430. (* this function allows any code to handle casts as if it were inside the cast_detect module *)
  431. mutable ghandle_cast : t->t->texpr->texpr;
  432. (* when an unsafe cast is made, we can warn the user *)
  433. mutable gon_unsafe_cast : t->t->pos->unit;
  434. (* does this type needs to be boxed? Normally always false, unless special type handling must be made *)
  435. mutable gneeds_box : t->bool;
  436. (* does this 'special type' needs cast to this other type? *)
  437. (* this is here so we can implement custom behavior for "opaque" typedefs *)
  438. mutable gspecial_needs_cast : t->t->bool;
  439. (* sometimes we may want to support unrelated conversions on cast detection *)
  440. (* for example, haxe.lang.Null<T> -> T on C# *)
  441. (* every time an unrelated conversion is found, each to/from path is searched on this hashtbl *)
  442. (* if found, the function will be executed with from_type, to_type. If returns true, it means that *)
  443. (* it is a supported conversion, and the unsafe cast routine changes to a simple cast *)
  444. gsupported_conversions : (path, t->t->bool) Hashtbl.t;
  445. (* API for filters *)
  446. (* add type can be called at any time, and will add a new module_def that may or may not be filtered *)
  447. (* module_type -> should_filter *)
  448. mutable gadd_type : module_type -> bool -> unit;
  449. (* 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 *)
  450. mutable gadd_to_module : module_type -> float -> unit;
  451. (* during expr filters, shows the current class path *)
  452. mutable gcurrent_path : path;
  453. (* current class *)
  454. mutable gcurrent_class : tclass option;
  455. (* current class field, if any *)
  456. mutable gcurrent_classfield : tclass_field option;
  457. (* events *)
  458. (* is executed once every new classfield *)
  459. mutable gon_classfield_start : (unit -> unit) list;
  460. (* is executed once every new module type *)
  461. mutable gon_new_module_type : (unit -> unit) list;
  462. (* after module filters ended *)
  463. mutable gafter_mod_filters_ended : (unit -> unit) list;
  464. (* after expression filters ended *)
  465. mutable gafter_expr_filters_ended : (unit -> unit) list;
  466. (* after all filters are run *)
  467. mutable gafter_filters_ended : (unit -> unit) list;
  468. mutable gbase_class_fields : (string, tclass_field) PMap.t;
  469. (* real type is the type as it is read by the target. *)
  470. (* This function is here because most targets don't have *)
  471. (* a 1:1 translation between haxe types and its native types *)
  472. (* But types aren't changed to this representation as we might lose *)
  473. (* some valuable type information in the process *)
  474. mutable greal_type : t -> t;
  475. (*
  476. the same as greal_type but for type parameters.
  477. *)
  478. mutable greal_type_param : module_type -> tparams -> tparams;
  479. (*
  480. is the type a value type?
  481. This may be used in some optimizations where reference types and value types
  482. are handled differently. At first the default is very good to use, and if tweaks are needed,
  483. it's best to be done by adding @:struct meta to the value types
  484. *
  485. mutable gis_value_type : t -> bool;*)
  486. (* misc configuration *)
  487. (*
  488. Should the target allow type parameter dynamic conversion,
  489. or should we add a cast to those cases as well?
  490. *)
  491. mutable gallow_tp_dynamic_conversion : bool;
  492. (*
  493. Does the target support type parameter constraints?
  494. If not, they will be ignored when detecting casts
  495. *)
  496. mutable guse_tp_constraints : bool;
  497. (* internal apis *)
  498. (* param_func_call : used by TypeParams and CastDetection *)
  499. mutable gparam_func_call : texpr->texpr->tparams->texpr list->texpr;
  500. (* does it already have a type parameter cast handler? This is used by CastDetect to know if it should handle type parameter casts *)
  501. mutable ghas_tparam_cast_handler : bool;
  502. (* type parameter casts - special cases *)
  503. (* function cast_from, cast_to -> texpr *)
  504. gtparam_cast : (path, (texpr->t->texpr)) Hashtbl.t;
  505. (*
  506. special vars are used for adding special behavior to
  507. *)
  508. gspecial_vars : (string, bool) Hashtbl.t;
  509. }
  510. and gen_classes =
  511. {
  512. cl_reflect : tclass;
  513. cl_type : tclass;
  514. cl_dyn : tclass;
  515. t_iterator : tdef;
  516. }
  517. (* add here all reflection transformation additions *)
  518. and gen_tools =
  519. {
  520. (* (klass : texpr, t : t) : texpr *)
  521. mutable r_create_empty : texpr->t->texpr;
  522. (* 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 *)
  523. mutable r_fields : bool->texpr->texpr;
  524. (* (first argument = return type. should be void in most cases) Reflect.setField(obj, field, val) *)
  525. mutable r_set_field : t->texpr->texpr->texpr->texpr;
  526. (* Reflect.field. bool indicates if is safe (no error throwing) or unsafe; t is the expected return type true = safe *)
  527. mutable r_field : bool->t->texpr->texpr->texpr;
  528. (*
  529. these are now the functions that will later be used when creating the reflection classes
  530. *)
  531. (* on the default implementation (at OverloadingCtors), it will be new SomeClass<params>(EmptyInstance) *)
  532. mutable rf_create_empty : tclass->tparams->pos->texpr;
  533. }
  534. let get_type types path =
  535. List.find (fun md -> match md with
  536. | TClassDecl cl when cl.cl_path = path -> true
  537. | TEnumDecl e when e.e_path = path -> true
  538. | TTypeDecl t when t.t_path = path -> true
  539. | TAbstractDecl a when a.a_path = path -> true
  540. | _ -> false
  541. ) types
  542. let new_ctx con =
  543. let types = Hashtbl.create (List.length con.types) in
  544. List.iter (fun mt ->
  545. match mt with
  546. | TClassDecl cl -> Hashtbl.add types cl.cl_path mt
  547. | TEnumDecl e -> Hashtbl.add types e.e_path mt
  548. | TTypeDecl t -> Hashtbl.add types t.t_path mt
  549. | TAbstractDecl a -> Hashtbl.add types a.a_path mt
  550. ) con.types;
  551. let cl_dyn = match get_type con.types ([], "Dynamic") with
  552. | TClassDecl c -> c
  553. | TAbstractDecl a ->
  554. mk_class a.a_module ([], "Dynamic") a.a_pos
  555. | _ -> assert false
  556. in
  557. let rec gen = {
  558. gcon = con;
  559. gclasses = {
  560. cl_reflect = get_cl (get_type con.types ([], "Reflect"));
  561. cl_type = get_cl (get_type con.types ([], "Type"));
  562. cl_dyn = cl_dyn;
  563. t_iterator = get_tdef (get_type con.types ([], "Iterator"));
  564. };
  565. gtools = {
  566. r_create_empty = (fun eclass t ->
  567. let fieldcall = mk_static_field_access_infer gen.gclasses.cl_type "createEmptyInstance" eclass.epos [t] in
  568. { eexpr = TCall(fieldcall, [eclass]); etype = t; epos = eclass.epos }
  569. );
  570. r_fields = (fun is_used_only_by_iteration expr ->
  571. let fieldcall = mk_static_field_access_infer gen.gclasses.cl_reflect "fields" expr.epos [] in
  572. { eexpr = TCall(fieldcall, [expr]); etype = gen.gcon.basic.tarray gen.gcon.basic.tstring; epos = expr.epos }
  573. );
  574. (* Reflect.setField(obj, field, val). t by now is ignored. FIXME : fix this implementation *)
  575. r_set_field = (fun t obj field v ->
  576. let fieldcall = mk_static_field_access_infer gen.gclasses.cl_reflect "setField" v.epos [] in
  577. { eexpr = TCall(fieldcall, [obj; field; v]); etype = t_dynamic; epos = v.epos }
  578. );
  579. (* Reflect.field. bool indicates if is safe (no error throwing) or unsafe. true = safe *)
  580. r_field = (fun is_safe t obj field ->
  581. let fieldcall = mk_static_field_access_infer gen.gclasses.cl_reflect "field" obj.epos [] in
  582. (* FIXME: should we see if needs to cast? *)
  583. mk_cast t { eexpr = TCall(fieldcall, [obj; field]); etype = t_dynamic; epos = obj.epos }
  584. );
  585. rf_create_empty = (fun cl p pos ->
  586. gen.gtools.r_create_empty { eexpr = TTypeExpr(TClassDecl cl); epos = pos; etype = t_dynamic } (TInst(cl,p))
  587. ); (* TODO: Maybe implement using normal reflection? Type.createEmpty(MyClass) *)
  588. };
  589. gmk_internal_name = (fun ns s -> sprintf "__%s_%s" ns s);
  590. gexpr_filters = new rule_map_dispatcher "gexpr_filters";
  591. gmodule_filters = new rule_map_dispatcher "gmodule_filters";
  592. gsyntax_filters = new rule_map_dispatcher "gsyntax_filters";
  593. gfollow = new rule_dispatcher "gfollow" false;
  594. gtypes = types;
  595. greal_field_types = Hashtbl.create 0;
  596. ghandle_cast = (fun to_t from_t e -> mk_cast to_t e);
  597. 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));
  598. gneeds_box = (fun t -> false);
  599. gspecial_needs_cast = (fun to_t from_t -> true);
  600. gsupported_conversions = Hashtbl.create 0;
  601. gadd_type = (fun md should_filter ->
  602. if should_filter then begin
  603. con.types <- md :: con.types;
  604. con.modules <- { m_id = alloc_mid(); m_path = (t_path md); m_types = [md]; m_extra = module_extra "" "" 0. MFake } :: con.modules
  605. end else gen.gafter_filters_ended <- (fun () ->
  606. con.types <- md :: con.types;
  607. con.modules <- { m_id = alloc_mid(); m_path = (t_path md); m_types = [md]; m_extra = module_extra "" "" 0. MFake } :: con.modules
  608. ) :: gen.gafter_filters_ended;
  609. );
  610. gadd_to_module = (fun md pr -> failwith "module added outside expr filters");
  611. gcurrent_path = ([],"");
  612. gcurrent_class = None;
  613. gcurrent_classfield = None;
  614. gon_classfield_start = [];
  615. gon_new_module_type = [];
  616. gafter_mod_filters_ended = [];
  617. gafter_expr_filters_ended = [];
  618. gafter_filters_ended = [];
  619. gbase_class_fields = PMap.empty;
  620. greal_type = (fun t -> t);
  621. greal_type_param = (fun _ t -> t);
  622. gallow_tp_dynamic_conversion = false;
  623. guse_tp_constraints = false;
  624. (* as a default, ignore the params *)
  625. gparam_func_call = (fun ecall efield params elist -> { ecall with eexpr = TCall(efield, elist) });
  626. ghas_tparam_cast_handler = false;
  627. gtparam_cast = Hashtbl.create 0;
  628. gspecial_vars = Hashtbl.create 0;
  629. } in
  630. (*gen.gtools.r_create_empty <-
  631. gen.gtools.r_get_class <-
  632. gen.gtools.r_fields <- *)
  633. gen
  634. let init_ctx gen =
  635. (* ultimately add a follow once handler as the last follow handler *)
  636. let follow_f = gen.gfollow#run in
  637. let follow t =
  638. match t with
  639. | TMono r ->
  640. (match !r with
  641. | Some t -> follow_f t
  642. | _ -> Some t)
  643. | TLazy f ->
  644. follow_f (!f())
  645. | TType (t,tl) ->
  646. follow_f (apply_params t.t_params tl t.t_type)
  647. | _ -> Some t
  648. in
  649. gen.gfollow#add ~name:"final" ~priority:PLast follow
  650. (* run_follow (gen:generator_ctx) (t:t) *)
  651. let run_follow gen = gen.gfollow#run_f
  652. let reorder_modules gen =
  653. let modules = Hashtbl.create 20 in
  654. List.iter (fun md ->
  655. Hashtbl.add modules ( (t_infos md).mt_module ).m_path md
  656. ) gen.gcon.types;
  657. let con = gen.gcon in
  658. con.modules <- [];
  659. let processed = Hashtbl.create 20 in
  660. Hashtbl.iter (fun md_path md ->
  661. if not (Hashtbl.mem processed md_path) then begin
  662. Hashtbl.add processed md_path true;
  663. con.modules <- { m_id = alloc_mid(); m_path = md_path; m_types = List.rev ( Hashtbl.find_all modules md_path ); m_extra = (t_infos md).mt_module.m_extra } :: con.modules
  664. end
  665. ) modules
  666. let run_filters_from gen t filters =
  667. match t with
  668. | TClassDecl c ->
  669. trace (snd c.cl_path);
  670. gen.gcurrent_path <- c.cl_path;
  671. gen.gcurrent_class <- Some(c);
  672. List.iter (fun fn -> fn()) gen.gon_new_module_type;
  673. gen.gcurrent_classfield <- None;
  674. let rec process_field f =
  675. gen.gcurrent_classfield <- Some(f);
  676. List.iter (fun fn -> fn()) gen.gon_classfield_start;
  677. trace f.cf_name;
  678. (match f.cf_expr with
  679. | None -> ()
  680. | Some e ->
  681. f.cf_expr <- Some (List.fold_left (fun e f -> f e) e filters));
  682. List.iter process_field f.cf_overloads;
  683. in
  684. List.iter process_field c.cl_ordered_fields;
  685. List.iter process_field c.cl_ordered_statics;
  686. gen.gcurrent_classfield <- None;
  687. (match c.cl_constructor with
  688. | None -> ()
  689. | Some f -> process_field f);
  690. (match c.cl_init with
  691. | None -> ()
  692. | Some e ->
  693. c.cl_init <- Some (List.fold_left (fun e f -> f e) e filters));
  694. | TEnumDecl _ -> ()
  695. | TTypeDecl _ -> ()
  696. | TAbstractDecl _ -> ()
  697. let run_filters gen =
  698. let last_error = gen.gcon.error in
  699. let has_errors = ref false in
  700. gen.gcon.error <- (fun msg pos -> has_errors := true; last_error msg pos);
  701. (* first of all, we have to make sure that the filters won't trigger a major Gc collection *)
  702. let t = Common.timer "gencommon_filters" in
  703. (if Common.defined gen.gcon Define.GencommonDebug then debug_mode := true);
  704. let run_filters filter =
  705. let rec loop acc mds =
  706. match mds with
  707. | [] -> acc
  708. | md :: tl ->
  709. let filters = [ filter#run_f ] in
  710. let added_types = ref [] in
  711. gen.gadd_to_module <- (fun md_type priority ->
  712. gen.gcon.types <- md_type :: gen.gcon.types;
  713. added_types := (md_type, priority) :: !added_types
  714. );
  715. run_filters_from gen md filters;
  716. let added_types = List.map (fun (t,p) ->
  717. run_filters_from gen t [ fun e -> get (filter#run_from p e) ];
  718. if Hashtbl.mem gen.gtypes (t_path t) then begin
  719. let rec loop i =
  720. let p = t_path t in
  721. let new_p = (fst p, snd p ^ "_" ^ (string_of_int i)) in
  722. if Hashtbl.mem gen.gtypes new_p then
  723. loop (i+1)
  724. else
  725. match t with
  726. | TClassDecl cl -> cl.cl_path <- new_p
  727. | TEnumDecl e -> e.e_path <- new_p
  728. | TTypeDecl _ | TAbstractDecl _ -> ()
  729. in
  730. loop 0
  731. end;
  732. Hashtbl.add gen.gtypes (t_path t) t;
  733. t
  734. ) !added_types in
  735. loop (added_types @ (md :: acc)) tl
  736. in
  737. List.rev (loop [] gen.gcon.types)
  738. in
  739. let run_mod_filter filter =
  740. let last_add_to_module = gen.gadd_to_module in
  741. let added_types = ref [] in
  742. gen.gadd_to_module <- (fun md_type priority ->
  743. Hashtbl.add gen.gtypes (t_path md_type) md_type;
  744. added_types := (md_type, priority) :: !added_types
  745. );
  746. let rec loop processed not_processed =
  747. match not_processed with
  748. | hd :: tl ->
  749. (match hd with
  750. | TClassDecl c ->
  751. gen.gcurrent_class <- Some c
  752. | _ ->
  753. gen.gcurrent_class <- None);
  754. let new_hd = filter#run_f hd in
  755. let added_types_new = !added_types in
  756. added_types := [];
  757. let added_types = List.map (fun (t,p) ->
  758. get (filter#run_from p t)
  759. ) added_types_new in
  760. loop ( added_types @ (new_hd :: processed) ) tl
  761. | [] ->
  762. processed
  763. in
  764. let filtered = loop [] gen.gcon.types in
  765. gen.gadd_to_module <- last_add_to_module;
  766. gen.gcon.types <- List.rev (filtered)
  767. in
  768. run_mod_filter gen.gmodule_filters;
  769. List.iter (fun fn -> fn()) gen.gafter_mod_filters_ended;
  770. let last_add_to_module = gen.gadd_to_module in
  771. gen.gcon.types <- run_filters gen.gexpr_filters;
  772. gen.gadd_to_module <- last_add_to_module;
  773. List.iter (fun fn -> fn()) gen.gafter_expr_filters_ended;
  774. (* Codegen.post_process gen.gcon.types [gen.gexpr_filters#run_f]; *)
  775. gen.gcon.types <- run_filters gen.gsyntax_filters;
  776. List.iter (fun fn -> fn()) gen.gafter_filters_ended;
  777. reorder_modules gen;
  778. t();
  779. if !has_errors then raise (Abort("Compilation aborted with errors",null_pos))
  780. (* ******************************************* *)
  781. (* basic generation module that source code compilation implementations can use *)
  782. (* ******************************************* *)
  783. let write_file gen w source_dir path extension out_files =
  784. let t = timer "write file" in
  785. let s_path = source_dir ^ "/" ^ (snd path) ^ "." ^ (extension) in
  786. (* create the folders if they don't exist *)
  787. mkdir_from_path s_path;
  788. let contents = SourceWriter.contents w in
  789. let should_write = if not (Common.defined gen.gcon Define.ReplaceFiles) && Sys.file_exists s_path then begin
  790. let in_file = open_in s_path in
  791. let old_contents = Std.input_all in_file in
  792. close_in in_file;
  793. contents <> old_contents
  794. end else true in
  795. if should_write then begin
  796. let f = open_out s_path in
  797. output_string f contents;
  798. close_out f
  799. end;
  800. out_files := (unique_full_path s_path) :: !out_files;
  801. t()
  802. let clean_files path excludes verbose =
  803. let rec iter_files pack dir path = try
  804. let file = Unix.readdir dir in
  805. if file <> "." && file <> ".." then begin
  806. let filepath = path ^ "/" ^ file in
  807. if (Unix.stat filepath).st_kind = S_DIR then
  808. let pack = pack @ [file] in
  809. iter_files (pack) (Unix.opendir filepath) filepath;
  810. try Unix.rmdir filepath with Unix.Unix_error (ENOTEMPTY,_,_) -> ();
  811. else if not (String.ends_with filepath ".meta") && not (List.mem (unique_full_path filepath) excludes) then begin
  812. if verbose then print_endline ("Removing " ^ filepath);
  813. Sys.remove filepath
  814. end
  815. end;
  816. iter_files pack dir path
  817. with | End_of_file | Unix.Unix_error _ ->
  818. Unix.closedir dir
  819. in
  820. iter_files [] (Unix.opendir path) path
  821. let dump_descriptor gen name path_s module_s =
  822. let w = SourceWriter.new_source_writer () in
  823. (* dump called path *)
  824. SourceWriter.write w (Sys.getcwd());
  825. SourceWriter.newline w;
  826. (* dump all defines. deprecated *)
  827. SourceWriter.write w "begin defines";
  828. SourceWriter.newline w;
  829. PMap.iter (fun name _ ->
  830. SourceWriter.write w name;
  831. SourceWriter.newline w
  832. ) gen.gcon.defines;
  833. SourceWriter.write w "end defines";
  834. SourceWriter.newline w;
  835. (* dump all defines with their values; keeping the old defines for compatibility *)
  836. SourceWriter.write w "begin defines_data";
  837. SourceWriter.newline w;
  838. PMap.iter (fun name v ->
  839. SourceWriter.write w name;
  840. SourceWriter.write w "=";
  841. SourceWriter.write w v;
  842. SourceWriter.newline w
  843. ) gen.gcon.defines;
  844. SourceWriter.write w "end defines_data";
  845. SourceWriter.newline w;
  846. (* dump all generated types *)
  847. SourceWriter.write w "begin modules";
  848. SourceWriter.newline w;
  849. let main_paths = Hashtbl.create 0 in
  850. List.iter (fun md_def ->
  851. SourceWriter.write w "M ";
  852. SourceWriter.write w (path_s (path_of_md_def md_def));
  853. SourceWriter.newline w;
  854. List.iter (fun m ->
  855. match m with
  856. | TClassDecl cl when not cl.cl_extern ->
  857. SourceWriter.write w "C ";
  858. let s = module_s m in
  859. Hashtbl.add main_paths cl.cl_path s;
  860. SourceWriter.write w (s);
  861. SourceWriter.newline w
  862. | TEnumDecl e when not e.e_extern ->
  863. SourceWriter.write w "E ";
  864. SourceWriter.write w (module_s m);
  865. SourceWriter.newline w
  866. | _ -> () (* still no typedef or abstract is generated *)
  867. ) md_def.m_types
  868. ) gen.gcon.modules;
  869. SourceWriter.write w "end modules";
  870. SourceWriter.newline w;
  871. (* dump all resources *)
  872. (match gen.gcon.main_class with
  873. | Some path ->
  874. SourceWriter.write w "begin main";
  875. SourceWriter.newline w;
  876. (try
  877. SourceWriter.write w (Hashtbl.find main_paths path)
  878. with
  879. | Not_found -> SourceWriter.write w (path_s path));
  880. SourceWriter.newline w;
  881. SourceWriter.write w "end main";
  882. SourceWriter.newline w
  883. | _ -> ()
  884. );
  885. SourceWriter.write w "begin resources";
  886. SourceWriter.newline w;
  887. Hashtbl.iter (fun name _ ->
  888. SourceWriter.write w name;
  889. SourceWriter.newline w
  890. ) gen.gcon.resources;
  891. SourceWriter.write w "end resources";
  892. SourceWriter.newline w;
  893. SourceWriter.write w "begin libs";
  894. SourceWriter.newline w;
  895. let path file ext =
  896. if Sys.file_exists file then
  897. file
  898. else try Common.find_file gen.gcon file with
  899. | Not_found -> try Common.find_file gen.gcon (file ^ ext) with
  900. | Not_found ->
  901. file
  902. in
  903. if Common.platform gen.gcon Java then
  904. List.iter (fun (s,std,_,_,_) ->
  905. if not std then begin
  906. SourceWriter.write w (path s ".jar");
  907. SourceWriter.newline w;
  908. end
  909. ) gen.gcon.java_libs
  910. else if Common.platform gen.gcon Cs then
  911. List.iter (fun (s,std,_,_) ->
  912. if not std then begin
  913. SourceWriter.write w (path s ".dll");
  914. SourceWriter.newline w;
  915. end
  916. ) gen.gcon.net_libs;
  917. SourceWriter.write w "end libs";
  918. SourceWriter.newline w;
  919. let args = gen.gcon.c_args in
  920. if args <> [] then begin
  921. SourceWriter.write w "begin opts";
  922. SourceWriter.newline w;
  923. List.iter (fun opt -> SourceWriter.write w opt; SourceWriter.newline w) (List.rev args);
  924. SourceWriter.write w "end opts";
  925. SourceWriter.newline w;
  926. end;
  927. let contents = SourceWriter.contents w in
  928. let f = open_out (gen.gcon.file ^ "/" ^ name) in
  929. output_string f contents;
  930. close_out f
  931. let path_regex = Str.regexp "[/\\]+"
  932. let normalize path =
  933. let rec normalize acc m = match m with
  934. | [] ->
  935. List.rev acc
  936. | Str.Text "." :: Str.Delim _ :: tl when acc = [] ->
  937. normalize [] tl
  938. | Str.Text ".." :: Str.Delim _ :: tl -> (match acc with
  939. | [] -> raise Exit
  940. | _ :: acc -> normalize acc tl)
  941. | Str.Text t :: Str.Delim _ :: tl ->
  942. normalize (t :: acc) tl
  943. | Str.Delim _ :: tl ->
  944. normalize ("" :: acc) tl
  945. | Str.Text t :: [] ->
  946. List.rev (t :: acc)
  947. | Str.Text _ :: Str.Text _ :: _ -> assert false
  948. in
  949. String.concat "/" (normalize [] (Str.full_split path_regex path))
  950. let is_relative cwd rel =
  951. try
  952. let rel = normalize rel in
  953. Filename.is_relative rel || (String.starts_with rel cwd || String.starts_with (Common.unique_full_path rel) cwd)
  954. with | Exit ->
  955. String.starts_with rel cwd || String.starts_with (Common.unique_full_path rel) cwd
  956. (*
  957. helper function to create the source structure. Will send each module_def to the function passed.
  958. If received true, it means that module_gen has generated this content, so the file must be saved.
  959. See that it will write a whole module
  960. *)
  961. let generate_modules gen extension source_dir (module_gen : SourceWriter.source_writer->module_def->bool) out_files =
  962. let cwd = Common.unique_full_path (Sys.getcwd()) in
  963. List.iter (fun md_def ->
  964. let source_dir =
  965. if Common.defined gen.gcon Define.UnityStdTarget then
  966. let file = md_def.m_extra.m_file in
  967. let file = if file = "" then "." else file in
  968. if is_relative cwd file then
  969. let base_path = try
  970. let last = Str.search_backward path_regex file (String.length file - 1) in
  971. String.sub file 0 last
  972. with | Not_found ->
  973. "."
  974. in
  975. match List.rev (fst md_def.m_path) with
  976. | "editor" :: _ ->
  977. base_path ^ "/" ^ gen.gcon.file ^ "/Editor"
  978. | _ ->
  979. base_path ^ "/" ^ gen.gcon.file
  980. else match List.rev (fst md_def.m_path) with
  981. | "editor" :: _ ->
  982. Common.defined_value gen.gcon Define.UnityStdTarget ^ "/Editor/" ^ (String.concat "/" (fst md_def.m_path))
  983. | _ ->
  984. Common.defined_value gen.gcon Define.UnityStdTarget ^ "/Haxe-Std/" ^ (String.concat "/" (fst md_def.m_path))
  985. else
  986. gen.gcon.file ^ "/" ^ source_dir ^ "/" ^ (String.concat "/" (fst (path_of_md_def md_def)))
  987. in
  988. let w = SourceWriter.new_source_writer () in
  989. (*let should_write = List.fold_left (fun should md -> module_gen w md or should) false md_def.m_types in*)
  990. let should_write = module_gen w md_def in
  991. if should_write then begin
  992. let path = path_of_md_def md_def in
  993. write_file gen w source_dir path extension out_files
  994. end
  995. ) gen.gcon.modules
  996. let generate_modules_t gen extension source_dir change_path (module_gen : SourceWriter.source_writer->module_type->bool) out_files =
  997. let source_dir = gen.gcon.file ^ "/" ^ source_dir in
  998. List.iter (fun md ->
  999. let w = SourceWriter.new_source_writer () in
  1000. (*let should_write = List.fold_left (fun should md -> module_gen w md or should) false md_def.m_types in*)
  1001. let should_write = module_gen w md in
  1002. if should_write then begin
  1003. let path = change_path (t_path md) in
  1004. write_file gen w (source_dir ^ "/" ^ (String.concat "/" (fst path))) path extension out_files;
  1005. end
  1006. ) gen.gcon.types
  1007. (*
  1008. various helper functions
  1009. *)
  1010. let mk_paren e =
  1011. match e.eexpr with | TParenthesis _ -> e | _ -> { e with eexpr=TParenthesis(e) }
  1012. (* private *)
  1013. let tmp_count = ref 0
  1014. let get_real_fun gen t =
  1015. match follow t with
  1016. | TFun(args,t) -> TFun(List.map (fun (n,o,t) -> n,o,gen.greal_type t) args, gen.greal_type t)
  1017. | _ -> t
  1018. let mk_int gen i pos = { eexpr = TConst(TInt ( Int32.of_int i)); etype = gen.gcon.basic.tint; epos = pos }
  1019. let mk_return e = { eexpr = TReturn (Some e); etype = e.etype; epos = e.epos }
  1020. let mk_temp gen name t =
  1021. incr tmp_count;
  1022. let name = gen.gmk_internal_name "temp" (name ^ (string_of_int !tmp_count)) in
  1023. alloc_var name t
  1024. let ensure_local gen block name e =
  1025. match e.eexpr with
  1026. | TLocal _ -> e
  1027. | _ ->
  1028. let var = mk_temp gen name e.etype in
  1029. block := { e with eexpr = TVar(var, Some e); etype = gen.gcon.basic.tvoid; } :: !block;
  1030. { e with eexpr = TLocal var }
  1031. let reset_temps () = tmp_count := 0
  1032. let follow_module follow_func md = match md with
  1033. | TClassDecl _
  1034. | TEnumDecl _
  1035. | TAbstractDecl _ -> md
  1036. | TTypeDecl tdecl -> match (follow_func (TType(tdecl, List.map snd tdecl.t_params))) with
  1037. | TInst(cl,_) -> TClassDecl cl
  1038. | TEnum(e,_) -> TEnumDecl e
  1039. | TType(t,_) -> TTypeDecl t
  1040. | TAbstract(a,_) -> TAbstractDecl a
  1041. | _ -> assert false
  1042. (*
  1043. hxgen means if the type was generated by haxe. If a type was generated by haxe, it means
  1044. it will contain special constructs for speedy reflection, for example
  1045. @see SetHXGen module
  1046. *)
  1047. let rec is_hxgen md =
  1048. match md with
  1049. | TClassDecl cl -> Meta.has Meta.HxGen cl.cl_meta
  1050. | TEnumDecl e -> Meta.has Meta.HxGen e.e_meta
  1051. | 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 )
  1052. | TAbstractDecl a -> Meta.has Meta.HxGen a.a_meta
  1053. let is_hxgen_t t =
  1054. match t with
  1055. | TInst (cl, _) -> Meta.has Meta.HxGen cl.cl_meta
  1056. | TEnum (e, _) -> Meta.has Meta.HxGen e.e_meta
  1057. | TAbstract (a, _) -> Meta.has Meta.HxGen a.a_meta
  1058. | TType (t, _) -> Meta.has Meta.HxGen t.t_meta
  1059. | _ -> false
  1060. let mt_to_t_dyn md =
  1061. match md with
  1062. | TClassDecl cl -> TInst(cl, List.map (fun _ -> t_dynamic) cl.cl_params)
  1063. | TEnumDecl e -> TEnum(e, List.map (fun _ -> t_dynamic) e.e_params)
  1064. | TAbstractDecl a -> TAbstract(a, List.map (fun _ -> t_dynamic) a.a_params)
  1065. | TTypeDecl t -> TType(t, List.map (fun _ -> t_dynamic) t.t_params)
  1066. let mt_to_t mt params =
  1067. match mt with
  1068. | TClassDecl (cl) -> TInst(cl, params)
  1069. | TEnumDecl (e) -> TEnum(e, params)
  1070. | TAbstractDecl a -> TAbstract(a, params)
  1071. | _ -> assert false
  1072. let t_to_mt t =
  1073. match follow t with
  1074. | TInst(cl, _) -> TClassDecl(cl)
  1075. | TEnum(e, _) -> TEnumDecl(e)
  1076. | TAbstract(a, _) -> TAbstractDecl a
  1077. | _ -> assert false
  1078. let rec get_last_ctor cl =
  1079. 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
  1080. let add_constructor cl cf =
  1081. match cl.cl_constructor with
  1082. | None -> cl.cl_constructor <- Some cf
  1083. | Some ctor ->
  1084. if ctor != cf && not (List.memq cf ctor.cf_overloads) then
  1085. ctor.cf_overloads <- cf :: ctor.cf_overloads
  1086. (* replace open TMonos with TDynamic *)
  1087. let rec replace_mono t =
  1088. match t with
  1089. | TMono t ->
  1090. (match !t with
  1091. | None -> t := Some t_dynamic
  1092. | Some _ -> ())
  1093. | TEnum (_,p) | TInst (_,p) | TType (_,p) | TAbstract (_,p) ->
  1094. List.iter replace_mono p
  1095. | TFun (args,ret) ->
  1096. List.iter (fun (_,_,t) -> replace_mono t) args;
  1097. replace_mono ret
  1098. | TAnon _
  1099. | TDynamic _ -> ()
  1100. | TLazy f ->
  1101. replace_mono (!f())
  1102. (* helper *)
  1103. let mk_class_field name t public pos kind params =
  1104. {
  1105. cf_name = name;
  1106. cf_type = t;
  1107. cf_public = public;
  1108. cf_pos = pos;
  1109. cf_doc = None;
  1110. cf_meta = [ Meta.CompilerGenerated, [], Ast.null_pos ]; (* annotate that this class field was generated by the compiler *)
  1111. cf_kind = kind;
  1112. cf_params = params;
  1113. cf_expr = None;
  1114. cf_overloads = [];
  1115. }
  1116. (* this helper just duplicates the type parameter class, which is assumed that cl is. *)
  1117. (* This is so we can use class parameters on function parameters, without running the risk of name clash *)
  1118. (* between both *)
  1119. let map_param cl =
  1120. let ret = mk_class cl.cl_module (fst cl.cl_path, snd cl.cl_path ^ "_c") cl.cl_pos in
  1121. ret.cl_implements <- cl.cl_implements;
  1122. ret.cl_kind <- cl.cl_kind;
  1123. ret
  1124. let get_cl_t t =
  1125. match follow t with | TInst (cl,_) -> cl | _ -> assert false
  1126. let mk_class m path pos =
  1127. let cl = Type.mk_class m path pos in
  1128. cl.cl_meta <- [ Meta.CompilerGenerated, [], Ast.null_pos ];
  1129. cl
  1130. type tfield_access =
  1131. | 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 *)
  1132. | FEnumField of tenum * tenum_field * bool (* is parameterized enum ? *)
  1133. | FAnonField of tclass_field
  1134. | FDynamicField of t
  1135. | FNotFound
  1136. let find_first_declared_field gen orig_cl ?exact_field field =
  1137. let chosen = ref None in
  1138. let is_overload = ref false in
  1139. let rec loop_cl depth c tl tlch =
  1140. (try
  1141. let ret = PMap.find field c.cl_fields in
  1142. if Meta.has Meta.Overload ret.cf_meta then is_overload := true;
  1143. match !chosen, exact_field with
  1144. | Some(d,_,_,_,_), _ when depth <= d -> ()
  1145. | _, None ->
  1146. chosen := Some(depth,ret,c,tl,tlch)
  1147. | _, Some f2 ->
  1148. List.iter (fun f ->
  1149. let declared_t = apply_params c.cl_params tl f.cf_type in
  1150. if Typeload.same_overload_args declared_t f2.cf_type f f2 then
  1151. chosen := Some(depth,f,c,tl,tlch)
  1152. ) (ret :: ret.cf_overloads)
  1153. with | Not_found -> ());
  1154. (match c.cl_super with
  1155. | Some (sup,stl) ->
  1156. let tl = List.map (apply_params c.cl_params tl) stl in
  1157. let stl = gen.greal_type_param (TClassDecl sup) stl in
  1158. let tlch = List.map (apply_params c.cl_params tlch) stl in
  1159. loop_cl (depth+1) sup tl tlch
  1160. | None -> ());
  1161. if c.cl_interface then
  1162. List.iter (fun (sup,stl) ->
  1163. let tl = List.map (apply_params c.cl_params tl) stl in
  1164. let stl = gen.greal_type_param (TClassDecl sup) stl in
  1165. let tlch = List.map (apply_params c.cl_params tlch) stl in
  1166. loop_cl (depth+1) sup tl tlch
  1167. ) c.cl_implements
  1168. in
  1169. loop_cl 0 orig_cl (List.map snd orig_cl.cl_params) (List.map snd orig_cl.cl_params);
  1170. match !chosen with
  1171. | None -> None
  1172. | Some(_,f,c,tl,tlch) ->
  1173. if !is_overload && not (Meta.has Meta.Overload f.cf_meta) then
  1174. f.cf_meta <- (Meta.Overload,[],f.cf_pos) :: f.cf_meta;
  1175. let declared_t = apply_params c.cl_params tl f.cf_type in
  1176. let params_t = apply_params c.cl_params tlch f.cf_type in
  1177. let actual_t = match follow params_t with
  1178. | TFun(args,ret) -> TFun(List.map (fun (n,o,t) -> (n,o,gen.greal_type t)) args, gen.greal_type ret)
  1179. | _ -> gen.greal_type params_t in
  1180. Some(f,actual_t,declared_t,params_t,c,tl,tlch)
  1181. let field_access gen (t:t) (field:string) : (tfield_access) =
  1182. (*
  1183. t can be either an haxe-type as a real-type;
  1184. 'follow' should be applied here since we can generalize that a TType will be accessible as its
  1185. underlying type.
  1186. *)
  1187. (* let pointers to values be accessed as the underlying values *)
  1188. let t = match gen.greal_type t with
  1189. | TAbstract({ a_path = ["cs"],"Pointer" },[t]) ->
  1190. gen.greal_type t
  1191. | _ -> t
  1192. in
  1193. match follow t with
  1194. | TInst(cl, params) ->
  1195. let orig_cl = cl in
  1196. let orig_params = params in
  1197. let rec not_found cl params =
  1198. match cl.cl_dynamic with
  1199. | Some t ->
  1200. let t = apply_params cl.cl_params params t in
  1201. FDynamicField t
  1202. | None ->
  1203. match cl.cl_super with
  1204. | None -> FNotFound
  1205. | Some (super,p) -> not_found super p
  1206. in
  1207. let not_found () =
  1208. try
  1209. let cf = PMap.find field gen.gbase_class_fields in
  1210. FClassField (orig_cl, orig_params, gen.gclasses.cl_dyn, cf, false, cf.cf_type, cf.cf_type)
  1211. with
  1212. | Not_found -> not_found cl params
  1213. in
  1214. (* this is a hack for C#'s different generic types with same path *)
  1215. let hashtbl_field = (String.concat "" (List.map (fun _ -> "]") cl.cl_params)) ^ field in
  1216. let types = try
  1217. Hashtbl.find gen.greal_field_types (orig_cl.cl_path, hashtbl_field)
  1218. with | Not_found ->
  1219. let ret = find_first_declared_field gen cl field in
  1220. let ret = match ret with
  1221. | None -> None
  1222. | Some(cf,t,dt,_,cl,_,_) -> Some(cf,t,dt,cl)
  1223. in
  1224. Hashtbl.add gen.greal_field_types (orig_cl.cl_path, hashtbl_field) ret;
  1225. ret
  1226. in
  1227. (match types with
  1228. | None -> not_found()
  1229. | Some (cf, actual_t, declared_t, declared_cl) ->
  1230. FClassField(orig_cl, orig_params, declared_cl, cf, false, actual_t, declared_t))
  1231. | TEnum _ | TAbstract _ ->
  1232. (* enums have no field *) FNotFound
  1233. | TAnon anon ->
  1234. (try match !(anon.a_status) with
  1235. | Statics cl ->
  1236. let cf = PMap.find field cl.cl_statics in
  1237. FClassField(cl, List.map (fun _ -> t_dynamic) cl.cl_params, cl, cf, true, cf.cf_type, cf.cf_type)
  1238. | EnumStatics e ->
  1239. let f = PMap.find field e.e_constrs in
  1240. let is_param = match follow f.ef_type with | TFun _ -> true | _ -> false in
  1241. FEnumField(e, f, is_param)
  1242. | _ when PMap.mem field gen.gbase_class_fields ->
  1243. let cf = PMap.find field gen.gbase_class_fields in
  1244. FClassField(gen.gclasses.cl_dyn, [t_dynamic], gen.gclasses.cl_dyn, cf, false, cf.cf_type, cf.cf_type)
  1245. | _ ->
  1246. FAnonField(PMap.find field anon.a_fields)
  1247. with | Not_found -> FNotFound)
  1248. | _ when PMap.mem field gen.gbase_class_fields ->
  1249. let cf = PMap.find field gen.gbase_class_fields in
  1250. FClassField(gen.gclasses.cl_dyn, [t_dynamic], gen.gclasses.cl_dyn, cf, false, cf.cf_type, cf.cf_type)
  1251. | TDynamic t -> FDynamicField t
  1252. | TMono _ -> FDynamicField t_dynamic
  1253. | _ -> FNotFound
  1254. let field_access_esp gen t field = match field with
  1255. | FStatic(cl,cf) | FInstance(cl,_,cf) when Meta.has Meta.Extern cf.cf_meta ->
  1256. let static = match field with
  1257. | FStatic _ -> true
  1258. | _ -> false
  1259. in
  1260. let p = match follow (run_follow gen t) with
  1261. | TInst(_,p) -> p
  1262. | _ -> List.map snd cl.cl_params
  1263. in
  1264. FClassField(cl,p,cl,cf,static,cf.cf_type,cf.cf_type)
  1265. | _ -> field_access gen t (field_name field)
  1266. let mk_field_access gen expr field pos =
  1267. match field_access gen expr.etype field with
  1268. | FClassField(c,p,dc,cf,false,at,_) ->
  1269. { eexpr = TField(expr, FInstance(dc,p,cf)); etype = apply_params c.cl_params p at; epos = pos }
  1270. | FClassField(c,p,dc,cf,true,at,_) ->
  1271. { eexpr = TField(expr, FStatic(dc,cf)); etype = at; epos = pos }
  1272. | FAnonField cf ->
  1273. { eexpr = TField(expr, FAnon cf); etype = cf.cf_type; epos = pos }
  1274. | FDynamicField t ->
  1275. { eexpr = TField(expr, FDynamic field); etype = t; epos = pos }
  1276. | FNotFound ->
  1277. { eexpr = TField(expr, FDynamic field); etype = t_dynamic; epos = pos }
  1278. | FEnumField _ -> assert false
  1279. let mk_iterator_access gen t expr =
  1280. let pos = expr.epos in
  1281. let itf = mk_field_access gen expr "iterator" pos in
  1282. { eexpr = TCall(itf, []); epos = pos; etype = snd (get_fun itf.etype) }
  1283. (* ******************************************* *)
  1284. (* Module dependency resolution *)
  1285. (* ******************************************* *)
  1286. type t_dependency =
  1287. | DAfter of float
  1288. | DBefore of float
  1289. exception ImpossibleDependency of string
  1290. let max_dep = 10000.0
  1291. let min_dep = - (10000.0)
  1292. let solve_deps name (deps:t_dependency list) =
  1293. let vmin = min_dep -. 1.0 in
  1294. let vmax = max_dep +. 1.0 in
  1295. let rec loop dep vmin vmax =
  1296. match dep with
  1297. | [] ->
  1298. (if vmin >= vmax then raise (ImpossibleDependency name));
  1299. (vmin +. vmax) /. 2.0
  1300. | head :: tail ->
  1301. match head with
  1302. | DBefore f ->
  1303. loop tail (max vmin f) vmax
  1304. | DAfter f ->
  1305. loop tail vmin (min vmax f)
  1306. in
  1307. loop deps vmin vmax
  1308. (* type resolution *)
  1309. exception TypeNotFound of path
  1310. let get_type gen path =
  1311. try Hashtbl.find gen.gtypes path with | Not_found -> raise (TypeNotFound path)
  1312. (* ******************************************* *)
  1313. (* follow all module *)
  1314. (* ******************************************* *)
  1315. (*
  1316. this module will follow each and every type using the rules defined in
  1317. gen.gfollow. This is a minor helper module, so we don't end up
  1318. having to follow the same time multiple times in the many filter iterations
  1319. because of this, it will be one of the first modules to run.
  1320. *)
  1321. module FollowAll =
  1322. struct
  1323. let follow gen e =
  1324. let follow_func = gen.gfollow#run_f in
  1325. Some (Type.map_expr_type (fun e->e) (follow_func) (fun tvar-> tvar.v_type <- (follow_func tvar.v_type); tvar) e)
  1326. let priority = max_dep
  1327. (* will add an expression filter as the first filter *)
  1328. let configure gen =
  1329. gen.gexpr_filters#add ~name:"follow_all" ~priority:(PCustom(priority)) (follow gen)
  1330. end;;
  1331. (* ******************************************* *)
  1332. (* set hxgen module *)
  1333. (* ******************************************* *)
  1334. (*
  1335. goes through all module types and sets the :hxgen meta on all which
  1336. then is_hxgen_func returns true. There is a default is_hxgen_func implementation also
  1337. *)
  1338. module SetHXGen =
  1339. struct
  1340. (*
  1341. basically, everything that is extern is assumed to not be hxgen, unless meta :hxgen is set, and
  1342. everything that is not extern is assumed to be hxgen, unless meta :nativegen is set
  1343. *)
  1344. let rec default_hxgen_func md =
  1345. match md with
  1346. | TClassDecl { cl_kind = KAbstractImpl a } ->
  1347. default_hxgen_func (TAbstractDecl a)
  1348. | TClassDecl cl ->
  1349. let rec is_hxgen_class (c,_) =
  1350. if c.cl_extern then begin
  1351. if Meta.has Meta.HxGen c.cl_meta then true else Option.map_default (is_hxgen_class) false c.cl_super || List.exists is_hxgen_class c.cl_implements
  1352. end else begin
  1353. if Meta.has Meta.NativeChildren c.cl_meta || Meta.has Meta.NativeGen c.cl_meta then
  1354. Option.map_default (is_hxgen_class) false c.cl_super || List.exists is_hxgen_class c.cl_implements
  1355. else
  1356. let rec has_nativec (c,p) =
  1357. if is_hxgen_class (c,p) then
  1358. false
  1359. else
  1360. (Meta.has Meta.NativeChildren c.cl_meta && not (Option.map_default is_hxgen_class false c.cl_super || List.exists is_hxgen_class c.cl_implements))
  1361. || Option.map_default has_nativec false c.cl_super
  1362. in
  1363. if Option.map_default has_nativec false c.cl_super && not (List.exists is_hxgen_class c.cl_implements) then
  1364. false
  1365. else
  1366. true
  1367. end
  1368. in
  1369. is_hxgen_class (cl,[])
  1370. | TEnumDecl e -> if e.e_extern then Meta.has Meta.HxGen e.e_meta else not (Meta.has Meta.NativeGen e.e_meta)
  1371. | TAbstractDecl a when Meta.has Meta.CoreType a.a_meta -> not (Meta.has Meta.NativeGen a.a_meta)
  1372. | TAbstractDecl a -> (match follow a.a_this with
  1373. | TInst _ | TEnum _ | TAbstract _ ->
  1374. default_hxgen_func (t_to_md (follow a.a_this))
  1375. | _ ->
  1376. Meta.has Meta.NativeGen a.a_meta)
  1377. | TTypeDecl t -> (* TODO see when would we use this *)
  1378. false
  1379. (*
  1380. by now the only option is to run it eagerly, because it must be one of the first filters to run,
  1381. since many others depend of it
  1382. *)
  1383. let run_filter gen is_hxgen_func =
  1384. let filter md =
  1385. let meta = if is_hxgen_func md then Meta.HxGen else Meta.NativeGen in
  1386. begin
  1387. match md with
  1388. | TClassDecl cl -> cl.cl_meta <- (meta, [], cl.cl_pos) :: cl.cl_meta
  1389. | TEnumDecl e -> e.e_meta <- (meta, [], e.e_pos) :: e.e_meta
  1390. | TTypeDecl t -> t.t_meta <- (meta, [], t.t_pos) :: t.t_meta
  1391. | TAbstractDecl a -> a.a_meta <- (meta, [], a.a_pos) :: a.a_meta
  1392. end
  1393. in
  1394. List.iter filter gen.gcon.types
  1395. end;;
  1396. (* ******************************************* *)
  1397. (* overloading reflection constructors *)
  1398. (* ******************************************* *)
  1399. (*
  1400. this module works on languages that support function overloading and
  1401. enable function hiding via static functions.
  1402. it takes the constructor body out of the constructor and adds it to a special ctor
  1403. static function. The static function will receive the same parameters as the constructor,
  1404. plus the special "me" var, which will replace "this"
  1405. Then it always adds two constructors to the function: one that receives a special class,
  1406. indicating that it should be constructed without any parameters, and one that receives its normal constructor.
  1407. Both will only include a super() call to the superclasses' emtpy constructor.
  1408. This enables two things:
  1409. empty construction without the need of incompatibility with the platform's native construction method
  1410. the ability to call super() constructor in any place in the constructor
  1411. This will insert itself in the default reflection-related module filter
  1412. *)
  1413. module OverloadingConstructor =
  1414. struct
  1415. let priority = 0.0
  1416. let name = "overloading_constructor"
  1417. let set_new_create_empty gen empty_ctor_expr =
  1418. let old = gen.gtools.rf_create_empty in
  1419. gen.gtools.rf_create_empty <- (fun cl params pos ->
  1420. if is_hxgen (TClassDecl cl) then
  1421. { eexpr = TNew(cl,params,[empty_ctor_expr]); etype = TInst(cl,params); epos = pos }
  1422. else
  1423. old cl params pos
  1424. )
  1425. let rec cur_ctor c tl =
  1426. match c.cl_constructor with
  1427. | Some ctor -> ctor, c, tl
  1428. | None -> match c.cl_super with
  1429. | None -> raise Not_found
  1430. | Some (sup,stl) ->
  1431. cur_ctor sup (List.map (apply_params c.cl_params tl) stl)
  1432. let rec prev_ctor c tl =
  1433. match c.cl_super with
  1434. | None -> raise Not_found
  1435. | Some (sup,stl) -> let stl = List.map (apply_params c.cl_params tl) stl in
  1436. match sup.cl_constructor with
  1437. | None -> prev_ctor sup stl
  1438. | Some ctor -> ctor, sup, stl
  1439. (* replaces super() call with last static constructor call *)
  1440. let replace_super_call gen name c tl with_params me p =
  1441. let rec loop_super c tl = match c.cl_super with
  1442. | None -> raise Not_found
  1443. | Some(sup,stl) ->
  1444. let stl = List.map (apply_params c.cl_params tl) stl in
  1445. try
  1446. let static_ctor_name = name ^ "_" ^ (String.concat "_" (fst sup.cl_path)) ^ "_" ^ (snd sup.cl_path) in
  1447. sup, stl, PMap.find static_ctor_name sup.cl_statics
  1448. with | Not_found ->
  1449. loop_super sup stl
  1450. in
  1451. let sup, stl, cf = loop_super c tl in
  1452. let with_params = { eexpr = TLocal me; etype = me.v_type; epos = p } :: with_params in
  1453. let cf = match cf.cf_overloads with
  1454. (* | [] -> cf *)
  1455. | _ -> try
  1456. (* choose best super function *)
  1457. List.iter (fun e -> replace_mono e.etype) with_params;
  1458. List.find (fun cf ->
  1459. replace_mono cf.cf_type;
  1460. let args, _ = get_fun (apply_params cf.cf_params stl cf.cf_type) in
  1461. try
  1462. List.for_all2 (fun (_,_,t) e -> try
  1463. let e_etype = run_follow gen e.etype in
  1464. let t = run_follow gen t in
  1465. unify e_etype t; true
  1466. with | Unify_error _ -> false) args with_params
  1467. with | Invalid_argument("List.for_all2") -> false
  1468. ) (cf :: cf.cf_overloads)
  1469. with | Not_found ->
  1470. gen.gcon.error "No suitable overload for the super call arguments was found" p; cf
  1471. in
  1472. {
  1473. eexpr = TCall({
  1474. eexpr = TField(
  1475. mk_classtype_access sup p,
  1476. FStatic(sup,cf));
  1477. etype = apply_params cf.cf_params stl cf.cf_type;
  1478. epos = p},
  1479. with_params);
  1480. etype = gen.gcon.basic.tvoid;
  1481. epos = p;
  1482. }
  1483. (* will create a static counterpart of 'ctor', and replace its contents to a call to the static version*)
  1484. let create_static_ctor gen ~empty_ctor_expr cl name ctor =
  1485. match Meta.has Meta.SkipCtor ctor.cf_meta with
  1486. | true -> ()
  1487. | false when is_none ctor.cf_expr -> ()
  1488. | false ->
  1489. let static_ctor_name = name ^ "_" ^ (String.concat "_" (fst cl.cl_path)) ^ "_" ^ (snd cl.cl_path) in
  1490. (* create the static constructor *)
  1491. let basic = gen.gcon.basic in
  1492. let ctor_types = List.map (fun (s,t) -> (s, TInst(map_param (get_cl_t t), []))) cl.cl_params in
  1493. let me = mk_temp gen "me" (TInst(cl, List.map snd ctor_types)) in
  1494. me.v_capture <- true;
  1495. let fn_args, _ = get_fun ctor.cf_type in
  1496. let ctor_params = List.map snd ctor_types in
  1497. let fn_type = TFun((me.v_name,false, me.v_type) :: List.map (fun (n,o,t) -> (n,o,apply_params cl.cl_params ctor_params t)) fn_args, basic.tvoid) in
  1498. let cur_tf_args = match ctor.cf_expr with
  1499. | Some { eexpr = TFunction(tf) } -> tf.tf_args
  1500. | _ -> assert false
  1501. in
  1502. let changed_tf_args = List.map (fun (v,_) -> (v,None)) cur_tf_args in
  1503. let local_map = Hashtbl.create (List.length cur_tf_args) in
  1504. let static_tf_args = (me, None) :: List.map (fun (v,b) ->
  1505. let new_v = alloc_var v.v_name (apply_params cl.cl_params ctor_params v.v_type) in
  1506. new_v.v_capture <- v.v_capture;
  1507. Hashtbl.add local_map v.v_id new_v;
  1508. (new_v, b)
  1509. ) cur_tf_args in
  1510. let static_ctor = mk_class_field static_ctor_name fn_type false ctor.cf_pos (Method MethNormal) ctor_types in
  1511. (* change ctor contents to reference the 'me' var instead of 'this' *)
  1512. let actual_super_call = ref None in
  1513. let rec map_expr ~is_first e = match e.eexpr with
  1514. | TCall (({ eexpr = TConst TSuper } as tsuper), params) -> (try
  1515. let params = List.map (fun e -> map_expr ~is_first:false e) params in
  1516. actual_super_call := Some { e with eexpr = TCall(tsuper, [empty_ctor_expr]) };
  1517. replace_super_call gen name cl ctor_params params me e.epos
  1518. with | Not_found ->
  1519. (* last static function was not found *)
  1520. actual_super_call := Some e;
  1521. if not is_first then
  1522. gen.gcon.error "Super call must be the first call when extending native types" e.epos;
  1523. { e with eexpr = TBlock([]) })
  1524. | TFunction tf when is_first ->
  1525. do_map ~is_first:true e
  1526. | TConst TThis ->
  1527. mk_local me e.epos
  1528. | TBlock (fst :: bl) ->
  1529. let fst = map_expr ~is_first:is_first fst in
  1530. { e with eexpr = TBlock(fst :: List.map (fun e -> map_expr ~is_first:false e) bl); etype = apply_params cl.cl_params ctor_params e.etype }
  1531. | _ ->
  1532. do_map e
  1533. and do_map ?(is_first=false) e =
  1534. let do_t = apply_params cl.cl_params ctor_params in
  1535. let do_v v = try
  1536. Hashtbl.find local_map v.v_id
  1537. with | Not_found ->
  1538. v.v_type <- do_t v.v_type; v
  1539. in
  1540. Type.map_expr_type (map_expr ~is_first:is_first) do_t do_v e
  1541. in
  1542. let expr = do_map ~is_first:true (get ctor.cf_expr) in
  1543. let expr = match expr.eexpr with
  1544. | TFunction(tf) ->
  1545. { expr with etype = fn_type; eexpr = TFunction({ tf with tf_args = static_tf_args }) }
  1546. | _ -> assert false in
  1547. static_ctor.cf_expr <- Some expr;
  1548. (* add to the statics *)
  1549. (try
  1550. let stat = PMap.find static_ctor_name cl.cl_statics in
  1551. stat.cf_overloads <- static_ctor :: stat.cf_overloads
  1552. with | Not_found ->
  1553. cl.cl_ordered_statics <- static_ctor :: cl.cl_ordered_statics;
  1554. cl.cl_statics <- PMap.add static_ctor_name static_ctor cl.cl_statics);
  1555. (* change current super call *)
  1556. match ctor.cf_expr with
  1557. | Some({ eexpr = TFunction(tf) } as e) ->
  1558. let block_contents, p = match !actual_super_call with
  1559. | None -> [], ctor.cf_pos
  1560. | Some super -> [super], super.epos
  1561. in
  1562. let block_contents = block_contents @ [{
  1563. eexpr = TCall(
  1564. {
  1565. eexpr = TField(
  1566. mk_classtype_access cl p,
  1567. FStatic(cl, static_ctor));
  1568. etype = apply_params static_ctor.cf_params (List.map snd cl.cl_params) static_ctor.cf_type;
  1569. epos = p
  1570. },
  1571. [{ eexpr = TConst TThis; etype = TInst(cl, List.map snd cl.cl_params); epos = p }]
  1572. @ List.map (fun (v,_) -> mk_local v p) cur_tf_args
  1573. );
  1574. etype = basic.tvoid;
  1575. epos = p
  1576. }] in
  1577. 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 }) }
  1578. | _ -> assert false
  1579. (* makes constructors that only call super() for the 'ctor' argument *)
  1580. let clone_ctors gen ctor sup stl cl =
  1581. let basic = gen.gcon.basic in
  1582. let rec clone cf =
  1583. let ncf = mk_class_field "new" (apply_params sup.cl_params stl cf.cf_type) cf.cf_public cf.cf_pos cf.cf_kind cf.cf_params in
  1584. let args, ret = get_fun ncf.cf_type in
  1585. (* single expression: call to super() *)
  1586. let tf_args = List.map (fun (name,_,t) ->
  1587. (* the constructor will have no optional arguments, as presumably this will be handled by the underlying expr *)
  1588. alloc_var name t, None
  1589. ) args in
  1590. let super_call =
  1591. {
  1592. eexpr = TCall(
  1593. { eexpr = TConst TSuper; etype = TInst(cl, List.map snd cl.cl_params); epos = ctor.cf_pos },
  1594. List.map (fun (v,_) -> mk_local v ctor.cf_pos) tf_args);
  1595. etype = basic.tvoid;
  1596. epos = ctor.cf_pos;
  1597. } in
  1598. ncf.cf_expr <- Some
  1599. {
  1600. eexpr = TFunction {
  1601. tf_args = tf_args;
  1602. tf_type = basic.tvoid;
  1603. tf_expr = mk_block super_call;
  1604. };
  1605. etype = ncf.cf_type;
  1606. epos = ctor.cf_pos;
  1607. };
  1608. ncf
  1609. in
  1610. (* take off createEmpty *)
  1611. let all = List.filter (fun cf -> replace_mono cf.cf_type; not (Meta.has Meta.SkipCtor cf.cf_meta)) (ctor :: ctor.cf_overloads) in
  1612. let clones = List.map clone all in
  1613. match clones with
  1614. | [] ->
  1615. (* raise Not_found *)
  1616. assert false (* should never happen *)
  1617. | cf :: [] -> cf
  1618. | cf :: overl ->
  1619. cf.cf_meta <- (Meta.Overload,[],cf.cf_pos) :: cf.cf_meta;
  1620. cf.cf_overloads <- overl; cf
  1621. let rec descends_from_native_or_skipctor cl =
  1622. not (is_hxgen (TClassDecl cl)) || Meta.has Meta.SkipCtor cl.cl_meta || match cl.cl_super with
  1623. | None -> false
  1624. | Some(c,_) -> descends_from_native_or_skipctor c
  1625. let ensure_super_is_first gen cf =
  1626. let rec loop e =
  1627. match e.eexpr with
  1628. | TBlock (b :: block) ->
  1629. loop b
  1630. | TBlock []
  1631. | TCall({ eexpr = TConst TSuper },_) -> ()
  1632. | _ ->
  1633. 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
  1634. in
  1635. match cf.cf_expr with
  1636. | None -> ()
  1637. | Some e -> Type.iter loop e
  1638. (* major restructring made at r6493 *)
  1639. let configure ~(empty_ctor_type : t) ~(empty_ctor_expr : texpr) ~supports_ctor_inheritance gen =
  1640. set_new_create_empty gen empty_ctor_expr;
  1641. let basic = gen.gcon.basic in
  1642. 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
  1643. let static_ctor_name = gen.gmk_internal_name "hx" "ctor" in
  1644. let msize = List.length gen.gcon.types in
  1645. let processed, empty_ctors = Hashtbl.create msize, Hashtbl.create msize in
  1646. let rec get_last_empty cl =
  1647. try
  1648. Hashtbl.find empty_ctors cl.cl_path
  1649. with | Not_found ->
  1650. match cl.cl_super with
  1651. | None -> raise Not_found
  1652. | Some (sup,_) -> get_last_empty sup
  1653. in
  1654. let rec change cl =
  1655. match Hashtbl.mem processed cl.cl_path with
  1656. | true -> ()
  1657. | false ->
  1658. Hashtbl.add processed cl.cl_path true;
  1659. (* make sure we've processed the super types *)
  1660. (match cl.cl_super with
  1661. | Some (super,_) when should_change super && not (Hashtbl.mem processed super.cl_path) ->
  1662. change super
  1663. | _ -> ());
  1664. (* implement static hx_ctor and reimplement constructors *)
  1665. (try
  1666. let ctor = match cl.cl_constructor with
  1667. | Some ctor -> ctor
  1668. | None -> try
  1669. let sctor, sup, stl = prev_ctor cl (List.map snd cl.cl_params) in
  1670. (* we have a previous constructor. if we support inheritance, exit *)
  1671. if supports_ctor_inheritance then raise Exit;
  1672. (* we'll make constructors that will only call super() *)
  1673. let ctor = clone_ctors gen sctor sup stl cl in
  1674. cl.cl_constructor <- Some ctor;
  1675. ctor
  1676. with | Not_found -> (* create default constructor *)
  1677. let ctor = mk_class_field "new" (TFun([], basic.tvoid)) false cl.cl_pos (Method MethNormal) [] in
  1678. ctor.cf_expr <- Some
  1679. {
  1680. eexpr = TFunction {
  1681. tf_args = [];
  1682. tf_type = basic.tvoid;
  1683. tf_expr = { eexpr = TBlock[]; etype = basic.tvoid; epos = cl.cl_pos };
  1684. };
  1685. etype = ctor.cf_type;
  1686. epos = ctor.cf_pos;
  1687. };
  1688. cl.cl_constructor <- Some ctor;
  1689. ctor
  1690. in
  1691. (* now that we made sure we have a constructor, exit if native gen *)
  1692. if not (is_hxgen (TClassDecl cl)) || Meta.has Meta.SkipCtor cl.cl_meta then begin
  1693. if descends_from_native_or_skipctor cl && is_some cl.cl_super then
  1694. List.iter (fun cf -> ensure_super_is_first gen cf) (ctor :: ctor.cf_overloads);
  1695. raise Exit
  1696. end;
  1697. (* if cl descends from a native class, we cannot use the static constructor strategy *)
  1698. if descends_from_native_or_skipctor cl && is_some cl.cl_super then
  1699. List.iter (fun cf -> ensure_super_is_first gen cf) (ctor :: ctor.cf_overloads)
  1700. else
  1701. (* now that we have a current ctor, create the static counterparts *)
  1702. List.iter (fun cf ->
  1703. create_static_ctor gen ~empty_ctor_expr:empty_ctor_expr cl static_ctor_name cf
  1704. ) (ctor :: ctor.cf_overloads)
  1705. with | Exit ->());
  1706. (* implement empty ctor *)
  1707. (try
  1708. (* now that we made sure we have a constructor, exit if native gen *)
  1709. if not (is_hxgen (TClassDecl cl)) then raise Exit;
  1710. (* get first *)
  1711. let empty_type = TFun(["empty",false,empty_ctor_type],basic.tvoid) in
  1712. let super = match cl.cl_super with
  1713. | None -> (* implement empty *)
  1714. []
  1715. | Some (sup,_) -> try
  1716. ignore (get_last_empty sup);
  1717. if supports_ctor_inheritance && is_none cl.cl_constructor then raise Exit;
  1718. [{
  1719. eexpr = TCall(
  1720. { eexpr = TConst TSuper; etype = TInst(cl, List.map snd cl.cl_params); epos = cl.cl_pos },
  1721. [ empty_ctor_expr ]);
  1722. etype = basic.tvoid;
  1723. epos = cl.cl_pos
  1724. }]
  1725. with | Not_found -> try
  1726. (* super type is native: find super constructor with least arguments *)
  1727. let sctor, sup, stl = prev_ctor cl (List.map snd cl.cl_params) in
  1728. let rec loop remaining (best,n) =
  1729. match remaining with
  1730. | [] -> best
  1731. | cf :: r ->
  1732. let args,_ = get_fun cf.cf_type in
  1733. if (List.length args) < n then
  1734. loop r (cf,List.length args)
  1735. else
  1736. loop r (best,n)
  1737. in
  1738. let args,_ = get_fun sctor.cf_type in
  1739. let best = loop sctor.cf_overloads (sctor, List.length args) in
  1740. let args,_ = get_fun best.cf_type in
  1741. [{
  1742. eexpr = TCall(
  1743. { eexpr = TConst TSuper; etype = TInst(cl, List.map snd cl.cl_params); epos = cl.cl_pos },
  1744. List.map (fun (n,o,t) -> null t cl.cl_pos) args);
  1745. etype = basic.tvoid;
  1746. epos = cl.cl_pos
  1747. }]
  1748. with | Not_found ->
  1749. (* extends native type, but no ctor found *)
  1750. []
  1751. in
  1752. let ctor = mk_class_field "new" empty_type false cl.cl_pos (Method MethNormal) [] in
  1753. ctor.cf_expr <- Some {
  1754. eexpr = TFunction {
  1755. tf_type = basic.tvoid;
  1756. tf_args = [alloc_var "empty" empty_ctor_type, None];
  1757. tf_expr = { eexpr = TBlock super; etype = basic.tvoid; epos = cl.cl_pos }
  1758. };
  1759. etype = empty_type;
  1760. epos = cl.cl_pos;
  1761. };
  1762. ctor.cf_meta <- [Meta.SkipCtor, [], ctor.cf_pos];
  1763. Hashtbl.add empty_ctors cl.cl_path ctor;
  1764. match cl.cl_constructor with
  1765. | None -> cl.cl_constructor <- Some ctor
  1766. | Some c -> c.cf_overloads <- ctor :: c.cf_overloads
  1767. with | Exit -> ());
  1768. in
  1769. let module_filter md = match md with
  1770. | TClassDecl cl when should_change cl && not (Hashtbl.mem processed cl.cl_path) ->
  1771. change cl;
  1772. None
  1773. | _ -> None
  1774. in
  1775. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) module_filter
  1776. end;;
  1777. (* ******************************************* *)
  1778. (* init function module *)
  1779. (* ******************************************* *)
  1780. (*
  1781. This module will take proper care of the init function, by taking off all expressions from static vars and putting them
  1782. in order in the init function.
  1783. It will also initialize dynamic functions, both by putting them in the constructor and in the init function
  1784. depends on:
  1785. (syntax) must run before ExprStatement module
  1786. (ok) must run before OverloadingCtor module so the constructor can be in the correct place
  1787. (syntax) must run before FunctionToClass module
  1788. *)
  1789. module InitFunction =
  1790. struct
  1791. let name = "init_funcs"
  1792. let priority = solve_deps name [DBefore OverloadingConstructor.priority]
  1793. let ensure_simple_expr gen e =
  1794. let rec iter e = match e.eexpr with
  1795. | TConst _ | TLocal _ | TArray _ | TBinop _
  1796. | TField _ | TTypeExpr _ | TParenthesis _
  1797. | TCall _ | TNew _ | TUnop _ ->
  1798. Type.iter iter e
  1799. | _ ->
  1800. gen.gcon.error "Expression is too complex for a readonly variable initialization" e.epos
  1801. in
  1802. iter e
  1803. let configure gen should_handle_dynamic_functions readonly_support =
  1804. let handle_override_dynfun acc e this field =
  1805. let add_expr = ref None in
  1806. let v = mk_temp gen ("super_" ^ field) e.etype in
  1807. v.v_capture <- true;
  1808. let rec loop e =
  1809. match e.eexpr with
  1810. | TField({ eexpr = TConst(TSuper) }, f) ->
  1811. let n = field_name f in
  1812. (if n <> field then assert false);
  1813. let local = mk_local v e.epos in
  1814. (match !add_expr with
  1815. | None ->
  1816. add_expr := Some { e with eexpr = TVar(v, Some this) }
  1817. | Some _ -> ());
  1818. local
  1819. | TConst TSuper -> assert false
  1820. | _ -> Type.map_expr loop e
  1821. in
  1822. let e = loop e in
  1823. match !add_expr with
  1824. | None -> e :: acc
  1825. | Some add_expr -> add_expr :: e :: acc
  1826. in
  1827. let handle_class cl =
  1828. let init = match cl.cl_init with
  1829. | None -> []
  1830. | Some i -> [i]
  1831. in
  1832. let init = List.fold_left (fun acc cf ->
  1833. match cf.cf_kind, should_handle_dynamic_functions with
  1834. | (Var v, _) when Meta.has Meta.ReadOnly cf.cf_meta && readonly_support ->
  1835. if v.v_write <> AccNever then gen.gcon.warning "@:readOnly variable declared without `never` setter modifier" cf.cf_pos;
  1836. (match cf.cf_expr with
  1837. | None -> gen.gcon.warning "Uninitialized readonly variable" cf.cf_pos; acc
  1838. | Some e -> ensure_simple_expr gen e; acc)
  1839. | (Var _, _)
  1840. | (Method (MethDynamic), true) when not (Type.is_extern_field cf) ->
  1841. (match cf.cf_expr with
  1842. | Some e ->
  1843. (match cf.cf_params with
  1844. | [] ->
  1845. let var = { eexpr = TField(mk_classtype_access cl cf.cf_pos, FStatic(cl,cf)); etype = cf.cf_type; epos = cf.cf_pos } in
  1846. let ret = ({ eexpr = TBinop(Ast.OpAssign, var, e); etype = cf.cf_type; epos = cf.cf_pos; }) in
  1847. cf.cf_expr <- None;
  1848. ret :: acc
  1849. | _ ->
  1850. let params = List.map (fun _ -> t_dynamic) cf.cf_params in
  1851. let fn = apply_params cf.cf_params params in
  1852. let var = { eexpr = TField(mk_classtype_access cl cf.cf_pos, FStatic(cl,cf)); etype = fn cf.cf_type; epos = cf.cf_pos } in
  1853. let rec change_expr e =
  1854. Type.map_expr_type (change_expr) fn (fun v -> v.v_type <- fn v.v_type; v) e
  1855. in
  1856. let ret = ({ eexpr = TBinop(Ast.OpAssign, var, change_expr e); etype = fn cf.cf_type; epos = cf.cf_pos; }) in
  1857. cf.cf_expr <- None;
  1858. ret :: acc
  1859. )
  1860. | None -> acc)
  1861. | _ -> acc
  1862. ) init cl.cl_ordered_statics
  1863. in
  1864. let init = List.rev init in
  1865. (match init with
  1866. | [] -> cl.cl_init <- None
  1867. | _ -> cl.cl_init <- Some { eexpr = TBlock(init); epos = cl.cl_pos; etype = gen.gcon.basic.tvoid; });
  1868. (* FIXME: find a way to tell OverloadingCtors to execute this code even with empty constructors *)
  1869. if should_handle_dynamic_functions then begin
  1870. let vars, funs = List.fold_left (fun (acc_vars,acc_funs) cf ->
  1871. match cf.cf_kind with
  1872. | Var v when Meta.has Meta.ReadOnly cf.cf_meta && readonly_support ->
  1873. if v.v_write <> AccNever then gen.gcon.warning "@:readOnly variable declared without `never` setter modifier" cf.cf_pos;
  1874. (match cf.cf_expr with
  1875. | None -> (acc_vars,acc_funs)
  1876. | Some e -> ensure_simple_expr gen e; (acc_vars,acc_funs))
  1877. | Var _
  1878. | Method(MethDynamic) ->
  1879. let is_var = match cf.cf_kind with | Var _ -> true | _ -> false in
  1880. (match cf.cf_expr, cf.cf_params with
  1881. | Some e, [] ->
  1882. let var = { eexpr = TField({ eexpr = TConst(TThis); epos = cf.cf_pos; etype = TInst(cl, List.map snd cl.cl_params); }, FInstance(cl, List.map snd cl.cl_params, cf)); etype = cf.cf_type; epos = cf.cf_pos } in
  1883. let ret = ({ eexpr = TBinop(Ast.OpAssign, var, e); etype = cf.cf_type; epos = cf.cf_pos; }) in
  1884. cf.cf_expr <- None;
  1885. let is_override = List.memq cf cl.cl_overrides in
  1886. if is_override then begin
  1887. cl.cl_ordered_fields <- List.filter (fun f -> f.cf_name <> cf.cf_name) cl.cl_ordered_fields;
  1888. cl.cl_fields <- PMap.remove cf.cf_name cl.cl_fields;
  1889. acc_vars, handle_override_dynfun acc_funs ret var cf.cf_name
  1890. end else if is_var then
  1891. ret :: acc_vars, acc_funs
  1892. else
  1893. acc_vars, ret :: acc_funs
  1894. | Some e, _ ->
  1895. let params = List.map (fun _ -> t_dynamic) cf.cf_params in
  1896. let fn = apply_params cf.cf_params params in
  1897. let var = { eexpr = TField({ eexpr = TConst(TThis); epos = cf.cf_pos; etype = TInst(cl, List.map snd cl.cl_params); }, FInstance(cl, List.map snd cl.cl_params, cf)); etype = cf.cf_type; epos = cf.cf_pos } in
  1898. let rec change_expr e =
  1899. Type.map_expr_type (change_expr) fn (fun v -> v.v_type <- fn v.v_type; v) e
  1900. in
  1901. let ret = ({ eexpr = TBinop(Ast.OpAssign, var, change_expr e); etype = fn cf.cf_type; epos = cf.cf_pos; }) in
  1902. cf.cf_expr <- None;
  1903. let is_override = List.memq cf cl.cl_overrides in
  1904. if is_override then begin
  1905. cl.cl_ordered_fields <- List.filter (fun f -> f.cf_name <> cf.cf_name) cl.cl_ordered_fields;
  1906. cl.cl_fields <- PMap.remove cf.cf_name cl.cl_fields;
  1907. acc_vars, handle_override_dynfun acc_funs ret var cf.cf_name
  1908. end else if is_var then
  1909. ret :: acc_vars, acc_funs
  1910. else
  1911. acc_vars, ret :: acc_funs
  1912. | None, _ -> acc_vars,acc_funs)
  1913. | _ -> acc_vars,acc_funs
  1914. ) ([],[]) cl.cl_ordered_fields
  1915. in
  1916. (* let vars = List.rev vars in *)
  1917. (* let funs = List.rev funs in *)
  1918. (* see if there is any *)
  1919. (match vars, funs with
  1920. | [], [] -> ()
  1921. | _ ->
  1922. (* if there is, we need to find the constructor *)
  1923. let ctors = match cl.cl_constructor with
  1924. | Some ctor -> ctor
  1925. | None -> try
  1926. let sctor, sup, stl = OverloadingConstructor.prev_ctor cl (List.map snd cl.cl_params) in
  1927. let ctor = OverloadingConstructor.clone_ctors gen sctor sup stl cl in
  1928. cl.cl_constructor <- Some ctor;
  1929. ctor
  1930. with | Not_found ->
  1931. let basic = gen.gcon.basic in
  1932. let ctor = mk_class_field "new" (TFun([], basic.tvoid)) false cl.cl_pos (Method MethNormal) [] in
  1933. ctor.cf_expr <- Some
  1934. {
  1935. eexpr = TFunction {
  1936. tf_args = [];
  1937. tf_type = basic.tvoid;
  1938. tf_expr = { eexpr = TBlock[]; etype = basic.tvoid; epos = cl.cl_pos };
  1939. };
  1940. etype = ctor.cf_type;
  1941. epos = ctor.cf_pos;
  1942. };
  1943. cl.cl_constructor <- Some ctor;
  1944. ctor
  1945. in
  1946. let process ctor =
  1947. let func = match ctor.cf_expr with
  1948. | Some({eexpr = TFunction(tf)} as e) ->
  1949. let rec add_fn e = match e.eexpr with
  1950. | TBlock(hd :: tl) -> (match hd.eexpr with
  1951. | TCall({ eexpr = TConst TSuper }, _) ->
  1952. if is_hxgen (TClassDecl cl) then
  1953. { e with eexpr = TBlock(vars @ (hd :: (funs @ tl))) }
  1954. else
  1955. { e with eexpr = TBlock(hd :: (vars @ funs @ tl)) }
  1956. | TBlock(_) ->
  1957. { e with eexpr = TBlock( (add_fn hd) :: tl ) }
  1958. | _ ->
  1959. { e with eexpr = TBlock( vars @ funs @ (hd :: tl) ) })
  1960. | _ -> Type.concat { e with eexpr = TBlock(vars @ funs) } e
  1961. in
  1962. let tf_expr = add_fn (mk_block tf.tf_expr) in
  1963. { e with eexpr = TFunction({ tf with tf_expr = tf_expr }) }
  1964. | _ -> assert false
  1965. in
  1966. ctor.cf_expr <- Some(func)
  1967. in
  1968. List.iter process (ctors :: ctors.cf_overloads)
  1969. )
  1970. end
  1971. in
  1972. let mod_filter = function
  1973. | TClassDecl cl -> (if not cl.cl_extern then handle_class cl); None
  1974. | _ -> None in
  1975. gen.gmodule_filters#add ~name:"init_funcs" ~priority:(PCustom priority) mod_filter
  1976. end;;
  1977. (* ******************************************* *)
  1978. (* Dynamic Binop/Unop handler *)
  1979. (* ******************************************* *)
  1980. (*
  1981. On some languages there is limited support for operations on
  1982. dynamic variables, so those operations must be changed.
  1983. There are 5 types of binary operators:
  1984. 1 - can take any variable and returns a bool (== and !=)
  1985. 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)
  1986. 3 - take numbers and return a number ( *, /, ...)
  1987. 4 - take ints and return an int (bit manipulation)
  1988. 5 - take a bool and returns a bool ( &&, || ...)
  1989. On the default implementation, type 1 and the plus function will be handled with a function call;
  1990. Type 2 will be handled with the parameter "compare_handler", which will do something like Reflect.compare(x1, x2);
  1991. Types 3, 4 and 5 will perform a cast to double, int and bool, which will then be handled normally by the platform
  1992. Unary operators are the most difficult to handle correctly.
  1993. With unary operators, there are 2 types:
  1994. 1 - can take a number, changes and returns the result (++, --, ~)
  1995. 2 - can take a number (-) or bool (!), and returns the result
  1996. 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,
  1997. but this is how we will handle right now.
  1998. something like that:
  1999. var x:Dynamic = 10;
  2000. x++;
  2001. will be:
  2002. object x = 10;
  2003. x = ((IConvertible)x).ToDouble(null) + 1;
  2004. depends on:
  2005. (syntax) must run before expression/statment normalization because it may generate complex expressions
  2006. must run before OverloadingCtor due to later priority conflicts. Since ExpressionUnwrap is only
  2007. defined afterwards, we will set this value with absolute values
  2008. *)
  2009. module DynamicOperators =
  2010. struct
  2011. let name = "dyn_ops"
  2012. let priority = 0.0
  2013. let priority_as_synf = 100.0 (*solve_deps name [DBefore ExpressionUnwrap.priority]*)
  2014. 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) =
  2015. let get_etype_one e =
  2016. if like_int e.etype then
  2017. (gen.gcon.basic.tint, { eexpr = TConst(TInt(Int32.one)); etype = gen.gcon.basic.tint; epos = e.epos })
  2018. else
  2019. (gen.gcon.basic.tfloat, { eexpr = TConst(TFloat("1.0")); etype = gen.gcon.basic.tfloat; epos = e.epos })
  2020. in
  2021. let basic = gen.gcon.basic in
  2022. let rec run e =
  2023. match e.eexpr with
  2024. | TBinop (OpAssignOp op, e1, e2) when should_change e -> (* e1 will never contain another TBinop *)
  2025. (match e1.eexpr with
  2026. | TLocal _ ->
  2027. mk_paren { e with eexpr = TBinop(OpAssign, e1, run { e with eexpr = TBinop(op, e1, e2) }) }
  2028. | TField _ | TArray _ ->
  2029. let eleft, rest = match e1.eexpr with
  2030. | TField(ef, f) ->
  2031. let v = mk_temp gen "dynop" ef.etype in
  2032. { e1 with eexpr = TField(mk_local v ef.epos, f) }, [ { eexpr = TVar(v,Some (run ef)); etype = basic.tvoid; epos = ef.epos } ]
  2033. | TArray(e1a, e2a) ->
  2034. let v = mk_temp gen "dynop" e1a.etype in
  2035. let v2 = mk_temp gen "dynopi" e2a.etype in
  2036. { e1 with eexpr = TArray(mk_local v e1a.epos, mk_local v2 e2a.epos) }, [
  2037. { eexpr = TVar(v,Some (run e1a)); etype = basic.tvoid; epos = e1.epos };
  2038. { eexpr = TVar(v2, Some (run e2a)); etype = basic.tvoid; epos = e1.epos }
  2039. ]
  2040. | _ -> assert false
  2041. in
  2042. { e with
  2043. eexpr = TBlock (rest @ [ { e with eexpr = TBinop(OpAssign, eleft, run { e with eexpr = TBinop(op, eleft, e2) }) } ]);
  2044. }
  2045. | _ ->
  2046. assert false
  2047. )
  2048. | TBinop (OpAssign, e1, e2)
  2049. | TBinop (OpInterval, e1, e2) -> Type.map_expr run e
  2050. | TBinop (op, e1, e2) when should_change e->
  2051. (match op with
  2052. | OpEq -> (* type 1 *)
  2053. equals_handler (run e1) (run e2)
  2054. | OpNotEq -> (* != -> !equals() *)
  2055. mk_paren { eexpr = TUnop(Ast.Not, Prefix, (equals_handler (run e1) (run e2))); etype = gen.gcon.basic.tbool; epos = e.epos }
  2056. | OpAdd ->
  2057. if handle_strings && (is_string e.etype || is_string e1.etype || is_string e2.etype) then
  2058. { e with eexpr = TBinop(op, mk_cast gen.gcon.basic.tstring (run e1), mk_cast gen.gcon.basic.tstring (run e2)) }
  2059. else
  2060. dyn_plus_handler e (run e1) (run e2)
  2061. | OpGt | OpGte | OpLt | OpLte -> (* type 2 *)
  2062. { 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 }
  2063. | OpMult | OpDiv | OpSub | OpMod -> (* always cast everything to double *)
  2064. let etype, _ = get_etype_one e in
  2065. { e with eexpr = TBinop(op, mk_cast etype (run e1), mk_cast etype (run e2)) }
  2066. | OpBoolAnd | OpBoolOr ->
  2067. { e with eexpr = TBinop(op, mk_cast gen.gcon.basic.tbool (run e1), mk_cast gen.gcon.basic.tbool (run e2)) }
  2068. | OpAnd | OpOr | OpXor | OpShl | OpShr | OpUShr ->
  2069. { e with eexpr = TBinop(op, mk_cast gen.gcon.basic.tint (run e1), mk_cast gen.gcon.basic.tint (run e2)) }
  2070. | OpAssign | OpAssignOp _ | OpInterval | OpArrow -> assert false)
  2071. | TUnop (Increment as op, flag, e1)
  2072. | TUnop (Decrement as op, flag, e1) when should_change e ->
  2073. (*
  2074. some naming definitions:
  2075. * ret => the returning variable
  2076. * _g => the get body
  2077. * getvar => the get variable expr
  2078. This will work like this:
  2079. - if e1 is a TField, set _g = get body, getvar = (get body).varname
  2080. - if Prefix, return getvar = getvar + 1.0
  2081. - if Postfix, set ret = getvar; getvar = getvar + 1.0; ret;
  2082. *)
  2083. let etype, one = get_etype_one e in
  2084. let op = (match op with Increment -> OpAdd | Decrement -> OpSub | _ -> assert false) in
  2085. let var, getvar =
  2086. match e1.eexpr with
  2087. | TField(fexpr, field) ->
  2088. let tmp = mk_temp gen "getvar" fexpr.etype in
  2089. let var = { eexpr = TVar(tmp, Some(run fexpr)); etype = gen.gcon.basic.tvoid; epos = e.epos } in
  2090. (Some var, { eexpr = TField( { fexpr with eexpr = TLocal(tmp) }, field); etype = etype; epos = e1.epos })
  2091. | _ ->
  2092. (None, e1)
  2093. in
  2094. (match flag with
  2095. | Prefix ->
  2096. let block = (match var with | Some e -> [e] | None -> []) @
  2097. [
  2098. 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; }
  2099. ]
  2100. in
  2101. { eexpr = TBlock(block); etype = etype; epos = e.epos }
  2102. | Postfix ->
  2103. let ret = mk_temp gen "ret" etype in
  2104. 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
  2105. let retlocal = { eexpr = TLocal(ret); etype = etype; epos = e.epos } in
  2106. let block = vars @
  2107. [
  2108. { e with eexpr = TBinop(OpAssign, getvar, { eexpr = TBinop(op, retlocal, one); etype = getvar.etype; epos = e.epos }) };
  2109. retlocal
  2110. ] in
  2111. { eexpr = TBlock(block); etype = etype; epos = e.epos }
  2112. )
  2113. | TUnop (op, flag, e1) when should_change e ->
  2114. let etype = match op with | Not -> gen.gcon.basic.tbool | _ -> gen.gcon.basic.tint in
  2115. mk_paren { eexpr = TUnop(op, flag, mk_cast etype (run e1)); etype = etype; epos = e.epos }
  2116. | _ -> Type.map_expr run e
  2117. in
  2118. run
  2119. let configure gen (mapping_func:texpr->texpr) =
  2120. let map e = Some(mapping_func e) in
  2121. gen.gexpr_filters#add ~name:"dyn_ops" ~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:"dyn_ops" ~priority:(PCustom priority_as_synf) map
  2125. end;;
  2126. (* ******************************************* *)
  2127. (* Dynamic Field Access *)
  2128. (* ******************************************* *)
  2129. (*
  2130. This module will filter every dynamic field access in haxe.
  2131. On platforms that do not support dynamic access, it is with this that you should
  2132. replace dynamic calls with x.field / Reflect.setField calls, and guess what -
  2133. this is the default implemenation!
  2134. Actually there is a problem with Reflect.setField because it returns void, which is a bad thing for us,
  2135. so even in the default implementation, the function call should be specified to a Reflect.setField version that returns
  2136. the value that was set
  2137. (TODO: should it be separated?)
  2138. As a plus, the default implementation adds something that doesn't hurt anybody, it looks for
  2139. TAnon with Statics / EnumStatics field accesses and transforms them into real static calls.
  2140. This means it will take this
  2141. var m = Math;
  2142. for (i in 0...1000) m.cos(10);
  2143. which is an optimization in dynamic platforms, but performs horribly on strongly typed platforms
  2144. and transform into:
  2145. var m = Math;
  2146. for (i in 0...1000) Math.cos(10);
  2147. (addendum:)
  2148. configure_generate_classes will already take care of generating the reflection-enabled class fields and calling abstract_implementation
  2149. with the right arguments.
  2150. Also
  2151. depends on:
  2152. (ok) must run AFTER Binop/Unop handler - so Unops / Binops are already unrolled
  2153. *)
  2154. module DynamicFieldAccess =
  2155. struct
  2156. let name = "dynamic_field_access"
  2157. let priority = solve_deps name [DAfter DynamicOperators.priority]
  2158. let priority_as_synf = solve_deps name [DAfter DynamicOperators.priority_as_synf]
  2159. (*
  2160. is_dynamic (expr) (field_access_expr) (field) : a function that indicates if the field access should be changed
  2161. change_expr (expr) (field_access_expr) (field) (setting expr) (is_unsafe) : changes the expression
  2162. call_expr (expr) (field_access_expr) (field) (call_params) : changes a call expression
  2163. *)
  2164. 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) =
  2165. let rec run e =
  2166. match e.eexpr with
  2167. (* class types *)
  2168. | TField(fexpr, f) when is_some (anon_class fexpr.etype) ->
  2169. let decl = get (anon_class fexpr.etype) in
  2170. let name = field_name f in
  2171. (try
  2172. match decl with
  2173. | TClassDecl cl ->
  2174. let cf = PMap.find name cl.cl_statics in
  2175. { e with eexpr = TField({ fexpr with eexpr = TTypeExpr decl }, FStatic(cl, cf)) }
  2176. | TEnumDecl en ->
  2177. let ef = PMap.find name en.e_constrs in
  2178. { e with eexpr = TField({ fexpr with eexpr = TTypeExpr decl }, FEnum(en, ef)) }
  2179. | TAbstractDecl _ -> (* abstracts don't have TFields *) assert false
  2180. | TTypeDecl _ -> (* anon_class doesn't return TTypeDecl *) assert false
  2181. with
  2182. | Not_found -> match f with
  2183. | FStatic(cl,cf) when Meta.has Meta.Extern cf.cf_meta ->
  2184. { e with eexpr = TField({ fexpr with eexpr = TTypeExpr decl }, FStatic(cl, cf)) }
  2185. | _ ->
  2186. change_expr e { fexpr with eexpr = TTypeExpr decl } (field_name f) None true
  2187. )
  2188. | TField(fexpr, f) when is_dynamic e fexpr (f) ->
  2189. change_expr e (run fexpr) (field_name f) None true
  2190. | TCall(
  2191. { eexpr = TField(_, FStatic({ cl_path = ([], "Reflect") }, { cf_name = "field" })) } ,
  2192. [obj; { eexpr = TConst(TString(field)) }]
  2193. ) ->
  2194. let t = match gen.greal_type obj.etype with
  2195. | TDynamic _ | TAnon _ | TMono _ -> t_dynamic
  2196. | t -> t
  2197. in
  2198. change_expr (mk_field_access gen { obj with etype = t } field obj.epos) (run obj) field None false
  2199. | TCall(
  2200. { eexpr = TField(_, FStatic({ cl_path = ([], "Reflect") }, { cf_name = "setField" } )) },
  2201. [obj; { eexpr = TConst(TString(field)) }; evalue]
  2202. ) ->
  2203. change_expr (mk_field_access gen obj field obj.epos) (run obj) field (Some (run evalue)) false
  2204. | TBinop(OpAssign, ({eexpr = TField(fexpr, f)}), evalue) when is_dynamic e fexpr (f) ->
  2205. change_expr e (run fexpr) (field_name f) (Some (run evalue)) true
  2206. | TBinop(OpAssign, { eexpr = TField(fexpr, f) }, evalue) ->
  2207. (match field_access_esp gen fexpr.etype (f) with
  2208. | FClassField(_,_,_,cf,false,t,_) when (try PMap.find cf.cf_name gen.gbase_class_fields == cf with Not_found -> false) ->
  2209. change_expr e (run fexpr) (field_name f) (Some (run evalue)) true
  2210. | _ -> Type.map_expr run e
  2211. )
  2212. (* #if debug *)
  2213. | TBinop(OpAssignOp op, ({eexpr = TField(fexpr, f)}), evalue) when is_dynamic e fexpr (f) -> assert false (* this case shouldn't happen *)
  2214. | TUnop(Increment, _, ({eexpr = TField( ( { eexpr=TLocal(local) } as fexpr ), f)}))
  2215. | TUnop(Decrement, _, ({eexpr = TField( ( { eexpr=TLocal(local) } as fexpr ), f)})) when is_dynamic e fexpr (f) -> assert false (* this case shouldn't happen *)
  2216. (* #end *)
  2217. | TCall( ({ eexpr = TField(fexpr, f) }), params ) when is_dynamic e fexpr (f) ->
  2218. call_expr e (run fexpr) (field_name f) (List.map run params)
  2219. | _ -> Type.map_expr run e
  2220. in run
  2221. (*
  2222. this function will already configure with the abstract implementation, and also will create the needed class fields to
  2223. enable reflection on platforms that don't support reflection.
  2224. this means it will create the following class methods:
  2225. - getField(field, isStatic) - gets the value of the field. isStatic
  2226. - setField -
  2227. -
  2228. *)
  2229. let configure_generate_classes gen optimize (runtime_getset_field:texpr->texpr->string->texpr option->texpr) (runtime_call_expr:texpr->texpr->string->texpr list->texpr) =
  2230. ()
  2231. let configure gen (mapping_func:texpr->texpr) =
  2232. let map e = Some(mapping_func e) in
  2233. gen.gexpr_filters#add ~name:"dynamic_field_access" ~priority:(PCustom(priority)) map
  2234. let configure_as_synf gen (mapping_func:texpr->texpr) =
  2235. let map e = Some(mapping_func e) in
  2236. gen.gexpr_filters#add ~name:"dynamic_field_access" ~priority:(PCustom(priority_as_synf)) map
  2237. end;;
  2238. (* ******************************************* *)
  2239. (* Closure Detection *)
  2240. (* ******************************************* *)
  2241. (*
  2242. Just a small utility filter that detects when a closure must be created.
  2243. On the default implementation, this means when a function field is being accessed
  2244. not via reflection and not to be called instantly
  2245. dependencies:
  2246. must run after DynamicFieldAccess, so any TAnon { Statics / EnumStatics } will be changed to the corresponding TTypeExpr
  2247. *)
  2248. module FilterClosures =
  2249. struct
  2250. let name = "filter_closures"
  2251. let priority = solve_deps name [DAfter DynamicFieldAccess.priority]
  2252. let traverse gen (should_change:texpr->string->bool) (filter:texpr->texpr->string->bool->texpr) =
  2253. let rec run e =
  2254. match e.eexpr with
  2255. (*(* this is precisely the only case where we won't even ask if we should change, because it is a direct use of TClosure *)
  2256. | TCall ( {eexpr = TClosure(e1,s)} as clos, args ) ->
  2257. { e with eexpr = TCall({ clos with eexpr = TClosure(run e1, s) }, List.map run args ) }
  2258. | TCall ( clos, args ) ->
  2259. let rec loop clos = match clos.eexpr with
  2260. | TClosure(e1,s) -> Some (clos, e1, s)
  2261. | TParenthesis p -> loop p
  2262. | _ -> None
  2263. in
  2264. let clos = loop clos in
  2265. (match clos with
  2266. | Some (clos, e1, s) -> { e with eexpr = TCall({ clos with eexpr = TClosure(run e1, s) }, List.map run args ) }
  2267. | None -> Type.map_expr run e)*)
  2268. | TCall({ eexpr = TLocal{ v_name = "__delegate__" } } as local, [del]) ->
  2269. { e with eexpr = TCall(local, [Type.map_expr run del]) }
  2270. | TCall(({ eexpr = TField(_, _) } as ef), params) ->
  2271. { e with eexpr = TCall(Type.map_expr run ef, List.map run params) }
  2272. | TField(ef, FEnum(en, field)) ->
  2273. (* FIXME replace t_dynamic with actual enum Anon field *)
  2274. let ef = run ef in
  2275. (match follow field.ef_type with
  2276. | TFun _ when should_change ef field.ef_name ->
  2277. filter e ef field.ef_name true
  2278. | _ ->
  2279. { e with eexpr = TField(ef, FEnum(en,field)) }
  2280. )
  2281. | TField(({ eexpr = TTypeExpr _ } as tf), f) ->
  2282. (match field_access_esp gen tf.etype (f) with
  2283. | FClassField(_,_,_,cf,_,_,_) ->
  2284. (match cf.cf_kind with
  2285. | Method(MethDynamic)
  2286. | Var _ ->
  2287. e
  2288. | _ when should_change tf cf.cf_name ->
  2289. filter e tf cf.cf_name true
  2290. | _ ->
  2291. e
  2292. )
  2293. | _ -> e)
  2294. | TField(e1, FClosure (Some _, cf)) when should_change e1 cf.cf_name ->
  2295. (match cf.cf_kind with
  2296. | Method MethDynamic | Var _ ->
  2297. Type.map_expr run e
  2298. | _ ->
  2299. filter e (run e1) cf.cf_name false)
  2300. | _ -> Type.map_expr run e
  2301. in
  2302. run
  2303. let configure gen (mapping_func:texpr->texpr) =
  2304. let map e = Some(mapping_func e) in
  2305. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority) map
  2306. end;;
  2307. (* ******************************************* *)
  2308. (* Dynamic TArray Handling *)
  2309. (* ******************************************* *)
  2310. (*
  2311. In some languages you cannot overload the [] operator,
  2312. so we need to decide what is kept as TArray and what gets mapped.
  2313. - in order to do this you must ensure that
  2314. depends on:
  2315. (syntax) must run before expression/statment normalization because it may generate complex expressions
  2316. (ok) must run before binop transformations because it may generate some untreated binop ops
  2317. (ok) must run before dynamic field access is transformed into reflection
  2318. *)
  2319. module TArrayTransform =
  2320. struct
  2321. let name = "dyn_tarray"
  2322. let priority = solve_deps name [DBefore DynamicOperators.priority; DBefore DynamicFieldAccess.priority]
  2323. let priority_as_synf = solve_deps name [DBefore DynamicOperators.priority_as_synf; DBefore DynamicFieldAccess.priority_as_synf]
  2324. (* should change signature: tarray expr -> binop operation -> should change? *)
  2325. let default_implementation gen (should_change:texpr->Ast.binop option->bool) (get_fun:string) (set_fun:string) =
  2326. let basic = gen.gcon.basic in
  2327. let mk_get e e1 e2 =
  2328. let efield = mk_field_access gen e1 get_fun e.epos in
  2329. { e with eexpr = TCall(efield, [e2]) }
  2330. in
  2331. let mk_set e e1 e2 evalue =
  2332. let efield = mk_field_access gen e1 set_fun e.epos in
  2333. { e with eexpr = TCall(efield, [e2; evalue]) }
  2334. in
  2335. let rec run e =
  2336. match e.eexpr with
  2337. | TArray(e1, e2) ->
  2338. (* e1 should always be a var; no need to map there *)
  2339. if should_change e None then mk_get e (run e1) (run e2) else Type.map_expr run e
  2340. | TBinop (Ast.OpAssign, ({ eexpr = TArray(e1a,e2a) } as earray), evalue) when should_change earray (Some Ast.OpAssign) ->
  2341. mk_set e (run e1a) (run e2a) (run evalue)
  2342. | TBinop (Ast.OpAssignOp op,({ eexpr = TArray(e1a,e2a) } as earray) , evalue) when should_change earray (Some (Ast.OpAssignOp op)) ->
  2343. (* cache all arguments in vars so they don't get executed twice *)
  2344. (* let ensure_local gen block name e = *)
  2345. let block = ref [] in
  2346. let arr_local = ensure_local gen block "array" (run e1a) in
  2347. let idx_local = ensure_local gen block "index" (run e2a) in
  2348. block := (mk_set e arr_local idx_local ( { e with eexpr=TBinop(op, mk_get earray arr_local idx_local, run evalue) } )) :: !block;
  2349. { e with eexpr = TBlock (List.rev !block) }
  2350. | TUnop(op, flag, ({ eexpr = TArray(e1a, e2a) } as earray)) ->
  2351. if should_change earray None && match op with | Not | Neg -> false | _ -> true then begin
  2352. let block = ref [] in
  2353. let actual_t = match op with
  2354. | Ast.Increment | Ast.Decrement -> (match follow earray.etype with
  2355. | TInst _ | TAbstract _ | TEnum _ -> earray.etype
  2356. | _ -> basic.tfloat)
  2357. | Ast.Not -> basic.tbool
  2358. | _ -> basic.tint
  2359. in
  2360. let val_v = mk_temp gen "arrVal" actual_t in
  2361. let ret_v = mk_temp gen "arrRet" actual_t in
  2362. let arr_local = ensure_local gen block "arr" (run e1a) in
  2363. let idx_local = ensure_local gen block "arrIndex" (run e2a) in
  2364. let val_local = { earray with eexpr = TLocal(val_v) } in
  2365. let ret_local = { earray with eexpr = TLocal(ret_v) } in
  2366. (* var idx = 1; var val = x._get(idx); var ret = val++; x._set(idx, val); ret; *)
  2367. block := { eexpr = TVar(val_v, Some(mk_get earray arr_local idx_local)); (* var val = x._get(idx) *)
  2368. etype = gen.gcon.basic.tvoid;
  2369. epos = e2a.epos
  2370. } :: !block;
  2371. block := { eexpr = TVar(ret_v, Some { e with eexpr = TUnop(op, flag, val_local) }); (* var ret = val++ *)
  2372. etype = gen.gcon.basic.tvoid;
  2373. epos = e2a.epos
  2374. } :: !block;
  2375. block := (mk_set e arr_local idx_local val_local) (*x._set(idx,val)*) :: !block;
  2376. block := ret_local :: !block;
  2377. { e with eexpr = TBlock (List.rev !block) }
  2378. end else
  2379. Type.map_expr run e
  2380. | _ -> Type.map_expr run e
  2381. in run
  2382. let configure gen (mapping_func:texpr->texpr) =
  2383. let map e = Some(mapping_func e) in
  2384. gen.gexpr_filters#add ~name:"dyn_tarray" ~priority:(PCustom priority) map
  2385. let configure_as_synf gen (mapping_func:texpr->texpr) =
  2386. let map e = Some(mapping_func e) in
  2387. gen.gexpr_filters#add ~name:"dyn_tarray" ~priority:(PCustom priority_as_synf) map
  2388. end;;
  2389. (* ******************************************* *)
  2390. (* Try / Catch + throw native types handling *)
  2391. (* ******************************************* *)
  2392. (*
  2393. Some languages/vm's do not support throwing any kind of value. For them, only
  2394. special kinds of objects can be thrown. Because of this, we must wrap some throw
  2395. statements with an expression, and also we must unwrap it on the catch() phase, and
  2396. maybe manually test with Std.is()
  2397. dependencies:
  2398. must run before dynamic field access (?) TODO review
  2399. It's a syntax filter, as it alters types (throw wrapper)
  2400. *)
  2401. module TryCatchWrapper =
  2402. struct
  2403. let priority = solve_deps "try_catch" [DBefore DynamicFieldAccess.priority]
  2404. (*
  2405. 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
  2406. wrap_throw : the wrapper for throw (throw expr->expr inside throw->returning wrapped expression)
  2407. unwrap_expr : the other way around : given the catch var (maybe will need casting to wrapper_type) , return the unwrap expr
  2408. rethrow_expr : how to rethrow ane exception in the platform
  2409. catchall_type : the class used for catchall (e:Dynamic)
  2410. wrapper_type : the wrapper type, so we can test if exception is of type 'wrapper'
  2411. catch_map : maps the catch expression to include some intialization code (e.g. setting up Stack.exceptionStack)
  2412. *)
  2413. 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) =
  2414. let rec run e =
  2415. match e.eexpr with
  2416. | TThrow texpr when should_wrap texpr.etype -> wrap_throw e (run texpr)
  2417. | TTry (ttry, catches) ->
  2418. let nowrap_catches, must_wrap_catches, catchall = List.fold_left (fun (nowrap_catches, must_wrap_catches, catchall) (v, catch) ->
  2419. (* first we'll see if the type is Dynamic (catchall) *)
  2420. match follow v.v_type with
  2421. | TDynamic _ ->
  2422. assert (is_none catchall);
  2423. (nowrap_catches, must_wrap_catches, Some(v,run catch))
  2424. (* see if we should unwrap it *)
  2425. | _ when should_wrap (follow v.v_type) ->
  2426. (nowrap_catches, (v,run catch) :: must_wrap_catches, catchall)
  2427. | _ ->
  2428. ( (v,catch_map v (run catch)) :: nowrap_catches, must_wrap_catches, catchall )
  2429. ) ([], [], None) catches
  2430. in
  2431. (*
  2432. 1st catch all nowrap "the easy way"
  2433. 2nd see if there are any must_wrap or catchall. If there is,
  2434. do a catchall first with a temp var.
  2435. then get catchall var (as dynamic) (or create one), and declare it = catchall exception
  2436. then test if it is of type wrapper_type. If it is, unwrap it
  2437. then start doing Std.is() tests for each catch type
  2438. if there is a catchall in the end, end with it. If there isn't, rethrow
  2439. *)
  2440. let dyn_catch = match (catchall, must_wrap_catches) with
  2441. | Some (v,c), _
  2442. | _, (v, c) :: _ ->
  2443. let pos = c.epos in
  2444. let temp_var = mk_temp gen "catchallException" catchall_type in
  2445. let temp_local = { eexpr=TLocal(temp_var); etype = temp_var.v_type; epos = pos } in
  2446. let catchall_var = (*match catchall with
  2447. | None -> *) mk_temp gen "catchall" t_dynamic
  2448. (*| Some (v,_) -> v*)
  2449. in
  2450. let catchall_decl = { eexpr = TVar(catchall_var, Some(temp_local)); etype=gen.gcon.basic.tvoid; epos = pos } in
  2451. let catchall_local = { eexpr = TLocal(catchall_var); etype = t_dynamic; epos = pos } in
  2452. (* if it is of type wrapper_type, unwrap it *)
  2453. 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
  2454. 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
  2455. let if_is_wrapper_expr = { eexpr = TIf(mk_std_is wrapper_type pos,
  2456. { eexpr = TBinop(OpAssign, catchall_local, unwrap_expr temp_var pos); etype = t_dynamic; epos = pos }
  2457. , None); etype = gen.gcon.basic.tvoid; epos = pos } in
  2458. let rec loop must_wrap_catches = match must_wrap_catches with
  2459. | (vcatch,catch) :: tl ->
  2460. { eexpr = TIf(mk_std_is vcatch.v_type catch.epos,
  2461. { 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 },
  2462. Some (loop tl));
  2463. etype = catch.etype; epos = catch.epos }
  2464. | [] ->
  2465. match catchall with
  2466. | Some (v,s) ->
  2467. Type.concat { eexpr = TVar(v, Some(catchall_local)); etype = gen.gcon.basic.tvoid; epos = pos } s
  2468. | None ->
  2469. mk_block (rethrow_expr temp_local)
  2470. in
  2471. [ ( temp_var, catch_map temp_var { e with eexpr = TBlock([ catchall_decl; if_is_wrapper_expr; loop must_wrap_catches ]) } ) ]
  2472. | _ ->
  2473. []
  2474. in
  2475. { e with eexpr = TTry(run ttry, (List.rev nowrap_catches) @ dyn_catch) }
  2476. | _ -> Type.map_expr run e
  2477. in
  2478. run
  2479. let configure gen (mapping_func:texpr->texpr) =
  2480. let map e = Some(mapping_func e) in
  2481. gen.gsyntax_filters#add ~name:"try_catch" ~priority:(PCustom priority) map
  2482. end;;
  2483. let fun_args = List.map (function | (v,s) -> (v.v_name, (match s with | None -> false | Some _ -> true), v.v_type))
  2484. (* ******************************************* *)
  2485. (* Closures To Class *)
  2486. (* ******************************************* *)
  2487. (*
  2488. 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
  2489. that implements an abstract interface for calling functions. This is very important for targets that don't support anonymous functions to work correctly.
  2490. 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
  2491. from this interface.
  2492. dependencies:
  2493. must run after dynamic field access, because of conflicting ways to deal with invokeField
  2494. (module filter) must run after OverloadingCtor so we can also change the dynamic function expressions
  2495. uses TArray expressions for array. TODO see interaction
  2496. uses TThrow expressions.
  2497. *)
  2498. module ClosuresToClass =
  2499. struct
  2500. let name = "closures_to_class"
  2501. let priority = solve_deps name [ DAfter DynamicFieldAccess.priority ]
  2502. let priority_as_synf = solve_deps name [ DAfter DynamicFieldAccess.priority_as_synf ]
  2503. type closures_ctx =
  2504. {
  2505. fgen : generator_ctx;
  2506. mutable func_class : tclass;
  2507. (*
  2508. this is what will actually turn the function into class field.
  2509. The standard implementation by default will already take care of creating the class, and setting the captured variables.
  2510. It will also return the super arguments to be called
  2511. *)
  2512. mutable closure_to_classfield : tfunc->t->pos->tclass_field * (texpr list);
  2513. (*
  2514. when a dynamic function call is made, we need to convert it as if it were calling the dynamic function interface.
  2515. TCall expr -> new TCall expr
  2516. *)
  2517. mutable dynamic_fun_call : texpr->texpr;
  2518. (*
  2519. called once so the implementation can make one of a time initializations in the base class
  2520. for all functions
  2521. *)
  2522. mutable initialize_base_class : tclass->unit;
  2523. (*
  2524. Base classfields are the class fields for the abstract implementation of either the Function implementation,
  2525. or the invokeField implementation for the classes
  2526. They will either try to call the right function or will fail with
  2527. (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
  2528. *)
  2529. mutable get_base_classfields_for : tclass->bool->(unit->(tvar * tconstant option) list)->tclass_field list;
  2530. (*
  2531. This is a more complex version of get_base_classfields_for.
  2532. It's meant to provide a toolchain so we can easily create classes that extend Function
  2533. and add more functionality on top of it.
  2534. arguments:
  2535. tclass -> subject (so we know the type of this)
  2536. bool -> is it a function type
  2537. ( int -> (int->t->tconstant option->texpr) -> ( (tvar * tconstant option) list * texpr) )
  2538. 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
  2539. t -> the return type of the function
  2540. (int->t->tconstant option->texpr) -> api to get exprs that unwrap arguments correctly
  2541. int -> argument wanted to unwrap
  2542. t -> solicited type
  2543. tconstant option -> map to this default value if null
  2544. returns a texpr that tells how the default
  2545. should return a list with additional arguments (only works if is_function_base = true)
  2546. and the underlying function expression
  2547. *)
  2548. mutable map_base_classfields : tclass->bool->( int -> t -> (tvar list) -> (int->t->tconstant option->texpr) -> ( (tvar * tconstant option) list * texpr) )->tclass_field list;
  2549. mutable transform_closure : texpr->texpr->string->texpr;
  2550. }
  2551. type map_info = {
  2552. in_unsafe : bool;
  2553. in_unused : bool;
  2554. }
  2555. let null_map_info = { in_unsafe = false; in_unused = false; }
  2556. (*
  2557. the default implementation will take 3 transformation functions:
  2558. * one that will transform closures that are not called immediately (instance.myFunc).
  2559. 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
  2560. * one that will actually handle the anonymous functions themselves.
  2561. * one that will transform calling a dynamic function. So for example, dynFunc(arg1, arg2) might turn into dynFunc.apply2(arg1, arg2);
  2562. ( suspended ) * an option to match papplied functions
  2563. * handling parameterized anonymous function declaration (optional - tparam_anon_decl and tparam_anon_acc)
  2564. *)
  2565. let rec cleanup_delegate e = match e.eexpr with
  2566. | TParenthesis e | TMeta(_,e)
  2567. | TCast(e,_) -> cleanup_delegate e
  2568. | _ -> e
  2569. let funct gen t = match follow (run_follow gen t) with
  2570. | TFun(args,ret) -> args,ret
  2571. | _ -> raise Not_found
  2572. let mk_conversion_fun gen e =
  2573. let args, ret = funct gen e.etype in
  2574. let tf_args = List.map (fun (n,o,t) -> alloc_var n t,None) args in
  2575. let block, local = match e.eexpr with
  2576. | TLocal v ->
  2577. v.v_capture <- true;
  2578. [],e
  2579. | _ ->
  2580. let tmp = mk_temp gen "delegate_conv" e.etype in
  2581. tmp.v_capture <- true;
  2582. [{ eexpr = TVar(tmp,Some e); etype = gen.gcon.basic.tvoid; epos = e.epos }], mk_local tmp e.epos
  2583. in
  2584. let body = {
  2585. eexpr = TCall(local, List.map (fun (v,_) -> mk_local v e.epos) tf_args);
  2586. etype = ret;
  2587. epos = e.epos;
  2588. } in
  2589. let body = if not (is_void ret) then
  2590. { body with eexpr = TReturn( Some body ) }
  2591. else
  2592. body
  2593. in
  2594. let body = {
  2595. eexpr = TBlock(block @ [body]);
  2596. etype = body.etype;
  2597. epos = body.epos;
  2598. } in
  2599. {
  2600. tf_args = tf_args;
  2601. tf_expr = body;
  2602. tf_type = ret;
  2603. }
  2604. let traverse gen ?tparam_anon_decl ?tparam_anon_acc (transform_closure:texpr->texpr->string->texpr) (handle_anon_func:texpr->tfunc->map_info->t option->texpr) (dynamic_func_call:texpr->texpr) e =
  2605. let info = ref null_map_info in
  2606. let rec run e =
  2607. match e.eexpr with
  2608. | TCast({ eexpr = TCall({ eexpr = TLocal{ v_name = "__delegate__" } } as local, [del] ) } as e2, _) ->
  2609. let e2 = { e2 with etype = e.etype } in
  2610. let replace_delegate ex =
  2611. { e with eexpr = TCast({ e2 with eexpr = TCall(local, [ex]) }, None) }
  2612. in
  2613. (* found a delegate; let's see if it's a closure or not *)
  2614. let clean = cleanup_delegate del in
  2615. (match clean.eexpr with
  2616. | TField( ef, (FClosure _ as f)) | TField( ef, (FStatic _ as f)) ->
  2617. (* a closure; let's leave this unchanged for FilterClosures to handle it *)
  2618. replace_delegate { clean with eexpr = TField( run ef, f ) }
  2619. | TFunction tf ->
  2620. (* handle like we'd handle a normal function, but create an unchanged closure field for it *)
  2621. let ret = handle_anon_func clean { tf with tf_expr = run tf.tf_expr } !info (Some e.etype) in
  2622. replace_delegate ret
  2623. | _ -> try
  2624. let tf = mk_conversion_fun gen del in
  2625. let ret = handle_anon_func del { tf with tf_expr = run tf.tf_expr } !info (Some e.etype) in
  2626. replace_delegate ret
  2627. with Not_found ->
  2628. gen.gcon.error "This delegate construct is unsupported" e.epos;
  2629. replace_delegate (run clean))
  2630. | TCall(({ eexpr = TLocal{ v_name = "__unsafe__" } } as local), [arg]) ->
  2631. let old = !info in
  2632. info := { !info with in_unsafe = true };
  2633. let arg2 = run arg in
  2634. info := old;
  2635. { e with eexpr = TCall(local,[arg2]) }
  2636. (* parameterized functions handling *)
  2637. | TVar(vv, ve) -> (match tparam_anon_decl with
  2638. | None -> Type.map_expr run e
  2639. | Some tparam_anon_decl ->
  2640. (match (vv, ve) with
  2641. | ({ v_extra = Some( _ :: _, _) } as v), Some ({ eexpr = TFunction tf } as f)
  2642. | ({ v_extra = Some( _ :: _, _) } as v), Some { eexpr = TArrayDecl([{ eexpr = TFunction tf } as f]) | TCall({ eexpr = TLocal { v_name = "__array__" } }, [{ eexpr = TFunction tf } as f]) } -> (* captured transformation *)
  2643. ignore(tparam_anon_decl v f { tf with tf_expr = run tf.tf_expr });
  2644. { e with eexpr = TBlock([]) }
  2645. | _ ->
  2646. Type.map_expr run { e with eexpr = TVar(vv, ve) })
  2647. )
  2648. | TLocal ({ v_extra = Some( _ :: _, _) } as v)
  2649. | TArray ({ eexpr = TLocal ({ v_extra = Some( _ :: _, _) } as v) }, _) -> (* captured transformation *)
  2650. (match tparam_anon_acc with
  2651. | None -> Type.map_expr run e
  2652. | Some tparam_anon_acc -> tparam_anon_acc v e)
  2653. | TCall( { eexpr = TField(_, FEnum _) }, _ ) ->
  2654. Type.map_expr run e
  2655. (* if a TClosure is being call immediately, there's no need to convert it to a TClosure *)
  2656. | TCall(( { eexpr = TField(ecl,f) } as e1), params) ->
  2657. (* check to see if called field is known and if it is a MethNormal (only MethNormal fields can be called directly) *)
  2658. (* let name = field_name f in *)
  2659. (match field_access_esp gen (gen.greal_type ecl.etype) f with
  2660. | FClassField(_,_,_,cf,_,_,_) ->
  2661. (match cf.cf_kind with
  2662. | Method MethNormal
  2663. | Method MethInline ->
  2664. { e with eexpr = TCall({ e1 with eexpr = TField(run ecl, f) }, List.map run params) }
  2665. | _ ->
  2666. match gen.gfollow#run_f e1.etype with
  2667. | TFun _ ->
  2668. dynamic_func_call { e with eexpr = TCall(run e1, List.map run params) }
  2669. | _ ->
  2670. let i = ref 0 in
  2671. let t = TFun(List.map (fun e -> incr i; "arg" ^ (string_of_int !i), false, e.etype) params, e.etype) in
  2672. dynamic_func_call { e with eexpr = TCall( mk_cast t (run e1), List.map run params ) }
  2673. )
  2674. (* | FNotFound ->
  2675. { e with eexpr = TCall({ e1 with eexpr = TField(run ecl, f) }, List.map run params) }
  2676. (* expressions by now may have generated invalid expressions *) *)
  2677. | _ ->
  2678. match gen.gfollow#run_f e1.etype with
  2679. | TFun _ ->
  2680. dynamic_func_call { e with eexpr = TCall(run e1, List.map run params) }
  2681. | _ ->
  2682. let i = ref 0 in
  2683. let t = TFun(List.map (fun e -> incr i; "arg" ^ (string_of_int !i), false, e.etype) params, e.etype) in
  2684. dynamic_func_call { e with eexpr = TCall( mk_cast t (run e1), List.map run params ) }
  2685. )
  2686. | TField(ecl, FClosure (_,cf)) ->
  2687. transform_closure e (run ecl) cf.cf_name
  2688. | TFunction tf ->
  2689. handle_anon_func e { tf with tf_expr = run tf.tf_expr } !info None
  2690. | TCall({ eexpr = TConst(TSuper) }, _) ->
  2691. Type.map_expr run e
  2692. | TCall({ eexpr = TLocal(v) }, args) when String.get v.v_name 0 = '_' && Hashtbl.mem gen.gspecial_vars v.v_name ->
  2693. Type.map_expr run e
  2694. | TCall(tc,params) ->
  2695. let i = ref 0 in
  2696. let may_cast = match gen.gfollow#run_f tc.etype with
  2697. | TFun _ -> fun e -> e
  2698. | _ ->
  2699. let t = TFun(List.map (fun e ->
  2700. incr i;
  2701. ("p" ^ (string_of_int !i), false, e.etype)
  2702. ) params, e.etype)
  2703. in
  2704. fun e -> mk_cast t e
  2705. in
  2706. dynamic_func_call { e with eexpr = TCall(run (may_cast tc), List.map run params) }
  2707. | _ -> Type.map_expr run e
  2708. in
  2709. (match e.eexpr with
  2710. | TFunction(tf) -> Type.map_expr run e
  2711. | _ -> run e)
  2712. let rec get_type_params acc t =
  2713. match t with
  2714. | TInst(( { cl_kind = KTypeParameter _ } as cl), []) ->
  2715. if List.memq cl acc then acc else cl :: acc
  2716. | TFun (params,tret) ->
  2717. List.fold_left get_type_params acc ( tret :: List.map (fun (_,_,t) -> t) params )
  2718. | TDynamic t ->
  2719. (match t with | TDynamic _ -> acc | _ -> get_type_params acc t)
  2720. | TAbstract (a, pl) when not (Meta.has Meta.CoreType a.a_meta) ->
  2721. get_type_params acc ( Abstract.get_underlying_type a pl)
  2722. | TAnon a ->
  2723. PMap.fold (fun cf acc ->
  2724. let params = List.map (fun (_,t) -> match follow t with
  2725. | TInst(c,_) -> c
  2726. | _ -> assert false) cf.cf_params
  2727. in
  2728. List.filter (fun t -> not (List.memq t params)) (get_type_params acc cf.cf_type)
  2729. ) a.a_fields acc
  2730. | TType(_, [])
  2731. | TAbstract (_, [])
  2732. | TInst(_, [])
  2733. | TEnum(_, []) ->
  2734. acc
  2735. | TType(_, params)
  2736. | TAbstract(_, params)
  2737. | TEnum(_, params)
  2738. | TInst(_, params) ->
  2739. List.fold_left get_type_params acc params
  2740. | TMono r -> (match !r with
  2741. | Some t -> get_type_params acc t
  2742. | None -> acc)
  2743. | _ -> get_type_params acc (follow_once t)
  2744. let get_captured expr =
  2745. let ret = Hashtbl.create 1 in
  2746. let ignored = Hashtbl.create 0 in
  2747. let params = ref [] in
  2748. let check_params t = params := get_type_params !params t in
  2749. let rec traverse expr =
  2750. match expr.eexpr with
  2751. | TFor (v, _, _) ->
  2752. Hashtbl.add ignored v.v_id v;
  2753. check_params v.v_type;
  2754. Type.iter traverse expr
  2755. | TFunction(tf) ->
  2756. List.iter (fun (v,_) -> Hashtbl.add ignored v.v_id v) tf.tf_args;
  2757. (match follow expr.etype with
  2758. | TFun(args,ret) ->
  2759. List.iter (fun (_,_,t) ->
  2760. check_params t
  2761. ) args;
  2762. check_params ret
  2763. | _ -> ());
  2764. Type.iter traverse expr
  2765. | TVar (v, opt) ->
  2766. (match v.v_extra with
  2767. | Some(_ :: _, _) -> ()
  2768. | _ ->
  2769. check_params v.v_type);
  2770. Hashtbl.add ignored v.v_id v;
  2771. ignore(Option.map traverse opt)
  2772. | TLocal { v_extra = Some( (_ :: _ ),_) } ->
  2773. ()
  2774. | TLocal(( { v_capture = true } ) as v) ->
  2775. (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);
  2776. | _ -> Type.iter traverse expr
  2777. in traverse expr;
  2778. ret, !params
  2779. (*
  2780. OPTIMIZEME:
  2781. Take off from Codegen the code that wraps captured variables,
  2782. traverse through all variables, looking for their use (just like local_usage)
  2783. three possible outcomes for captured variables:
  2784. - become a function member variable <- best performance.
  2785. Will not work on functions that can be created more than once (functions inside a loop or functions inside functions)
  2786. The function will have to be created on top of the block, so its variables can be filled in instead of being declared
  2787. - single-element array - the most compatible way, though also creates a slight overhead.
  2788. - we'll have some labels for captured variables:
  2789. - used in loop
  2790. *)
  2791. (*
  2792. The default implementation will impose a naming convention:
  2793. invoke(arity)_(o for returning object/d for returning double) when arity < max_arity
  2794. invoke_dynamic_(o/d) when arity > max_arity
  2795. 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.
  2796. *)
  2797. let default_implementation ft parent_func_class (* e.g. new haxe.lang.ClassClosure *) =
  2798. let gen = ft.fgen in
  2799. ft.initialize_base_class parent_func_class;
  2800. let cfs = ft.get_base_classfields_for parent_func_class true (fun () -> []) in
  2801. List.iter (fun cf ->
  2802. (if cf.cf_name = "new" then parent_func_class.cl_constructor <- Some cf else
  2803. parent_func_class.cl_fields <- PMap.add cf.cf_name cf parent_func_class.cl_fields
  2804. )
  2805. ) cfs;
  2806. parent_func_class.cl_ordered_fields <- (List.filter (fun cf -> cf.cf_name <> "new") cfs) @ parent_func_class.cl_ordered_fields;
  2807. ft.func_class <- parent_func_class;
  2808. let handle_anon_func fexpr tfunc mapinfo delegate_type : texpr * (tclass * texpr list) =
  2809. let gen = ft.fgen in
  2810. let in_unsafe = mapinfo.in_unsafe || match gen.gcurrent_class, gen.gcurrent_classfield with
  2811. | Some c, _ when Meta.has Meta.Unsafe c.cl_meta -> true
  2812. | _, Some cf when Meta.has Meta.Unsafe cf.cf_meta -> true
  2813. | _ -> false
  2814. in
  2815. (* get all captured variables it uses *)
  2816. let captured_ht, tparams = get_captured fexpr in
  2817. let captured = Hashtbl.fold (fun _ e acc -> e :: acc) captured_ht [] in
  2818. (*let cltypes = List.map (fun cl -> (snd cl.cl_path, TInst(map_param cl, []) )) tparams in*)
  2819. let cltypes = List.map (fun cl -> (snd cl.cl_path, TInst(cl, []) )) tparams in
  2820. (* create a new class that extends abstract function class, with a ctor implementation that will setup all captured variables *)
  2821. let cfield = match ft.fgen.gcurrent_classfield with
  2822. | None -> "Anon"
  2823. | Some cf -> cf.cf_name
  2824. in
  2825. let cur_line = Lexer.get_error_line fexpr.epos in
  2826. let path = (fst ft.fgen.gcurrent_path, Printf.sprintf "%s_%s_%d__Fun" (snd ft.fgen.gcurrent_path) cfield cur_line) in
  2827. let cls = mk_class (get ft.fgen.gcurrent_class).cl_module path tfunc.tf_expr.epos in
  2828. if in_unsafe then cls.cl_meta <- (Meta.Unsafe,[],Ast.null_pos) :: cls.cl_meta;
  2829. cls.cl_module <- (get ft.fgen.gcurrent_class).cl_module;
  2830. cls.cl_params <- cltypes;
  2831. let mk_this v pos =
  2832. {
  2833. (mk_field_access gen { eexpr = TConst TThis; etype = TInst(cls, List.map snd cls.cl_params); epos = pos } v.v_name pos)
  2834. with etype = v.v_type
  2835. }
  2836. in
  2837. let mk_this_assign v pos =
  2838. {
  2839. eexpr = TBinop(OpAssign, mk_this v pos, { eexpr = TLocal(v); etype = v.v_type; epos = pos });
  2840. etype = v.v_type;
  2841. epos = pos
  2842. } in
  2843. (* mk_class_field name t public pos kind params *)
  2844. let ctor_args, ctor_sig, ctor_exprs = List.fold_left (fun (ctor_args, ctor_sig, ctor_exprs) lexpr ->
  2845. match lexpr.eexpr with
  2846. | TLocal(v) ->
  2847. let cf = mk_class_field v.v_name v.v_type false lexpr.epos (Var({ v_read = AccNormal; v_write = AccNormal; })) [] in
  2848. cls.cl_fields <- PMap.add v.v_name cf cls.cl_fields;
  2849. cls.cl_ordered_fields <- cf :: cls.cl_ordered_fields;
  2850. let ctor_v = alloc_var v.v_name v.v_type in
  2851. ((ctor_v, None) :: ctor_args, (v.v_name, false, v.v_type) :: ctor_sig, (mk_this_assign v cls.cl_pos) :: ctor_exprs)
  2852. | _ -> assert false
  2853. ) ([],[],[]) captured in
  2854. (* change all captured variables to this.capturedVariable *)
  2855. let rec change_captured e =
  2856. match e.eexpr with
  2857. | TLocal( ({ v_capture = true }) as v ) when Hashtbl.mem captured_ht v.v_id ->
  2858. mk_this v e.epos
  2859. | _ -> Type.map_expr change_captured e
  2860. in
  2861. let func_expr = change_captured tfunc.tf_expr in
  2862. let invokecf, invoke_field, super_args = match delegate_type with
  2863. | None -> (* no delegate *)
  2864. let ifield, sa = ft.closure_to_classfield { tfunc with tf_expr = func_expr } fexpr.etype fexpr.epos in
  2865. ifield,ifield,sa
  2866. | Some _ ->
  2867. let pos = cls.cl_pos in
  2868. let cf = mk_class_field "Delegate" (TFun(fun_args tfunc.tf_args, tfunc.tf_type)) true pos (Method MethNormal) [] in
  2869. cf.cf_expr <- Some { fexpr with eexpr = TFunction { tfunc with tf_expr = func_expr }; };
  2870. cf.cf_meta <- (Meta.Final,[],pos) :: cf.cf_meta;
  2871. cls.cl_ordered_fields <- cf :: cls.cl_ordered_fields;
  2872. cls.cl_fields <- PMap.add cf.cf_name cf cls.cl_fields;
  2873. (* invoke function body: call Delegate function *)
  2874. let ibody = {
  2875. eexpr = TCall({
  2876. eexpr = TField({
  2877. eexpr = TConst TThis;
  2878. etype = TInst(cls, List.map snd cls.cl_params);
  2879. epos = pos;
  2880. }, FInstance(cls, List.map snd cls.cl_params, cf));
  2881. etype = cf.cf_type;
  2882. epos = pos;
  2883. }, List.map (fun (v,_) -> mk_local v pos) tfunc.tf_args);
  2884. etype = tfunc.tf_type;
  2885. epos = pos
  2886. } in
  2887. let ibody = if not (is_void tfunc.tf_type) then
  2888. { ibody with eexpr = TReturn( Some ibody ) }
  2889. else
  2890. ibody
  2891. in
  2892. let ifield, sa = ft.closure_to_classfield { tfunc with tf_expr = ibody } fexpr.etype fexpr.epos in
  2893. cf,ifield,sa
  2894. in
  2895. (* create the constructor *)
  2896. (* todo properly abstract how type var is set *)
  2897. cls.cl_super <- Some(parent_func_class, []);
  2898. let pos = cls.cl_pos in
  2899. let super_call =
  2900. {
  2901. eexpr = TCall({ eexpr = TConst(TSuper); etype = TInst(parent_func_class,[]); epos = pos }, super_args);
  2902. etype = ft.fgen.gcon.basic.tvoid;
  2903. epos = pos;
  2904. } in
  2905. let ctor_type = (TFun(ctor_sig, ft.fgen.gcon.basic.tvoid)) in
  2906. let ctor = mk_class_field "new" ctor_type true cls.cl_pos (Method(MethNormal)) [] in
  2907. ctor.cf_expr <- Some(
  2908. {
  2909. eexpr = TFunction(
  2910. {
  2911. tf_args = ctor_args;
  2912. tf_type = ft.fgen.gcon.basic.tvoid;
  2913. tf_expr = { eexpr = TBlock(super_call :: ctor_exprs); etype = ft.fgen.gcon.basic.tvoid; epos = cls.cl_pos }
  2914. });
  2915. etype = ctor_type;
  2916. epos = cls.cl_pos;
  2917. });
  2918. cls.cl_constructor <- Some(ctor);
  2919. (* add invoke function to the class *)
  2920. cls.cl_ordered_fields <- invoke_field :: cls.cl_ordered_fields;
  2921. cls.cl_fields <- PMap.add invoke_field.cf_name invoke_field cls.cl_fields;
  2922. cls.cl_overrides <- invoke_field :: cls.cl_overrides;
  2923. (* add this class to the module with gadd_to_module *)
  2924. ft.fgen.gadd_to_module (TClassDecl(cls)) priority;
  2925. (* if there are no captured variables, we can create a cache so subsequent calls don't need to create a new function *)
  2926. let expr, clscapt =
  2927. match captured, tparams with
  2928. | [], [] ->
  2929. let cache_var = ft.fgen.gmk_internal_name "hx" "current" in
  2930. let cache_cf = mk_class_field cache_var (TInst(cls,[])) false func_expr.epos (Var({ v_read = AccNormal; v_write = AccNormal })) [] in
  2931. cls.cl_ordered_statics <- cache_cf :: cls.cl_ordered_statics;
  2932. cls.cl_statics <- PMap.add cache_var cache_cf cls.cl_statics;
  2933. (* if (FuncClass.hx_current != null) FuncClass.hx_current; else (FuncClass.hx_current = new FuncClass()); *)
  2934. (* let mk_static_field_access cl field fieldt pos = *)
  2935. let hx_current = mk_static_field_access cls cache_var (TInst(cls,[])) func_expr.epos in
  2936. let pos = func_expr.epos in
  2937. { fexpr with
  2938. eexpr = TIf(
  2939. {
  2940. eexpr = TBinop(OpNotEq, hx_current, null (TInst(cls,[])) pos);
  2941. etype = ft.fgen.gcon.basic.tbool;
  2942. epos = pos;
  2943. },
  2944. hx_current,
  2945. Some(
  2946. {
  2947. eexpr = TBinop(OpAssign, hx_current, { fexpr with eexpr = TNew(cls, [], captured) });
  2948. etype = (TInst(cls,[]));
  2949. epos = pos;
  2950. }))
  2951. }, (cls,captured)
  2952. | _ ->
  2953. (* change the expression so it will be a new "added class" ( captured variables arguments ) *)
  2954. { fexpr with eexpr = TNew(cls, List.map (fun cl -> TInst(cl,[])) tparams, List.rev captured) }, (cls,captured)
  2955. in
  2956. match delegate_type with
  2957. | None ->
  2958. expr,clscapt
  2959. | Some _ ->
  2960. {
  2961. eexpr = TField(expr, FClosure(Some (cls,[]),invokecf)); (* TODO: FClosure change *)
  2962. etype = invokecf.cf_type;
  2963. epos = cls.cl_pos
  2964. }, clscapt
  2965. in
  2966. let tvar_to_cdecl = Hashtbl.create 0 in
  2967. traverse
  2968. ft.fgen
  2969. ~tparam_anon_decl:(fun v e fn ->
  2970. let _, info = handle_anon_func e fn null_map_info None in
  2971. Hashtbl.add tvar_to_cdecl v.v_id info
  2972. )
  2973. ~tparam_anon_acc:(fun v e -> try
  2974. let cls, captured = Hashtbl.find tvar_to_cdecl v.v_id in
  2975. let types = match v.v_extra with
  2976. | Some(t,_) -> t
  2977. | _ -> assert false
  2978. in
  2979. let monos = List.map (fun _ -> mk_mono()) types in
  2980. let vt = match follow v.v_type with
  2981. | TInst(_, [v]) -> v
  2982. | v -> v
  2983. in
  2984. let et = match follow e.etype with
  2985. | TInst(_, [v]) -> v
  2986. | v -> v
  2987. in
  2988. let original = apply_params types monos vt in
  2989. unify et original;
  2990. let monos = List.map (fun t -> apply_params types (List.map (fun _ -> t_dynamic) types) t) monos in
  2991. let same_cl t1 t2 = match follow t1, follow t2 with
  2992. | TInst(c,_), TInst(c2,_) -> c == c2
  2993. | _ -> false
  2994. in
  2995. let passoc = List.map2 (fun (_,t) m -> t,m) types monos in
  2996. let cltparams = List.map (fun (_,t) ->
  2997. try
  2998. snd (List.find (fun (t2,_) -> same_cl t t2) passoc)
  2999. with | Not_found -> t) cls.cl_params
  3000. in
  3001. { e with eexpr = TNew(cls, cltparams, captured) }
  3002. with
  3003. | Not_found ->
  3004. gen.gcon.warning "This expression may be invalid" e.epos;
  3005. e
  3006. | Unify_error el ->
  3007. List.iter (fun el -> gen.gcon.warning (Typecore.unify_error_msg (print_context()) el) e.epos) el;
  3008. gen.gcon.warning "This expression may be invalid" e.epos;
  3009. e
  3010. )
  3011. (* (transform_closure:texpr->texpr->string->texpr) (handle_anon_func:texpr->tfunc->texpr) (dynamic_func_call:texpr->texpr->texpr list->texpr) *)
  3012. ft.transform_closure
  3013. (fun e f info delegate_type -> fst (handle_anon_func e f info delegate_type))
  3014. ft.dynamic_fun_call
  3015. (* (dynamic_func_call:texpr->texpr->texpr list->texpr) *)
  3016. let configure gen (mapping_func:texpr->texpr) =
  3017. let map e = Some(mapping_func e) in
  3018. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority) map
  3019. let configure_as_synf gen (mapping_func:texpr->texpr) =
  3020. let map e = Some(mapping_func e) in
  3021. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority_as_synf) map
  3022. (*
  3023. this submodule will provide the default implementation for the C# and Java targets.
  3024. it will have two return types: double and dynamic, and
  3025. *)
  3026. module DoubleAndDynamicClosureImpl =
  3027. struct
  3028. let get_ctx gen max_arity =
  3029. let basic = gen.gcon.basic in
  3030. let func_args_i i =
  3031. let rec loop i (acc) =
  3032. if i = 0 then (acc) else begin
  3033. let vfloat = alloc_var (gen.gmk_internal_name "fn" ("float" ^ string_of_int i)) basic.tfloat in
  3034. let vdyn = alloc_var (gen.gmk_internal_name "fn" ("dyn" ^ string_of_int i)) t_dynamic in
  3035. loop (i - 1) ((vfloat, None) :: (vdyn, None) :: acc)
  3036. end
  3037. in
  3038. loop i []
  3039. in
  3040. let args_real_to_func args =
  3041. let arity = List.length args in
  3042. if arity >= max_arity then
  3043. [ alloc_var (gen.gmk_internal_name "fn" "dynargs") (basic.tarray t_dynamic), None ]
  3044. else func_args_i arity
  3045. in
  3046. let func_sig_i i =
  3047. let rec loop i acc =
  3048. if i = 0 then acc else begin
  3049. let vfloat = gen.gmk_internal_name "fn" ("float" ^ string_of_int i) in
  3050. let vdyn = gen.gmk_internal_name "fn" ("dyn" ^ string_of_int i) in
  3051. loop (i - 1) ( (vfloat,false,basic.tfloat) :: (vdyn,false,t_dynamic) :: acc )
  3052. end
  3053. in
  3054. loop i []
  3055. in
  3056. let args_real_to_func_sig args =
  3057. let arity = List.length args in
  3058. if arity >= max_arity then
  3059. [gen.gmk_internal_name "fn" "dynargs", false, basic.tarray t_dynamic]
  3060. else begin
  3061. func_sig_i arity
  3062. end
  3063. in
  3064. let rettype_real_to_func t = match run_follow gen t with
  3065. | TType({ t_path = [],"Null" }, _) ->
  3066. 0,t_dynamic
  3067. | _ when like_float t && not (like_i64 t) ->
  3068. (1, basic.tfloat)
  3069. | _ ->
  3070. (0, t_dynamic)
  3071. in
  3072. let args_real_to_func_call el (pos:Ast.pos) =
  3073. if List.length el >= max_arity then
  3074. [{ eexpr = TArrayDecl el; etype = basic.tarray t_dynamic; epos = pos }]
  3075. else begin
  3076. List.fold_left (fun acc e ->
  3077. if like_float (gen.greal_type e.etype) && not (like_i64 (gen.greal_type e.etype)) then
  3078. ( e :: undefined e.epos :: acc )
  3079. else
  3080. ( null basic.tfloat e.epos :: e :: acc )
  3081. ) ([]) (List.rev el)
  3082. end
  3083. in
  3084. let const_type c def =
  3085. match c with
  3086. | TString _ -> basic.tstring | TInt _ -> basic.tint
  3087. | TFloat _ -> basic.tfloat | TBool _ -> basic.tbool
  3088. | _ -> def
  3089. in
  3090. let get_args_func args changed_args pos =
  3091. let arity = List.length args in
  3092. let mk_const const elocal t =
  3093. match const with
  3094. | None -> mk_cast t elocal
  3095. | Some const ->
  3096. { eexpr = TIf(
  3097. { elocal with eexpr = TBinop(Ast.OpEq, elocal, null elocal.etype elocal.epos); etype = basic.tbool },
  3098. { elocal with eexpr = TConst(const); etype = const_type const t },
  3099. Some ( mk_cast t elocal )
  3100. ); etype = t; epos = elocal.epos }
  3101. in
  3102. if arity >= max_arity then begin
  3103. let varray = match changed_args with | [v,_] -> v | _ -> assert false in
  3104. let varray_local = mk_local varray pos in
  3105. 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
  3106. snd (List.fold_left (fun (count,acc) (v,const) ->
  3107. (count + 1,
  3108. {
  3109. eexpr = TVar(v, Some(mk_const const ( mk_varray count ) v.v_type));
  3110. etype = basic.tvoid;
  3111. epos = pos;
  3112. } :: acc)
  3113. ) (0,[]) args)
  3114. end else begin
  3115. let _, dyn_args, float_args = List.fold_left (fun (count,fargs, dargs) arg ->
  3116. if count land 1 = 0 then
  3117. (count + 1, fargs, arg :: dargs)
  3118. else
  3119. (count + 1, arg :: fargs, dargs)
  3120. ) (1,[],[]) (List.rev changed_args) in
  3121. let rec loop acc args fargs dargs =
  3122. match args, fargs, dargs with
  3123. | [], [], [] -> acc
  3124. | (v,const) :: args, (vf,_) :: fargs, (vd,_) :: dargs ->
  3125. let acc = { eexpr = TVar(v, Some(
  3126. {
  3127. eexpr = TIf(
  3128. { eexpr = TBinop(Ast.OpEq, mk_local vd pos, undefined pos); etype = basic.tbool; epos = pos },
  3129. mk_cast v.v_type (mk_local vf pos),
  3130. Some ( mk_const const (mk_local vd pos) v.v_type )
  3131. );
  3132. etype = v.v_type;
  3133. epos = pos
  3134. } )); etype = basic.tvoid; epos = pos } :: acc in
  3135. loop acc args fargs dargs
  3136. | _ -> assert false
  3137. in
  3138. loop [] args float_args dyn_args
  3139. end
  3140. in
  3141. let closure_to_classfield tfunc old_sig pos =
  3142. (* change function signature *)
  3143. let old_args = tfunc.tf_args in
  3144. let changed_args = args_real_to_func old_args in
  3145. (*
  3146. FIXME properly handle int64 cases, which will break here (because of inference to int)
  3147. UPDATE: the fix will be that Int64 won't be a typedef to Float/Int
  3148. *)
  3149. let changed_sig, arity, type_number, changed_sig_ret, is_void, is_dynamic_func = match follow old_sig with
  3150. | TFun(_sig, ret) ->
  3151. let type_n, ret_t = rettype_real_to_func ret in
  3152. let arity = List.length _sig in
  3153. let is_dynamic_func = arity >= max_arity in
  3154. let ret_t = if is_dynamic_func then t_dynamic else ret_t in
  3155. (TFun(args_real_to_func_sig _sig, ret_t), arity, type_n, ret_t, is_void ret, is_dynamic_func)
  3156. | _ -> (print_endline (s_type (print_context()) (follow old_sig) )); assert false
  3157. in
  3158. let tf_expr = if is_void then begin
  3159. let rec map e =
  3160. match e.eexpr with
  3161. | TReturn None -> { e with eexpr = TReturn (Some (null t_dynamic e.epos)) }
  3162. | _ -> Type.map_expr map e
  3163. in
  3164. let e = mk_block (map tfunc.tf_expr) in
  3165. match e.eexpr with
  3166. | TBlock(bl) ->
  3167. { e with eexpr = TBlock(bl @ [{ eexpr = TReturn (Some (null t_dynamic e.epos)); etype = t_dynamic; epos = e.epos }]) }
  3168. | _ -> assert false
  3169. end else tfunc.tf_expr in
  3170. let changed_sig_ret = if is_dynamic_func then t_dynamic else changed_sig_ret in
  3171. (* get real arguments on top of function body *)
  3172. let get_args = get_args_func tfunc.tf_args changed_args pos in
  3173. (*
  3174. FIXME HACK: in order to be able to run the filters that have already ran for this piece of code,
  3175. we will cheat and run it as if it was the whole code
  3176. We could just make ClosuresToClass run before TArrayTransform, but we cannot because of the
  3177. dependency between ClosuresToClass (after DynamicFieldAccess, and before TArrayTransform)
  3178. maybe a way to solve this would be to add an "until" field to run_from
  3179. *)
  3180. let real_get_args = gen.gexpr_filters#run_f { eexpr = TBlock(get_args); etype = basic.tvoid; epos = pos } in
  3181. let func_expr = Type.concat real_get_args tf_expr in
  3182. (* set invoke function *)
  3183. (* todo properly abstract how naming for invoke is made *)
  3184. let invoke_name = if is_dynamic_func then "invokeDynamic" else ("invoke" ^ (string_of_int arity) ^ (if type_number = 0 then "_o" else "_f")) in
  3185. let invoke_name = gen.gmk_internal_name "hx" invoke_name in
  3186. let invoke_field = mk_class_field invoke_name changed_sig false func_expr.epos (Method(MethNormal)) [] in
  3187. let invoke_fun =
  3188. {
  3189. eexpr = TFunction(
  3190. {
  3191. tf_args = changed_args;
  3192. tf_type = changed_sig_ret;
  3193. tf_expr = func_expr;
  3194. });
  3195. etype = changed_sig;
  3196. epos = func_expr.epos;
  3197. } in
  3198. invoke_field.cf_expr <- Some(invoke_fun);
  3199. (invoke_field, [
  3200. { eexpr = TConst(TInt( Int32.of_int arity )); etype = gen.gcon.basic.tint; epos = pos };
  3201. { eexpr = TConst(TInt( Int32.of_int type_number )); etype = gen.gcon.basic.tint; epos = pos };
  3202. ])
  3203. in
  3204. let dynamic_fun_call call_expr =
  3205. let tc, params = match call_expr.eexpr with
  3206. | TCall(tc, params) -> (tc, params)
  3207. | _ -> assert false
  3208. in
  3209. let ct = gen.greal_type call_expr.etype in
  3210. let postfix, ret_t =
  3211. if like_float ct && not (like_i64 ct) then
  3212. "_f", gen.gcon.basic.tfloat
  3213. else
  3214. "_o", t_dynamic
  3215. in
  3216. let params_len = List.length params in
  3217. let ret_t = if params_len >= max_arity then t_dynamic else ret_t in
  3218. let invoke_fun = if params_len >= max_arity then "invokeDynamic" else "invoke" ^ (string_of_int params_len) ^ postfix in
  3219. let invoke_fun = gen.gmk_internal_name "hx" invoke_fun in
  3220. let fun_t = match follow tc.etype with
  3221. | TFun(_sig, _) ->
  3222. TFun(args_real_to_func_sig _sig, ret_t)
  3223. | _ ->
  3224. let i = ref 0 in
  3225. let _sig = List.map (fun p -> let name = "arg" ^ (string_of_int !i) in incr i; (name,false,p.etype) ) params in
  3226. TFun(args_real_to_func_sig _sig, ret_t)
  3227. in
  3228. let may_cast = match follow call_expr.etype with
  3229. | TAbstract ({ a_path = ([], "Void") },[]) -> (fun e -> e)
  3230. | _ -> mk_cast call_expr.etype
  3231. in
  3232. may_cast
  3233. {
  3234. eexpr = TCall(
  3235. { (mk_field_access gen { tc with etype = gen.greal_type tc.etype } invoke_fun tc.epos) with etype = fun_t },
  3236. args_real_to_func_call params call_expr.epos
  3237. );
  3238. etype = ret_t;
  3239. epos = call_expr.epos
  3240. }
  3241. in
  3242. let iname is_function i is_float =
  3243. let postfix = if is_float then "_f" else "_o" in
  3244. gen.gmk_internal_name "hx" ("invoke" ^ (if not is_function then "Field" else "") ^ string_of_int i) ^ postfix
  3245. in
  3246. let map_base_classfields cl is_function map_fn =
  3247. let pos = cl.cl_pos in
  3248. let this_t = TInst(cl,List.map snd cl.cl_params) in
  3249. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  3250. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  3251. let mk_invoke_i i is_float =
  3252. 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
  3253. cf
  3254. in
  3255. let type_name = gen.gmk_internal_name "fn" "type" in
  3256. let dynamic_arg = alloc_var (gen.gmk_internal_name "fn" "dynargs") (basic.tarray t_dynamic) in
  3257. let mk_invoke_complete_i i is_float =
  3258. (* let arity = i in *)
  3259. let args = func_args_i i in
  3260. (* api fn *)
  3261. (* only cast if needed *)
  3262. let mk_cast tto efrom = gen.ghandle_cast (gen.greal_type tto) (gen.greal_type efrom.etype) efrom in
  3263. let api i t const =
  3264. let vf, _ = List.nth args (i * 2) in
  3265. let vo, _ = List.nth args (i * 2 + 1) in
  3266. let needs_cast, is_float = match t, like_float t && not (like_i64 t) with
  3267. | TAbstract({ a_path = ([], "Float") },[]), _ -> false, true
  3268. | _, true -> true, true
  3269. | _ -> false,false
  3270. in
  3271. let olocal = mk_local vo pos in
  3272. let flocal = mk_local vf pos in
  3273. let get_from_obj e = match const with
  3274. | None -> mk_cast t e
  3275. | Some tc ->
  3276. {
  3277. eexpr = TIf(
  3278. { eexpr = TBinop(Ast.OpEq, olocal, null t_dynamic pos); etype = basic.tbool; epos = pos } ,
  3279. { eexpr = TConst(tc); etype = t; epos = pos },
  3280. Some (mk_cast t e)
  3281. );
  3282. etype = t;
  3283. epos = pos;
  3284. }
  3285. in
  3286. {
  3287. eexpr = TIf(
  3288. { eexpr = TBinop(Ast.OpEq, olocal, undefined pos); etype = basic.tbool; epos = pos },
  3289. (if needs_cast then mk_cast t flocal else flocal),
  3290. Some ( get_from_obj olocal )
  3291. );
  3292. etype = t;
  3293. epos = pos
  3294. }
  3295. in
  3296. (* end of api fn *)
  3297. let ret = if is_float then basic.tfloat else t_dynamic in
  3298. let added_args, fn_expr = map_fn i ret (List.map fst args) api in
  3299. let args = added_args @ args in
  3300. let t = TFun(fun_args args, ret) in
  3301. let tfunction =
  3302. {
  3303. eexpr = TFunction({
  3304. tf_args = args;
  3305. tf_type = ret;
  3306. tf_expr =
  3307. mk_block fn_expr
  3308. });
  3309. etype = t;
  3310. epos = pos;
  3311. }
  3312. in
  3313. let cf = mk_invoke_i i is_float in
  3314. cf.cf_expr <- Some tfunction;
  3315. cf
  3316. in
  3317. let rec loop i cfs =
  3318. if i < 0 then cfs else begin
  3319. (*let mk_invoke_complete_i i is_float =*)
  3320. (mk_invoke_complete_i i false) :: (mk_invoke_complete_i i true) :: (loop (i-1) cfs)
  3321. end
  3322. in
  3323. let cfs = loop max_arity [] in
  3324. let added_s_args, switch =
  3325. let api i t const =
  3326. match i with
  3327. | -1 ->
  3328. mk_local dynamic_arg pos
  3329. | _ ->
  3330. mk_cast t {
  3331. eexpr = TArray(
  3332. mk_local dynamic_arg pos,
  3333. { eexpr = TConst(TInt(Int32.of_int i)); etype = basic.tint; epos = pos });
  3334. etype = t;
  3335. epos = pos;
  3336. }
  3337. in
  3338. map_fn (-1) t_dynamic [dynamic_arg] api
  3339. in
  3340. let args = added_s_args @ [dynamic_arg, None] in
  3341. let dyn_t = TFun(fun_args args, t_dynamic) in
  3342. let dyn_cf = mk_class_field (gen.gmk_internal_name "hx" "invokeDynamic") dyn_t false pos (Method MethNormal) [] in
  3343. dyn_cf.cf_expr <-
  3344. Some {
  3345. eexpr = TFunction({
  3346. tf_args = args;
  3347. tf_type = t_dynamic;
  3348. tf_expr = mk_block switch
  3349. });
  3350. etype = dyn_t;
  3351. epos = pos;
  3352. };
  3353. let additional_cfs = if is_function then begin
  3354. let new_t = TFun(["arity", false, basic.tint; "type", false, basic.tint],basic.tvoid) in
  3355. let new_cf = mk_class_field "new" (new_t) true pos (Method MethNormal) [] in
  3356. let v_arity, v_type = alloc_var "arity" basic.tint, alloc_var "type" basic.tint in
  3357. 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
  3358. let arity_name = gen.gmk_internal_name "hx" "arity" in
  3359. new_cf.cf_expr <-
  3360. Some {
  3361. eexpr = TFunction({
  3362. tf_args = [v_arity, None; v_type, None];
  3363. tf_type = basic.tvoid;
  3364. tf_expr =
  3365. {
  3366. eexpr = TBlock([
  3367. mk_assign v_type type_name;
  3368. mk_assign v_arity arity_name
  3369. ]);
  3370. etype = basic.tvoid;
  3371. epos = pos;
  3372. }
  3373. });
  3374. etype = new_t;
  3375. epos = pos;
  3376. }
  3377. ;
  3378. [
  3379. new_cf;
  3380. mk_class_field type_name basic.tint true pos (Var { v_read = AccNormal; v_write = AccNormal }) [];
  3381. mk_class_field arity_name basic.tint true pos (Var { v_read = AccNormal; v_write = AccNormal }) [];
  3382. ]
  3383. end else [] in
  3384. dyn_cf :: (additional_cfs @ cfs)
  3385. in
  3386. (* maybe another param for prefix *)
  3387. let get_base_classfields_for cl is_function mk_additional_args =
  3388. let pos = cl.cl_pos in
  3389. let this_t = TInst(cl,List.map snd cl.cl_params) in
  3390. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  3391. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  3392. let rec mk_dyn_call arity api =
  3393. let zero = { eexpr = TConst(TFloat("0.0")); etype = basic.tfloat; epos = pos } in
  3394. let rec loop i acc =
  3395. if i = 0 then acc else begin
  3396. let arr = api (i-1) t_dynamic None in
  3397. loop (i - 1) (zero :: arr :: acc)
  3398. end
  3399. in
  3400. loop arity ([])
  3401. in
  3402. let mk_invoke_switch i (api:(int->t->tconstant option->texpr)) =
  3403. let t = TFun(func_sig_i i,t_dynamic) in
  3404. (* case i: return this.invokeX_o(0, 0, 0, 0, 0, ... arg[0], args[1]....); *)
  3405. ( [{ eexpr = TConst(TInt(Int32.of_int i)); etype = basic.tint; epos = pos }],
  3406. {
  3407. eexpr = TReturn(Some( {
  3408. eexpr = TCall(mk_this (iname is_function i false) t, mk_dyn_call i api);
  3409. etype = t_dynamic;
  3410. epos = pos;
  3411. } ));
  3412. etype = t_dynamic;
  3413. epos = pos;
  3414. } )
  3415. in
  3416. let cl_t = TInst(cl,List.map snd cl.cl_params) in
  3417. let this = { eexpr = TConst(TThis); etype = cl_t; epos = pos } in
  3418. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  3419. let mk_int i = { eexpr = TConst(TInt ( Int32.of_int i)); etype = basic.tint; epos = pos } in
  3420. let mk_string s = { eexpr = TConst(TString s); etype = basic.tstring; epos = pos } in
  3421. (*
  3422. if it is the Function class, the base class fields will be
  3423. * hx::invokeX_d|o (where X is from 0 to max_arity) (args)
  3424. {
  3425. if (this.type == 0|1) return invokeX_o|d(args); else throw "Invalid number of arguments."
  3426. }
  3427. hx::invokeDynamic, which will work in the same way
  3428. new(arity, type)
  3429. {
  3430. if (type != 0 && type != 1) throw "Invalid type";
  3431. this.arity = arity;
  3432. this.type = type;
  3433. }
  3434. *)
  3435. let type_name = gen.gmk_internal_name "fn" "type" in
  3436. let mk_expr i is_float vars =
  3437. let name = if is_function then "invoke" else "invokeField" in
  3438. let look_ahead = alloc_var "lookAhead" basic.tbool in
  3439. let add_args = if not is_function then mk_additional_args() else [] in
  3440. let vars = if not is_function then (List.map fst add_args) @ (look_ahead :: vars) else vars in
  3441. let call_expr =
  3442. 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
  3443. {
  3444. 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 );
  3445. etype = if is_float then t_dynamic else basic.tfloat;
  3446. epos = pos
  3447. }
  3448. in
  3449. (*let call_expr = if is_float then mk_cast basic.tfloat call_expr else call_expr in*)
  3450. let if_cond = if is_function then
  3451. { eexpr=TBinop(Ast.OpNotEq, mk_this type_name basic.tint, mk_int (if is_float then 0 else 1) ); etype = basic.tbool; epos = pos }
  3452. else
  3453. mk_local look_ahead pos
  3454. in
  3455. let if_expr = if is_function then
  3456. {
  3457. eexpr = TIf(if_cond,
  3458. { eexpr = TThrow(mk_string "Wrong number of arguments"); etype = basic.tstring; epos = pos },
  3459. Some( { eexpr = TReturn( Some( call_expr ) ); etype = call_expr.etype; epos = pos } )
  3460. );
  3461. etype = t_dynamic;
  3462. epos = pos;
  3463. }
  3464. else
  3465. {
  3466. eexpr = TIf(if_cond,
  3467. { eexpr = TReturn( Some( call_expr ) ); etype = call_expr.etype; epos = pos },
  3468. Some( { eexpr = TThrow(mk_string "Field not found or wrong number of arguments"); etype = basic.tstring; epos = pos } )
  3469. );
  3470. etype = t_dynamic;
  3471. epos = pos;
  3472. }
  3473. in
  3474. let args = if not is_function then (mk_additional_args()) @ [look_ahead, None] else [] in
  3475. (args, if_expr)
  3476. in
  3477. let arities_processed = Hashtbl.create 10 in
  3478. let max_arity = ref 0 in
  3479. let rec loop_cases api arity acc =
  3480. if arity < 0 then acc else
  3481. loop_cases api (arity - 1) (mk_invoke_switch arity api :: acc)
  3482. in
  3483. (* let rec loop goes here *)
  3484. let map_fn cur_arity fun_ret_type vars (api:(int->t->tconstant option->texpr)) =
  3485. let is_float = like_float fun_ret_type && not (like_i64 fun_ret_type) in
  3486. match cur_arity with
  3487. | -1 ->
  3488. let dynargs = api (-1) (t_dynamic) None in
  3489. let switch_cond = mk_field_access gen dynargs "length" pos in
  3490. let switch_cond = {
  3491. eexpr = TIf(
  3492. { eexpr = TBinop(Ast.OpEq, dynargs, null dynargs.etype pos); etype = basic.tbool; epos = pos; },
  3493. { eexpr = TConst(TInt(Int32.zero)); etype = basic.tint; epos = pos },
  3494. Some switch_cond);
  3495. etype = basic.tint;
  3496. epos = pos;
  3497. } in
  3498. let switch =
  3499. {
  3500. eexpr = TSwitch( switch_cond,
  3501. loop_cases api !max_arity [],
  3502. Some({ eexpr = TThrow(mk_string "Too many arguments"); etype = basic.tvoid; epos = pos; }) );
  3503. etype = basic.tvoid;
  3504. epos = pos;
  3505. } in
  3506. ( (if not is_function then mk_additional_args () else []), switch )
  3507. | _ ->
  3508. if not (Hashtbl.mem arities_processed cur_arity) then begin
  3509. Hashtbl.add arities_processed cur_arity true;
  3510. if cur_arity > !max_arity then max_arity := cur_arity
  3511. end;
  3512. mk_expr cur_arity is_float vars
  3513. in
  3514. map_base_classfields cl is_function map_fn
  3515. in
  3516. let initialize_base_class cl =
  3517. ()
  3518. in
  3519. {
  3520. fgen = gen;
  3521. func_class = null_class;
  3522. closure_to_classfield = closure_to_classfield;
  3523. dynamic_fun_call = dynamic_fun_call;
  3524. (*
  3525. called once so the implementation can make one of a time initializations in the base class
  3526. for all functions
  3527. *)
  3528. initialize_base_class = initialize_base_class;
  3529. (*
  3530. Base classfields are the class fields for the abstract implementation of either the Function implementation,
  3531. or the invokeField implementation for the classes
  3532. They will either try to call the right function or will fail with
  3533. (tclass - subject (so we know the type of this)) -> is_function_base -> list of the abstract implementation class fields
  3534. *)
  3535. get_base_classfields_for = get_base_classfields_for;
  3536. map_base_classfields = map_base_classfields;
  3537. (*
  3538. for now we won't deal with the closures.
  3539. They can be dealt with the module ReflectionCFs,
  3540. or a custom implementation
  3541. *)
  3542. transform_closure = (fun tclosure texpr str -> tclosure);
  3543. }
  3544. end;;
  3545. end;;
  3546. (* ******************************************* *)
  3547. (* Type Parameters *)
  3548. (* ******************************************* *)
  3549. (*
  3550. This module will handle type parameters. There are lots of changes we need to do to correctly support type parameters:
  3551. traverse will:
  3552. V Detect when parameterized function calls are made
  3553. * Detect when a parameterized class instance is being cast to another parameter
  3554. * Change new<> parameterized function calls
  3555. *
  3556. extras:
  3557. * On languages that support "real" type parameters, a Cast function is provided that will convert from a <Dynamic> to the requested type.
  3558. 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.
  3559. Other implementations may be delegated to the runtime.
  3560. * 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())
  3561. * Type parameter renaming to avoid name clash
  3562. * Detect type parameter casting and call Cast<> instead
  3563. for java:
  3564. * 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.
  3565. dependencies:
  3566. must run after casts are detected. This will be ensured at CastDetect module.
  3567. *)
  3568. module TypeParams =
  3569. struct
  3570. let name = "type_params"
  3571. let priority = max_dep -. 20.
  3572. (* this function will receive the original function argument, the applied function argument and the original function parameters. *)
  3573. (* from this info, it will infer the applied tparams for the function *)
  3574. (* this function is used by CastDetection module *)
  3575. 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 =
  3576. match params with
  3577. | [] -> []
  3578. | _ ->
  3579. 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
  3580. let monos = List.map (fun _ -> mk_mono()) params in
  3581. let original = args_list (get_fun (apply_params params monos (TFun(fst original_args,snd original_args)))) in
  3582. let applied = args_list applied_args in
  3583. (try
  3584. List.iter2 (fun a o ->
  3585. let o = run_follow gen o in
  3586. let a = run_follow gen a in
  3587. unify a o
  3588. (* type_eq EqStrict a o *)
  3589. ) applied original
  3590. (* unify applied original *)
  3591. with | Unify_error el ->
  3592. (* List.iter (fun el -> gen.gcon.warning (Typecore.unify_error_msg (print_context()) el) pos) el; *)
  3593. gen.gcon.warning ("This expression may be invalid") pos
  3594. | Invalid_argument("List.map2") ->
  3595. gen.gcon.warning ("This expression may be invalid") pos
  3596. );
  3597. List.map (fun t ->
  3598. match follow t with
  3599. | TMono _ -> t_empty
  3600. | t -> t
  3601. ) monos
  3602. (* ******************************************* *)
  3603. (* Real Type Parameters Module *)
  3604. (* ******************************************* *)
  3605. (*
  3606. This submodule is by now specially made for the .NET platform. There might be other targets that will
  3607. make use of this, but it IS very specific.
  3608. On the .NET platform, generics are real specialized classes that are JIT compiled. For this reason, we cannot
  3609. cast from one type parameter to another. Also there is no common type for the type parameters, so for example
  3610. an instance of type Array<Int> will return false for instance is Array<object> .
  3611. So we need to:
  3612. 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
  3613. 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.
  3614. 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
  3615. 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)
  3616. 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.
  3617. special literals:
  3618. 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,
  3619. so we can compare them. In C# it's the equivalent of typeof(T).TypeHandle (TypeHandle compare is faster than System.Type.Equals())
  3620. dependencies:
  3621. (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
  3622. Must run AFTER CastDetect. This will be ensured per CastDetect
  3623. *)
  3624. module RealTypeParams =
  3625. struct
  3626. let name = "real_type_params"
  3627. let priority = priority
  3628. let cast_field_name = "cast"
  3629. let rec has_type_params t =
  3630. match follow t with
  3631. | TInst( { cl_kind = KTypeParameter _ }, _) -> true
  3632. | TAbstract(_, params)
  3633. | TEnum(_, params)
  3634. | TInst(_, params) -> List.fold_left (fun acc t -> acc || has_type_params t) false params
  3635. | _ -> false
  3636. let is_hxgeneric = function
  3637. | TClassDecl(cl) ->
  3638. not (Meta.has Meta.NativeGeneric cl.cl_meta)
  3639. | TEnumDecl(e) ->
  3640. not (Meta.has Meta.NativeGeneric e.e_meta)
  3641. | TTypeDecl(t) ->
  3642. not (Meta.has Meta.NativeGeneric t.t_meta)
  3643. | TAbstractDecl a ->
  3644. not (Meta.has Meta.NativeGeneric a.a_meta)
  3645. let rec set_hxgeneric gen mds isfirst md =
  3646. let path = t_path md in
  3647. if List.exists (fun m -> path = t_path m) mds then begin
  3648. if isfirst then
  3649. None (* we still can't determine *)
  3650. else
  3651. Some true (* if we're in second pass and still can't determine, it's because it can be hxgeneric *)
  3652. end else begin
  3653. let has_unresolved = ref false in
  3654. let is_false v =
  3655. match v with
  3656. | Some false -> true
  3657. | None -> has_unresolved := true; false
  3658. | Some true -> false
  3659. in
  3660. let mds = md :: mds in
  3661. match md with
  3662. | TClassDecl(cl) ->
  3663. (* first see if any meta is present (already processed) *)
  3664. if Meta.has Meta.NativeGeneric cl.cl_meta then
  3665. Some false
  3666. else if Meta.has Meta.HaxeGeneric cl.cl_meta then
  3667. Some true
  3668. else if cl.cl_params = [] then
  3669. (cl.cl_meta <- (Meta.HaxeGeneric,[],cl.cl_pos) :: cl.cl_meta;
  3670. Some true)
  3671. else if not (is_hxgen md) then
  3672. (cl.cl_meta <- (Meta.NativeGeneric, [], cl.cl_pos) :: cl.cl_meta;
  3673. Some false)
  3674. else begin
  3675. (*
  3676. if it's not present, see if any superclass is nativegeneric.
  3677. nativegeneric is inherited, while hxgeneric can be later changed to nativegeneric
  3678. *)
  3679. (* on the first pass, our job is to find any evidence that makes it not be hxgeneric. Otherwise it will be hxgeneric *)
  3680. match cl.cl_super with
  3681. | Some (c,_) when is_false (set_hxgeneric gen mds isfirst (TClassDecl c)) ->
  3682. cl.cl_meta <- (Meta.NativeGeneric, [], cl.cl_pos) :: cl.cl_meta;
  3683. Some false
  3684. | _ ->
  3685. (* see if it's a generic class *)
  3686. match cl.cl_params with
  3687. | [] ->
  3688. (* if it's not, then it will be hxgeneric *)
  3689. cl.cl_meta <- (Meta.HaxeGeneric, [], cl.cl_pos) :: cl.cl_meta;
  3690. Some true
  3691. | _ ->
  3692. (* if it is, loop through all fields + statics and look for non-hxgeneric
  3693. generic classes that have KTypeParameter as params *)
  3694. let rec loop cfs =
  3695. match cfs with
  3696. | [] -> false
  3697. | cf :: cfs ->
  3698. let t = follow (gen.greal_type cf.cf_type) in
  3699. match t with
  3700. | TInst( { cl_kind = KTypeParameter _ }, _ ) -> loop cfs
  3701. | TInst(cl,p) when has_type_params t && is_false (set_hxgeneric gen mds isfirst (TClassDecl cl)) ->
  3702. if not (Hashtbl.mem gen.gtparam_cast cl.cl_path) then true else loop cfs
  3703. | TEnum(e,p) when has_type_params t && is_false (set_hxgeneric gen mds isfirst (TEnumDecl e)) ->
  3704. if not (Hashtbl.mem gen.gtparam_cast e.e_path) then true else loop cfs
  3705. | _ -> loop cfs (* TAbstracts / Dynamics can't be generic *)
  3706. in
  3707. if loop cl.cl_ordered_fields then begin
  3708. cl.cl_meta <- (Meta.NativeGeneric, [], cl.cl_pos) :: cl.cl_meta;
  3709. Some false
  3710. end else if isfirst && !has_unresolved then
  3711. None
  3712. else begin
  3713. cl.cl_meta <- (Meta.HaxeGeneric, [], cl.cl_pos) :: cl.cl_meta;
  3714. Some true
  3715. end
  3716. end
  3717. | TEnumDecl e ->
  3718. if Meta.has Meta.NativeGeneric e.e_meta then
  3719. Some false
  3720. else if Meta.has Meta.HaxeGeneric e.e_meta then
  3721. Some true
  3722. else if not (is_hxgen (TEnumDecl e)) then begin
  3723. e.e_meta <- (Meta.NativeGeneric, [], e.e_pos) :: e.e_meta;
  3724. Some false
  3725. end else begin
  3726. (* if enum is not generic, then it's hxgeneric *)
  3727. match e.e_params with
  3728. | [] ->
  3729. e.e_meta <- (Meta.HaxeGeneric, [], e.e_pos) :: e.e_meta;
  3730. Some true
  3731. | _ ->
  3732. let rec loop efs =
  3733. match efs with
  3734. | [] -> false
  3735. | ef :: efs ->
  3736. let t = follow (gen.greal_type ef.ef_type) in
  3737. match t with
  3738. | TFun(args, _) ->
  3739. if List.exists (fun (n,o,t) ->
  3740. let t = follow t in
  3741. match t with
  3742. | TInst( { cl_kind = KTypeParameter _ }, _ ) ->
  3743. false
  3744. | TInst(cl,p) when has_type_params t && is_false (set_hxgeneric gen mds isfirst (TClassDecl cl)) ->
  3745. not (Hashtbl.mem gen.gtparam_cast cl.cl_path)
  3746. | TEnum(e,p) when has_type_params t && is_false (set_hxgeneric gen mds isfirst (TEnumDecl e)) ->
  3747. not (Hashtbl.mem gen.gtparam_cast e.e_path)
  3748. | _ -> false
  3749. ) args then
  3750. true
  3751. else
  3752. loop efs
  3753. | _ -> loop efs
  3754. in
  3755. let efs = PMap.fold (fun ef acc -> ef :: acc) e.e_constrs [] in
  3756. if loop efs then begin
  3757. e.e_meta <- (Meta.NativeGeneric, [], e.e_pos) :: e.e_meta;
  3758. Some false
  3759. end else if isfirst && !has_unresolved then
  3760. None
  3761. else begin
  3762. e.e_meta <- (Meta.HaxeGeneric, [], e.e_pos) :: e.e_meta;
  3763. Some true
  3764. end
  3765. end
  3766. | _ -> assert false
  3767. end
  3768. let set_hxgeneric gen md =
  3769. match set_hxgeneric gen [] true md with
  3770. | None ->
  3771. get (set_hxgeneric gen [] false md)
  3772. | Some v -> v
  3773. let params_has_tparams params =
  3774. List.fold_left (fun acc t -> acc || has_type_params t) false params
  3775. (* ******************************************* *)
  3776. (* RealTypeParamsModf *)
  3777. (* ******************************************* *)
  3778. (*
  3779. This is the module filter of Real Type Parameters. It will traverse through all types and look for hxgeneric classes (only classes).
  3780. When found, a parameterless interface will be created and associated via the "ifaces" Hashtbl to the original class.
  3781. Also a "cast" function will be automatically generated which will handle unsafe downcasts to more specific type parameters (necessary for serialization)
  3782. dependencies:
  3783. Anything that may create hxgeneric classes must run before it.
  3784. Should run before ReflectionCFs (this dependency will be added to ReflectionCFs), so the added interfaces also get to be real IHxObject's
  3785. *)
  3786. module RealTypeParamsModf =
  3787. struct
  3788. let name = "real_type_params_modf"
  3789. let priority = solve_deps name []
  3790. let rec get_fields gen cl params_cl params_cf acc =
  3791. let fields = List.fold_left (fun acc cf ->
  3792. match follow (gen.greal_type (gen.gfollow#run_f (cf.cf_type))) with
  3793. | TInst(cli, ((_ :: _) as p)) when (not (is_hxgeneric (TClassDecl cli))) && params_has_tparams p ->
  3794. (cf, apply_params cl.cl_params params_cl cf.cf_type, apply_params cl.cl_params params_cf cf.cf_type) :: acc
  3795. | TEnum(e, ((_ :: _) as p)) when not (is_hxgeneric (TEnumDecl e)) && params_has_tparams p ->
  3796. (cf, apply_params cl.cl_params params_cl cf.cf_type, apply_params cl.cl_params params_cf cf.cf_type) :: acc
  3797. | _ -> acc
  3798. ) [] cl.cl_ordered_fields in
  3799. match cl.cl_super with
  3800. | Some(cs, tls) ->
  3801. get_fields gen cs (List.map (apply_params cl.cl_params params_cl) tls) (List.map (apply_params cl.cl_params params_cf) tls) (fields @ acc)
  3802. | None -> (fields @ acc)
  3803. (* overrides all needed cast functions from super classes / interfaces to call the new cast function *)
  3804. let create_stub_casts gen cl cast_cfield =
  3805. (* go through superclasses and interfaces *)
  3806. let p = cl.cl_pos in
  3807. let this = { eexpr = TConst TThis; etype = (TInst(cl, List.map snd cl.cl_params)); epos = p } in
  3808. let rec loop cls tls level reverse_params =
  3809. if (level <> 0 || cls.cl_interface) && tls <> [] && is_hxgeneric (TClassDecl cls) then begin
  3810. let cparams = List.map (fun (s,t) -> (s, TInst (map_param (get_cl_t t), []))) cls.cl_params in
  3811. let name = String.concat "_" ((fst cls.cl_path) @ [snd cls.cl_path; cast_field_name]) in
  3812. if not (PMap.mem name cl.cl_fields) then begin
  3813. let reverse_params = List.map (apply_params cls.cl_params (List.map snd cparams)) reverse_params in
  3814. let cfield = mk_class_field name (TFun([], t_dynamic)) false cl.cl_pos (Method MethNormal) cparams in
  3815. let field = { eexpr = TField(this, FInstance(cl,List.map snd cl.cl_params, cast_cfield)); etype = apply_params cast_cfield.cf_params reverse_params cast_cfield.cf_type; epos = p } in
  3816. let call =
  3817. {
  3818. eexpr = TCall(field, []);
  3819. etype = t_dynamic;
  3820. epos = p;
  3821. } in
  3822. let call = gen.gparam_func_call call field reverse_params [] in
  3823. let delay () =
  3824. cfield.cf_expr <-
  3825. Some {
  3826. eexpr = TFunction(
  3827. {
  3828. tf_args = [];
  3829. tf_type = t_dynamic;
  3830. tf_expr =
  3831. {
  3832. eexpr = TReturn( Some call );
  3833. etype = t_dynamic;
  3834. epos = p;
  3835. }
  3836. });
  3837. etype = cfield.cf_type;
  3838. epos = p;
  3839. }
  3840. in
  3841. gen.gafter_filters_ended <- delay :: gen.gafter_filters_ended; (* do not let filters alter this expression content *)
  3842. cl.cl_ordered_fields <- cfield :: cl.cl_ordered_fields;
  3843. cl.cl_fields <- PMap.add cfield.cf_name cfield cl.cl_fields;
  3844. if level <> 0 then cl.cl_overrides <- cfield :: cl.cl_overrides
  3845. end
  3846. end;
  3847. let get_reverse super supertl =
  3848. let kv = List.map2 (fun (_,tparam) applied -> (follow applied, follow tparam)) super.cl_params supertl in
  3849. List.map (fun t ->
  3850. try
  3851. List.assq (follow t) kv
  3852. with | Not_found -> t
  3853. ) reverse_params
  3854. in
  3855. (match cls.cl_super with
  3856. | None -> ()
  3857. | Some(super, supertl) ->
  3858. loop super supertl (level + 1) (get_reverse super supertl));
  3859. List.iter (fun (iface, ifacetl) ->
  3860. loop iface ifacetl level (get_reverse iface ifacetl)
  3861. ) cls.cl_implements
  3862. in
  3863. loop cl (List.map snd cl.cl_params) 0 (List.map snd cl.cl_params)
  3864. (*
  3865. Creates a cast classfield, with the desired name
  3866. Will also look for previous cast() definitions and override them, to reflect the current type and fields
  3867. 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
  3868. 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
  3869. the current type correctly.
  3870. *)
  3871. let create_cast_cfield gen cl name =
  3872. let basic = gen.gcon.basic in
  3873. let cparams = List.map (fun (s,t) -> (s, TInst (map_param (get_cl_t t), []))) cl.cl_params in
  3874. let cfield = mk_class_field name (TFun([], t_dynamic)) false cl.cl_pos (Method MethNormal) cparams in
  3875. let params = List.map snd cparams in
  3876. let fields = get_fields gen cl (List.map snd cl.cl_params) params [] in
  3877. (* now create the contents of the function *)
  3878. (*
  3879. it will look something like:
  3880. if (typeof(T) == typeof(T2)) return this;
  3881. var new_me = new CurrentClass<T2>(EmptyInstnace);
  3882. for (field in Reflect.fields(this))
  3883. {
  3884. switch(field)
  3885. {
  3886. case "aNativeArray":
  3887. var newArray = new NativeArray(this.aNativeArray.Length);
  3888. default:
  3889. Reflect.setField(new_me, field, Reflect.field(this, field));
  3890. }
  3891. }
  3892. *)
  3893. let new_t = TInst(cl, params) in
  3894. let pos = cl.cl_pos in
  3895. let new_me_var = alloc_var "new_me" new_t in
  3896. let local_new_me = { eexpr = TLocal(new_me_var); etype = new_t; epos = pos } in
  3897. let this = { eexpr = TConst(TThis); etype = (TInst(cl, List.map snd cl.cl_params)); epos = pos } in
  3898. let field_var = alloc_var "field" gen.gcon.basic.tstring in
  3899. let local_field = { eexpr = TLocal(field_var); etype = field_var.v_type; epos = pos } in
  3900. let i_var = alloc_var "i" gen.gcon.basic.tint in
  3901. let local_i = { eexpr = TLocal(i_var); etype = gen.gcon.basic.tint; epos = pos } in
  3902. let incr_i = { eexpr = TUnop(Ast.Increment, Ast.Postfix, local_i); etype = basic.tint; epos = pos } in
  3903. let fields_var = alloc_var "fields" (gen.gcon.basic.tarray gen.gcon.basic.tstring) in
  3904. let local_fields = { eexpr = TLocal(fields_var); etype = (gen.gcon.basic.tarray gen.gcon.basic.tstring); epos = pos } in
  3905. let get_path t =
  3906. match follow t with
  3907. | TInst(cl,_) -> cl.cl_path
  3908. | TEnum(e,_) -> e.e_path
  3909. | TAbstract(a,_) -> a.a_path
  3910. | TMono _
  3911. | TDynamic _ -> ([], "Dynamic")
  3912. | _ -> assert false
  3913. in
  3914. (* this will take all fields that were *)
  3915. let fields_to_cases fields =
  3916. List.map (fun (cf, t_cl, t_cf) ->
  3917. let this_field = { eexpr = TField(this, FInstance(cl, List.map snd cl.cl_params, cf)); etype = t_cl; epos = pos } in
  3918. let expr =
  3919. {
  3920. eexpr = TBinop(OpAssign, { eexpr = TField(local_new_me, FInstance(cl, List.map snd cl.cl_params, cf) ); etype = t_cf; epos = pos },
  3921. 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
  3922. );
  3923. etype = t_cf;
  3924. epos = pos;
  3925. } in
  3926. ([{ eexpr = TConst(TString(cf.cf_name)); etype = gen.gcon.basic.tstring; epos = pos }], expr)
  3927. ) fields
  3928. in
  3929. let mk_typehandle =
  3930. let thandle = alloc_var "__typeof__" t_dynamic in
  3931. (fun cl -> { eexpr = TCall(mk_local thandle pos, [ mk_classtype_access cl pos ]); etype = t_dynamic; epos = pos })
  3932. in
  3933. let mk_eq cl1 cl2 =
  3934. { eexpr = TBinop(Ast.OpEq, mk_typehandle cl1, mk_typehandle cl2); etype = basic.tbool; epos = pos }
  3935. in
  3936. let rec mk_typehandle_cond thisparams cfparams =
  3937. match thisparams, cfparams with
  3938. | TInst(cl_this,[]) :: [], TInst(cl_cf,[]) :: [] ->
  3939. mk_eq cl_this cl_cf
  3940. | TInst(cl_this,[]) :: hd, TInst(cl_cf,[]) :: hd2 ->
  3941. { eexpr = TBinop(Ast.OpBoolAnd, mk_eq cl_this cl_cf, mk_typehandle_cond hd hd2); etype = basic.tbool; epos = pos }
  3942. | v :: hd, v2 :: hd2 ->
  3943. (match follow v, follow v2 with
  3944. | (TInst(cl1,[]) as v), (TInst(cl2,[]) as v2) ->
  3945. mk_typehandle_cond (v :: hd) (v2 :: hd2)
  3946. | _ ->
  3947. assert false
  3948. )
  3949. | _ -> assert false
  3950. in
  3951. let fn =
  3952. {
  3953. tf_args = [];
  3954. tf_type = t_dynamic;
  3955. tf_expr =
  3956. {
  3957. eexpr = TBlock([
  3958. (* if (typeof(T) == typeof(T2)) return this *)
  3959. {
  3960. eexpr = TIf(
  3961. mk_typehandle_cond (List.map snd cl.cl_params) params,
  3962. mk_return this,
  3963. None);
  3964. etype = basic.tvoid;
  3965. epos = pos;
  3966. };
  3967. (* var new_me = /*special create empty with tparams construct*/ *)
  3968. {
  3969. eexpr = TVar(new_me_var, Some(gen.gtools.rf_create_empty cl params pos));
  3970. etype = gen.gcon.basic.tvoid;
  3971. epos = pos
  3972. };
  3973. (* var fields = Reflect.fields(this); *)
  3974. {
  3975. eexpr = TVar(fields_var, Some(gen.gtools.r_fields true this));
  3976. etype = gen.gcon.basic.tvoid;
  3977. epos = pos
  3978. };
  3979. (* var i = 0; *)
  3980. {
  3981. eexpr = TVar(i_var, Some(mk_int gen 0 pos));
  3982. etype = gen.gcon.basic.tvoid;
  3983. epos = pos
  3984. };
  3985. {
  3986. eexpr = TWhile( (* while (i < fields.length) *)
  3987. {
  3988. eexpr = TBinop(Ast.OpLt,
  3989. local_i,
  3990. mk_field_access gen local_fields "length" pos);
  3991. etype = gen.gcon.basic.tbool;
  3992. epos = pos
  3993. },
  3994. {
  3995. eexpr = TBlock [
  3996. (* var field = fields[i++]; *)
  3997. {
  3998. eexpr = TVar(field_var, Some { eexpr = TArray (local_fields, incr_i); etype = gen.gcon.basic.tstring; epos = pos });
  3999. etype = gen.gcon.basic.tvoid;
  4000. epos = pos
  4001. };
  4002. (
  4003. (* default: Reflect.setField(new_me, field, Reflect.field(this, field)) *)
  4004. let edef = gen.gtools.r_set_field gen.gcon.basic.tvoid local_new_me local_field (gen.gtools.r_field false gen.gcon.basic.tvoid this local_field) in
  4005. if fields <> [] then
  4006. (* switch(field) { ... } *)
  4007. {
  4008. eexpr = TSwitch(local_field, fields_to_cases fields, Some(edef));
  4009. etype = gen.gcon.basic.tvoid;
  4010. epos = pos;
  4011. }
  4012. else
  4013. edef;
  4014. )
  4015. ];
  4016. etype = gen.gcon.basic.tvoid;
  4017. epos = pos
  4018. },
  4019. Ast.NormalWhile
  4020. );
  4021. etype = gen.gcon.basic.tvoid;
  4022. epos = pos;
  4023. };
  4024. (* return new_me *)
  4025. mk_return local_new_me
  4026. ]);
  4027. etype = t_dynamic;
  4028. epos = pos;
  4029. };
  4030. }
  4031. in
  4032. cfield.cf_expr <- Some( { eexpr = TFunction(fn); etype = cfield.cf_type; epos = pos } );
  4033. cfield
  4034. let create_static_cast_cf gen iface cf =
  4035. let p = iface.cl_pos in
  4036. let basic = gen.gcon.basic in
  4037. let cparams = List.map (fun (s,t) -> ("To_" ^ s, TInst (map_param (get_cl_t t), []))) cf.cf_params in
  4038. let me_type = TInst(iface,[]) in
  4039. let cfield = mk_class_field "__hx_cast" (TFun(["me",false,me_type], t_dynamic)) false iface.cl_pos (Method MethNormal) (cparams) in
  4040. let params = List.map snd cparams in
  4041. let me = alloc_var "me" me_type in
  4042. let field = { eexpr = TField(mk_local me p, FInstance(iface, List.map snd iface.cl_params, cf)); etype = apply_params cf.cf_params params cf.cf_type; epos = p } in
  4043. let call =
  4044. {
  4045. eexpr = TCall(field, []);
  4046. etype = t_dynamic;
  4047. epos = p;
  4048. } in
  4049. let call = gen.gparam_func_call call field params [] in
  4050. (* since object.someCall<ExplicitParameterDefinition>() isn't allowed on Haxe, we need to directly apply the params and delay this call *)
  4051. let delay () =
  4052. cfield.cf_expr <-
  4053. Some {
  4054. eexpr = TFunction(
  4055. {
  4056. tf_args = [me,None];
  4057. tf_type = t_dynamic;
  4058. tf_expr =
  4059. {
  4060. eexpr = TReturn( Some
  4061. {
  4062. eexpr = TIf(
  4063. { eexpr = TBinop(Ast.OpNotEq, mk_local me p, null me.v_type p); etype = basic.tbool; epos = p },
  4064. call,
  4065. Some( null me.v_type p )
  4066. );
  4067. etype = t_dynamic;
  4068. epos = p;
  4069. });
  4070. etype = basic.tvoid;
  4071. epos = p;
  4072. }
  4073. });
  4074. etype = cfield.cf_type;
  4075. epos = p;
  4076. }
  4077. in
  4078. cfield, delay
  4079. let get_cast_name cl = String.concat "_" ((fst cl.cl_path) @ [snd cl.cl_path; cast_field_name]) (* explicitly define it *)
  4080. let default_implementation gen ifaces base_generic =
  4081. let add_iface cl =
  4082. gen.gadd_to_module (TClassDecl cl) (max_dep);
  4083. in
  4084. let implement_stub_cast cthis iface tl =
  4085. let name = get_cast_name iface in
  4086. if not (PMap.mem name cthis.cl_fields) then begin
  4087. let cparams = List.map (fun (s,t) -> ("To_" ^ s, TInst(map_param (get_cl_t t), []))) iface.cl_params in
  4088. let field = mk_class_field name (TFun([],t_dynamic)) false iface.cl_pos (Method MethNormal) cparams in
  4089. let this = { eexpr = TConst TThis; etype = TInst(cthis, List.map snd cthis.cl_params); epos = cthis.cl_pos } in
  4090. field.cf_expr <- Some {
  4091. etype = TFun([],t_dynamic);
  4092. epos = this.epos;
  4093. eexpr = TFunction {
  4094. tf_type = t_dynamic;
  4095. tf_args = [];
  4096. tf_expr = mk_block { this with
  4097. eexpr = TReturn (Some this)
  4098. }
  4099. }
  4100. };
  4101. cthis.cl_ordered_fields <- field :: cthis.cl_ordered_fields;
  4102. cthis.cl_fields <- PMap.add name field cthis.cl_fields
  4103. end
  4104. in
  4105. let rec run md =
  4106. match md with
  4107. | TClassDecl ({ cl_params = [] } as cl) ->
  4108. (* see if we're implementing any generic interface *)
  4109. let rec check (iface,tl) =
  4110. if tl <> [] && set_hxgeneric gen (TClassDecl iface) then
  4111. (* implement cast stub *)
  4112. implement_stub_cast cl iface tl;
  4113. List.iter (fun (s,stl) -> check (s, List.map (apply_params iface.cl_params tl) stl)) iface.cl_implements;
  4114. in
  4115. List.iter (check) cl.cl_implements;
  4116. md
  4117. | TClassDecl ({ cl_params = hd :: tl } as cl) when set_hxgeneric gen md ->
  4118. let iface = mk_class cl.cl_module cl.cl_path cl.cl_pos in
  4119. iface.cl_array_access <- Option.map (apply_params (cl.cl_params) (List.map (fun _ -> t_dynamic) cl.cl_params)) cl.cl_array_access;
  4120. iface.cl_module <- cl.cl_module;
  4121. iface.cl_meta <- (Meta.HxGen, [], cl.cl_pos) :: iface.cl_meta;
  4122. Hashtbl.add ifaces cl.cl_path iface;
  4123. iface.cl_implements <- (base_generic, []) :: iface.cl_implements;
  4124. iface.cl_interface <- true;
  4125. cl.cl_implements <- (iface, []) :: cl.cl_implements;
  4126. let name = get_cast_name cl in
  4127. let cast_cf = create_cast_cfield gen cl name in
  4128. if not cl.cl_interface then create_stub_casts gen cl cast_cf;
  4129. let rec loop c = match c.cl_super with
  4130. | None -> ()
  4131. | Some(sup,_) -> try
  4132. let siface = Hashtbl.find ifaces sup.cl_path in
  4133. iface.cl_implements <- (siface,[]) :: iface.cl_implements;
  4134. ()
  4135. with | Not_found -> loop sup
  4136. in
  4137. loop cl;
  4138. (if not cl.cl_interface then cl.cl_ordered_fields <- cast_cf :: cl.cl_ordered_fields);
  4139. let iface_cf = mk_class_field name cast_cf.cf_type false cast_cf.cf_pos (Method MethNormal) cast_cf.cf_params in
  4140. let cast_static_cf, delay = create_static_cast_cf gen iface iface_cf in
  4141. cl.cl_ordered_statics <- cast_static_cf :: cl.cl_ordered_statics;
  4142. cl.cl_statics <- PMap.add cast_static_cf.cf_name cast_static_cf cl.cl_statics;
  4143. gen.gafter_filters_ended <- delay :: gen.gafter_filters_ended; (* do not let filters alter this expression content *)
  4144. iface_cf.cf_type <- cast_cf.cf_type;
  4145. iface.cl_fields <- PMap.add name iface_cf iface.cl_fields;
  4146. iface.cl_ordered_fields <- [iface_cf];
  4147. add_iface iface;
  4148. md
  4149. | TTypeDecl _ | TAbstractDecl _ -> md
  4150. | TEnumDecl _ ->
  4151. ignore (set_hxgeneric gen md);
  4152. md
  4153. | _ -> ignore (set_hxgeneric gen md); md
  4154. in
  4155. run
  4156. let configure gen mapping_func =
  4157. let map e = Some(mapping_func e) in
  4158. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  4159. end;;
  4160. (* create a common interface without type parameters and only a __Cast<> function *)
  4161. let default_implementation gen (dyn_tparam_cast:texpr->t->texpr) ifaces =
  4162. let change_expr e cl iface params =
  4163. let field = mk_static_field_access_infer cl "__hx_cast" e.epos params in
  4164. let elist = [mk_cast (TInst(iface,[])) e] in
  4165. let call = { eexpr = TCall(field, elist); etype = t_dynamic; epos = e.epos } in
  4166. gen.gparam_func_call call field params elist
  4167. in
  4168. let rec run e =
  4169. match e.eexpr with
  4170. | TCast(cast_expr, _) ->
  4171. (* see if casting to a native generic class *)
  4172. let t = gen.greal_type e.etype in
  4173. let unifies =
  4174. let ctype = gen.greal_type cast_expr.etype in
  4175. match follow ctype with
  4176. | TInst(cl,_) -> (try
  4177. unify ctype t;
  4178. true
  4179. with | Unify_error el ->
  4180. false)
  4181. | _ -> false
  4182. in
  4183. let unifies = unifies && not (PMap.mem "cs_safe_casts" gen.gcon.defines) in
  4184. (match follow t with
  4185. | TInst(cl, p1 :: pl) when is_hxgeneric (TClassDecl cl) && not unifies ->
  4186. let iface = Hashtbl.find ifaces cl.cl_path in
  4187. mk_cast e.etype (change_expr (Type.map_expr run cast_expr) cl iface (p1 :: pl))
  4188. | _ -> Type.map_expr run e
  4189. )
  4190. | _ -> Type.map_expr run e
  4191. in
  4192. run
  4193. let configure gen traverse =
  4194. gen.ghas_tparam_cast_handler <- true;
  4195. let map e = Some(traverse e) in
  4196. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  4197. let default_config gen (dyn_tparam_cast:texpr->t->texpr) ifaces base_generic =
  4198. configure gen (default_implementation gen dyn_tparam_cast ifaces);
  4199. RealTypeParamsModf.configure gen (RealTypeParamsModf.default_implementation gen ifaces base_generic)
  4200. end;;
  4201. (* ******************************************* *)
  4202. (* Rename Type Parameters *)
  4203. (* ******************************************* *)
  4204. (*
  4205. This module should run after everything is already applied,
  4206. it will look for possible type parameter name clashing and change the classes names to a
  4207. dependencies:
  4208. should run after everything is already applied. There's no configure on this module, only 'run'.
  4209. *)
  4210. module RenameTypeParameters =
  4211. struct
  4212. let name = "rename_type_parameters"
  4213. let run gen =
  4214. let i = ref 0 in
  4215. let found_types = ref PMap.empty in
  4216. let check_type name on_changed =
  4217. let rec loop name =
  4218. incr i;
  4219. let changed_name = (name ^ (string_of_int !i)) in
  4220. if PMap.mem changed_name !found_types then loop name else changed_name
  4221. in
  4222. if PMap.mem name !found_types then begin
  4223. let new_name = loop name in
  4224. found_types := PMap.add new_name true !found_types;
  4225. on_changed new_name
  4226. end else found_types := PMap.add name true !found_types
  4227. in
  4228. let get_cls t =
  4229. match follow t with
  4230. | TInst(cl,_) -> cl
  4231. | _ -> assert false
  4232. in
  4233. let iter_types (_,t) =
  4234. let cls = get_cls t in
  4235. check_type (snd cls.cl_path) (fun name -> cls.cl_path <- (fst cls.cl_path, name))
  4236. in
  4237. List.iter (function
  4238. | TClassDecl cl ->
  4239. i := 0;
  4240. found_types := PMap.empty;
  4241. List.iter iter_types cl.cl_params;
  4242. let cur_found_types = !found_types in
  4243. List.iter (fun cf ->
  4244. found_types := cur_found_types;
  4245. List.iter iter_types cf.cf_params
  4246. ) (cl.cl_ordered_fields @ cl.cl_ordered_statics)
  4247. | TEnumDecl ( ({ e_params = hd :: tl }) ) ->
  4248. i := 0;
  4249. found_types := PMap.empty;
  4250. List.iter iter_types (hd :: tl)
  4251. | TAbstractDecl { a_params = hd :: tl } ->
  4252. i := 0;
  4253. found_types := PMap.empty;
  4254. List.iter iter_types (hd :: tl)
  4255. | _ -> ()
  4256. ) gen.gcon.types
  4257. end;;
  4258. let configure gen (param_func_call:texpr->texpr->tparams->texpr list->texpr) =
  4259. (*let map e = Some(mapping_func e) in
  4260. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority) map*)
  4261. gen.gparam_func_call <- param_func_call
  4262. end;;
  4263. (**************************************************************************************************************************)
  4264. (* SYNTAX FILTERS *)
  4265. (**************************************************************************************************************************)
  4266. (* ******************************************* *)
  4267. (* Expression Unwrap *)
  4268. (* ******************************************* *)
  4269. (*
  4270. 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,
  4271. and will unwrap statements where expressions are expected, and vice-versa.
  4272. 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
  4273. 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
  4274. side-effects free, for example
  4275. 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,
  4276. 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)"
  4277. dependencies:
  4278. While it's best for Expression Unwrap to delay its execution as much as possible, since theoretically any
  4279. filter can return an expression that needs to be unwrapped, it is also desirable for ExpresionUnwrap to have
  4280. the AST as close as possible as Haxe's, so it can make some correct predictions (for example, so it can
  4281. more accurately know what can be side-effects-free and what can't).
  4282. This way, it will run slightly after the Normal priority, so if you don't say that a syntax filter must run
  4283. before Expression Unwrap, it will run after it.
  4284. TODO : While statement must become do / while, with the actual block inside an if for the condition, and else for 'break'
  4285. *)
  4286. module ExpressionUnwrap =
  4287. struct
  4288. let name = "expression_unwrap"
  4289. (* priority: first syntax filter *)
  4290. let priority = -10.0
  4291. (*
  4292. We always need to rely on Blocks to be able to unwrap expressions correctly.
  4293. So the the standard traverse will always be based on blocks.
  4294. Normal block statements, like for(), while(), if(), ... will be mk_block'ed so there is always a block inside of them.
  4295. At the block level, we'll define an "add_statement" function, which will allow the current expression to
  4296. 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.
  4297. - traverse will always evaluate TBlocks
  4298. - for each texpr in a TBlock list,
  4299. check shallow type
  4300. if type is Statement or Both when it has problematic expression (var problematic_expr = count_problematic_expressions),
  4301. if we can eagerly call unwrap_statement on the whole expression (try_call_unwrap_statement), use the return expression
  4302. else
  4303. check expr_type of each underlying type (with expr_stat_map)
  4304. if it has ExprWithStatement or Statement,
  4305. call problematic_expression_unwrap in it
  4306. problematic_expr--
  4307. else if problematic_expr == 0, just add the unchanged expression
  4308. else if NoSideEffects and doesn't have short-circuit, just add the unchanged expression
  4309. else call problematic_expression_unwrap in it
  4310. if type is Expression, check if there are statements or Both inside.
  4311. if there are, problematic_expression_unwrap in it
  4312. aftewards, use on_expr_as_statement to get it
  4313. helpers:
  4314. try_call_unwrap_statement: (returns texpr option)
  4315. 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.
  4316. apply_assign:
  4317. if is TVar, first declare the tvar with default expression = null;
  4318. will receive the left and right side of the assignment; right-side must be Statement
  4319. see if right side is a short-circuit operation, call short_circuit_op_unwrap
  4320. else see eexpr of the right side
  4321. if it's void, just add the statement with add_statement, and set the right side as null;
  4322. if not, it will have a block inside. set the left side = to the last expression on each block inside. add_statement for it.
  4323. short_circuit_op_unwrap: x() && (1 + {var x = 0; x + 1;} == 2) && z()
  4324. -> var x = x();
  4325. var y = false;
  4326. var z = false;
  4327. if (x) //for &&, neg for ||
  4328. {
  4329. var temp = null;
  4330. {
  4331. var x = 0;
  4332. temp = x + 1;
  4333. }
  4334. y = (1 + temp) == 2;
  4335. if (y)
  4336. {
  4337. z = z();
  4338. }
  4339. }
  4340. expects to receive a texpr with TBinop(OpBoolAnd/OpBoolOr)
  4341. 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.
  4342. will collect the return value, a mapped expr with all exprs as TLocal of the temp vars created
  4343. problematic_expression_unwrap:
  4344. check expr_kind:
  4345. if it is NoSideEffects and not short-circuit, leave it there
  4346. if it is ExprWithStatement and not short-circuit, call Type.map_expr problematic_expression_unwrap
  4347. if it is Statement or Expression or short-circuit expr, call add_assign for this expression
  4348. add_assign:
  4349. see if the type is void. If it is, just add_statement the expression argument, and return a null value
  4350. 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.
  4351. map_problematic_expr:
  4352. call expr_stat_map on statement with problematic_expression_unwrap
  4353. types:
  4354. type shallow_expr_type = | Statement | Expression | Both (* shallow expression classification. Both means that they can be either Statements as Expressions *)
  4355. type expr_kind = | NormalExpr | ExprNoSideEffects (* -> short-circuit is considered side-effects *) | ExprWithStatement | Statement
  4356. evaluates an expression (as in not a statement) type. If it is ExprWithStatement or Statement, it means it contains errors
  4357. functions:
  4358. shallow_expr_type (expr:texpr) : shallow_expr_type
  4359. expr_kind (expr:texpr) : expr_kind
  4360. deeply evaluates an expression type
  4361. expr_stat_map (fn:texpr->texpr) (expr:texpr) : texpr
  4362. it will traverse the AST looking for places where an expression is expected, and map the value according to fn
  4363. aggregate_expr_type (is_side_effects_free:bool) (children:expr_type list) : expr_type
  4364. helper function to deal with expr_type aggregation (e.g. an Expression + a Statement as a children, is a ExprWithStatement)
  4365. check_statement_in_expression (expr:texpr) : texpr option :
  4366. will check
  4367. *)
  4368. type shallow_expr_type = | Statement | Expression of texpr | Both of texpr (* shallow expression classification. Both means that they can be either Statements as Expressions *)
  4369. type expr_kind = | KNormalExpr | KNoSideEffects (* -> short-circuit is considered side-effects *) | KExprWithStatement | KStatement
  4370. let rec no_paren e =
  4371. match e.eexpr with
  4372. | TParenthesis e -> no_paren e
  4373. | _ -> e
  4374. (* must be called in a statement. Will execute fn whenever an expression (not statement) is expected *)
  4375. let rec expr_stat_map fn (expr:texpr) =
  4376. match (no_paren expr).eexpr with
  4377. | TBinop ( (Ast.OpAssign as op), left_e, right_e )
  4378. | TBinop ( (Ast.OpAssignOp _ as op), left_e, right_e ) ->
  4379. { expr with eexpr = TBinop(op, fn left_e, fn right_e) }
  4380. | TParenthesis _ -> assert false
  4381. | TCall(left_e, params) ->
  4382. { expr with eexpr = TCall(fn left_e, List.map fn params) }
  4383. | TNew(cl, tparams, params) ->
  4384. { expr with eexpr = TNew(cl, tparams, List.map fn params) }
  4385. | TVar(v,eopt) ->
  4386. { expr with eexpr = TVar(v, Option.map fn eopt) }
  4387. | TFor (v,cond,block) ->
  4388. { expr with eexpr = TFor(v, fn cond, block) }
  4389. | TIf(cond,eif,eelse) ->
  4390. { expr with eexpr = TIf(fn cond, eif, eelse) }
  4391. | TWhile(cond, block, flag) ->
  4392. { expr with eexpr = TWhile(fn cond, block, flag) }
  4393. | TSwitch(cond, el_block_l, default) ->
  4394. { expr with eexpr = TSwitch( fn cond, List.map (fun (el,block) -> (List.map fn el, block)) el_block_l, default ) }
  4395. (* | TMatch(cond, enum, cases, default) ->
  4396. { expr with eexpr = TMatch(fn cond, enum, cases, default) } *)
  4397. | TReturn(eopt) ->
  4398. { expr with eexpr = TReturn(Option.map fn eopt) }
  4399. | TThrow (texpr) ->
  4400. { expr with eexpr = TThrow(fn texpr) }
  4401. | TBreak
  4402. | TContinue
  4403. | TTry _
  4404. | TUnop (Ast.Increment, _, _)
  4405. | TUnop (Ast.Decrement, _, _) (* unop is a special case because the haxe compiler won't let us generate complex expressions with Increment/Decrement *)
  4406. | TBlock _ -> expr (* there is no expected expression here. Only statements *)
  4407. | TMeta(m,e) ->
  4408. { expr with eexpr = TMeta(m,expr_stat_map fn e) }
  4409. | _ -> assert false (* we only expect valid statements here. other expressions aren't valid statements *)
  4410. let is_expr = function | Expression _ -> true | _ -> false
  4411. let aggregate_expr_type map_fn side_effects_free children =
  4412. let rec loop acc children =
  4413. match children with
  4414. | [] -> acc
  4415. | hd :: children ->
  4416. match acc, map_fn hd with
  4417. | _, KExprWithStatement
  4418. | _, KStatement
  4419. | KExprWithStatement, _
  4420. | KStatement, _ -> KExprWithStatement
  4421. | KNormalExpr, KNoSideEffects
  4422. | KNoSideEffects, KNormalExpr
  4423. | KNormalExpr, KNormalExpr -> loop KNormalExpr children
  4424. | KNoSideEffects, KNoSideEffects -> loop KNoSideEffects children
  4425. in
  4426. loop (if side_effects_free then KNoSideEffects else KNormalExpr) children
  4427. (* statements: *)
  4428. (* Error CS0201: Only assignment, call, increment, *)
  4429. (* decrement, and new object expressions can be used as a *)
  4430. (* statement (CS0201). *)
  4431. let rec shallow_expr_type expr : shallow_expr_type =
  4432. match expr.eexpr with
  4433. | TCall _ when not (is_void expr.etype) -> Both expr
  4434. | TNew _
  4435. | TUnop (Ast.Increment, _, _)
  4436. | TUnop (Ast.Decrement, _, _)
  4437. | TBinop (Ast.OpAssign, _, _)
  4438. | TBinop (Ast.OpAssignOp _, _, _) -> Both expr
  4439. | TIf (cond, eif, Some(eelse)) -> (match aggregate_expr_type expr_kind true [cond;eif;eelse] with
  4440. | KExprWithStatement -> Statement
  4441. | _ -> Both expr)
  4442. | TConst _
  4443. | TLocal _
  4444. | TArray _
  4445. | TBinop _
  4446. | TField _
  4447. | TEnumParameter _
  4448. | TTypeExpr _
  4449. | TObjectDecl _
  4450. | TArrayDecl _
  4451. | TFunction _
  4452. | TCast _
  4453. | TUnop _ -> Expression (expr)
  4454. | TParenthesis p | TMeta(_,p) -> shallow_expr_type p
  4455. | TBlock ([e]) -> shallow_expr_type e
  4456. | TCall _
  4457. | TVar _
  4458. | TBlock _
  4459. | TFor _
  4460. | TWhile _
  4461. | TSwitch _
  4462. | TTry _
  4463. | TReturn _
  4464. | TBreak
  4465. | TContinue
  4466. | TIf _
  4467. | TThrow _ -> Statement
  4468. and expr_kind expr =
  4469. match shallow_expr_type expr with
  4470. | Statement -> KStatement
  4471. | Both expr | Expression expr ->
  4472. let aggregate = aggregate_expr_type expr_kind in
  4473. match expr.eexpr with
  4474. | TConst _
  4475. | TLocal _
  4476. | TFunction _
  4477. | TTypeExpr _ ->
  4478. KNoSideEffects
  4479. | TCall (ecall, params) ->
  4480. aggregate false (ecall :: params)
  4481. | TNew (_,_,params) ->
  4482. aggregate false params
  4483. | TUnop (Increment,_,e)
  4484. | TUnop (Decrement,_,e) ->
  4485. aggregate false [e]
  4486. | TUnop (_,_,e) ->
  4487. aggregate true [e]
  4488. | TBinop (Ast.OpBoolAnd, e1, e2)
  4489. | TBinop (Ast.OpBoolOr, e1, e2) -> (* TODO: should OpBool never be side-effects free? *)
  4490. aggregate true [e1;e2]
  4491. | TBinop (Ast.OpAssign, e1, e2)
  4492. | TBinop (Ast.OpAssignOp _, e1, e2) ->
  4493. aggregate false [e1;e2]
  4494. | TBinop (_, e1, e2) ->
  4495. aggregate true [e1;e2]
  4496. | TIf (cond, eif, Some(eelse)) -> (match aggregate true [cond;eif;eelse] with
  4497. | KExprWithStatement -> KStatement
  4498. | k -> k)
  4499. | TArray (e1,e2) ->
  4500. aggregate true [e1;e2]
  4501. | TParenthesis e
  4502. | TMeta(_,e)
  4503. | TField (e,_) ->
  4504. aggregate true [e]
  4505. | TArrayDecl (el) ->
  4506. aggregate true el
  4507. | TObjectDecl (sel) ->
  4508. aggregate true (List.map snd sel)
  4509. | TCast (e,_) ->
  4510. aggregate true [e]
  4511. | _ -> trace (debug_expr expr); assert false (* should have been read as Statement by shallow_expr_type *)
  4512. let is_side_effects_free e =
  4513. match expr_kind e with | KNoSideEffects -> true | _ -> false
  4514. let get_kinds (statement:texpr) =
  4515. let kinds = ref [] in
  4516. ignore (expr_stat_map (fun e ->
  4517. kinds := (expr_kind e) :: !kinds;
  4518. e
  4519. ) statement);
  4520. List.rev !kinds
  4521. let has_problematic_expressions (kinds:expr_kind list) =
  4522. let rec loop kinds =
  4523. match kinds with
  4524. | [] -> false
  4525. | KStatement :: _
  4526. | KExprWithStatement :: _ -> true
  4527. | _ :: tl -> loop tl
  4528. in
  4529. loop kinds
  4530. let count_problematic_expressions (statement:texpr) =
  4531. let count = ref 0 in
  4532. ignore (expr_stat_map (fun e ->
  4533. (match expr_kind e with
  4534. | KStatement | KExprWithStatement -> incr count
  4535. | _ -> ()
  4536. );
  4537. e
  4538. ) statement);
  4539. !count
  4540. let apply_assign_block assign_fun elist =
  4541. let rec assign acc elist =
  4542. match elist with
  4543. | [] -> acc
  4544. | last :: [] ->
  4545. (assign_fun last) :: acc
  4546. | hd :: tl ->
  4547. assign (hd :: acc) tl
  4548. in
  4549. List.rev (assign [] elist)
  4550. let mk_get_block assign_fun e =
  4551. match e.eexpr with
  4552. | TBlock [] -> e
  4553. | TBlock (el) ->
  4554. { e with eexpr = TBlock(apply_assign_block assign_fun el) }
  4555. | _ ->
  4556. { e with eexpr = TBlock([ assign_fun e ]) }
  4557. let add_assign gen add_statement expr =
  4558. match expr.eexpr, follow expr.etype with
  4559. | _, TAbstract ({ a_path = ([],"Void") },[])
  4560. | TThrow _, _ ->
  4561. add_statement expr;
  4562. null expr.etype expr.epos
  4563. | _ ->
  4564. let var = mk_temp gen "stmt" expr.etype in
  4565. let tvars = { expr with eexpr = TVar(var,Some(expr)) } in
  4566. let local = { expr with eexpr = TLocal(var) } in
  4567. add_statement tvars;
  4568. local
  4569. (* requirement: right must be a statement *)
  4570. let rec apply_assign assign_fun right =
  4571. match right.eexpr with
  4572. | TBlock el ->
  4573. { right with eexpr = TBlock(apply_assign_block assign_fun el) }
  4574. | TSwitch (cond, elblock_l, default) ->
  4575. { 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) }
  4576. (* | TMatch (cond, ep, il_vlo_e_l, default) ->
  4577. { 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) } *)
  4578. | TTry (block, catches) ->
  4579. { right with eexpr = TTry(mk_get_block assign_fun block, List.map (fun (v,block) -> (v,mk_get_block assign_fun block) ) catches) }
  4580. | TIf (cond,eif,eelse) ->
  4581. { right with eexpr = TIf(cond, mk_get_block assign_fun eif, Option.map (mk_get_block assign_fun) eelse) }
  4582. | TThrow _
  4583. | TWhile _
  4584. | TFor _
  4585. | TReturn _
  4586. | TBreak
  4587. | TContinue -> right
  4588. | TParenthesis p | TMeta(_,p) ->
  4589. apply_assign assign_fun p
  4590. | TVar _ ->
  4591. right
  4592. | _ ->
  4593. match follow right.etype with
  4594. | TAbstract ({ a_path = ([], "Void") },[]) ->
  4595. right
  4596. | _ -> trace (debug_expr right); assert false (* a statement is required *)
  4597. let short_circuit_op_unwrap gen add_statement expr :texpr =
  4598. let do_not expr =
  4599. { expr with eexpr = TUnop(Ast.Not, Ast.Prefix, expr) }
  4600. in
  4601. (* loop will always return its own TBlock, and the mapped expression *)
  4602. let rec loop acc expr =
  4603. match expr.eexpr with
  4604. | TBinop ( (Ast.OpBoolAnd as op), left, right) ->
  4605. let var = mk_temp gen "boolv" right.etype in
  4606. 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
  4607. let local = { right with eexpr = TLocal(var) } in
  4608. let mapped_left, ret_acc = loop ( (local, { right with eexpr = TBinop(Ast.OpAssign, local, right) } ) :: acc) left in
  4609. add_statement tvars;
  4610. ({ expr with eexpr = TBinop(op, mapped_left, local) }, ret_acc)
  4611. (* we only accept OpBoolOr when it's the first to be evaluated *)
  4612. | TBinop ( (Ast.OpBoolOr as op), left, right) when acc = [] ->
  4613. let left = match left.eexpr with
  4614. | TLocal _ | TConst _ -> left
  4615. | _ -> add_assign gen add_statement left
  4616. in
  4617. let var = mk_temp gen "boolv" right.etype in
  4618. 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
  4619. let local = { right with eexpr = TLocal(var) } in
  4620. add_statement tvars;
  4621. ({ expr with eexpr = TBinop(op, left, local) }, [ do_not left, { right with eexpr = TBinop(Ast.OpAssign, local, right) } ])
  4622. | _ when acc = [] -> assert false
  4623. | _ ->
  4624. let var = mk_temp gen "boolv" expr.etype in
  4625. let tvars = { expr with eexpr = TVar(var, Some( { expr with etype = gen.gcon.basic.tbool } )); etype = gen.gcon.basic.tvoid } in
  4626. let local = { expr with eexpr = TLocal(var) } in
  4627. let last_local = ref local in
  4628. let acc = List.map (fun (local, assign) ->
  4629. let l = !last_local in
  4630. last_local := local;
  4631. (l, assign)
  4632. ) acc in
  4633. add_statement tvars;
  4634. (local, acc)
  4635. in
  4636. let mapped_expr, local_assign_list = loop [] expr in
  4637. let rec loop local_assign_list : texpr =
  4638. match local_assign_list with
  4639. | [local, assign] ->
  4640. { eexpr = TIf(local, assign, None); etype = gen.gcon.basic.tvoid; epos = assign.epos }
  4641. | (local, assign) :: tl ->
  4642. { eexpr = TIf(local,
  4643. {
  4644. eexpr = TBlock ( assign :: [loop tl] );
  4645. etype = gen.gcon.basic.tvoid;
  4646. epos = assign.epos;
  4647. },
  4648. None); etype = gen.gcon.basic.tvoid; epos = assign.epos }
  4649. | [] -> assert false
  4650. in
  4651. add_statement (loop local_assign_list);
  4652. mapped_expr
  4653. (* there are two short_circuit fuctions as I'm still testing the best way to do it *)
  4654. (*let short_circuit_op_unwrap gen add_statement expr :texpr =
  4655. let block = ref [] in
  4656. let rec short_circuit_op_unwrap is_first last_block expr =
  4657. match expr.eexpr with
  4658. | TBinop ( (Ast.OpBoolAnd as op), left, right)
  4659. | TBinop ( (Ast.OpBoolOr as op), left, right) ->
  4660. let var = mk_temp gen "boolv" left.etype in
  4661. 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
  4662. let local = { left with eexpr = TLocal(var) } in
  4663. if not is_first then begin
  4664. last_block := !last_block @ [ { left with eexpr = TBinop(Ast.OpAssign, local, left) } ]
  4665. end;
  4666. add_statement tvars;
  4667. let local_op = match op with | Ast.OpBoolAnd -> local | Ast.OpBoolOr -> { local with eexpr = TUnop(Ast.Not, Ast.Prefix, local) } | _ -> assert false in
  4668. let new_block = ref [] in
  4669. let new_right = short_circuit_op_unwrap false new_block right in
  4670. last_block := !last_block @ [ { expr with eexpr = TIf(local_op, { right with eexpr = TBlock(!new_block) }, None) } ];
  4671. { expr with eexpr = TBinop(op, local, new_right) }
  4672. | _ when is_first -> assert false
  4673. | _ ->
  4674. let var = mk_temp gen "boolv" expr.etype in
  4675. let tvars = { expr with eexpr = TVar([var, Some ( { expr with eexpr = TConst(TBool false) } ) ]); etype = gen.gcon.basic.tvoid } in
  4676. let local = { expr with eexpr = TLocal(var) } in
  4677. last_block := !last_block @ [ { expr with eexpr = TBinop(Ast.OpAssign, local, expr) } ];
  4678. add_statement tvars;
  4679. local
  4680. in
  4681. let mapped_expr = short_circuit_op_unwrap true block expr in
  4682. add_statement { eexpr = TBlock(!block); etype = gen.gcon.basic.tvoid; epos = expr.epos };
  4683. mapped_expr*)
  4684. let twhile_with_condition_statement gen add_statement twhile cond e1 flag =
  4685. (* when a TWhile is found with a problematic condition *)
  4686. let basic = gen.gcon.basic in
  4687. let block = if flag = Ast.NormalWhile then
  4688. { e1 with eexpr = TIf(cond, e1, Some({ e1 with eexpr = TBreak; etype = basic.tvoid })) }
  4689. else
  4690. Type.concat e1 { e1 with
  4691. eexpr = TIf({
  4692. eexpr = TUnop(Ast.Not, Ast.Prefix, mk_paren cond);
  4693. etype = basic.tbool;
  4694. epos = cond.epos
  4695. }, { e1 with eexpr = TBreak; etype = basic.tvoid }, None);
  4696. etype = basic.tvoid
  4697. }
  4698. in
  4699. add_statement { twhile with
  4700. eexpr = TWhile(
  4701. { eexpr = TConst(TBool true); etype = basic.tbool; epos = cond.epos },
  4702. block,
  4703. Ast.DoWhile
  4704. );
  4705. }
  4706. let try_call_unwrap_statement gen problematic_expression_unwrap (add_statement:texpr->unit) (expr:texpr) : texpr option =
  4707. let check_left left =
  4708. match expr_kind left with
  4709. | KExprWithStatement ->
  4710. problematic_expression_unwrap add_statement left KExprWithStatement
  4711. | KStatement -> assert false (* doesn't make sense a KStatement as a left side expression *)
  4712. | _ -> left
  4713. in
  4714. let handle_assign op left right =
  4715. let left = check_left left in
  4716. 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 )
  4717. in
  4718. let handle_return e =
  4719. Some( apply_assign (fun e ->
  4720. match e.eexpr with
  4721. | TThrow _ -> e
  4722. | _ when is_void e.etype ->
  4723. { e with eexpr = TBlock([e; { e with eexpr = TReturn None }]) }
  4724. | _ ->
  4725. { e with eexpr = TReturn( Some e ) }
  4726. ) e )
  4727. in
  4728. let is_problematic_if right =
  4729. match expr_kind right with
  4730. | KStatement | KExprWithStatement -> true
  4731. | _ -> false
  4732. in
  4733. match expr.eexpr with
  4734. | TBinop((Ast.OpAssign as op),left,right)
  4735. | TBinop((Ast.OpAssignOp _ as op),left,right) when shallow_expr_type right = Statement ->
  4736. handle_assign op left right
  4737. | TReturn( Some right ) when shallow_expr_type right = Statement ->
  4738. handle_return right
  4739. | TBinop((Ast.OpAssign as op),left, ({ eexpr = TBinop(Ast.OpBoolAnd,_,_) } as right) )
  4740. | TBinop((Ast.OpAssign as op),left,({ eexpr = TBinop(Ast.OpBoolOr,_,_) } as right))
  4741. | TBinop((Ast.OpAssignOp _ as op),left,({ eexpr = TBinop(Ast.OpBoolAnd,_,_) } as right) )
  4742. | TBinop((Ast.OpAssignOp _ as op),left,({ eexpr = TBinop(Ast.OpBoolOr,_,_) } as right) ) ->
  4743. let right = short_circuit_op_unwrap gen add_statement right in
  4744. Some { expr with eexpr = TBinop(op, check_left left, right) }
  4745. | TVar(v,Some({ eexpr = TBinop(Ast.OpBoolAnd,_,_) } as right))
  4746. | TVar(v,Some({ eexpr = TBinop(Ast.OpBoolOr,_,_) } as right)) ->
  4747. let right = short_circuit_op_unwrap gen add_statement right in
  4748. Some { expr with eexpr = TVar(v, Some(right)) }
  4749. | TVar(v,Some(right)) when shallow_expr_type right = Statement ->
  4750. add_statement ({ expr with eexpr = TVar(v, Some(null right.etype right.epos)) });
  4751. handle_assign Ast.OpAssign { expr with eexpr = TLocal(v); etype = v.v_type } right
  4752. (* TIf handling *)
  4753. | TBinop((Ast.OpAssign as op),left, ({ eexpr = TIf _ } as right))
  4754. | TBinop((Ast.OpAssignOp _ as op),left,({ eexpr = TIf _ } as right)) when is_problematic_if right ->
  4755. handle_assign op left right
  4756. | TVar(v,Some({ eexpr = TIf _ } as right)) when is_problematic_if right ->
  4757. add_statement ({ expr with eexpr = TVar(v, Some(null right.etype right.epos)) });
  4758. handle_assign Ast.OpAssign { expr with eexpr = TLocal(v); etype = v.v_type } right
  4759. | TWhile(cond, e1, flag) when is_problematic_if cond ->
  4760. twhile_with_condition_statement gen add_statement expr cond e1 flag;
  4761. Some (null expr.etype expr.epos)
  4762. | _ -> None
  4763. let traverse gen (on_expr_as_statement:texpr->texpr option) =
  4764. let add_assign = add_assign gen in
  4765. let problematic_expression_unwrap add_statement expr e_type =
  4766. let rec problematic_expression_unwrap is_first expr e_type =
  4767. match e_type, expr.eexpr with
  4768. | _, TBinop(Ast.OpBoolAnd, _, _)
  4769. | _, TBinop(Ast.OpBoolOr, _, _) -> add_assign add_statement expr (* add_assign so try_call_unwrap_expr *)
  4770. | KNoSideEffects, _ -> expr
  4771. | KStatement, _
  4772. | KNormalExpr, _ -> add_assign add_statement expr
  4773. | KExprWithStatement, TCall _
  4774. | KExprWithStatement, TNew _
  4775. | KExprWithStatement, TBinop (Ast.OpAssign,_,_)
  4776. | KExprWithStatement, TBinop (Ast.OpAssignOp _,_,_)
  4777. | KExprWithStatement, TUnop (Ast.Increment,_,_) (* all of these may have side-effects, so they must also be add_assign'ed . is_first avoids infinite loop *)
  4778. | KExprWithStatement, TUnop (Ast.Decrement,_,_) when not is_first -> add_assign add_statement expr
  4779. (* bugfix: Type.map_expr doesn't guarantee the correct order of execution *)
  4780. | KExprWithStatement, TBinop(op,e1,e2) ->
  4781. let e1 = problematic_expression_unwrap false e1 (expr_kind e1) in
  4782. let e2 = problematic_expression_unwrap false e2 (expr_kind e2) in
  4783. { expr with eexpr = TBinop(op, e1, e2) }
  4784. | KExprWithStatement, TArray(e1,e2) ->
  4785. let e1 = problematic_expression_unwrap false e1 (expr_kind e1) in
  4786. let e2 = problematic_expression_unwrap false e2 (expr_kind e2) in
  4787. { expr with eexpr = TArray(e1, e2) }
  4788. (* bugfix: calls should not be transformed into closure calls *)
  4789. | KExprWithStatement, TCall(( { eexpr = TField (ef_left, f) } as ef ), eargs) ->
  4790. { expr with eexpr = TCall(
  4791. { ef with eexpr = TField(problematic_expression_unwrap false ef_left (expr_kind ef_left), f) },
  4792. List.map (fun e -> problematic_expression_unwrap false e (expr_kind e)) eargs)
  4793. }
  4794. | KExprWithStatement, _ -> Type.map_expr (fun e -> problematic_expression_unwrap false e (expr_kind e)) expr
  4795. in
  4796. problematic_expression_unwrap true expr e_type
  4797. in
  4798. let rec traverse e =
  4799. match e.eexpr with
  4800. | TBlock el ->
  4801. let new_block = ref [] in
  4802. let rec process_statement e =
  4803. let e = no_paren e in
  4804. match e.eexpr, shallow_expr_type e with
  4805. | TCall( { eexpr = TLocal v } as elocal, elist ), _ when String.get v.v_name 0 = '_' && Hashtbl.mem gen.gspecial_vars v.v_name ->
  4806. new_block := { e with eexpr = TCall( elocal, List.map (fun e ->
  4807. match e.eexpr with
  4808. | TBlock _ -> traverse e
  4809. | _ -> e
  4810. ) elist ) } :: !new_block
  4811. | _, Statement | _, Both _ ->
  4812. let e = match e.eexpr with | TReturn (Some ({ eexpr = TThrow _ } as ethrow)) -> ethrow | _ -> e in
  4813. let kinds = get_kinds e in
  4814. if has_problematic_expressions kinds then begin
  4815. match try_call_unwrap_statement gen problematic_expression_unwrap add_statement e with
  4816. | Some { eexpr = TConst(TNull) } (* no op *)
  4817. | Some { eexpr = TBlock [] } -> ()
  4818. | Some e ->
  4819. if has_problematic_expressions (get_kinds e) then begin
  4820. process_statement e
  4821. end else
  4822. new_block := (traverse e) :: !new_block
  4823. | None ->
  4824. (
  4825. let acc = ref kinds in
  4826. let new_e = expr_stat_map (fun e ->
  4827. match !acc with
  4828. | hd :: tl ->
  4829. acc := tl;
  4830. if has_problematic_expressions (hd :: tl) then begin
  4831. problematic_expression_unwrap add_statement e hd
  4832. end else
  4833. e
  4834. | [] -> assert false
  4835. ) e in
  4836. new_block := (traverse new_e) :: !new_block
  4837. )
  4838. end else begin new_block := (traverse e) :: !new_block end
  4839. | _, Expression e ->
  4840. match on_expr_as_statement e with
  4841. | None -> ()
  4842. | Some e -> process_statement e
  4843. and add_statement expr =
  4844. process_statement expr
  4845. in
  4846. List.iter (process_statement) el;
  4847. let block = List.rev !new_block in
  4848. { e with eexpr = TBlock(block) }
  4849. | TTry (block, catches) ->
  4850. { e with eexpr = TTry(traverse (mk_block block), List.map (fun (v,block) -> (v, traverse (mk_block block))) catches) }
  4851. (* | TMatch (cond,ep,il_vol_e_l,default) ->
  4852. { 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) } *)
  4853. | TSwitch (cond,el_e_l, default) ->
  4854. { 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) }
  4855. | TWhile (cond,block,flag) ->
  4856. {e with eexpr = TWhile(cond,traverse (mk_block block), flag) }
  4857. | TIf (cond, eif, eelse) ->
  4858. { e with eexpr = TIf(cond, traverse (mk_block eif), Option.map (fun e -> traverse (mk_block e)) eelse) }
  4859. | TFor (v,it,block) ->
  4860. { e with eexpr = TFor(v,it, traverse (mk_block block)) }
  4861. | TFunction (tfunc) ->
  4862. { e with eexpr = TFunction({ tfunc with tf_expr = traverse (mk_block tfunc.tf_expr) }) }
  4863. | _ -> e (* if expression doesn't have a block, we will exit *)
  4864. in
  4865. traverse
  4866. let configure gen (mapping_func:texpr->texpr) =
  4867. let map e = Some(mapping_func e) in
  4868. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  4869. end;;
  4870. (* ******************************************* *)
  4871. (* Casts detection v2 *)
  4872. (* ******************************************* *)
  4873. (*
  4874. Will detect implicit casts and add TCast for them. Since everything is already followed by follow_all, typedefs are considered a new type altogether
  4875. Types shouldn't be cast if:
  4876. * When an instance is being coerced to a superclass or to an implemented interface
  4877. * When anything is being coerced to Dynamic
  4878. edit:
  4879. 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,
  4880. with maybe even some loss of information
  4881. * TAnon / TDynamic will call
  4882. * Type parameter handling will be abstracted
  4883. dependencies:
  4884. Must run before ExpressionUnwrap
  4885. *)
  4886. module CastDetect =
  4887. struct
  4888. let name = "cast_detect_2"
  4889. let priority = solve_deps name [DBefore TypeParams.priority; DBefore ExpressionUnwrap.priority]
  4890. (* ******************************************* *)
  4891. (* ReturnCast *)
  4892. (* ******************************************* *)
  4893. (*
  4894. Cast detection for return types can't be done at CastDetect time, since we need an
  4895. unwrapped expression to make sure we catch all return cast detections. So this module
  4896. is specifically to deal with that, and is configured automatically by CastDetect
  4897. dependencies:
  4898. *)
  4899. module ReturnCast =
  4900. struct
  4901. let name = "return_cast"
  4902. let priority = solve_deps name [DAfter priority; DAfter ExpressionUnwrap.priority]
  4903. let default_implementation gen =
  4904. let rec extract_expr e = match e.eexpr with
  4905. | TParenthesis e
  4906. | TMeta (_,e)
  4907. | TCast(e,_) -> extract_expr e
  4908. | _ -> e
  4909. in
  4910. let current_ret_type = ref None in
  4911. let handle e tto tfrom = gen.ghandle_cast (gen.greal_type tto) (gen.greal_type tfrom) e in
  4912. let in_value = ref false in
  4913. let rec run e =
  4914. let was_in_value = !in_value in
  4915. in_value := true;
  4916. match e.eexpr with
  4917. | TReturn (eopt) ->
  4918. (* a return must be inside a function *)
  4919. 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
  4920. (match eopt with
  4921. | None when not (is_void ret_type) ->
  4922. { e with eexpr = TReturn( Some(null ret_type e.epos)) }
  4923. | None -> e
  4924. | Some eret ->
  4925. { e with eexpr = TReturn( Some(handle (run eret) ret_type eret.etype ) ) })
  4926. | TFunction(tfunc) ->
  4927. let last_ret = !current_ret_type in
  4928. current_ret_type := Some(tfunc.tf_type);
  4929. let ret = Type.map_expr run e in
  4930. current_ret_type := last_ret;
  4931. ret
  4932. | TBlock el ->
  4933. { e with eexpr = TBlock ( List.map (fun e -> in_value := false; run e) el ) }
  4934. | TBinop ( (Ast.OpAssign as op),e1,e2)
  4935. | TBinop ( (Ast.OpAssignOp _ as op),e1,e2) when was_in_value ->
  4936. let e1 = extract_expr (run e1) in
  4937. let r = { e with eexpr = TBinop(op, e1, handle (run e2) e1.etype e2.etype); etype = e1.etype } in
  4938. handle r e.etype e1.etype
  4939. | TBinop ( (Ast.OpAssign as op),({ eexpr = TField(tf, f) } as e1), e2 )
  4940. | TBinop ( (Ast.OpAssignOp _ as op),({ eexpr = TField(tf, f) } as e1), e2 ) ->
  4941. (match field_access_esp gen (gen.greal_type tf.etype) (f) with
  4942. | FClassField(cl,params,_,_,is_static,actual_t,_) ->
  4943. let actual_t = if is_static then actual_t else apply_params cl.cl_params params actual_t in
  4944. let e1 = extract_expr (run e1) in
  4945. { e with eexpr = TBinop(op, e1, handle (run e2) actual_t e2.etype); etype = e1.etype }
  4946. | _ ->
  4947. let e1 = extract_expr (run e1) in
  4948. { e with eexpr = TBinop(op, e1, handle (run e2) e1.etype e2.etype); etype = e1.etype }
  4949. )
  4950. | TBinop ( (Ast.OpAssign as op),e1,e2)
  4951. | TBinop ( (Ast.OpAssignOp _ as op),e1,e2) ->
  4952. let e1 = extract_expr (run e1) in
  4953. { e with eexpr = TBinop(op, e1, handle (run e2) e1.etype e2.etype); etype = e1.etype }
  4954. | _ -> Type.map_expr run e
  4955. in
  4956. run
  4957. let configure gen =
  4958. let map e = Some(default_implementation gen e) in
  4959. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  4960. end;;
  4961. let get_args t = match follow t with
  4962. | TFun(args,ret) -> args,ret
  4963. | _ -> trace (debug_type t); assert false
  4964. let s_path (pack,n) = (String.concat "." (pack @ [n]))
  4965. (*
  4966. Since this function is applied under native-context only, the type paraters will already be changed
  4967. *)
  4968. let map_cls gen also_implements fn super =
  4969. let rec loop c tl =
  4970. if c == super then
  4971. fn c tl
  4972. else (match c.cl_super with
  4973. | None -> false
  4974. | Some (cs,tls) ->
  4975. let tls = gen.greal_type_param (TClassDecl cs) tls in
  4976. loop cs (List.map (apply_params c.cl_params tl) tls)
  4977. ) || (if also_implements then List.exists (fun (cs,tls) ->
  4978. loop cs (List.map (apply_params c.cl_params tl) tls)
  4979. ) c.cl_implements else false)
  4980. in
  4981. loop
  4982. let follow_dyn t = match follow t with
  4983. | TMono _ | TLazy _ -> t_dynamic
  4984. | t -> t
  4985. (*
  4986. this has a slight change from the type.ml version, in which it doesn't
  4987. change a TMono into the other parameter
  4988. *)
  4989. let rec type_eq gen param a b =
  4990. if a == b then
  4991. ()
  4992. else match follow_dyn (gen.greal_type a) , follow_dyn (gen.greal_type b) with
  4993. | TEnum (e1,tl1) , TEnum (e2,tl2) ->
  4994. if e1 != e2 && not (param = EqCoreType && e1.e_path = e2.e_path) then Type.error [cannot_unify a b];
  4995. List.iter2 (type_eq gen param) tl1 tl2
  4996. | TAbstract (a1,tl1) , TAbstract (a2,tl2) ->
  4997. if a1 != a2 && not (param = EqCoreType && a1.a_path = a2.a_path) then Type.error [cannot_unify a b];
  4998. List.iter2 (type_eq gen param) tl1 tl2
  4999. | TInst (c1,tl1) , TInst (c2,tl2) ->
  5000. 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];
  5001. List.iter2 (type_eq gen param) tl1 tl2
  5002. | TFun (l1,r1) , TFun (l2,r2) when List.length l1 = List.length l2 ->
  5003. (try
  5004. type_eq gen param r1 r2;
  5005. List.iter2 (fun (n,o1,t1) (_,o2,t2) ->
  5006. if o1 <> o2 then Type.error [Not_matching_optional n];
  5007. type_eq gen param t1 t2
  5008. ) l1 l2
  5009. with
  5010. Unify_error l -> Type.error (cannot_unify a b :: l))
  5011. | TDynamic a , TDynamic b ->
  5012. type_eq gen param a b
  5013. | TAnon a1, TAnon a2 ->
  5014. (try
  5015. PMap.iter (fun n f1 ->
  5016. try
  5017. let f2 = PMap.find n a2.a_fields in
  5018. 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];
  5019. try
  5020. type_eq gen param f1.cf_type f2.cf_type
  5021. with
  5022. Unify_error l -> Type.error (invalid_field n :: l)
  5023. with
  5024. Not_found ->
  5025. if is_closed a2 then Type.error [has_no_field b n];
  5026. if not (link (ref None) b f1.cf_type) then Type.error [cannot_unify a b];
  5027. a2.a_fields <- PMap.add n f1 a2.a_fields
  5028. ) a1.a_fields;
  5029. PMap.iter (fun n f2 ->
  5030. if not (PMap.mem n a1.a_fields) then begin
  5031. if is_closed a1 then Type.error [has_no_field a n];
  5032. if not (link (ref None) a f2.cf_type) then Type.error [cannot_unify a b];
  5033. a1.a_fields <- PMap.add n f2 a1.a_fields
  5034. end;
  5035. ) a2.a_fields;
  5036. with
  5037. Unify_error l -> Type.error (cannot_unify a b :: l))
  5038. | _ , _ ->
  5039. if b == t_dynamic && (param = EqRightDynamic || param = EqBothDynamic) then
  5040. ()
  5041. else if a == t_dynamic && param = EqBothDynamic then
  5042. ()
  5043. else
  5044. Type.error [cannot_unify a b]
  5045. let type_iseq gen a b =
  5046. try
  5047. type_eq gen EqStrict a b;
  5048. true
  5049. with
  5050. Unify_error _ -> false
  5051. (* will return true if both arguments are compatible. If it's not the case, a runtime error is very likely *)
  5052. let is_cl_related gen cl tl super superl =
  5053. 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
  5054. is_cl_related cl tl super superl || is_cl_related super superl cl tl
  5055. let rec is_unsafe_cast gen to_t from_t =
  5056. match (follow to_t, follow from_t) with
  5057. | TInst(cl_to, to_params), TInst(cl_from, from_params) ->
  5058. not (is_cl_related gen cl_from from_params cl_to to_params)
  5059. | TEnum(e_to, _), TEnum(e_from, _) ->
  5060. e_to.e_path <> e_from.e_path
  5061. | TFun _, TFun _ ->
  5062. (* functions are never unsafe cast by default. This behavior might be changed *)
  5063. (* with a later AST pass which will run through TFun to TFun casts *)
  5064. false
  5065. | TMono _, _
  5066. | _, TMono _
  5067. | TDynamic _, _
  5068. | _, TDynamic _ ->
  5069. false
  5070. | TAnon _, _
  5071. | _, TAnon _ ->
  5072. (* anonymous are never unsafe also. *)
  5073. (* Though they will generate a cast, so if this cast is unneeded it's better to avoid them by tweaking gen.greal_type *)
  5074. false
  5075. | TAbstract _, _
  5076. | _, TAbstract _ ->
  5077. (try
  5078. unify from_t to_t;
  5079. false
  5080. with | Unify_error _ ->
  5081. try
  5082. unify to_t from_t; (* still not unsafe *)
  5083. false
  5084. with | Unify_error _ ->
  5085. true)
  5086. | _ -> true
  5087. let do_unsafe_cast gen from_t to_t e =
  5088. let t_path t =
  5089. match t with
  5090. | TInst(cl, _) -> cl.cl_path
  5091. | TEnum(e, _) -> e.e_path
  5092. | TType(t, _) -> t.t_path
  5093. | TAbstract(a, _) -> a.a_path
  5094. | TDynamic _ -> ([], "Dynamic")
  5095. | _ -> raise Not_found
  5096. in
  5097. let do_default () =
  5098. gen.gon_unsafe_cast to_t e.etype e.epos;
  5099. mk_cast to_t (mk_cast t_dynamic e)
  5100. in
  5101. (* TODO: there really should be a better way to write that *)
  5102. try
  5103. if (Hashtbl.find gen.gsupported_conversions (t_path from_t)) from_t to_t then
  5104. mk_cast to_t e
  5105. else
  5106. do_default()
  5107. with
  5108. | Not_found ->
  5109. try
  5110. if (Hashtbl.find gen.gsupported_conversions (t_path to_t)) from_t to_t then
  5111. mk_cast to_t e
  5112. else
  5113. do_default()
  5114. with
  5115. | Not_found -> do_default()
  5116. (* ****************************** *)
  5117. (* cast handler *)
  5118. (* decides if a cast should be emitted, given a from and a to type *)
  5119. (*
  5120. this function is like a mini unify, without e.g. subtyping, which makes sense
  5121. at the backend level, since most probably Anons and TInst will have a different representation there
  5122. *)
  5123. let rec handle_cast gen e real_to_t real_from_t =
  5124. let do_unsafe_cast () = do_unsafe_cast gen real_from_t real_to_t { e with etype = real_from_t } in
  5125. let to_t, from_t = real_to_t, real_from_t in
  5126. let mk_cast t e =
  5127. match e.eexpr with
  5128. (* TThrow is always typed as Dynamic, we just need to type it accordingly *)
  5129. | TThrow _ -> { e with etype = t }
  5130. | _ -> mk_cast t e
  5131. in
  5132. let e = { e with etype = real_from_t } in
  5133. if try fast_eq real_to_t real_from_t with Invalid_argument("List.for_all2") -> false then e else
  5134. match real_to_t, real_from_t with
  5135. (* string is the only type that can be implicitly converted from any other *)
  5136. | TInst( { cl_path = ([], "String") }, []), _ ->
  5137. mk_cast to_t e
  5138. | TInst(cl_to, params_to), TInst(cl_from, params_from) ->
  5139. let ret = ref None in
  5140. (*
  5141. this is a little confusing:
  5142. we are here mapping classes until we have the same to and from classes, applying the type parameters in each step, so we can
  5143. compare the type parameters;
  5144. If a class is found - meaning that the cl_from can be converted without a cast into cl_to,
  5145. we still need to check their type parameters.
  5146. *)
  5147. ignore (map_cls gen (gen.guse_tp_constraints || (match cl_from.cl_kind,cl_to.cl_kind with KTypeParameter _, _ | _,KTypeParameter _ -> false | _ -> true)) (fun _ tl ->
  5148. try
  5149. (* type found, checking type parameters *)
  5150. List.iter2 (type_eq gen EqStrict) tl params_to;
  5151. ret := Some e;
  5152. true
  5153. with | Unify_error _ ->
  5154. (* type parameters need casting *)
  5155. if gen.ghas_tparam_cast_handler then begin
  5156. (*
  5157. if we are already handling type parameter casts on other part of code (e.g. RealTypeParameters),
  5158. we'll just make a cast to indicate that this place needs type parameter-involved casting
  5159. *)
  5160. ret := Some (mk_cast to_t e);
  5161. true
  5162. end else
  5163. (*
  5164. if not, we're going to check if we only need a simple cast,
  5165. or if we need to first cast into the dynamic version of it
  5166. *)
  5167. try
  5168. List.iter2 (type_eq gen EqRightDynamic) tl params_to;
  5169. ret := Some (mk_cast to_t e);
  5170. true
  5171. with | Unify_error _ ->
  5172. ret := Some (mk_cast to_t (mk_cast (TInst(cl_to, List.map (fun _ -> t_dynamic) params_to)) e));
  5173. true
  5174. ) cl_to cl_from params_from);
  5175. if is_some !ret then
  5176. get !ret
  5177. else if is_cl_related gen cl_from params_from cl_to params_to then
  5178. mk_cast to_t e
  5179. else
  5180. (* potential unsafe cast *)
  5181. (do_unsafe_cast ())
  5182. | TMono _, TMono _
  5183. | TMono _, TDynamic _
  5184. | TDynamic _, TDynamic _
  5185. | TDynamic _, TMono _ ->
  5186. e
  5187. | TMono _, _
  5188. | TDynamic _, _
  5189. | TAnon _, _ when gen.gneeds_box real_from_t ->
  5190. mk_cast to_t e
  5191. | TMono _, _
  5192. | TDynamic _, _ -> e
  5193. | _, TMono _
  5194. | _, TDynamic _ -> mk_cast to_t e
  5195. | TAnon (a_to), TAnon (a_from) ->
  5196. if a_to == a_from then
  5197. e
  5198. else if type_iseq gen to_t from_t then (* FIXME apply unify correctly *)
  5199. e
  5200. else
  5201. mk_cast to_t e
  5202. | _, TAnon(anon) -> (try
  5203. let p2 = match !(anon.a_status) with
  5204. | Statics c -> TInst(c,List.map (fun _ -> t_dynamic) c.cl_params)
  5205. | EnumStatics e -> TEnum(e, List.map (fun _ -> t_dynamic) e.e_params)
  5206. | AbstractStatics a -> TAbstract(a, List.map (fun _ -> t_dynamic) a.a_params)
  5207. | _ -> raise Not_found
  5208. in
  5209. let tclass = match get_type gen ([],"Class") with
  5210. | TAbstractDecl(a) -> a
  5211. | _ -> assert false in
  5212. handle_cast gen e real_to_t (gen.greal_type (TAbstract(tclass, [p2])))
  5213. with | Not_found ->
  5214. mk_cast to_t e)
  5215. | TAbstract (a_to, _), TAbstract(a_from, _) when a_to == a_from ->
  5216. e
  5217. | TAbstract _, TInst({ cl_kind = KTypeParameter _ }, _)
  5218. | TInst({ cl_kind = KTypeParameter _ }, _), TAbstract _ ->
  5219. do_unsafe_cast()
  5220. | TAbstract _, _
  5221. | _, TAbstract _ ->
  5222. (try
  5223. unify from_t to_t;
  5224. mk_cast to_t e
  5225. with | Unify_error _ ->
  5226. try
  5227. unify to_t from_t;
  5228. mk_cast to_t e
  5229. with | Unify_error _ ->
  5230. do_unsafe_cast())
  5231. | TEnum(e_to, []), TEnum(e_from, []) ->
  5232. if e_to == e_from then
  5233. e
  5234. else
  5235. (* potential unsafe cast *)
  5236. (do_unsafe_cast ())
  5237. | TEnum(e_to, params_to), TEnum(e_from, params_from) when e_to.e_path = e_from.e_path ->
  5238. (try
  5239. List.iter2 (type_eq gen (if gen.gallow_tp_dynamic_conversion then EqRightDynamic else EqStrict)) params_from params_to;
  5240. e
  5241. with
  5242. | Unify_error _ -> do_unsafe_cast ()
  5243. )
  5244. | TEnum(en, params_to), TInst(cl, params_from)
  5245. | TInst(cl, params_to), TEnum(en, params_from) ->
  5246. (* this is here for max compatibility with EnumsToClass module *)
  5247. if en.e_path = cl.cl_path && en.e_extern then begin
  5248. (try
  5249. List.iter2 (type_eq gen (if gen.gallow_tp_dynamic_conversion then EqRightDynamic else EqStrict)) params_from params_to;
  5250. e
  5251. with
  5252. | Invalid_argument("List.iter2") ->
  5253. (*
  5254. this is a hack for RealTypeParams. Since there is no way at this stage to know if the class is the actual
  5255. EnumsToClass derived from the enum, we need to imply from possible ArgumentErrors (because of RealTypeParams interfaces),
  5256. that they would only happen if they were a RealTypeParams created interface
  5257. *)
  5258. e
  5259. | Unify_error _ -> do_unsafe_cast ()
  5260. )
  5261. end else
  5262. do_unsafe_cast ()
  5263. | TType(t_to, params_to), TType(t_from, params_from) when t_to == t_from ->
  5264. if gen.gspecial_needs_cast real_to_t real_from_t then
  5265. (try
  5266. List.iter2 (type_eq gen (if gen.gallow_tp_dynamic_conversion then EqRightDynamic else EqStrict)) params_from params_to;
  5267. e
  5268. with
  5269. | Unify_error _ -> do_unsafe_cast ()
  5270. )
  5271. else
  5272. e
  5273. | TType(t_to, _), TType(t_from,_) ->
  5274. if gen.gspecial_needs_cast real_to_t real_from_t then
  5275. mk_cast to_t e
  5276. else
  5277. e
  5278. | TType _, _ when gen.gspecial_needs_cast real_to_t real_from_t ->
  5279. mk_cast to_t e
  5280. | _, TType _ when gen.gspecial_needs_cast real_to_t real_from_t ->
  5281. mk_cast to_t e
  5282. (*| TType(t_to, _), TType(t_from, _) ->
  5283. if t_to.t_path = t_from.t_path then
  5284. e
  5285. else if is_unsafe_cast gen real_to_t real_from_t then (* is_unsafe_cast will already follow both *)
  5286. (do_unsafe_cast ())
  5287. else
  5288. mk_cast to_t e*)
  5289. | TType _, _
  5290. | _, TType _ ->
  5291. if is_unsafe_cast gen real_to_t real_from_t then (* is_unsafe_cast will already follow both *)
  5292. (do_unsafe_cast ())
  5293. else
  5294. mk_cast to_t e
  5295. | TAnon anon, _ ->
  5296. if PMap.is_empty anon.a_fields then
  5297. e
  5298. else
  5299. mk_cast to_t e
  5300. | TFun(args, ret), TFun(args2, ret2) ->
  5301. let get_args = List.map (fun (_,_,t) -> t) in
  5302. (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)
  5303. | _, _ ->
  5304. do_unsafe_cast ()
  5305. (* end of cast handler *)
  5306. (* ******************* *)
  5307. let is_static_overload c name =
  5308. match c.cl_super with
  5309. | None -> false
  5310. | Some (sup,_) ->
  5311. let rec loop c =
  5312. (PMap.mem name c.cl_statics) || (match c.cl_super with
  5313. | None -> false
  5314. | Some (sup,_) -> loop sup)
  5315. in
  5316. loop sup
  5317. let does_unify a b =
  5318. try
  5319. unify a b;
  5320. true
  5321. with | Unify_error _ -> false
  5322. (* this is a workaround for issue #1743, as FInstance() is returning the incorrect classfield *)
  5323. let rec clean_t t = match follow t with
  5324. | TAbstract(a,tl) when not (Meta.has Meta.CoreType a.a_meta) ->
  5325. clean_t (Abstract.get_underlying_type a tl)
  5326. | t -> t
  5327. let select_overload gen applied_f overloads types params =
  5328. let rec check_arg arglist elist =
  5329. match arglist, elist with
  5330. | [], [] -> true (* it is valid *)
  5331. | (_,_,t) :: arglist, (_,_,et) :: elist when Type.type_iseq (clean_t et) (clean_t t) ->
  5332. check_arg arglist elist
  5333. | _ -> false
  5334. in
  5335. match follow applied_f with
  5336. | TFun _ ->
  5337. replace_mono applied_f;
  5338. let args, _ = get_fun applied_f in
  5339. let elist = List.rev args in
  5340. let rec check_overload overloads =
  5341. match overloads with
  5342. | (t, cf) :: overloads ->
  5343. let cft = apply_params types params t in
  5344. let cft = monomorphs cf.cf_params cft in
  5345. let args, _ = get_fun cft in
  5346. if check_arg (List.rev args) elist then
  5347. cf,t,false
  5348. else if overloads = [] then
  5349. cf,t,true (* no compatible overload was found *)
  5350. else
  5351. check_overload overloads
  5352. | [] -> assert false
  5353. in
  5354. check_overload overloads
  5355. | _ -> match overloads with (* issue #1742 *)
  5356. | (t,cf) :: [] -> cf,t,true
  5357. | (t,cf) :: _ -> cf,t,false
  5358. | _ -> assert false
  5359. let choose_ctor gen cl tparams etl maybe_empty_t p =
  5360. let ctor, sup, stl = OverloadingConstructor.cur_ctor cl tparams in
  5361. (* get returned stl, with Dynamic as t_empty *)
  5362. let rec get_changed_stl c tl =
  5363. if c == sup then
  5364. tl
  5365. else match c.cl_super with
  5366. | None -> stl
  5367. | Some(sup,stl) -> get_changed_stl sup (List.map (apply_params c.cl_params tl) stl)
  5368. in
  5369. let ret_tparams = List.map (fun t -> match follow t with
  5370. | TDynamic _ | TMono _ -> t_empty
  5371. | _ -> t) tparams in
  5372. let ret_stl = get_changed_stl cl ret_tparams in
  5373. let ctors = ctor :: ctor.cf_overloads in
  5374. List.iter replace_mono etl;
  5375. (* first filter out or select outright maybe_empty *)
  5376. let ctors, is_overload = match etl, maybe_empty_t with
  5377. | [t], Some empty_t ->
  5378. let count = ref 0 in
  5379. let is_empty_call = Type.type_iseq t empty_t in
  5380. let ret = List.filter (fun cf -> match follow cf.cf_type with
  5381. (* | TFun([_,_,t],_) -> incr count; true *)
  5382. | TFun([_,_,t],_) -> replace_mono t; incr count; is_empty_call = (Type.type_iseq t empty_t)
  5383. | _ -> false) ctors in
  5384. ret, !count > 1
  5385. | _ ->
  5386. let len = List.length etl in
  5387. let ret = List.filter (fun cf -> List.length (fst (get_fun cf.cf_type)) = len) ctors in
  5388. ret, (match ret with | _ :: [] -> false | _ -> true)
  5389. in
  5390. let rec check_arg arglist elist =
  5391. match arglist, elist with
  5392. | [], [] -> true
  5393. | (_,_,t) :: arglist, et :: elist -> (try
  5394. let t = run_follow gen t in
  5395. unify et t;
  5396. check_arg arglist elist
  5397. with | Unify_error el ->
  5398. (* List.iter (fun el -> gen.gcon.warning (Typecore.unify_error_msg (print_context()) el) p) el; *)
  5399. false)
  5400. | _ -> false
  5401. in
  5402. let rec check_cf cf =
  5403. let t = apply_params sup.cl_params stl cf.cf_type in
  5404. replace_mono t;
  5405. let args, _ = get_fun t in
  5406. check_arg args etl
  5407. in
  5408. match is_overload, ctors with
  5409. | false, [c] ->
  5410. false, c, sup, ret_stl
  5411. | _ ->
  5412. is_overload, List.find check_cf ctors, sup, ret_stl
  5413. (*
  5414. Type parameter handling
  5415. It will detect if/what type parameters were used, and call the cast handler
  5416. It will handle both TCall(TField) and TCall by receiving a texpr option field: e
  5417. Also it will transform the type parameters with greal_type_param and make
  5418. handle_impossible_tparam - should cases where the type parameter is impossible to be determined from the called parameters be Dynamic?
  5419. e.g. static function test<T>():T {}
  5420. *)
  5421. (* match e.eexpr with | TCall( ({ eexpr = TField(ef, f) }) as e1, elist ) -> *)
  5422. let handle_type_parameter gen e e1 ef ~clean_ef ~overloads_cast_to_base f elist calls_parameters_explicitly =
  5423. (* the ONLY way to know if this call has parameters is to analyze the calling field. *)
  5424. (* To make matters a little worse, on both C# and Java only in some special cases that type parameters will be used *)
  5425. (* Namely, when using reflection type parameters are useless, of course. This also includes anonymous types *)
  5426. (* this will have to be handled by gparam_func_call *)
  5427. let return_var efield =
  5428. match e with
  5429. | None ->
  5430. efield
  5431. | Some ecall ->
  5432. match follow efield.etype with
  5433. | TFun(_,ret) ->
  5434. (* closures will be handled by the closure handler. So we will just hint what's the expected type *)
  5435. (* FIXME: should closures have also its arguments cast correctly? In the current implementation I think not. TO_REVIEW *)
  5436. handle_cast gen { ecall with eexpr = TCall(efield, elist) } (gen.greal_type ecall.etype) ret
  5437. | _ ->
  5438. { ecall with eexpr = TCall(efield, elist) }
  5439. in
  5440. let real_type = gen.greal_type ef.etype in
  5441. (* this part was rewritten at roughly r6477 in order to correctly support overloads *)
  5442. (match field_access_esp gen real_type (f) with
  5443. | FClassField (cl, params, _, cf, is_static, actual_t, declared_t) when e <> None && (cf.cf_kind = Method MethNormal || cf.cf_kind = Method MethInline) ->
  5444. (* C# target changes params with a real_type function *)
  5445. let params = match follow clean_ef.etype with
  5446. | TInst(_,params) -> params
  5447. | _ -> params in
  5448. let ecall = get e in
  5449. let ef = ref ef in
  5450. let is_overload = cf.cf_overloads <> [] || Meta.has Meta.Overload cf.cf_meta || (is_static && is_static_overload cl (field_name f)) in
  5451. let cf, actual_t, error = match is_overload with
  5452. | false ->
  5453. (* since actual_t from FClassField already applies greal_type, we're using the get_overloads helper to get this info *)
  5454. let t = if cf.cf_params = [] then (* this if statement must be eliminated - it's a workaround for #3516 + infer params. *)
  5455. actual_t
  5456. else
  5457. declared_t
  5458. in
  5459. cf,t,false
  5460. | true ->
  5461. let (cf, actual_t, error), is_static = match f with
  5462. | FInstance(c,_,cf) | FClosure(Some (c,_),cf) ->
  5463. (* get from overloads *)
  5464. (* FIXME: this is a workaround for issue #1743 . Uncomment this code after it was solved *)
  5465. (* let t, cf = List.find (fun (t,cf2) -> cf == cf2) (Typeload.get_overloads cl (field_name f)) in *)
  5466. (* cf, t, false *)
  5467. select_overload gen e1.etype (Typeload.get_overloads cl (field_name f)) cl.cl_params params, false
  5468. | FStatic(c,f) ->
  5469. (* workaround for issue #1743 *)
  5470. (* f,f.cf_type, false *)
  5471. select_overload gen e1.etype ((f.cf_type,f) :: List.map (fun f -> f.cf_type,f) f.cf_overloads) [] [], true
  5472. | _ ->
  5473. gen.gcon.warning "Overloaded classfield typed as anonymous" ecall.epos;
  5474. (cf, actual_t, true), true
  5475. in
  5476. 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
  5477. | Some(cf_orig,actual_t,_,_,declared_cl,tl,tlch) ->
  5478. let rec is_super e = match e.eexpr with
  5479. | TConst TSuper -> true
  5480. | TParenthesis p | TMeta(_,p) -> is_super p
  5481. | _ -> false
  5482. in
  5483. if declared_cl != cl && overloads_cast_to_base && not (is_super !ef) then begin
  5484. let pos = (!ef).epos in
  5485. ef := {
  5486. eexpr = TCall(
  5487. { eexpr = TLocal(alloc_var "__as__" t_dynamic); etype = t_dynamic; epos = pos },
  5488. [!ef]);
  5489. etype = TInst(declared_cl,List.map (apply_params cl.cl_params params) tl);
  5490. epos = pos
  5491. }
  5492. end;
  5493. { cf_orig with cf_name = cf.cf_name },actual_t,false
  5494. | None ->
  5495. gen.gcon.warning "Cannot find matching overload" ecall.epos;
  5496. cf, actual_t, true
  5497. else
  5498. cf,actual_t,error
  5499. in
  5500. (* set the real (selected) class field *)
  5501. let f = match f with
  5502. | FInstance(c,tl,_) -> FInstance(c,tl,cf)
  5503. | FClosure(c,_) -> FClosure(c,cf)
  5504. | FStatic(c,_) -> FStatic(c,cf)
  5505. | f -> f
  5506. in
  5507. let error = error || (match follow actual_t with | TFun _ -> false | _ -> true) in
  5508. if error then (* if error, ignore arguments *)
  5509. if is_void ecall.etype then
  5510. { ecall with eexpr = TCall({ e1 with eexpr = TField(!ef, f) }, elist ) }
  5511. else
  5512. mk_cast ecall.etype { ecall with eexpr = TCall({ e1 with eexpr = TField(!ef, f) }, elist ) }
  5513. else begin
  5514. (* infer arguments *)
  5515. (* let called_t = TFun(List.map (fun e -> "arg",false,e.etype) elist, ecall.etype) in *)
  5516. 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 *)
  5517. let fparams = TypeParams.infer_params gen ecall.epos (get_fun (apply_params cl.cl_params params actual_t)) (get_fun called_t) cf.cf_params calls_parameters_explicitly in
  5518. (* get what the backend actually sees *)
  5519. (* actual field's function *)
  5520. let actual_t = get_real_fun gen actual_t in
  5521. let real_params = gen.greal_type_param (TClassDecl cl) params in
  5522. let function_t = apply_params cl.cl_params real_params actual_t in
  5523. let real_fparams = if calls_parameters_explicitly then
  5524. gen.greal_type_param (TClassDecl cl) fparams
  5525. else
  5526. 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
  5527. let function_t = get_real_fun gen (apply_params cf.cf_params real_fparams function_t) in
  5528. let args_ft, ret_ft = get_fun function_t in
  5529. (* applied function *)
  5530. let applied = elist in
  5531. (* check types list *)
  5532. let new_ecall, elist = try
  5533. let elist = List.map2 (fun applied (_,_,funct) ->
  5534. match is_overload, applied.eexpr with
  5535. | true, TConst TNull ->
  5536. mk_cast (gen.greal_type funct) applied
  5537. | true, _ -> (* when not (type_iseq gen (gen.greal_type applied.etype) funct) -> *)
  5538. let ret = handle_cast gen applied (funct) (gen.greal_type applied.etype) in
  5539. (match ret.eexpr with
  5540. | TCast _ -> ret
  5541. | _ -> mk_cast (funct) ret)
  5542. | _ ->
  5543. handle_cast gen applied (funct) (gen.greal_type applied.etype)
  5544. ) applied args_ft in
  5545. { ecall with
  5546. eexpr = TCall(
  5547. { e1 with eexpr = TField(!ef, f) },
  5548. elist);
  5549. }, elist
  5550. with | Invalid_argument("List.map2") ->
  5551. gen.gcon.warning ("This expression may be invalid" ) ecall.epos;
  5552. { ecall with eexpr = TCall({ e1 with eexpr = TField(!ef, f) }, elist) }, elist
  5553. in
  5554. let new_ecall = if fparams <> [] then gen.gparam_func_call new_ecall { e1 with eexpr = TField(!ef, f) } fparams elist else new_ecall in
  5555. let ret = handle_cast gen new_ecall (gen.greal_type ecall.etype) (gen.greal_type ret_ft) in
  5556. (match gen.gcon.platform, cf.cf_params, ret.eexpr with
  5557. | _, _, TCast _ -> ret
  5558. | Java, _ :: _, _ ->
  5559. (* this is a workaround for a javac openjdk issue with unused type parameters and return type inference *)
  5560. (* see more at issue #3123 *)
  5561. mk_cast (gen.greal_type ret_ft) new_ecall
  5562. | _ -> ret)
  5563. end
  5564. | FClassField (cl,params,_,{ cf_kind = (Method MethDynamic | Var _) },_,actual_t,_) ->
  5565. (* if it's a var, we will just try to apply the class parameters that have been changed with greal_type_param *)
  5566. let t = apply_params cl.cl_params (gen.greal_type_param (TClassDecl cl) params) (gen.greal_type actual_t) in
  5567. return_var (handle_cast gen { e1 with eexpr = TField(ef, f) } (gen.greal_type e1.etype) (gen.greal_type t))
  5568. | FClassField (cl,params,_,cf,_,actual_t,_) ->
  5569. 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 *)
  5570. | FEnumField (en, efield, true) ->
  5571. 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
  5572. (match en.e_params with
  5573. (*
  5574. | [] ->
  5575. let args, ret = get_args (efield.ef_type) in
  5576. let ef = { ef with eexpr = TTypeExpr( TEnumDecl en ); etype = TEnum(en, []) } in
  5577. 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)
  5578. *)
  5579. | _ ->
  5580. let pt = match e with | None -> real_type | Some _ -> snd (get_fun e1.etype) in
  5581. let _params = match follow pt with | TEnum(_, p) -> p | _ -> gen.gcon.warning (debug_expr e1) e1.epos; assert false in
  5582. let args, ret = get_args efield.ef_type in
  5583. let actual_t = TFun(List.map (fun (n,o,t) -> (n,o,gen.greal_type t)) args, gen.greal_type ret) in
  5584. (*
  5585. because of differences on how <Dynamic> is handled on the platforms, this is a hack to be able to
  5586. correctly use class field type parameters with RealTypeParams
  5587. *)
  5588. let cf_params = List.map (fun t -> match follow t with | TDynamic _ -> t_empty | _ -> t) _params in
  5589. let t = apply_params en.e_params (gen.greal_type_param (TEnumDecl en) cf_params) actual_t in
  5590. let t = apply_params efield.ef_params (List.map (fun _ -> t_dynamic) efield.ef_params) t in
  5591. let args, ret = get_args t in
  5592. let elist = List.map2 (fun param (_,_,t) -> handle_cast gen (param) (gen.greal_type t) (gen.greal_type param.etype)) elist args in
  5593. let e1 = { e1 with eexpr = TField({ ef with eexpr = TTypeExpr( TEnumDecl en ); etype = TEnum(en, _params) }, FEnum(en, efield) ) } in
  5594. let new_ecall = gen.gparam_func_call ecall e1 _params elist in
  5595. handle_cast gen new_ecall (gen.greal_type ecall.etype) (gen.greal_type ret)
  5596. )
  5597. | FEnumField _ when is_some e -> assert false
  5598. | FEnumField (en,efield,_) ->
  5599. return_var { e1 with eexpr = TField({ ef with eexpr = TTypeExpr( TEnumDecl en ); },FEnum(en,efield)) }
  5600. (* no target by date will uses this.so this code may not be correct at all *)
  5601. | FAnonField cf ->
  5602. let t = gen.greal_type cf.cf_type in
  5603. return_var (handle_cast gen { e1 with eexpr = TField(ef, f) } (gen.greal_type e1.etype) t)
  5604. | FNotFound
  5605. | FDynamicField _ ->
  5606. if is_some e then
  5607. return_var { e1 with eexpr = TField(ef, f) }
  5608. else
  5609. 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 *)
  5610. )
  5611. (* end of type parameter handling *)
  5612. (* ****************************** *)
  5613. (** overloads_cast_to_base argument will cast overloaded function types to the class that declared it. **)
  5614. (** This is necessary for C#, and if true, will require the target to implement __as__, as a `quicker` form of casting **)
  5615. let default_implementation gen ?(native_string_cast = true) ?(overloads_cast_to_base = false) maybe_empty_t calls_parameters_explicitly =
  5616. let handle e t1 t2 = handle_cast gen e (gen.greal_type t1) (gen.greal_type t2) in
  5617. let in_value = ref false in
  5618. let rec clean_cast e = match e.eexpr with
  5619. | TCast(e,_) -> clean_cast e
  5620. | TParenthesis(e) | TMeta(_,e) -> clean_cast e
  5621. | _ -> e
  5622. in
  5623. let rec run ?(just_type = false) e =
  5624. let handle = if not just_type then handle else fun e t1 t2 -> { e with etype = gen.greal_type t2 } in
  5625. let was_in_value = !in_value in
  5626. in_value := true;
  5627. match e.eexpr with
  5628. | TConst ( TInt _ | TFloat _ | TBool _ as const ) ->
  5629. (* take off any Null<> that it may have *)
  5630. let t = follow (run_follow gen e.etype) in
  5631. (* do not allow constants typed as Single - need to cast them *)
  5632. let real_t = match const with
  5633. | TInt _ -> gen.gcon.basic.tint
  5634. | TFloat _ -> gen.gcon.basic.tfloat
  5635. | TBool _ -> gen.gcon.basic.tbool
  5636. | _ -> assert false
  5637. in
  5638. handle e t real_t
  5639. | TCast( { eexpr = TCall( { eexpr = TLocal { v_name = "__delegate__" } } as local, [del] ) } as e2, _) ->
  5640. { e with eexpr = TCast({ e2 with eexpr = TCall(local, [Type.map_expr run del]) }, None) }
  5641. | TBinop ( (Ast.OpAssign | Ast.OpAssignOp _ as op), e1, e2 ) ->
  5642. let e1 = run ~just_type:true e1 in
  5643. let e2 = handle (run e2) e1.etype e2.etype in
  5644. { e with eexpr = TBinop(op, clean_cast e1, e2) }
  5645. | TBinop ( (Ast.OpShl | Ast.OpShr | Ast.OpUShr as op), e1, e2 ) ->
  5646. let e1 = run e1 in
  5647. let e2 = handle (run e2) (gen.gcon.basic.tint) e2.etype in
  5648. { e with eexpr = TBinop(op, e1, e2) }
  5649. | TField(ef, f) ->
  5650. handle_type_parameter gen None e (run ef) ~clean_ef:ef ~overloads_cast_to_base:overloads_cast_to_base f [] calls_parameters_explicitly
  5651. | TArrayDecl el ->
  5652. let et = e.etype in
  5653. let base_type = match follow et with
  5654. | TInst({ cl_path = ([], "Array") } as cl, bt) -> gen.greal_type_param (TClassDecl cl) bt
  5655. | _ -> assert false
  5656. in
  5657. let base_type = List.hd base_type in
  5658. { e with eexpr = TArrayDecl( List.map (fun e -> handle (run e) base_type e.etype) el ); etype = et }
  5659. | TCall ({ eexpr = TLocal { v_name = "__array__" } } as arr_local, el) ->
  5660. let et = e.etype in
  5661. let base_type = match follow et with
  5662. | TInst(cl, bt) -> gen.greal_type_param (TClassDecl cl) bt
  5663. | _ -> assert false
  5664. in
  5665. let base_type = List.hd base_type in
  5666. { e with eexpr = TCall(arr_local, List.map (fun e -> handle (run e) base_type e.etype) el ); etype = et }
  5667. | 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 ->
  5668. { e with eexpr = TCall(local, List.map (fun e -> (match e.eexpr with TBlock _ -> in_value := false | _ -> ()); run e) params) }
  5669. | TCall( ({ eexpr = TField(ef, f) }) as e1, elist ) ->
  5670. 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
  5671. (* the TNew and TSuper code was modified at r6497 *)
  5672. | TCall( { eexpr = TConst TSuper } as ef, eparams ) ->
  5673. let cl, tparams = match follow ef.etype with
  5674. | TInst(cl,p) -> cl, p
  5675. | _ -> assert false in
  5676. (try
  5677. let is_overload, cf, sup, stl = choose_ctor gen cl tparams (List.map (fun e -> e.etype) eparams) maybe_empty_t e.epos in
  5678. let handle e t1 t2 =
  5679. if is_overload then
  5680. let ret = handle e t1 t2 in
  5681. match ret.eexpr with
  5682. | TCast _ -> ret
  5683. | _ -> mk_cast (gen.greal_type t1) e
  5684. else
  5685. handle e t1 t2
  5686. in
  5687. let stl = gen.greal_type_param (TClassDecl sup) stl in
  5688. let args, _ = get_fun (apply_params sup.cl_params stl cf.cf_type) in
  5689. let eparams = List.map2 (fun e (_,_,t) ->
  5690. handle (run e) t e.etype
  5691. ) eparams args in
  5692. { e with eexpr = TCall(ef, eparams) }
  5693. with | Not_found ->
  5694. gen.gcon.warning "No overload found for this constructor call" e.epos;
  5695. { e with eexpr = TCall(ef, List.map run eparams) })
  5696. | TCall (ef, eparams) ->
  5697. (match ef.etype with
  5698. | TFun(p, ret) ->
  5699. handle ({ e with eexpr = TCall(run ef, List.map2 (fun param (_,_,t) -> handle (run param) t param.etype) eparams p) }) e.etype ret
  5700. | _ -> Type.map_expr run e
  5701. )
  5702. (* the TNew and TSuper code was modified at r6497 *)
  5703. | TNew ({ cl_kind = KTypeParameter _ }, _, _) ->
  5704. Type.map_expr run e
  5705. | TNew (cl, tparams, eparams) -> (try
  5706. let is_overload, cf, sup, stl = choose_ctor gen cl tparams (List.map (fun e -> e.etype) eparams) maybe_empty_t e.epos in
  5707. let handle e t1 t2 =
  5708. if is_overload then
  5709. let ret = handle e t1 t2 in
  5710. match ret.eexpr with
  5711. | TCast _ -> ret
  5712. | _ -> mk_cast (gen.greal_type t1) e
  5713. else
  5714. handle e t1 t2
  5715. in
  5716. let stl = gen.greal_type_param (TClassDecl sup) stl in
  5717. let args, _ = get_fun (apply_params sup.cl_params stl cf.cf_type) in
  5718. let eparams = List.map2 (fun e (_,_,t) ->
  5719. handle (run e) t e.etype
  5720. ) eparams args in
  5721. { e with eexpr = TNew(cl, tparams, eparams) }
  5722. with | Not_found ->
  5723. gen.gcon.warning "No overload found for this constructor call" e.epos;
  5724. { e with eexpr = TNew(cl, tparams, List.map run eparams) })
  5725. | TArray(arr, idx) ->
  5726. let arr_etype = match follow arr.etype with
  5727. | (TInst _ as t) -> t
  5728. | TAbstract (a, pl) when not (Meta.has Meta.CoreType a.a_meta) ->
  5729. follow (Abstract.get_underlying_type a pl)
  5730. | t -> t in
  5731. let idx = match gen.greal_type idx.etype with
  5732. | TAbstract({ a_path = [],"Int" },_) -> run idx
  5733. | _ -> match handle (run idx) gen.gcon.basic.tint (gen.greal_type idx.etype) with
  5734. | ({ eexpr = TCast _ } as idx) -> idx
  5735. | idx -> mk_cast gen.gcon.basic.tint idx
  5736. in
  5737. let e = { e with eexpr = TArray(run arr, idx) } in
  5738. (* get underlying class (if it's a class *)
  5739. (match arr_etype with
  5740. | TInst(cl, params) ->
  5741. (* see if it implements ArrayAccess *)
  5742. (match cl.cl_array_access with
  5743. | None -> e
  5744. | Some t ->
  5745. (* if it does, apply current parameters (and change them) *)
  5746. (* let real_t = apply_params_internal (List.map (gen.greal_type_param (TClassDecl cl))) cl params t in *)
  5747. let param = apply_params cl.cl_params (gen.greal_type_param (TClassDecl cl) params) t in
  5748. let real_t = apply_params cl.cl_params params param in
  5749. (* see if it needs a cast *)
  5750. handle (e) (gen.greal_type e.etype) (gen.greal_type real_t)
  5751. )
  5752. | _ -> Type.map_expr run e)
  5753. | TVar (v, eopt) ->
  5754. { e with eexpr = TVar (v, match eopt with
  5755. | None -> eopt
  5756. | Some e -> Some( handle (run e) v.v_type e.etype ))
  5757. }
  5758. (* FIXME deal with in_value when using other statements that may not have a TBlock wrapped on them *)
  5759. | TIf (econd, ethen, Some(eelse)) when was_in_value ->
  5760. { 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 ) ) }
  5761. | TIf (econd, ethen, eelse) ->
  5762. { 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) }
  5763. | TWhile (econd, e1, flag) ->
  5764. { e with eexpr = TWhile (handle (run econd) gen.gcon.basic.tbool econd.etype, (in_value := false; run (mk_block e1)), flag) }
  5765. | TSwitch (cond, el_e_l, edef) ->
  5766. { 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) }
  5767. (* | TMatch (cond, en, il_vl_e_l, edef) ->
  5768. { 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) } *)
  5769. | TFor (v,cond,e1) ->
  5770. { e with eexpr = TFor(v, run cond, (in_value := false; run (mk_block e1))) }
  5771. | TTry (e, ve_l) ->
  5772. { 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) }
  5773. | TBlock el ->
  5774. let i = ref 0 in
  5775. let len = List.length el in
  5776. { e with eexpr = TBlock ( List.map (fun e ->
  5777. incr i;
  5778. if !i <> len || not was_in_value then
  5779. in_value := false;
  5780. run e
  5781. ) el ) }
  5782. | TCast (expr, md) when is_void (follow e.etype) ->
  5783. run expr
  5784. | TCast (expr, md) ->
  5785. let rec get_null e =
  5786. match e.eexpr with
  5787. | TConst TNull -> Some e
  5788. | TParenthesis e | TMeta(_,e) -> get_null e
  5789. | _ -> None
  5790. in
  5791. (match get_null expr with
  5792. | Some enull ->
  5793. if gen.gcon.platform = Cs then
  5794. { enull with etype = gen.greal_type e.etype }
  5795. else
  5796. mk_cast (gen.greal_type e.etype) enull
  5797. | _ ->
  5798. let last_unsafe = gen.gon_unsafe_cast in
  5799. gen.gon_unsafe_cast <- (fun t t2 pos -> ());
  5800. let ret = handle (run expr) e.etype expr.etype in
  5801. gen.gon_unsafe_cast <- last_unsafe;
  5802. match ret.eexpr with
  5803. | TCast _ -> ret
  5804. | _ -> { e with eexpr = TCast(ret,md); etype = gen.greal_type e.etype }
  5805. )
  5806. (*| TCast _ ->
  5807. (* if there is already a cast, we should skip this cast check *)
  5808. Type.map_expr run e*)
  5809. | TFunction f ->
  5810. in_value := false;
  5811. Type.map_expr run e
  5812. | _ -> Type.map_expr run e
  5813. in
  5814. run
  5815. let configure gen (mapping_func:texpr->texpr) =
  5816. gen.ghandle_cast <- (fun tto tfrom expr -> handle_cast gen expr (gen.greal_type tto) (gen.greal_type tfrom));
  5817. let map e = Some(mapping_func e) in
  5818. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map;
  5819. ReturnCast.configure gen
  5820. end;;
  5821. (* ******************************************* *)
  5822. (* Reflection-enabling Class fields *)
  5823. (* ******************************************* *)
  5824. (*
  5825. 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)
  5826. This module will create class fields that enable reflection for targets that have a slow or inexistent reflection abilities. Because of the similarity
  5827. of strategies between what should have been different modules, they are all unified in this reflection-enabling class fields.
  5828. They include:
  5829. * Get(isStatic, throwErrors, isCheck) / Set fields . Remember to allow implements Dynamic also.
  5830. * Invoke fields(isStatic) -> You need to configure how many invoke_field fields there will be. + invokeDynamic
  5831. * Has field -> parameter in get field that returns __undefined__ if it doesn't exist.
  5832. * GetType -> return the current Class<> / Enum<>
  5833. * Fields(isStatic) -> returns all the fields / static fields. Remember to allow implements Dynamic also
  5834. * Create(arguments array), CreateEmpty - calls new() or create empty
  5835. * getInstanceFields / getClassFields -> show even function fields, everything!
  5836. * deleteField -> only for implements Dynamic
  5837. for enums:
  5838. * createEnum -> invokeField for classes
  5839. * createEnumIndex -> use invokeField as well, and use numbers e.g. "0", "1", "2" .... For this, use "@:alias" metadata
  5840. * getEnumConstructs -> fields()
  5841. need to be solved outside:
  5842. * getEnumName
  5843. * enumIndex
  5844. *
  5845. need to be solved by haxe code:
  5846. * enumParameters -> for (field in Reflect.fields(enum)) arr.push(Reflect.field(enum, field))
  5847. Standard:
  5848. if a class contains a @:$enum metadata, it's treated as a converted enum to class
  5849. Optimizations:
  5850. * 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
  5851. a string (which is nullable for compile-time hashes) + an int.
  5852. At compile-time, a collision will throw an error (like neko).
  5853. At runtime, a collision will make a negative int. Negative ints will always resolve to a special Hash<> field which takes a string.
  5854. * 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,
  5855. if the type is detected to already be hxgen
  5856. * TODO: if for() optimization for arrays is disabled, we can replace for(field in Reflect.fields(obj)) to:
  5857. 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
  5858. the already hashed fields.
  5859. Mappings:
  5860. * if create Dynamic class is true, TObjectDecl will be mapped to new DynamicClass(fields, [hashedFields], values)
  5861. *
  5862. dependencies:
  5863. 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,
  5864. while the AST has its meaning close to haxe's.
  5865. Should run before InitFunction so it detects variables containing expressions as "always-execute" expressions, even when using CreateEmpty
  5866. * Must run before switch() syntax changes
  5867. *)
  5868. open ClosuresToClass;;
  5869. module ReflectionCFs =
  5870. struct
  5871. let name = "reflection_cfs"
  5872. type rcf_ctx =
  5873. {
  5874. rcf_gen : generator_ctx;
  5875. rcf_ft : ClosuresToClass.closures_ctx;
  5876. rcf_optimize : bool;
  5877. mutable rcf_float_special_case : bool;
  5878. mutable rcf_object_iface : tclass;
  5879. mutable rcf_create_getsetinvoke_fields : bool;
  5880. (* should we create the get type (get Class)? *)
  5881. mutable rcf_create_get_type : bool;
  5882. (* should we handle implements dynamic? *)
  5883. mutable rcf_handle_impl_dynamic : bool;
  5884. (*
  5885. create_dyn_overloading_ctor :
  5886. when creating the implements dynamic code, we can also create a special constructor for
  5887. the actual DynamicObject class, which will receive all its <implements Dynamic> fields from the code outside.
  5888. Note that this will only work on targets that support overloading contrstuctors, as any class that extends
  5889. our DynamicObject will have an empty super() call
  5890. *)
  5891. mutable rcf_create_dyn_ctor : bool;
  5892. mutable rcf_max_func_arity : int;
  5893. (*
  5894. the hash lookup function. can be an inlined expr or simply a function call.
  5895. its only needed features is that it should return the index of the key if found, and the
  5896. complement of the index of where it should be inserted if not found (Ints).
  5897. hash->hash_array->returning expression
  5898. *)
  5899. mutable rcf_hash_function : texpr->texpr->texpr;
  5900. mutable rcf_lookup_function : texpr->texpr;
  5901. (*
  5902. class_cl is the real class for Class<> instances.
  5903. In the current implementation, due to some targets' limitations, (in particular, Java),
  5904. we have to use an empty object so we can access its virtual mehtods.
  5905. FIXME find a better way to create Class<> objects in a performant way
  5906. *)
  5907. mutable rcf_class_cl : tclass option;
  5908. (*
  5909. Also about the Class<> type, should we crate all classes eagerly?
  5910. If false, it means that we should have a way at runtime to create the class when needed by
  5911. Type.resolveClass/Enum
  5912. *)
  5913. mutable rcf_class_eager_creation : bool;
  5914. rcf_hash_fields : (int, string) Hashtbl.t;
  5915. (*
  5916. main expr -> field expr -> field string -> possible hash int (if optimize) -> possible set expr -> should_throw_exceptions -> changed expression
  5917. Changes a get / set field to the runtime resolution function
  5918. *)
  5919. mutable rcf_on_getset_field : texpr->texpr->string->int32 option->texpr option->bool->texpr;
  5920. mutable rcf_on_call_field : texpr->texpr->string->int32 option->texpr list->texpr;
  5921. mutable rcf_handle_statics : bool;
  5922. }
  5923. let new_ctx gen ft object_iface optimize dynamic_getset_field dynamic_call_field hash_function lookup_function handle_statics =
  5924. {
  5925. rcf_gen = gen;
  5926. rcf_ft = ft;
  5927. rcf_optimize = optimize;
  5928. rcf_float_special_case = true;
  5929. rcf_object_iface = object_iface;
  5930. rcf_create_getsetinvoke_fields = true;
  5931. rcf_create_get_type = true;
  5932. rcf_handle_impl_dynamic = true;
  5933. rcf_create_dyn_ctor = true;
  5934. rcf_max_func_arity = 10;
  5935. rcf_hash_function = hash_function;
  5936. rcf_lookup_function = lookup_function;
  5937. rcf_class_cl = None;
  5938. rcf_class_eager_creation = false;
  5939. rcf_hash_fields = Hashtbl.create 100;
  5940. rcf_on_getset_field = dynamic_getset_field;
  5941. rcf_on_call_field = dynamic_call_field;
  5942. rcf_handle_statics = handle_statics;
  5943. }
  5944. (*
  5945. methods as a bool option is a little laziness of my part.
  5946. None means that methods are included with normal fields;
  5947. Some(true) means collect only methods
  5948. Some(false) means collect only fields (and MethDynamic fields)
  5949. *)
  5950. let collect_fields cl (methods : bool option) (statics : bool option) =
  5951. let collected = Hashtbl.create 0 in
  5952. let collect cf acc =
  5953. if Meta.has Meta.CompilerGenerated cf.cf_meta || Meta.has Meta.SkipReflection cf.cf_meta then
  5954. acc
  5955. else match methods, cf.cf_kind with
  5956. | None, _ when not (Hashtbl.mem collected cf.cf_name) -> Hashtbl.add collected cf.cf_name true; ([cf.cf_name], cf) :: acc
  5957. | Some true, Method MethDynamic -> acc
  5958. | Some true, Method _ when not (Hashtbl.mem collected cf.cf_name) -> Hashtbl.add collected cf.cf_name true; ([cf.cf_name], cf) :: acc
  5959. | Some false, Method MethDynamic
  5960. | Some false, Var _ when not (Hashtbl.mem collected cf.cf_name) -> Hashtbl.add collected cf.cf_name true; ([cf.cf_name], cf) :: acc
  5961. | _ -> acc
  5962. in
  5963. let collect_cfs cfs acc =
  5964. let rec loop cfs acc =
  5965. match cfs with
  5966. | [] -> acc
  5967. | hd :: tl -> loop tl (collect hd acc)
  5968. in
  5969. loop cfs acc
  5970. in
  5971. let rec loop cl acc =
  5972. let acc = match statics with
  5973. | None -> collect_cfs cl.cl_ordered_fields (collect_cfs cl.cl_ordered_statics acc)
  5974. | Some true -> collect_cfs cl.cl_ordered_statics acc
  5975. | Some false -> collect_cfs cl.cl_ordered_fields acc
  5976. in
  5977. match cl.cl_super with
  5978. | None -> acc
  5979. | Some(cl,_) ->
  5980. if not (is_hxgen (TClassDecl cl)) then loop cl acc else acc
  5981. in
  5982. loop cl []
  5983. let hash f =
  5984. let h = ref 0 in
  5985. for i = 0 to String.length f - 1 do
  5986. h := !h * 223 + int_of_char (String.unsafe_get f i);
  5987. done;
  5988. if Sys.word_size = 64 then Int32.to_int (Int32.shift_right (Int32.shift_left (Int32.of_int !h) 1) 1) else !h
  5989. let hash_field ctx f pos =
  5990. let h = hash f in
  5991. (try
  5992. let f2 = Hashtbl.find ctx.rcf_hash_fields h in
  5993. if f <> f2 then ctx.rcf_gen.gcon.error ("Field conflict between " ^ f ^ " and " ^ f2) pos
  5994. with Not_found ->
  5995. Hashtbl.add ctx.rcf_hash_fields h f);
  5996. h
  5997. (* ( tf_args, switch_var ) *)
  5998. let field_type_args ctx pos =
  5999. match ctx.rcf_optimize with
  6000. | true ->
  6001. let field_name, field_hash = alloc_var "field" ctx.rcf_gen.gcon.basic.tstring, alloc_var "hash" ctx.rcf_gen.gcon.basic.tint in
  6002. [field_name, None; field_hash, None], field_hash
  6003. | false ->
  6004. let field_name = alloc_var "field" ctx.rcf_gen.gcon.basic.tstring in
  6005. [field_name, None], field_name
  6006. let hash_field_i32 ctx pos field_name =
  6007. let i = hash_field ctx field_name pos in
  6008. let i = Int32.of_int (i) in
  6009. if i < Int32.zero then
  6010. Int32.logor (Int32.logand i (Int32.of_int 0x3FFFFFFF)) (Int32.shift_left Int32.one 30)
  6011. else i
  6012. let switch_case ctx pos field_name =
  6013. match ctx.rcf_optimize with
  6014. | true ->
  6015. let i = hash_field_i32 ctx pos field_name in
  6016. { eexpr = TConst(TInt(i)); etype = ctx.rcf_gen.gcon.basic.tint; epos = pos }
  6017. | false ->
  6018. { eexpr = TConst(TString(field_name)); etype = ctx.rcf_gen.gcon.basic.tstring; epos = pos }
  6019. (*
  6020. Will implement getField / setField which will follow the following rule:
  6021. function getField(field, isStatic, throwErrors, isCheck, handleProperty, isFirst):Dynamic
  6022. {
  6023. if (isStatic)
  6024. {
  6025. switch(field)
  6026. {
  6027. case "aStaticField": return ThisClass.aStaticField;
  6028. case "aDynamicField": return ThisClass.aDynamicField;
  6029. default:
  6030. if (isFirst) return getField_d(field, isStatic, throwErrors, handleProperty, false);
  6031. if(throwErrors) throw "Field not found"; else if (isCheck) return __undefined__ else return null;
  6032. }
  6033. } else {
  6034. switch(field)
  6035. {
  6036. case "aNormalField": return this.aNormalField;
  6037. case "aBoolField": return this.aBoolField;
  6038. case "aDoubleField": return this.aDoubleField;
  6039. default: return getField_d(field, isStatic, throwErrors, isCheck);
  6040. }
  6041. }
  6042. }
  6043. function getField_d(field, isStatic, throwErrors, handleProperty, isFirst):Float
  6044. {
  6045. if (isStatic)
  6046. {
  6047. switch(field)
  6048. {
  6049. case "aDynamicField": return cast ThisClass.aDynamicField;
  6050. default: if (throwErrors) throw "Field not found"; else return null;
  6051. }
  6052. }
  6053. etc...
  6054. }
  6055. function setField(field, value, isStatic):Dynamic {}
  6056. function setField_d(field, value:Float, isStatic):Float {}
  6057. *)
  6058. let call_super ctx fn_args ret_t cf cl this_t pos =
  6059. {
  6060. eexpr = TCall({
  6061. eexpr = TField({ eexpr = TConst(TSuper); etype = this_t; epos = pos }, FInstance(cl,List.map snd cl.cl_params,cf));
  6062. etype = TFun(fun_args fn_args, ret_t);
  6063. epos = pos;
  6064. }, List.map (fun (v,_) -> mk_local v pos) fn_args);
  6065. etype = ret_t;
  6066. epos = pos;
  6067. }
  6068. let mk_string ctx str pos =
  6069. { eexpr = TConst(TString(str)); etype = ctx.rcf_gen.gcon.basic.tstring; epos = pos }
  6070. let mk_int ctx i pos =
  6071. { eexpr = TConst(TInt(Int32.of_int i)); etype = ctx.rcf_gen.gcon.basic.tint; epos = pos }
  6072. let mk_bool ctx b pos =
  6073. { eexpr = TConst(TBool(b)); etype = ctx.rcf_gen.gcon.basic.tbool; epos = pos }
  6074. let mk_throw ctx str pos = { eexpr = TThrow (mk_string ctx str pos); etype = ctx.rcf_gen.gcon.basic.tvoid; epos = pos }
  6075. let enumerate_dynamic_fields ctx cl when_found =
  6076. let gen = ctx.rcf_gen in
  6077. let basic = gen.gcon.basic in
  6078. let pos = cl.cl_pos in
  6079. let vtmp = mk_temp gen "i" basic.tint in
  6080. let vlen = mk_temp gen "len" basic.tint in
  6081. let mk_for arr =
  6082. let t = if ctx.rcf_optimize then basic.tint else basic.tstring in
  6083. let convert_str e = if ctx.rcf_optimize then ctx.rcf_lookup_function e else e in
  6084. let lenlocal = mk_local vlen pos in
  6085. let tmpinc = { eexpr = TUnop(Ast.Increment, Ast.Postfix, mk_local vtmp pos); etype = basic.tint; epos = pos } in
  6086. {
  6087. eexpr = TBlock [
  6088. { eexpr = TBinop(OpAssign, mk_local vtmp pos, mk_int ctx 0 pos); etype = basic.tint; epos = pos };
  6089. { eexpr = TBinop(OpAssign, lenlocal, mk_field_access gen arr "length" pos); etype = basic.tint; epos = pos };
  6090. {
  6091. eexpr = TWhile (
  6092. { eexpr = TBinop(Ast.OpLt, mk_local vtmp pos, lenlocal); etype = basic.tbool; epos = pos },
  6093. mk_block (when_found (convert_str { eexpr = TArray (arr, tmpinc); etype = t; epos = pos })),
  6094. Ast.NormalWhile
  6095. );
  6096. etype = basic.tvoid;
  6097. epos = pos
  6098. }
  6099. ];
  6100. etype = basic.tvoid;
  6101. epos = pos;
  6102. }
  6103. in
  6104. let this_t = TInst(cl, List.map snd cl.cl_params) in
  6105. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  6106. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  6107. [
  6108. { eexpr = TVar (vtmp,None); etype = basic.tvoid; epos = pos };
  6109. { eexpr = TVar (vlen,None); etype = basic.tvoid; epos = pos };
  6110. ]
  6111. @
  6112. if ctx.rcf_optimize then
  6113. [
  6114. mk_for (mk_this (gen.gmk_internal_name "hx" "hashes") (basic.tarray basic.tint));
  6115. mk_for (mk_this (gen.gmk_internal_name "hx" "hashes_f") (basic.tarray basic.tint));
  6116. ] else [
  6117. mk_for (mk_this (gen.gmk_internal_name "hx" "hashes") (basic.tarray basic.tstring));
  6118. mk_for (mk_this (gen.gmk_internal_name "hx" "hashes_f") (basic.tarray basic.tstring));
  6119. ]
  6120. (* *********************
  6121. Dynamic lookup
  6122. *********************
  6123. This is the behavior of standard <implements Dynamic> classes. It will replace the error throwing
  6124. if a field doesn't exists when looking it up.
  6125. In order for it to work, an implementation for hash_function must be created.
  6126. hash_function is the function to be called/inlined that will allow us to lookup the hash into a sorted array of hashes.
  6127. A binary search or linear search algorithm may be implemented. The only need is that if not found, the NegBits of
  6128. the place where it should be inserted must be returned.
  6129. *)
  6130. let abstract_dyn_lookup_implementation ctx this hash_local may_value is_float pos =
  6131. let gen = ctx.rcf_gen in
  6132. let basic = gen.gcon.basic in
  6133. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  6134. let a_t = if ctx.rcf_optimize then basic.tint else basic.tstring in
  6135. let hx_hashes = mk_this (gen.gmk_internal_name "hx" "hashes") (basic.tarray a_t) in
  6136. let hx_hashes_f = mk_this (gen.gmk_internal_name "hx" "hashes_f") (basic.tarray a_t) in
  6137. let hx_dynamics = mk_this (gen.gmk_internal_name "hx" "dynamics") (basic.tarray t_empty) in
  6138. let hx_dynamics_f = mk_this (gen.gmk_internal_name "hx" "dynamics_f") (basic.tarray basic.tfloat) in
  6139. let res = alloc_var "res" basic.tint in
  6140. let fst_hash, snd_hash, fst_dynamics, snd_dynamics =
  6141. 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
  6142. in
  6143. let res_local = mk_local res pos in
  6144. let gte = {
  6145. eexpr = TBinop(Ast.OpGte, res_local, { eexpr = TConst(TInt(Int32.zero)); etype = basic.tint; epos = pos });
  6146. etype = basic.tbool;
  6147. epos = pos;
  6148. } in
  6149. let get_array_t t = match follow t with | TInst({ cl_path = ([],"Array") },[arrtype]) -> arrtype | _ -> assert false in
  6150. let mk_tarray arr idx =
  6151. let t = get_array_t arr.etype in
  6152. {
  6153. eexpr = TArray(arr, idx);
  6154. etype = t;
  6155. epos = pos;
  6156. }
  6157. in
  6158. let ret_t = if is_float then basic.tfloat else t_dynamic in
  6159. match may_value with
  6160. | None ->
  6161. (*
  6162. var res = lookup(this.__hx_hashes/f, hash);
  6163. if (res < 0)
  6164. {
  6165. res = lookup(this.__hx_hashes_f/_, hash);
  6166. if(res < 0)
  6167. return null;
  6168. else
  6169. return __hx_dynamics_f[res];
  6170. } else {
  6171. return __hx_dynamics[res];
  6172. }
  6173. *)
  6174. let block =
  6175. [
  6176. { eexpr = TVar(res, Some(ctx.rcf_hash_function hash_local fst_hash)); etype = basic.tvoid; epos = pos };
  6177. { eexpr = TIf(gte, mk_return (mk_tarray fst_dynamics res_local), Some({
  6178. eexpr = TBlock(
  6179. [
  6180. { eexpr = TBinop(Ast.OpAssign, res_local, ctx.rcf_hash_function hash_local snd_hash); etype = basic.tint; epos = pos };
  6181. { eexpr = TIf(gte, mk_return (mk_tarray snd_dynamics res_local), None); etype = ret_t; epos = pos }
  6182. ]);
  6183. etype = ret_t;
  6184. epos = pos;
  6185. })); etype = ret_t; epos = pos }
  6186. ] in
  6187. block
  6188. | Some value_local ->
  6189. (*
  6190. //if is not float:
  6191. //if (isNumber(value_local)) return this.__hx_setField_f(field, getNumber(value_local), false(not static));
  6192. var res = lookup(this.__hx_hashes/f, hash);
  6193. if (res >= 0)
  6194. {
  6195. return __hx_dynamics/f[res] = value_local;
  6196. } else {
  6197. res = lookup(this.__hx_hashes_f/_, hash);
  6198. if (res >= 0)
  6199. {
  6200. __hx_dynamics_f/_.splice(res,1);
  6201. __hx_hashes_f/_.splice(res,1);
  6202. }
  6203. }
  6204. __hx_hashses/_f.insert(~res, hash);
  6205. __hx_dynamics/_f.insert(~res, value_local);
  6206. return value_local;
  6207. *)
  6208. let mk_splice arr at_pos = {
  6209. eexpr = TCall(
  6210. mk_field_access gen arr "splice" pos,
  6211. [at_pos; { eexpr = TConst(TInt Int32.one); etype = basic.tint; epos = pos }]
  6212. );
  6213. etype = arr.etype;
  6214. epos = pos
  6215. } in
  6216. let mk_insert arr at_pos value = {
  6217. eexpr = TCall(
  6218. mk_field_access gen arr "insert" pos,
  6219. [at_pos; value]);
  6220. etype = basic.tvoid;
  6221. epos = pos
  6222. } in
  6223. let neg_res = { eexpr = TUnop(Ast.NegBits, Ast.Prefix, res_local); etype = basic.tint; epos = pos } in
  6224. let res2 = alloc_var "res2" basic.tint in
  6225. let res2_local = mk_local res2 pos in
  6226. let gte2 = {
  6227. eexpr = TBinop(Ast.OpGte, res2_local, { eexpr = TConst(TInt(Int32.zero)); etype = basic.tint; epos = pos });
  6228. etype = basic.tbool;
  6229. epos = pos;
  6230. } in
  6231. let block =
  6232. [
  6233. { eexpr = TVar(res, Some(ctx.rcf_hash_function hash_local fst_hash)); etype = basic.tvoid; epos = pos };
  6234. {
  6235. eexpr = TIf(gte,
  6236. mk_return { eexpr = TBinop(Ast.OpAssign, mk_tarray fst_dynamics res_local, value_local); etype = value_local.etype; epos = pos },
  6237. Some({ eexpr = TBlock([
  6238. { eexpr = TVar( res2, Some(ctx.rcf_hash_function hash_local snd_hash)); etype = basic.tvoid; epos = pos };
  6239. {
  6240. eexpr = TIf(gte2, { eexpr = TBlock([
  6241. mk_splice snd_hash res2_local;
  6242. mk_splice snd_dynamics res2_local
  6243. ]); etype = t_dynamic; epos = pos }, None);
  6244. etype = t_dynamic;
  6245. epos = pos;
  6246. }
  6247. ]); etype = t_dynamic; epos = pos }));
  6248. etype = t_dynamic;
  6249. epos = pos;
  6250. };
  6251. mk_insert fst_hash neg_res hash_local;
  6252. mk_insert fst_dynamics neg_res value_local;
  6253. mk_return value_local
  6254. ] in
  6255. block
  6256. let get_delete_field ctx cl is_dynamic =
  6257. let pos = cl.cl_pos in
  6258. let this_t = TInst(cl, List.map snd cl.cl_params) in
  6259. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  6260. let gen = ctx.rcf_gen in
  6261. let basic = gen.gcon.basic in
  6262. let tf_args, switch_var = field_type_args ctx pos in
  6263. let local_switch_var = mk_local switch_var pos in
  6264. let fun_type = TFun(fun_args tf_args,basic.tbool) in
  6265. let cf = mk_class_field (gen.gmk_internal_name "hx" "deleteField") fun_type false pos (Method MethNormal) [] in
  6266. let body = if is_dynamic then begin
  6267. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  6268. let a_t = if ctx.rcf_optimize then basic.tint else basic.tstring in
  6269. let hx_hashes = mk_this (gen.gmk_internal_name "hx" "hashes") (basic.tarray a_t) in
  6270. let hx_hashes_f = mk_this (gen.gmk_internal_name "hx" "hashes_f") (basic.tarray a_t) in
  6271. let hx_dynamics = mk_this (gen.gmk_internal_name "hx" "dynamics") (basic.tarray t_empty) in
  6272. let hx_dynamics_f = mk_this (gen.gmk_internal_name "hx" "dynamics_f") (basic.tarray basic.tfloat) in
  6273. let res = alloc_var "res" basic.tint in
  6274. let res_local = mk_local res pos in
  6275. let gte = {
  6276. eexpr = TBinop(Ast.OpGte, res_local, { eexpr = TConst(TInt(Int32.zero)); etype = basic.tint; epos = pos });
  6277. etype = basic.tbool;
  6278. epos = pos;
  6279. } in
  6280. let mk_splice arr at_pos = {
  6281. eexpr = TCall(
  6282. mk_field_access gen arr "splice" pos,
  6283. [at_pos; { eexpr = TConst(TInt Int32.one); etype = basic.tint; epos = pos }]
  6284. );
  6285. etype = arr.etype;
  6286. epos = pos
  6287. } in
  6288. (*
  6289. var res = lookup(this.__hx_hashes, hash);
  6290. if (res >= 0)
  6291. {
  6292. __hx_dynamics.splice(res,1);
  6293. __hx_hashes.splice(res,1);
  6294. return true;
  6295. } else {
  6296. res = lookup(this.__hx_hashes_f, hash);
  6297. if (res >= 0)
  6298. {
  6299. __hx_dynamics_f.splice(res,1);
  6300. __hx_hashes_f.splice(res,1);
  6301. return true;
  6302. }
  6303. }
  6304. return false;
  6305. *)
  6306. [
  6307. { eexpr = TVar(res,Some(ctx.rcf_hash_function local_switch_var hx_hashes)); etype = basic.tvoid; epos = pos };
  6308. {
  6309. eexpr = TIf(gte, { eexpr = TBlock([
  6310. mk_splice hx_hashes res_local;
  6311. mk_splice hx_dynamics res_local;
  6312. mk_return { eexpr = TConst(TBool true); etype = basic.tbool; epos = pos }
  6313. ]); etype = t_dynamic; epos = pos }, Some({ eexpr = TBlock([
  6314. { eexpr = TBinop(Ast.OpAssign, res_local, ctx.rcf_hash_function local_switch_var hx_hashes_f); etype = basic.tint; epos = pos };
  6315. { eexpr = TIf(gte, { eexpr = TBlock([
  6316. mk_splice hx_hashes_f res_local;
  6317. mk_splice hx_dynamics_f res_local;
  6318. mk_return { eexpr = TConst(TBool true); etype = basic.tbool; epos = pos }
  6319. ]); etype = t_dynamic; epos = pos }, None); etype = t_dynamic; epos = pos }
  6320. ]); etype = t_dynamic; epos = pos }));
  6321. etype = t_dynamic;
  6322. epos = pos;
  6323. };
  6324. mk_return { eexpr = TConst(TBool false); etype = basic.tbool; epos = pos }
  6325. ]
  6326. end else
  6327. [
  6328. mk_return { eexpr = TConst(TBool false); etype = basic.tbool; epos = pos }
  6329. ] in
  6330. (* create function *)
  6331. let fn =
  6332. {
  6333. tf_args = tf_args;
  6334. tf_type = basic.tbool;
  6335. tf_expr = { eexpr = TBlock(body); etype = t_dynamic; epos = pos }
  6336. } in
  6337. cf.cf_expr <- Some({ eexpr = TFunction(fn); etype = fun_type; epos = pos });
  6338. cf
  6339. let rec is_first_dynamic cl =
  6340. match cl.cl_super with
  6341. | Some(cl,_) ->
  6342. if is_some cl.cl_dynamic then false else is_first_dynamic cl
  6343. | None -> true
  6344. let is_override cl = match cl.cl_super with
  6345. | Some (cl, _) when is_hxgen (TClassDecl cl) -> true
  6346. | _ -> false
  6347. let get_args t = match follow t with
  6348. | TFun(args,ret) -> args,ret
  6349. | _ -> assert false
  6350. (* WARNING: this will only work if overloading contructors is possible on target language *)
  6351. let implement_dynamic_object_ctor ctx cl =
  6352. let rec is_side_effects_free e =
  6353. match e.eexpr with
  6354. | TConst _
  6355. | TLocal _
  6356. | TFunction _
  6357. | TTypeExpr _ ->
  6358. true
  6359. | TNew(clnew,[],params) when clnew == cl ->
  6360. List.for_all is_side_effects_free params
  6361. | TUnop(Increment,_,_)
  6362. | TUnop(Decrement,_,_)
  6363. | TBinop(OpAssign,_,_)
  6364. | TBinop(OpAssignOp _,_,_) ->
  6365. false
  6366. | TUnop(_,_,e) ->
  6367. is_side_effects_free e
  6368. | TArray(e1,e2)
  6369. | TBinop(_,e1,e2) ->
  6370. is_side_effects_free e1 && is_side_effects_free e2
  6371. | TIf(cond,e1,Some e2) ->
  6372. is_side_effects_free cond && is_side_effects_free e1 && is_side_effects_free e2
  6373. | TField(e,_)
  6374. | TParenthesis e | TMeta(_,e) -> is_side_effects_free e
  6375. | TArrayDecl el -> List.for_all is_side_effects_free el
  6376. | TCast(e,_) -> is_side_effects_free e
  6377. | _ -> false
  6378. in
  6379. let pos = cl.cl_pos in
  6380. let gen = ctx.rcf_gen in
  6381. let basic = gen.gcon.basic in
  6382. let hasht = if ctx.rcf_optimize then basic.tint else basic.tstring in
  6383. let fields =
  6384. [
  6385. gen.gmk_internal_name "hx" "hashes", basic.tarray hasht;
  6386. gen.gmk_internal_name "hx" "dynamics", basic.tarray t_empty;
  6387. gen.gmk_internal_name "hx" "hashes_f", basic.tarray hasht;
  6388. gen.gmk_internal_name "hx" "dynamics_f", basic.tarray basic.tfloat;
  6389. ] in
  6390. let tf_args = List.map (fun (name, t) ->
  6391. alloc_var name t, None
  6392. ) fields in
  6393. let this = { eexpr = TConst TThis; etype = TInst(cl, List.map snd cl.cl_params); epos = pos } in
  6394. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  6395. let fun_t = TFun(fun_args tf_args,basic.tvoid) in
  6396. let ctor = mk_class_field "new" fun_t true pos (Method MethNormal) [] in
  6397. ctor.cf_expr <- Some(
  6398. {
  6399. eexpr = TFunction({
  6400. tf_args = tf_args;
  6401. tf_type = basic.tvoid;
  6402. tf_expr =
  6403. {
  6404. eexpr = TBlock(List.map (fun (v,_) ->
  6405. { eexpr = TBinop(Ast.OpAssign, mk_this v.v_name v.v_type, mk_local v pos); etype = v.v_type; epos = pos }
  6406. ) tf_args);
  6407. etype = basic.tvoid;
  6408. epos = pos
  6409. }
  6410. });
  6411. etype = fun_t;
  6412. epos = pos
  6413. });
  6414. add_constructor cl ctor;
  6415. (* default ctor also *)
  6416. let ctor = mk_class_field "new" (TFun([],basic.tvoid)) false pos (Method MethNormal) [] in
  6417. ctor.cf_expr <- Some {
  6418. eexpr = TFunction {
  6419. tf_type = basic.tvoid;
  6420. tf_args = [];
  6421. tf_expr = {
  6422. eexpr = TBlock(List.map (fun (f,t) ->
  6423. { eexpr = TBinop(Ast.OpAssign, mk_this f t,{ eexpr = TArrayDecl([]); etype = t; epos = pos; }); etype = t; epos = pos }
  6424. ) fields);
  6425. etype = basic.tvoid;
  6426. epos = pos;
  6427. }
  6428. };
  6429. etype = ctor.cf_type;
  6430. epos = pos;
  6431. };
  6432. add_constructor cl ctor;
  6433. (* and finally we will return a function that transforms a TObjectDecl into a new DynamicObject() call *)
  6434. let rec loop objdecl acc acc_f =
  6435. match objdecl with
  6436. | [] -> acc,acc_f
  6437. | (name,expr) :: tl ->
  6438. let real_t = gen.greal_type expr.etype in
  6439. match follow expr.etype with
  6440. | TInst ( { cl_path = ["haxe"], "Int64" }, [] ) ->
  6441. loop tl ((name, gen.ghandle_cast t_dynamic real_t expr) :: acc) acc_f
  6442. | _ ->
  6443. if like_float real_t && not (like_i64 real_t) then
  6444. loop tl acc ((name, gen.ghandle_cast basic.tfloat real_t expr) :: acc_f)
  6445. else
  6446. loop tl ((name, gen.ghandle_cast t_dynamic real_t expr) :: acc) acc_f
  6447. in
  6448. let may_hash_field s =
  6449. if ctx.rcf_optimize then begin
  6450. (* let hash_field ctx f pos = *)
  6451. { eexpr = TConst(TInt (hash_field_i32 ctx pos s)); etype = basic.tint; epos = pos }
  6452. end else begin
  6453. { eexpr = TConst(TString s); etype = basic.tstring; epos = pos }
  6454. end
  6455. in
  6456. let do_objdecl e objdecl =
  6457. let exprs_before = ref [] in
  6458. let rec change_exprs decl acc = match decl with
  6459. | (name,expr) :: tl ->
  6460. if is_side_effects_free expr then
  6461. change_exprs tl ((name,expr) :: acc)
  6462. else begin
  6463. let var = mk_temp gen "odecl" expr.etype in
  6464. exprs_before := { eexpr = TVar(var,Some expr); etype = basic.tvoid; epos = expr.epos } :: !exprs_before;
  6465. change_exprs tl ((name,mk_local var expr.epos) :: acc)
  6466. end
  6467. | [] -> acc
  6468. in
  6469. let objdecl = change_exprs objdecl [] in
  6470. let odecl, odecl_f = loop objdecl [] [] in
  6471. let changed_expr = List.map (fun (s,e) -> (may_hash_field s,e)) in
  6472. let odecl, odecl_f = changed_expr odecl, changed_expr odecl_f in
  6473. let sort_fn (e1,_) (e2,_) =
  6474. match e1.eexpr, e2.eexpr with
  6475. | TConst(TInt i1), TConst(TInt i2) -> compare i1 i2
  6476. | TConst(TString s1), TConst(TString s2) -> compare s1 s2
  6477. | _ -> assert false
  6478. in
  6479. let odecl, odecl_f = List.sort sort_fn odecl, List.sort sort_fn odecl_f in
  6480. let mk_arrdecl el t = { eexpr = TArrayDecl(el); etype = t; epos = pos } in
  6481. let ret = {
  6482. e with eexpr = TNew(cl,[],
  6483. [
  6484. mk_arrdecl (List.map fst odecl) (basic.tarray hasht);
  6485. mk_arrdecl (List.map snd odecl) (basic.tarray t_empty);
  6486. mk_arrdecl (List.map fst odecl_f) (basic.tarray hasht);
  6487. mk_arrdecl (List.map snd odecl_f) (basic.tarray basic.tfloat)
  6488. ]);
  6489. } in
  6490. match !exprs_before with
  6491. | [] -> ret
  6492. | block ->
  6493. {
  6494. eexpr = TBlock(List.rev block @ [ret]);
  6495. etype = ret.etype;
  6496. epos = ret.epos;
  6497. }
  6498. in
  6499. do_objdecl
  6500. let implement_dynamics ctx cl =
  6501. let pos = cl.cl_pos in
  6502. let is_override = is_override cl in
  6503. if is_some cl.cl_dynamic then begin
  6504. if is_first_dynamic cl then begin
  6505. (*
  6506. * add hx_hashes, hx_hashes_f, hx_dynamics, hx_dynamics_f to class
  6507. * implement hx_deleteField
  6508. *)
  6509. let gen = ctx.rcf_gen in
  6510. let basic = gen.gcon.basic in
  6511. let hasht = if ctx.rcf_optimize then basic.tint else basic.tstring in
  6512. let new_fields =
  6513. [
  6514. mk_class_field (gen.gmk_internal_name "hx" "hashes") (basic.tarray hasht) false pos (Var { v_read = AccNormal; v_write = AccNormal }) [];
  6515. mk_class_field (gen.gmk_internal_name "hx" "dynamics") (basic.tarray t_empty) false pos (Var { v_read = AccNormal; v_write = AccNormal }) [];
  6516. mk_class_field (gen.gmk_internal_name "hx" "hashes_f") (basic.tarray hasht) false pos (Var { v_read = AccNormal; v_write = AccNormal }) [];
  6517. mk_class_field (gen.gmk_internal_name "hx" "dynamics_f") (basic.tarray basic.tfloat) false pos (Var { v_read = AccNormal; v_write = AccNormal }) [];
  6518. ] in
  6519. (if cl.cl_path <> (["haxe"; "lang"], "DynamicObject") then
  6520. List.iter (fun cf -> cf.cf_expr <- Some { eexpr = TArrayDecl([]); etype = cf.cf_type; epos = cf.cf_pos }) new_fields
  6521. );
  6522. let delete = get_delete_field ctx cl true in
  6523. List.iter (fun cf ->
  6524. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields
  6525. ) (delete :: new_fields);
  6526. (*
  6527. let rec last_ctor cl =
  6528. match cl.cl_constructor with
  6529. | None -> (match cl.cl_super with | None -> None | Some (cl,_) -> last_ctor cl)
  6530. | Some c -> Some c
  6531. in
  6532. *)
  6533. (*
  6534. 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
  6535. *)
  6536. (*
  6537. Now we need to add their initialization.
  6538. This will consist of different parts:
  6539. Check if there are constructors. If not, create one and add initialization to it (calling super, ok)
  6540. If there are, add as first statement (or second if there is a super() call in the first)
  6541. If class has @:$DynamicObject meta, also create another new() class with its parameters as constructor arguments
  6542. *)
  6543. List.iter (fun cf ->
  6544. cf.cf_expr <- Some({ eexpr = TArrayDecl([]); etype = cf.cf_type; epos = cf.cf_pos })
  6545. ) new_fields;
  6546. cl.cl_ordered_fields <- cl.cl_ordered_fields @ (delete :: new_fields);
  6547. if is_override then cl.cl_overrides <- delete :: cl.cl_overrides
  6548. end
  6549. end else if not is_override then begin
  6550. let delete = get_delete_field ctx cl false in
  6551. cl.cl_ordered_fields <- cl.cl_ordered_fields @ [delete];
  6552. cl.cl_fields <- PMap.add delete.cf_name delete cl.cl_fields
  6553. end
  6554. let implement_create_empty ctx cl =
  6555. let gen = ctx.rcf_gen in
  6556. let basic = gen.gcon.basic in
  6557. let pos = cl.cl_pos in
  6558. let is_override = is_override cl in
  6559. let tparams = List.map (fun _ -> t_empty) cl.cl_params in
  6560. let create =
  6561. let arr = alloc_var "arr" (basic.tarray t_dynamic) in
  6562. let tf_args = [ arr, None ] in
  6563. let t = TFun(fun_args tf_args, t_dynamic) in
  6564. let cf = mk_class_field (gen.gmk_internal_name "hx" "create") t false pos (Method MethNormal) [] in
  6565. let i = ref 0 in
  6566. let arr_local = mk_local arr pos in
  6567. let ctor = if is_some cl.cl_constructor then cl.cl_constructor else get_last_ctor cl in
  6568. let params = match ctor with
  6569. | None -> []
  6570. | Some ctor ->
  6571. List.map (fun (n,_,t) ->
  6572. let old = !i in
  6573. incr i;
  6574. {
  6575. eexpr = TArray(arr_local, { eexpr = TConst(TInt (Int32.of_int old)); etype = basic.tint; epos = pos } );
  6576. etype = t_dynamic;
  6577. epos = pos
  6578. }
  6579. ) ( fst ( get_fun ctor.cf_type ) )
  6580. in
  6581. let expr = mk_return {
  6582. eexpr = TNew(cl, tparams, params);
  6583. etype = TInst(cl, tparams);
  6584. epos = pos
  6585. } in
  6586. let fn = {
  6587. eexpr = TFunction({
  6588. tf_args = tf_args;
  6589. tf_type = t_dynamic;
  6590. tf_expr = mk_block expr
  6591. });
  6592. etype = t;
  6593. epos = pos
  6594. } in
  6595. cf.cf_expr <- Some fn;
  6596. cf
  6597. in
  6598. let create_empty =
  6599. let t = TFun([],t_dynamic) in
  6600. let cf = mk_class_field (gen.gmk_internal_name "hx" "createEmpty") t false pos (Method MethNormal) [] in
  6601. let fn = {
  6602. eexpr = TFunction({
  6603. tf_args = [];
  6604. tf_type = t_dynamic;
  6605. tf_expr = mk_block (mk_return ( gen.gtools.rf_create_empty cl tparams pos ))
  6606. });
  6607. etype = t;
  6608. epos = pos
  6609. } in
  6610. cf.cf_expr <- Some fn;
  6611. cf
  6612. in
  6613. (* if rcf_handle_statics is false, there is no reason to make createEmpty/create not be static *)
  6614. if ctx.rcf_handle_statics then begin
  6615. cl.cl_ordered_fields <- cl.cl_ordered_fields @ [create_empty; create];
  6616. cl.cl_fields <- PMap.add create_empty.cf_name create_empty cl.cl_fields;
  6617. cl.cl_fields <- PMap.add create.cf_name create cl.cl_fields;
  6618. if is_override then begin
  6619. cl.cl_overrides <- create_empty :: create :: cl.cl_overrides
  6620. end
  6621. end else begin
  6622. cl.cl_ordered_statics <- cl.cl_ordered_statics @ [create_empty; create];
  6623. cl.cl_statics <- PMap.add create_empty.cf_name create_empty cl.cl_statics;
  6624. cl.cl_statics <- PMap.add create.cf_name create cl.cl_statics
  6625. end
  6626. (*
  6627. Implements:
  6628. __hx_lookupField(field:String, throwErrors:Bool, isCheck:Bool, handleProperties:Bool, isFirst:Bool):Dynamic
  6629. __hx_lookupField_f(field:String, throwErrors:Bool, handleProperties:Bool, isFirst:Bool):Float
  6630. __hx_lookupSetField(field:String, value:Dynamic, handleProperties:Bool, isFirst:Bool):Dynamic;
  6631. __hx_lookupSetField(field:String, value:Float, handleProperties:Bool, isFirst:Bool):Float;
  6632. *)
  6633. let implement_final_lookup ctx cl =
  6634. let gen = ctx.rcf_gen in
  6635. let basic = gen.gcon.basic in
  6636. let pos = cl.cl_pos in
  6637. let is_override = is_override cl in
  6638. let this = { eexpr = TConst(TThis); etype = TInst(cl, List.map snd cl.cl_params); epos = pos } in
  6639. (*
  6640. this function will create the class fields and call callback for each version
  6641. callback : is_float fields_args switch_var throw_errors_option is_check_option value_option : texpr list
  6642. *)
  6643. let create_cfs is_dynamic callback =
  6644. let create_cf is_float is_set =
  6645. let name = gen.gmk_internal_name "hx" ( (if is_set then "lookupSetField" else "lookupField") ^ (if is_float then "_f" else "") ) in
  6646. let field_args, switch_var = field_type_args ctx pos in
  6647. let ret_t = if is_float then basic.tfloat else t_dynamic in
  6648. let tf_args, throw_errors_opt =
  6649. if is_set then
  6650. field_args, None
  6651. else
  6652. let v = alloc_var "throwErrors" basic.tbool in
  6653. field_args @ [v,None], Some v
  6654. in
  6655. let tf_args, is_check_opt =
  6656. if is_set || is_float then
  6657. tf_args, None
  6658. else
  6659. let v = alloc_var "isCheck" basic.tbool in
  6660. tf_args @ [v,None], Some v
  6661. in
  6662. let tf_args, value_opt =
  6663. if not is_set then
  6664. tf_args, None
  6665. else
  6666. let v = alloc_var "value" ret_t in
  6667. field_args @ [v,None], Some v
  6668. in
  6669. let fun_t = TFun(fun_args tf_args, ret_t) in
  6670. let cf = mk_class_field name fun_t false pos (Method MethNormal) [] in
  6671. let block = callback is_float field_args switch_var throw_errors_opt is_check_opt value_opt in
  6672. let block = if not is_set then let tl = begin
  6673. let throw_errors_local = mk_local (get throw_errors_opt) pos in
  6674. let mk_check_throw msg =
  6675. {
  6676. eexpr = TIf(throw_errors_local, mk_throw ctx msg pos, Some (mk_return (null ret_t pos)));
  6677. etype = ret_t;
  6678. epos = pos
  6679. } in
  6680. let mk_may_check_throw msg = if is_dynamic then mk_return (null ret_t pos) else mk_check_throw msg in
  6681. if is_float then begin
  6682. [
  6683. mk_may_check_throw "Field not found or incompatible field type.";
  6684. ]
  6685. end else begin
  6686. let is_check_local = mk_local (get is_check_opt) pos in
  6687. [
  6688. {
  6689. eexpr = TIf(is_check_local, mk_return (undefined pos), Some( mk_may_check_throw "Field not found." ));
  6690. etype = ret_t;
  6691. epos = pos;
  6692. }
  6693. ]
  6694. end
  6695. end in block @ tl else block in
  6696. cf.cf_expr <- Some(
  6697. {
  6698. eexpr = TFunction({
  6699. tf_args = tf_args;
  6700. tf_type = ret_t;
  6701. tf_expr = { eexpr = TBlock(block); etype = ret_t; epos = pos }
  6702. });
  6703. etype = fun_t;
  6704. epos = pos
  6705. }
  6706. );
  6707. cf
  6708. in
  6709. let cfs =
  6710. [
  6711. create_cf false false;
  6712. create_cf true false;
  6713. create_cf false true;
  6714. create_cf true true
  6715. ] in
  6716. cl.cl_ordered_fields <- cl.cl_ordered_fields @ cfs;
  6717. List.iter (fun cf ->
  6718. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields;
  6719. if is_override then cl.cl_overrides <- cf :: cl.cl_overrides
  6720. ) cfs
  6721. in
  6722. if is_some cl.cl_dynamic then begin
  6723. (* let abstract_dyn_lookup_implementation ctx this hash_local may_value is_float pos = *)
  6724. (* callback : is_float fields_args switch_var throw_errors_option is_check_option value_option : texpr list *)
  6725. if is_first_dynamic cl then
  6726. create_cfs true (fun is_float fields_args switch_var _ _ value_opt ->
  6727. abstract_dyn_lookup_implementation ctx this (mk_local switch_var pos) (Option.map (fun v -> mk_local v pos) value_opt) is_float pos
  6728. )
  6729. end else if not is_override then begin
  6730. create_cfs false (fun is_float fields_args switch_var _ _ value_opt ->
  6731. match value_opt with
  6732. | None -> (* is not set *)
  6733. []
  6734. | Some _ -> (* is set *)
  6735. if is_float then
  6736. [ mk_throw ctx "Cannot access field for writing or incompatible type." pos ]
  6737. else
  6738. [ mk_throw ctx "Cannot access field for writing." pos ]
  6739. )
  6740. end
  6741. (* *)
  6742. let implement_get_set ctx cl =
  6743. let gen = ctx.rcf_gen in
  6744. let mk_cfield is_set is_float =
  6745. let pos = cl.cl_pos in
  6746. let basic = ctx.rcf_gen.gcon.basic in
  6747. let tf_args, switch_var = field_type_args ctx pos in
  6748. let field_args = tf_args in
  6749. let local_switch_var = { eexpr = TLocal(switch_var); etype = switch_var.v_type; epos = pos } in
  6750. let is_static = alloc_var "isStatic" basic.tbool in
  6751. let is_static_local = { eexpr = TLocal(is_static); etype = basic.tbool; epos = pos } in
  6752. let handle_prop = alloc_var "handleProperties" basic.tbool in
  6753. let handle_prop_local = mk_local handle_prop pos in
  6754. let this = { eexpr = TConst TThis; etype = TInst(cl, List.map snd cl.cl_params); epos = pos } in
  6755. let mk_this_call_raw name fun_t params =
  6756. { eexpr = TCall( { (mk_field_access gen this name pos) with etype = fun_t; }, params ); etype = snd (get_args fun_t); epos = pos }
  6757. in
  6758. let tf_args = if ctx.rcf_handle_statics then tf_args @ [is_static, None] else tf_args in
  6759. let fun_type = ref (TFun([], basic.tvoid)) in
  6760. let fun_name = ctx.rcf_gen.gmk_internal_name "hx" ( (if is_set then "setField" else "getField") ^ (if is_float then "_f" else "") ) in
  6761. let cfield = mk_class_field fun_name !fun_type false pos (Method MethNormal) [] in
  6762. let maybe_cast e = e in
  6763. let t = TInst(cl, List.map snd cl.cl_params) in
  6764. (* if it's not latest hxgen class -> check super *)
  6765. let mk_do_default args do_default =
  6766. match cl.cl_super with
  6767. | None -> fun () -> maybe_cast (do_default ())
  6768. | Some (super, sparams) when not (is_hxgen (TClassDecl super)) ->
  6769. fun () -> maybe_cast (do_default ())
  6770. | _ ->
  6771. fun () ->
  6772. mk_return {
  6773. eexpr = TCall(
  6774. { eexpr = TField({ eexpr = TConst TSuper; etype = t; epos = pos }, FInstance(cl, List.map snd cl.cl_params, cfield)); etype = !fun_type; epos = pos },
  6775. (List.map (fun (v,_) -> mk_local v pos) args) );
  6776. etype = if is_float then basic.tfloat else t_dynamic;
  6777. epos = pos;
  6778. };
  6779. in
  6780. (* if it is set function, there are some different set fields to do *)
  6781. let do_default, do_default_static , do_field, tf_args = if is_set then begin
  6782. let value_var = alloc_var "value" (if is_float then basic.tfloat else t_dynamic) in
  6783. let value_local = { eexpr = TLocal(value_var); etype = value_var.v_type; epos = pos } in
  6784. let tf_args = tf_args @ [value_var,None; handle_prop, None; ] in
  6785. let lookup_name = gen.gmk_internal_name "hx" ("lookupSetField" ^ if is_float then "_f" else "") in
  6786. let do_default =
  6787. fun () ->
  6788. 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 ] ))
  6789. in
  6790. let do_field cf cf_type is_static =
  6791. let get_field ethis = { eexpr = TField (ethis, if is_static then FStatic (cl, cf) else FInstance(cl, List.map snd cl.cl_params, cf)); etype = cf_type; epos = pos } in
  6792. let this = if is_static then mk_classtype_access cl pos else { eexpr = TConst(TThis); etype = t; epos = pos } in
  6793. let value_local = if is_float then match follow cf_type with
  6794. | TInst({ cl_kind = KTypeParameter _ }, _) ->
  6795. mk_cast t_dynamic value_local
  6796. | _ ->
  6797. value_local
  6798. else
  6799. value_local
  6800. in
  6801. let ret =
  6802. {
  6803. eexpr = TBlock([
  6804. {
  6805. eexpr = TBinop(Ast.OpAssign,
  6806. get_field this,
  6807. mk_cast cf_type value_local);
  6808. etype = cf_type;
  6809. epos = pos;
  6810. };
  6811. mk_return value_local
  6812. ]);
  6813. etype = cf_type;
  6814. epos = pos;
  6815. } in
  6816. match cf.cf_kind with
  6817. | Var { v_write = AccCall } ->
  6818. let bl =
  6819. [
  6820. mk_this_call_raw ("set_" ^ cf.cf_name) (TFun(["value",false,cf.cf_type], cf.cf_type)) [ value_local ];
  6821. mk_return value_local
  6822. ] in
  6823. if Type.is_extern_field cf then
  6824. { eexpr = TBlock bl; etype = value_local.etype; epos = pos }
  6825. else
  6826. {
  6827. eexpr = TIf(
  6828. handle_prop_local,
  6829. { eexpr = TBlock bl; etype = value_local.etype; epos = pos },
  6830. Some ret);
  6831. etype = value_local.etype;
  6832. epos = pos;
  6833. }
  6834. | _ ->
  6835. ret
  6836. in
  6837. (mk_do_default tf_args do_default, do_default, do_field, tf_args)
  6838. end else begin
  6839. (* (field, isStatic, throwErrors, isCheck):Dynamic *)
  6840. let throw_errors = alloc_var "throwErrors" basic.tbool in
  6841. let throw_errors_local = mk_local throw_errors pos in
  6842. let do_default, tf_args = if not is_float then begin
  6843. let is_check = alloc_var "isCheck" basic.tbool in
  6844. let is_check_local = mk_local is_check pos in
  6845. let tf_args = tf_args @ [ throw_errors,None; ] in
  6846. (* default: if (isCheck) return __undefined__ else if(throwErrors) throw "Field not found"; else return null; *)
  6847. let lookup_name = gen.gmk_internal_name "hx" "lookupField" in
  6848. let do_default =
  6849. fun () ->
  6850. 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; ] ))
  6851. in
  6852. (do_default, tf_args @ [ is_check,None; handle_prop,None; ])
  6853. end else begin
  6854. let tf_args = tf_args @ [ throw_errors,None; ] in
  6855. let lookup_name = gen.gmk_internal_name "hx" "lookupField_f" in
  6856. let do_default =
  6857. fun () ->
  6858. 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; ] ))
  6859. in
  6860. (do_default, tf_args @ [ handle_prop,None; ])
  6861. end in
  6862. let get_field cf cf_type ethis cl name =
  6863. match cf.cf_kind with
  6864. | Var { v_read = AccCall } when Type.is_extern_field cf ->
  6865. mk_return (mk_this_call_raw ("get_" ^ cf.cf_name) (TFun(["value",false,cf.cf_type], cf.cf_type)) [ ])
  6866. | Var { v_read = AccCall } ->
  6867. {
  6868. eexpr = TIf(
  6869. handle_prop_local,
  6870. mk_return (mk_this_call_raw ("get_" ^ cf.cf_name) (TFun(["value",false,cf.cf_type], cf.cf_type)) [ ]),
  6871. Some { eexpr = TField (ethis, FInstance(cl, List.map snd cl.cl_params, cf)); etype = cf_type; epos = pos }
  6872. );
  6873. etype = cf_type;
  6874. epos = pos;
  6875. }
  6876. | Var _
  6877. | Method MethDynamic -> { eexpr = TField (ethis, FInstance(cl,List.map snd cl.cl_params,cf)); etype = cf_type; epos = pos }
  6878. | _ ->
  6879. { eexpr = TField (this, FClosure(Some (cl,[]), cf)); etype = cf_type; epos = pos } (* TODO: FClosure change *)
  6880. in
  6881. let do_field cf cf_type static =
  6882. let this = if static then mk_classtype_access cl pos else { eexpr = TConst(TThis); etype = t; epos = pos } in
  6883. match is_float, follow cf_type with
  6884. | true, TInst( { cl_kind = KTypeParameter _ }, _ ) ->
  6885. mk_return (mk_cast basic.tfloat (mk_cast t_dynamic (get_field cf cf_type this cl cf.cf_name)))
  6886. | _ ->
  6887. mk_return (maybe_cast (get_field cf cf_type this cl cf.cf_name ))
  6888. in
  6889. (mk_do_default tf_args do_default, do_default, do_field, tf_args)
  6890. end in
  6891. let get_fields static =
  6892. let ret = collect_fields cl ( if is_float || is_set then Some (false) else None ) (Some static) in
  6893. let ret = if is_set then List.filter (fun (_,cf) ->
  6894. match cf.cf_kind with
  6895. (* | Var { v_write = AccNever } -> false *)
  6896. | _ -> not (Meta.has Meta.ReadOnly cf.cf_meta)) ret
  6897. else
  6898. List.filter (fun (_,cf) ->
  6899. match cf.cf_kind with
  6900. (* | Var { v_read = AccNever } -> false *)
  6901. | _ -> true) ret in
  6902. if is_float then
  6903. List.filter (fun (_,cf) -> (* TODO: maybe really apply_params in cf.cf_type. The benefits would be limited, though *)
  6904. match follow (ctx.rcf_gen.greal_type (ctx.rcf_gen.gfollow#run_f cf.cf_type)) with
  6905. | TDynamic _ | TMono _
  6906. | TInst ({ cl_kind = KTypeParameter _ }, _) -> true
  6907. | t when like_float t && not (like_i64 t) -> true
  6908. | _ -> false
  6909. ) ret
  6910. else
  6911. (* dynamic will always contain all references *)
  6912. ret
  6913. in
  6914. (* now we have do_default, do_field and tf_args *)
  6915. (* so create the switch expr *)
  6916. 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 );
  6917. let has_fields = ref false in
  6918. let mk_switch static =
  6919. let fields = get_fields static in
  6920. let fields = List.filter (fun (_, cf) -> match is_set, cf.cf_kind with
  6921. | true, Var { v_write = AccCall } -> true
  6922. | false, Var { v_read = AccCall } -> true
  6923. | _ -> not (Type.is_extern_field cf)) fields
  6924. in
  6925. (if fields <> [] then has_fields := true);
  6926. let cases = List.map (fun (names, cf) ->
  6927. (if names = [] then assert false);
  6928. (List.map (switch_case ctx pos) names, do_field cf cf.cf_type static)
  6929. ) fields in
  6930. let default = Some(if static then do_default_static() else do_default()) in
  6931. { eexpr = TSwitch(local_switch_var, cases, default); etype = basic.tvoid; epos = pos }
  6932. in
  6933. let content = if ctx.rcf_handle_statics then
  6934. mk_block { eexpr = TIf(is_static_local, mk_switch true, Some(mk_switch false)); etype = basic.tvoid; epos = pos }
  6935. else
  6936. mk_block (mk_switch false)
  6937. in
  6938. let is_override = match cl.cl_super with
  6939. | Some (cl, _) when is_hxgen (TClassDecl cl) -> true
  6940. | _ -> false
  6941. in
  6942. if !has_fields || (not is_override) then begin
  6943. let func =
  6944. {
  6945. tf_args = tf_args;
  6946. tf_type = if is_float then basic.tfloat else t_dynamic;
  6947. tf_expr = content;
  6948. } in
  6949. let func = { eexpr = TFunction(func); etype = !fun_type; epos = pos } in
  6950. cfield.cf_type <- !fun_type;
  6951. cfield.cf_expr <- Some func;
  6952. cl.cl_ordered_fields <- cl.cl_ordered_fields @ [cfield];
  6953. cl.cl_fields <- PMap.add fun_name cfield cl.cl_fields;
  6954. (if is_override then cl.cl_overrides <- cfield :: cl.cl_overrides)
  6955. end else ()
  6956. in
  6957. (if ctx.rcf_float_special_case then mk_cfield true true);
  6958. mk_cfield true false;
  6959. mk_cfield false false;
  6960. (if ctx.rcf_float_special_case then mk_cfield false true)
  6961. let mk_field_access_r ctx pos local field is_float is_static throw_errors set_option =
  6962. let is_set = is_some set_option in
  6963. let gen = ctx.rcf_gen in
  6964. let basic = gen.gcon.basic in
  6965. let fun_name = ctx.rcf_gen.gmk_internal_name "hx" ( (if is_set then "setField" else "getField") ^ (if is_float then "_f" else "") ) in
  6966. let tf_args, _ = field_type_args ctx pos in
  6967. let tf_args, args = fun_args tf_args, field in
  6968. let rett = if is_float then basic.tfloat else t_dynamic in
  6969. let tf_args, args = if ctx.rcf_handle_statics then tf_args @ [ "isStatic", false, basic.tbool ], args @ [is_static] else tf_args, args in
  6970. let tf_args, args = if is_set then tf_args @ [ "setVal", false, rett ], args @ [get set_option] else tf_args, args in
  6971. let tf_args, args = tf_args @ [ "throwErrors",false,basic.tbool ], args @ [throw_errors] in
  6972. 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
  6973. let tf_args, args = tf_args @ [ "handleProperties",false,basic.tbool; ], args @ [ mk_bool ctx false pos; ] in
  6974. {
  6975. eexpr = TCall(
  6976. { (mk_field_access gen local fun_name pos) with etype = TFun(tf_args, rett) },
  6977. args);
  6978. etype = rett;
  6979. epos = pos;
  6980. }
  6981. let implement_fields ctx cl =
  6982. (*
  6983. implement two kinds of fields get:
  6984. classFields
  6985. generic 'fields': receives a parameter isInstance
  6986. will receive an Array<String> and start pushing the fields into it.
  6987. //add all common fields
  6988. if(isInstance)
  6989. {
  6990. //add methods
  6991. } else {
  6992. super.fields(isInstance, array);
  6993. }
  6994. *)
  6995. let gen = ctx.rcf_gen in
  6996. let basic = gen.gcon.basic in
  6997. let pos = cl.cl_pos in
  6998. (*
  6999. let rec has_no_dynamic cl =
  7000. if is_some cl.cl_dynamic then
  7001. false
  7002. else match cl.cl_super with
  7003. | None -> true
  7004. | Some(cl,_) -> has_no_dynamic cl
  7005. in
  7006. *)
  7007. (* Type.getClassFields() *)
  7008. if ctx.rcf_handle_statics then begin
  7009. let name = gen.gmk_internal_name "hx" "classFields" in
  7010. let v_base_arr = alloc_var "baseArr" (basic.tarray basic.tstring) in
  7011. let base_arr = mk_local v_base_arr pos in
  7012. let tf_args = [v_base_arr,None] in
  7013. let t = TFun(fun_args tf_args, basic.tvoid) in
  7014. let cf = mk_class_field name t false pos (Method MethNormal) [] in
  7015. cl.cl_ordered_fields <- cl.cl_ordered_fields @ [cf];
  7016. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields;
  7017. (if is_override cl then cl.cl_overrides <- cf :: cl.cl_overrides);
  7018. (*
  7019. var newarr = ["field1", "field2"] ...;
  7020. *)
  7021. let fields = collect_fields cl None (Some true) in
  7022. let mk_push value =
  7023. { 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 }
  7024. in
  7025. let new_arr_contents =
  7026. {
  7027. eexpr = TBlock(
  7028. List.map (fun (_,cf) -> mk_push { eexpr = TConst(TString(cf.cf_name)); etype = basic.tstring; epos = pos }) fields
  7029. );
  7030. etype = basic.tvoid;
  7031. epos = pos
  7032. } in
  7033. let expr = new_arr_contents in
  7034. let fn =
  7035. {
  7036. tf_args = tf_args;
  7037. tf_type = basic.tvoid;
  7038. tf_expr = mk_block expr
  7039. } in
  7040. cf.cf_expr <- Some { eexpr = TFunction(fn); etype = t; epos = pos }
  7041. end;
  7042. let fields =
  7043. (*
  7044. function __hx_fields(baseArr:Array<String>, isInstanceFields:Bool)
  7045. {
  7046. //add all variable fields
  7047. //then:
  7048. if (isInstanceFields)
  7049. {
  7050. //add all method fields as well
  7051. } else {
  7052. super.__hx_fields(baseArr, isInstanceFields);
  7053. }
  7054. }
  7055. *)
  7056. let name = gen.gmk_internal_name "hx" "getFields" in
  7057. let v_base_arr, v_is_inst = alloc_var "baseArr" (basic.tarray basic.tstring), alloc_var "isInstanceFields" basic.tbool in
  7058. let base_arr, is_inst = mk_local v_base_arr pos, mk_local v_is_inst pos in
  7059. let tf_args = (v_base_arr,None) :: (if ctx.rcf_handle_statics then [v_is_inst, None] else []) in
  7060. let t = TFun(fun_args tf_args, basic.tvoid) in
  7061. let cf = mk_class_field name t false pos (Method MethNormal) [] in
  7062. let mk_push value =
  7063. { 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 }
  7064. in
  7065. let has_value = ref false in
  7066. let map_fields =
  7067. List.map (fun (_,cf) ->
  7068. match cf.cf_kind with
  7069. | Var _
  7070. | Method MethDynamic when not (List.memq cf cl.cl_overrides) ->
  7071. has_value := true;
  7072. mk_push { eexpr = TConst(TString(cf.cf_name)); etype = basic.tstring; epos = pos }
  7073. | _ -> null basic.tvoid pos
  7074. )
  7075. in
  7076. (*
  7077. if it is first_dynamic, then we need to enumerate the dynamic fields
  7078. *)
  7079. let if_not_inst = if is_some cl.cl_dynamic && is_first_dynamic cl then begin
  7080. has_value := true;
  7081. Some (enumerate_dynamic_fields ctx cl mk_push)
  7082. end else
  7083. None
  7084. in
  7085. let if_not_inst = if is_override cl then
  7086. Some(
  7087. {
  7088. eexpr = TBlock(
  7089. (if is_some if_not_inst then get if_not_inst else []) @
  7090. [{
  7091. eexpr = TCall(
  7092. { eexpr = TField({ eexpr = TConst TSuper; etype = TInst(cl, List.map snd cl.cl_params); epos = pos }, FInstance(cl, List.map snd cl.cl_params, cf)); etype = t; epos = pos },
  7093. base_arr :: (if ctx.rcf_handle_statics then [is_inst] else [])
  7094. );
  7095. etype = basic.tvoid;
  7096. epos = pos
  7097. }]
  7098. );
  7099. etype = basic.tvoid;
  7100. epos = pos
  7101. }
  7102. ) else if is_some if_not_inst then
  7103. Some({ eexpr = TBlock(get if_not_inst); etype = basic.tvoid; epos = pos })
  7104. else
  7105. None
  7106. in
  7107. let expr_contents = map_fields (collect_fields cl (Some false) (Some false)) in
  7108. let expr_contents = if ctx.rcf_handle_statics then
  7109. expr_contents @
  7110. [ {
  7111. eexpr = TIf(is_inst,
  7112. { eexpr = TBlock( map_fields (collect_fields cl (Some true) (Some false)) ); etype = basic.tvoid; epos = pos },
  7113. if_not_inst
  7114. );
  7115. etype = basic.tvoid;
  7116. epos = pos
  7117. } ]
  7118. else
  7119. expr_contents @ (if is_some if_not_inst then [ get if_not_inst ] else [])
  7120. in
  7121. let expr =
  7122. {
  7123. eexpr = TBlock( expr_contents );
  7124. etype = basic.tvoid;
  7125. epos = pos;
  7126. } in
  7127. let fn =
  7128. {
  7129. tf_args = tf_args;
  7130. tf_type = basic.tvoid;
  7131. tf_expr = expr
  7132. } in
  7133. (if !has_value || (not (is_override cl)) then begin
  7134. cl.cl_ordered_fields <- cl.cl_ordered_fields @ [cf];
  7135. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields;
  7136. (if is_override cl then cl.cl_overrides <- cf :: cl.cl_overrides)
  7137. end);
  7138. cf.cf_expr <- Some { eexpr = TFunction(fn); etype = t; epos = pos }
  7139. in
  7140. ignore fields
  7141. let implement_class_methods ctx cl =
  7142. ctx.rcf_class_cl <- Some cl;
  7143. let pos = cl.cl_pos in
  7144. let gen = ctx.rcf_gen in
  7145. let basic = gen.gcon.basic in
  7146. (*
  7147. fields -> redirected to classFields
  7148. getField -> redirected to getField with isStatic true
  7149. setField -> isStatic true
  7150. invokeField -> isStatic true
  7151. getClass -> null
  7152. create -> proxy
  7153. createEmpty -> proxy
  7154. *)
  7155. let is_override = is_override cl in
  7156. let name = "classProxy" in
  7157. let t = (TInst(ctx.rcf_object_iface,[])) in
  7158. (* let cf = mk_class_field name t false pos (Var { v_read = AccNormal; v_write = AccNormal }) [] in *)
  7159. let register_cf cf override =
  7160. cl.cl_ordered_fields <- cf :: cl.cl_ordered_fields;
  7161. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields;
  7162. if override then cl.cl_overrides <- cf :: cl.cl_overrides
  7163. in
  7164. (* register_cf cf false; *)
  7165. let this_t = TInst(cl, List.map snd cl.cl_params) in
  7166. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  7167. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  7168. let proxy = mk_this name t in
  7169. (*let ctor =
  7170. let cls = alloc_var "cls" t in
  7171. let tf_args = [cls, None] in
  7172. let t = TFun(fun_args tf_args, basic.tvoid) in
  7173. let cf = mk_class_field "new" t true pos (Method MethNormal) [] in
  7174. cf.cf_expr <- Some({
  7175. eexpr = TFunction({
  7176. tf_args = tf_args;
  7177. tf_type = basic.tvoid;
  7178. tf_expr = mk_block {
  7179. eexpr = TBinop(Ast.OpAssign, proxy, mk_local cls pos);
  7180. etype = cls.v_type;
  7181. epos = pos;
  7182. }
  7183. });
  7184. etype = t;
  7185. epos = pos;
  7186. });
  7187. cf
  7188. in
  7189. register_cf ctor false;*)
  7190. (* setting it as DynamicObject makes getClass return null *)
  7191. let get_class =
  7192. cl.cl_meta <- (Meta.DynamicObject, [], pos) :: cl.cl_meta
  7193. in
  7194. ignore get_class;
  7195. (* fields -> if isInstanceField, redir the method. If not, return classFields *)
  7196. let fields =
  7197. let name = gen.gmk_internal_name "hx" "getFields" in
  7198. let v_base_arr, v_is_inst = alloc_var "baseArr" (basic.tarray basic.tstring), alloc_var "isInstanceFields" basic.tbool in
  7199. let base_arr, is_inst = mk_local v_base_arr pos, mk_local v_is_inst pos in
  7200. let tf_args = [ v_base_arr,None; v_is_inst, None ] in
  7201. let t = TFun(fun_args tf_args, basic.tvoid) in
  7202. let cf = mk_class_field name t false pos (Method MethNormal) [] in
  7203. cf.cf_expr <- Some({
  7204. eexpr = TFunction({
  7205. tf_args = tf_args;
  7206. tf_type = basic.tvoid;
  7207. tf_expr = mk_block {
  7208. eexpr = TIf(is_inst,
  7209. { eexpr = TCall( { (mk_field_access gen proxy name pos) with etype = t }, [base_arr;is_inst]); etype = basic.tvoid; epos = pos },
  7210. 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 });
  7211. etype = basic.tvoid;
  7212. epos = pos
  7213. }
  7214. });
  7215. etype = t;
  7216. epos = pos;
  7217. });
  7218. cf
  7219. in
  7220. register_cf fields (is_override);
  7221. let do_proxy field tf_args ret is_static_argnum =
  7222. let field = gen.gmk_internal_name "hx" field in
  7223. let t = TFun(fun_args tf_args, ret) in
  7224. let cf = mk_class_field field t false pos (Method MethNormal) [] in
  7225. let is_void = is_void ret in
  7226. let may_return e = if is_void then mk_block e else mk_block (mk_return e) in
  7227. let i = ref 0 in
  7228. cf.cf_expr <- Some({
  7229. eexpr = TFunction({
  7230. tf_args = tf_args;
  7231. tf_type = ret;
  7232. tf_expr = may_return {
  7233. eexpr = TCall(
  7234. { (mk_field_access gen proxy field pos) with etype = t },
  7235. List.map (fun (v,_) ->
  7236. let lasti = !i in
  7237. incr i;
  7238. if lasti = is_static_argnum then
  7239. { eexpr = TConst(TBool true); etype = basic.tbool; epos = pos }
  7240. else
  7241. mk_local v pos
  7242. ) tf_args);
  7243. etype = ret;
  7244. epos = pos
  7245. }
  7246. });
  7247. etype = t;
  7248. epos = pos;
  7249. });
  7250. cf
  7251. in
  7252. (* getClassFields -> redir *)
  7253. register_cf (do_proxy "classFields" [ alloc_var "baseArr" (basic.tarray basic.tstring), None ] basic.tvoid (-1)) true;
  7254. (*register_cf (do_proxy "classFields" [ alloc_var "baseArr" (basic.tarray basic.tstring), None ] basic.tvoid (-1)) true;*)
  7255. let fst_args, _ = field_type_args ctx pos in
  7256. let fst_args_len = List.length fst_args in
  7257. (* getField -> redir the method with static = true *)
  7258. (* setField -> redir the methods with static = true *)
  7259. (if ctx.rcf_float_special_case then
  7260. 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;
  7261. 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
  7262. );
  7263. 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;
  7264. 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;
  7265. (* invokeField -> redir the method with static = true *)
  7266. 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;
  7267. (* create / createEmpty -> redir the method *)
  7268. register_cf (do_proxy "create" [ alloc_var "arr" (basic.tarray t_dynamic), None ] t_dynamic (-1)) true;
  7269. register_cf (do_proxy "createEmpty" [ ] t_dynamic (-1)) true
  7270. let implement_get_class ctx cl =
  7271. (*
  7272. if it is DynamicObject, return null;
  7273. if it is not, just do the following:
  7274. if (typehandle(this.class) == typehandle(MyClass))
  7275. return (MyClass.__hx_class != null ? MyClass.__hx_class : MyClass.__hx_class = create_empty(MyClass));
  7276. return MyClass.__hx_class = haxe.lang.Runtime.getClass(MyClass);
  7277. implement both on static and non-static contexts. This way we can call without references.
  7278. *)
  7279. let gen = ctx.rcf_gen in
  7280. let basic = gen.gcon.basic in
  7281. let pos = cl.cl_pos in
  7282. let tclass = get_cl ( (Hashtbl.find gen.gtypes ([],"Class")) ) in
  7283. let cls = TInst(tclass, [ TInst(cl, List.map (fun _ -> t_dynamic) cl.cl_params) ]) in
  7284. let cls_dyn = TInst(tclass, [t_dynamic]) in
  7285. let expr, static_cfs =
  7286. if Meta.has Meta.DynamicObject cl.cl_meta then
  7287. mk_return (null t_dynamic pos), []
  7288. else
  7289. let cache_name = (gen.gmk_internal_name "hx" "class") in
  7290. let cache = mk_class_field cache_name cls false pos (Var { v_read = AccNormal; v_write = AccNormal }) [] in
  7291. cl.cl_ordered_statics <- cl.cl_ordered_statics @ [ cache ];
  7292. cl.cl_statics <- PMap.add cache_name cache cl.cl_statics;
  7293. let cache_access = mk_static_field_access cl cache_name cls pos in
  7294. let create_expr = {
  7295. eexpr = TNew(get ctx.rcf_class_cl, [], [gen.gtools.rf_create_empty cl (List.map (fun _ -> t_dynamic) cl.cl_params) pos]);
  7296. etype = cls;
  7297. epos = pos
  7298. } in
  7299. (if ctx.rcf_class_eager_creation then cache.cf_expr <- Some(create_expr));
  7300. let expr = if ctx.rcf_class_eager_creation then
  7301. mk_return cache_access
  7302. else
  7303. mk_return {
  7304. eexpr = TIf(
  7305. { eexpr = TBinop(Ast.OpNotEq, cache_access, null cls pos); etype = basic.tbool; epos = pos },
  7306. cache_access,
  7307. Some({ eexpr = TBinop(Ast.OpAssign, cache_access, create_expr); etype = cls; epos = pos })
  7308. );
  7309. etype = cls;
  7310. epos = pos
  7311. }
  7312. in
  7313. expr, []
  7314. in
  7315. let func =
  7316. {
  7317. eexpr = TFunction({
  7318. tf_args = [];
  7319. tf_type = cls_dyn;
  7320. tf_expr = expr
  7321. });
  7322. etype = TFun([],cls_dyn);
  7323. epos = pos
  7324. } in
  7325. let get_cl_static = mk_class_field (gen.gmk_internal_name "hx" "getClassStatic") (TFun([],cls_dyn)) false pos (Method MethNormal) [] in
  7326. let get_cl = mk_class_field (gen.gmk_internal_name "hx" "getClass") (TFun([],cls_dyn)) false pos (Method MethNormal) [] in
  7327. get_cl_static.cf_expr <- Some func;
  7328. get_cl.cf_expr <- Some func;
  7329. let all_f = [get_cl] in
  7330. cl.cl_ordered_fields <- cl.cl_ordered_fields @ all_f;
  7331. List.iter (fun cf -> cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields) all_f;
  7332. let all_f = get_cl_static :: static_cfs in
  7333. cl.cl_ordered_statics <- cl.cl_ordered_statics @ all_f;
  7334. List.iter (fun cf -> cl.cl_statics <- PMap.add cf.cf_name cf cl.cl_statics) all_f;
  7335. if is_override cl then cl.cl_overrides <- get_cl :: cl.cl_overrides
  7336. let implement_invokeField ctx ~slow_invoke cl =
  7337. (*
  7338. There are two ways to implement an haxe reflection-enabled class:
  7339. When we extend a non-hxgen class, and when we extend the base HxObject class.
  7340. Because of the added boiler plate we'd add every time we extend a non-hxgen class to implement a big IHxObject
  7341. interface, we'll handle the cases differently when implementing each interface.
  7342. At the IHxObject interface, there's only invokeDynamic(field, args[]), while at the HxObject class there are
  7343. the other, more optimized methods, that follow the Function class interface.
  7344. Since this will only be called by the Closure class, this conversion can be properly dealt with later.
  7345. TODO: create the faster version. By now only invokeDynamic will be implemented
  7346. *)
  7347. let gen = ctx.rcf_gen in
  7348. let basic = gen.gcon.basic in
  7349. let pos = cl.cl_pos in
  7350. let has_method = ref false in
  7351. let is_override = ref false in
  7352. let rec extends_hxobject cl =
  7353. match cl.cl_super with
  7354. | None -> true
  7355. | Some (cl,_) when is_hxgen (TClassDecl cl) -> is_override := true; extends_hxobject cl
  7356. | _ -> false
  7357. in
  7358. let field_args, switch_var = field_type_args ctx cl.cl_pos in
  7359. let field_args_exprs = List.map (fun (v,_) -> mk_local v pos) field_args in
  7360. let is_static = alloc_var "isStatic" basic.tbool in
  7361. let dynamic_arg = alloc_var "dynargs" (basic.tarray t_dynamic) in
  7362. let all_args = field_args @ (if ctx.rcf_handle_statics then [ is_static,None; dynamic_arg,None ] else [ dynamic_arg, None ] ) in
  7363. let fun_t = TFun(fun_args all_args, t_dynamic) in
  7364. let this_t = TInst(cl, List.map snd cl.cl_params) in
  7365. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  7366. let apply_object cf = apply_params cf.cf_params (List.map (fun _ -> t_dynamic) cf.cf_params) cf.cf_type in
  7367. let mk_this_call_raw name fun_t params =
  7368. { eexpr = TCall( { (mk_field_access gen this name pos) with etype = fun_t }, params ); etype = snd (get_args fun_t); epos = pos }
  7369. in
  7370. let mk_this_call cf params =
  7371. let t = apply_object cf in
  7372. (* the return type transformation into Dynamic *)
  7373. (* is meant to avoid return-type casting after functions with *)
  7374. (* type parameters are properly inferred at TypeParams.infer_params *)
  7375. (* e.g. function getArray<T : SomeType>(t:T):Array<T>; after infer_params, *)
  7376. (* T will be inferred as SomeType, but the returned type will still be typed *)
  7377. (* as Array<Dynamic> *)
  7378. let args, ret = get_args t in
  7379. let ret = match follow ret with
  7380. | TAbstract ({ a_path = ([], "Void") },[]) -> ret
  7381. | _ -> ret
  7382. in
  7383. mk_this_call_raw cf.cf_name (TFun(args, ret)) params
  7384. in
  7385. let mk_static_call cf params =
  7386. let t = apply_object cf in
  7387. let _, ret = get_fun (follow t) in
  7388. { eexpr = TCall( mk_static_field_access cl cf.cf_name t pos, params ); etype = ret; epos = pos }
  7389. in
  7390. let extends_hxobject = extends_hxobject cl in
  7391. ignore extends_hxobject;
  7392. (* creates a dynamicInvoke of the class fields listed here *)
  7393. (*
  7394. function dynamicInvoke(field, isStatic, dynargs)
  7395. {
  7396. switch(field)
  7397. {
  7398. case "a": this.a(dynargs[0], dynargs[1], dynargs[2]...);
  7399. default: super.dynamicInvoke //or this.getField(field).invokeField(dynargs)
  7400. }
  7401. }
  7402. *)
  7403. let dyn_fun = mk_class_field (ctx.rcf_gen.gmk_internal_name "hx" "invokeField") fun_t false cl.cl_pos (Method MethNormal) [] in
  7404. let mk_switch_dyn cfs static old =
  7405. (* mk_class_field name t public pos kind params = *)
  7406. let get_case (names,cf) =
  7407. has_method := true;
  7408. let i = ref 0 in
  7409. let dyn_arg_local = mk_local dynamic_arg pos in
  7410. let cases = List.map (switch_case ctx pos) names in
  7411. (cases,
  7412. { eexpr = TReturn(Some ( (if static then mk_static_call else mk_this_call) cf (List.map (fun (name,_,t) ->
  7413. let ret = { eexpr = TArray(dyn_arg_local, mk_int ctx !i pos); etype = t_dynamic; epos = pos } in
  7414. incr i;
  7415. ret
  7416. ) (fst (get_args (cf.cf_type))) ) ));
  7417. etype = basic.tvoid;
  7418. epos = pos
  7419. }
  7420. )
  7421. in
  7422. let cfs = List.filter (fun (_,cf) -> match cf.cf_kind with
  7423. | Method _ -> if List.memq cf cl.cl_overrides then false else true
  7424. | _ -> true) cfs
  7425. in
  7426. let cases = List.map get_case cfs in
  7427. let cases = match old with
  7428. | [] -> cases
  7429. | _ ->
  7430. let ncases = List.map (fun cf -> switch_case ctx pos cf.cf_name) old in
  7431. ( ncases, mk_return ((get slow_invoke) this (mk_local (fst (List.hd field_args)) pos) (mk_local dynamic_arg pos)) ) :: cases
  7432. in
  7433. let default = if !is_override && not(static) then
  7434. (* let call_super ctx fn_args ret_t fn_name this_t pos = *)
  7435. { eexpr = TReturn(Some (call_super ctx all_args t_dynamic dyn_fun cl this_t pos) ); etype = basic.tvoid; epos = pos }
  7436. (*else if ctx.rcf_create_getsetinvoke_fields then (* we always need to run create_getset before *)
  7437. let get_field_name = gen.gmk_internal_name "hx" "getField" in
  7438. { eexpr = TReturn( Some (mk_this_call (PMap.find get_field_name cl.cl_fields) [mk_local dynamic_arg pos] ) ); etype = basic.tvoid; epos = pos }*)
  7439. else (
  7440. (*let field = (gen.gtools.r_field false (TInst(ctx.rcf_ft.func_class,[])) this (mk_local (fst (List.hd all_args)) pos)) in*)
  7441. (* let mk_field_access ctx pos local field is_float is_static throw_errors set_option = *)
  7442. 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
  7443. let field = mk_cast (TInst(ctx.rcf_ft.func_class,[])) field in
  7444. mk_return {
  7445. eexpr = TCall(
  7446. mk_field_access gen field (gen.gmk_internal_name "hx" "invokeDynamic") pos,
  7447. [mk_local dynamic_arg pos]);
  7448. etype = t_dynamic;
  7449. epos = pos
  7450. } )
  7451. in
  7452. {
  7453. eexpr = TSwitch(mk_local switch_var pos, cases, Some default);
  7454. etype = basic.tvoid;
  7455. epos = pos;
  7456. }
  7457. in
  7458. let contents =
  7459. let statics = collect_fields cl (Some true) (Some true) in
  7460. let nonstatics = collect_fields cl (Some true) (Some false) in
  7461. let old_nonstatics = ref [] in
  7462. let nonstatics = match slow_invoke with
  7463. | None -> nonstatics
  7464. | Some _ ->
  7465. List.filter (fun (n,cf) ->
  7466. let is_old = not (PMap.mem cf.cf_name cl.cl_fields) || List.memq cf cl.cl_overrides in
  7467. (if is_old then old_nonstatics := cf :: !old_nonstatics);
  7468. not is_old
  7469. ) nonstatics
  7470. in
  7471. if ctx.rcf_handle_statics then
  7472. {
  7473. eexpr = TIf(mk_local is_static pos, mk_switch_dyn statics true [], Some(mk_switch_dyn nonstatics false !old_nonstatics));
  7474. etype = basic.tvoid;
  7475. epos = pos;
  7476. } else
  7477. mk_switch_dyn nonstatics false !old_nonstatics
  7478. in
  7479. dyn_fun.cf_expr <- Some
  7480. {
  7481. eexpr = TFunction(
  7482. {
  7483. tf_args = all_args;
  7484. tf_type = t_dynamic;
  7485. tf_expr = mk_block contents;
  7486. });
  7487. etype = TFun(fun_args all_args, t_dynamic);
  7488. epos = pos;
  7489. };
  7490. if !is_override && not (!has_method) then () else begin
  7491. cl.cl_ordered_fields <- cl.cl_ordered_fields @ [dyn_fun];
  7492. cl.cl_fields <- PMap.add dyn_fun.cf_name dyn_fun cl.cl_fields;
  7493. (if !is_override then cl.cl_overrides <- dyn_fun :: cl.cl_overrides)
  7494. end
  7495. let implement_varargs_cl ctx cl =
  7496. let pos = cl.cl_pos in
  7497. let gen = ctx.rcf_gen in
  7498. let basic = gen.gcon.basic in
  7499. let this_t = TInst(cl, List.map snd cl.cl_params) in
  7500. let this = { eexpr = TConst(TThis); etype = this_t ; epos = pos } in
  7501. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  7502. let invokedyn = gen.gmk_internal_name "hx" "invokeDynamic" in
  7503. let idyn_t = TFun([gen.gmk_internal_name "fn" "dynargs", false, basic.tarray t_dynamic], t_dynamic) in
  7504. let this_idyn = mk_this invokedyn idyn_t in
  7505. let map_fn arity ret vars api =
  7506. let rec loop i acc =
  7507. if i < 0 then
  7508. acc
  7509. else
  7510. let obj = api i t_dynamic None in
  7511. loop (i - 1) (obj :: acc)
  7512. in
  7513. let call_arg = if arity = (-1) then
  7514. api (-1) t_dynamic None
  7515. else if arity = 0 then
  7516. null (basic.tarray t_empty) pos
  7517. else
  7518. { eexpr = TArrayDecl(loop (arity - 1) []); etype = basic.tarray t_empty; epos = pos }
  7519. in
  7520. let expr = {
  7521. eexpr = TCall(
  7522. this_idyn,
  7523. [ call_arg ]
  7524. );
  7525. etype = t_dynamic;
  7526. epos = pos
  7527. } in
  7528. let expr = if like_float ret && not (like_int ret) then mk_cast ret expr else expr in
  7529. [], mk_return expr
  7530. in
  7531. 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
  7532. cl.cl_ordered_fields <- cl.cl_ordered_fields @ all_cfs;
  7533. List.iter (fun cf ->
  7534. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields
  7535. ) all_cfs;
  7536. List.iter (fun cf ->
  7537. cl.cl_overrides <- cf :: cl.cl_overrides
  7538. ) cl.cl_ordered_fields
  7539. let implement_closure_cl ctx cl =
  7540. let pos = cl.cl_pos in
  7541. let gen = ctx.rcf_gen in
  7542. let basic = gen.gcon.basic in
  7543. let field_args, _ = field_type_args ctx pos in
  7544. let obj_arg = alloc_var "target" (TInst(ctx.rcf_object_iface, [])) in
  7545. let this_t = TInst(cl, List.map snd cl.cl_params) in
  7546. let this = { eexpr = TConst(TThis); etype = this_t ; epos = pos } in
  7547. let mk_this field t = { (mk_field_access gen this field pos) with etype = t } in
  7548. let tf_args = field_args @ [obj_arg, None] in
  7549. let cfs, ctor_body = List.fold_left (fun (acc_cf,acc_expr) (v,_) ->
  7550. let cf = mk_class_field v.v_name v.v_type false pos (Var { v_read = AccNormal; v_write = AccNormal } ) [] in
  7551. 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
  7552. (cf :: acc_cf, expr :: acc_expr)
  7553. ) ([], []) tf_args in
  7554. let map_fn arity ret vars api =
  7555. let this_obj = mk_this "target" (TInst(ctx.rcf_object_iface, [])) in
  7556. let rec loop i acc =
  7557. if i < 0 then
  7558. acc
  7559. else
  7560. let obj = api i t_dynamic None in
  7561. loop (i - 1) (obj :: acc)
  7562. in
  7563. let call_arg = if arity = (-1) then
  7564. api (-1) t_dynamic None
  7565. else if arity = 0 then
  7566. null (basic.tarray t_empty) pos
  7567. else
  7568. { eexpr = TArrayDecl(loop (arity - 1) []); etype = basic.tarray t_empty; epos = pos }
  7569. in
  7570. let expr = {
  7571. eexpr = TCall(
  7572. mk_field_access gen this_obj (gen.gmk_internal_name "hx" "invokeField") pos,
  7573. (List.map (fun (v,_) -> mk_this v.v_name v.v_type) field_args) @
  7574. (if ctx.rcf_handle_statics then
  7575. [ { eexpr = TConst(TBool false); etype = basic.tbool; epos = pos }; call_arg ]
  7576. else
  7577. [ call_arg ]
  7578. )
  7579. );
  7580. etype = t_dynamic;
  7581. epos = pos
  7582. } in
  7583. let expr = if like_float ret && not (like_int ret) then mk_cast ret expr else expr in
  7584. [], mk_return expr
  7585. in
  7586. 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
  7587. List.iter (fun cf ->
  7588. cl.cl_overrides <- cf :: cl.cl_overrides
  7589. ) all_cfs;
  7590. let all_cfs = cfs @ all_cfs in
  7591. cl.cl_ordered_fields <- cl.cl_ordered_fields @ all_cfs;
  7592. List.iter (fun cf ->
  7593. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields
  7594. ) all_cfs;
  7595. let ctor_t = TFun(fun_args tf_args, basic.tvoid) in
  7596. let ctor_cf = mk_class_field "new" ctor_t true pos (Method MethNormal) [] in
  7597. ctor_cf.cf_expr <- Some {
  7598. eexpr = TFunction({
  7599. tf_args = tf_args;
  7600. tf_type = basic.tvoid;
  7601. tf_expr = { eexpr = TBlock({
  7602. eexpr = TCall({ eexpr = TConst(TSuper); etype = TInst(cl,[]); epos = pos }, [mk_int ctx (-1) pos; mk_int ctx (-1) pos]);
  7603. etype = basic.tvoid;
  7604. epos = pos
  7605. } :: ctor_body); etype = basic.tvoid; epos = pos }
  7606. });
  7607. etype = ctor_t;
  7608. epos = pos
  7609. };
  7610. cl.cl_constructor <- Some ctor_cf;
  7611. let closure_fun eclosure e field is_static =
  7612. let f = { eexpr = TConst(TString field); etype = basic.tstring; epos = eclosure.epos } in
  7613. 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
  7614. let args = args @ [ mk_cast (TInst(ctx.rcf_object_iface, [])) e ] in
  7615. { eclosure with eexpr = TNew(cl,[],args) }
  7616. in
  7617. closure_fun
  7618. let get_closure_func ctx closure_cl =
  7619. let gen = ctx.rcf_gen in
  7620. let basic = gen.gcon.basic in
  7621. let closure_func eclosure e field is_static =
  7622. mk_cast eclosure.etype { eclosure with
  7623. eexpr = TNew(closure_cl, [], [
  7624. e;
  7625. { eexpr = TConst(TString field); etype = basic.tstring; epos = eclosure.epos }
  7626. ] @ (
  7627. if ctx.rcf_optimize then [ { eexpr = TConst(TInt (hash_field_i32 ctx eclosure.epos field)); etype = basic.tint; epos = eclosure.epos } ] else []
  7628. ));
  7629. etype = TInst(closure_cl,[])
  7630. }
  7631. in
  7632. closure_func
  7633. (*
  7634. main expr -> field expr -> field string -> possible set expr -> should_throw_exceptions -> changed expression
  7635. Changes a get / set
  7636. *
  7637. mutable rcf_on_getset_field : texpr->texpr->string->texpr option->bool->texpr;*)
  7638. let configure_dynamic_field_access ctx is_synf =
  7639. let gen = ctx.rcf_gen in
  7640. let is_dynamic expr fexpr field =
  7641. match (field_access_esp gen (gen.greal_type fexpr.etype) field) with
  7642. | FEnumField _
  7643. | FClassField _ -> false
  7644. | _ -> true
  7645. in
  7646. let configure = if is_synf then DynamicFieldAccess.configure_as_synf else DynamicFieldAccess.configure in
  7647. let maybe_hash = if ctx.rcf_optimize then fun str pos -> Some (hash_field_i32 ctx pos str) else fun str pos -> None in
  7648. configure gen (DynamicFieldAccess.abstract_implementation gen is_dynamic
  7649. (fun expr fexpr field set is_unsafe ->
  7650. let hash = maybe_hash field fexpr.epos in
  7651. ctx.rcf_on_getset_field expr fexpr field hash set is_unsafe
  7652. )
  7653. (fun ecall fexpr field call_list ->
  7654. let hash = maybe_hash field fexpr.epos in
  7655. ctx.rcf_on_call_field ecall fexpr field hash call_list
  7656. )
  7657. );
  7658. ()
  7659. let replace_reflection ctx cl =
  7660. let gen = ctx.rcf_gen in
  7661. let pos = cl.cl_pos in
  7662. let this_t = TInst(cl, List.map snd cl.cl_params) in
  7663. let this = { eexpr = TConst(TThis); etype = this_t; epos = pos } in
  7664. let last_fields = match cl.cl_super with
  7665. | None -> PMap.empty
  7666. | Some (super,_) -> super.cl_fields
  7667. in
  7668. let new_fields = ref [] in
  7669. let process_cf static cf =
  7670. match cf.cf_kind with
  7671. | Var _ -> ()
  7672. | _ when Meta.has Meta.ReplaceReflection cf.cf_meta ->
  7673. 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
  7674. let new_name = gen.gmk_internal_name "hx" name in
  7675. let new_cf = mk_class_field new_name cf.cf_type cf.cf_public cf.cf_pos cf.cf_kind cf.cf_params in
  7676. let fn_args, ret = get_fun (follow cf.cf_type) in
  7677. let tf_args = List.map (fun (name,_,t) -> alloc_var name t, None) fn_args in
  7678. let is_void = is_void ret in
  7679. let expr = {
  7680. eexpr = TCall(
  7681. {
  7682. eexpr = (if static then TField(mk_classtype_access cl pos, FStatic(cl, cf)) else TField(this, FInstance(cl, List.map snd cl.cl_params, cf)));
  7683. etype = cf.cf_type;
  7684. epos = cf.cf_pos;
  7685. },
  7686. List.map (fun (v,_) -> mk_local v cf.cf_pos) tf_args);
  7687. etype = ret;
  7688. epos = cf.cf_pos
  7689. } in
  7690. let new_f =
  7691. {
  7692. tf_args = tf_args;
  7693. tf_type = ret;
  7694. tf_expr = {
  7695. eexpr = TBlock([if is_void then expr else mk_return expr]);
  7696. etype = ret;
  7697. epos = pos;
  7698. }
  7699. } in
  7700. new_cf.cf_expr <- Some({ eexpr = TFunction(new_f); etype = cf.cf_type; epos = cf.cf_pos});
  7701. new_fields := new_cf :: !new_fields;
  7702. (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);
  7703. if not static && PMap.mem new_name last_fields then cl.cl_overrides <- new_cf :: cl.cl_overrides
  7704. | _ -> ()
  7705. in
  7706. List.iter (process_cf false) cl.cl_ordered_fields;
  7707. cl.cl_ordered_fields <- cl.cl_ordered_fields @ !new_fields;
  7708. new_fields := [];
  7709. List.iter (process_cf true) cl.cl_ordered_statics;
  7710. cl.cl_ordered_statics <- cl.cl_ordered_statics @ !new_fields
  7711. (* ******************************************* *)
  7712. (* UniversalBaseClass *)
  7713. (* ******************************************* *)
  7714. (*
  7715. Sets the universal base class for hxgen types (HxObject / IHxObject)
  7716. dependencies:
  7717. As a rule, it should be one of the last module filters to run so any @:hxgen class created in the process
  7718. -Should- only run after TypeParams.RealTypeParams.Modf, since
  7719. *)
  7720. module UniversalBaseClass =
  7721. struct
  7722. let name = "rcf_universal_base_class"
  7723. let priority = min_dep +. 10.
  7724. let default_implementation gen baseclass baseinterface basedynamic =
  7725. (* baseinterface.cl_meta <- (Meta.BaseInterface, [], baseinterface.cl_pos) :: baseinterface.cl_meta; *)
  7726. let rec run md =
  7727. (if is_hxgen md then
  7728. match md with
  7729. | 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 ->
  7730. cl.cl_implements <- (baseinterface, []) :: cl.cl_implements
  7731. | TClassDecl ({ cl_kind = KAbstractImpl _ } as cl) ->
  7732. (*
  7733. TODO: probably here is not the best place to add @:final to KAbstractImpl, also:
  7734. Doesn't it make sense to add @:final to KAbstractImpls on all platforms?
  7735. *)
  7736. if not (Meta.has Meta.Final cl.cl_meta) then cl.cl_meta <- (Meta.Final, [], cl.cl_pos) :: cl.cl_meta
  7737. | 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 ->
  7738. if is_some cl.cl_dynamic then
  7739. cl.cl_super <- Some (basedynamic,[])
  7740. else
  7741. cl.cl_super <- Some (baseclass,[])
  7742. | 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) ) ->
  7743. cl.cl_implements <- (baseinterface, []) :: cl.cl_implements
  7744. | _ -> ()
  7745. );
  7746. md
  7747. in
  7748. run
  7749. let configure gen mapping_func =
  7750. let map e = Some(mapping_func e) in
  7751. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  7752. let default_config gen baseclass baseinterface basedynamic =
  7753. let impl = (default_implementation gen baseclass baseinterface basedynamic) in
  7754. configure gen impl
  7755. end;;
  7756. (*
  7757. Priority: must run AFTER UniversalBaseClass
  7758. *)
  7759. let priority = solve_deps name [DAfter UniversalBaseClass.priority]
  7760. let configure ?slow_invoke ctx baseinterface =
  7761. let gen = ctx.rcf_gen in
  7762. let run = (fun md -> match md with
  7763. | TClassDecl cl when is_hxgen md && ( not cl.cl_interface || cl.cl_path = baseinterface.cl_path ) && (match cl.cl_kind with KAbstractImpl _ -> false | _ -> true) ->
  7764. (if Meta.has Meta.ReplaceReflection cl.cl_meta then replace_reflection ctx cl);
  7765. (implement_dynamics ctx cl);
  7766. (if not (PMap.mem (gen.gmk_internal_name "hx" "lookupField") cl.cl_fields) then implement_final_lookup ctx cl);
  7767. (if not (PMap.mem (gen.gmk_internal_name "hx" "getField") cl.cl_fields) then implement_get_set ctx cl);
  7768. (if not (PMap.mem (gen.gmk_internal_name "hx" "invokeField") cl.cl_fields) then implement_invokeField ctx ~slow_invoke:slow_invoke cl);
  7769. (if not (PMap.mem (gen.gmk_internal_name "hx" "classFields") cl.cl_fields) then implement_fields ctx cl);
  7770. (if ctx.rcf_handle_statics && not (PMap.mem (gen.gmk_internal_name "hx" "getClassStatic") cl.cl_statics) then implement_get_class ctx cl);
  7771. (if not cl.cl_interface && not (PMap.mem (gen.gmk_internal_name "hx" "create") cl.cl_fields) then implement_create_empty ctx cl);
  7772. None
  7773. | _ -> None)
  7774. in
  7775. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) run
  7776. end;;
  7777. (* ******************************************* *)
  7778. (* Object Declaration Mapper *)
  7779. (* ******************************************* *)
  7780. (*
  7781. A simple Object Declaration Mapper. By default it will be a syntax filter, which only runs
  7782. after
  7783. dependencies:
  7784. *)
  7785. module ObjectDeclMap =
  7786. struct
  7787. let name = "object_decl_map"
  7788. let priority = solve_deps name []
  7789. let traverse gen map_fn =
  7790. let rec run e =
  7791. match e.eexpr with
  7792. | TObjectDecl odecl ->
  7793. let e = Type.map_expr run e in
  7794. (match e.eexpr with | TObjectDecl odecl -> map_fn e odecl | _ -> assert false)
  7795. | _ -> Type.map_expr run e
  7796. in
  7797. run
  7798. let configure gen (mapping_func:texpr->texpr) =
  7799. let map e = Some(mapping_func e) in
  7800. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  7801. end;;
  7802. (* ******************************************* *)
  7803. (* EnumToClass *)
  7804. (* ******************************************* *)
  7805. (*
  7806. For languages that don't support parameterized enums and/or metadata in enums, we need to transform
  7807. enums into normal classes. This is done at the first module pass by creating new classes with the same
  7808. path inside the modules, and removing the actual enum module by setting it as en extern.
  7809. Later, on the last expression pass, it will transform the TMatch codes into TSwitch. it will introduce a new
  7810. dependency, though:
  7811. * The target must create its own strategy to deal with reflection. As it is right now, we will have a base class
  7812. which the class will extend, create @:$IsEnum metadata for the class, and create @:alias() metadatas for the fields,
  7813. with their tag order (as a string) as their alias. If you are using ReflectionCFs, then you don't have to worry
  7814. about that, as it's already generating all information needed by the haxe runtime.
  7815. so they can be
  7816. dependencies:
  7817. The MatchToSwitch part must run after ExprStatementUnwrap as modified expressions might confuse it (not so true anymore)
  7818. *)
  7819. module EnumToClass =
  7820. struct
  7821. let name = "enum_to_class"
  7822. let priority = solve_deps name []
  7823. type t = {
  7824. ec_tbl : (path, tclass) Hashtbl.t;
  7825. }
  7826. let new_t () =
  7827. {
  7828. ec_tbl = Hashtbl.create 10
  7829. }
  7830. (* ******************************************* *)
  7831. (* EnumToClassModf *)
  7832. (* ******************************************* *)
  7833. (*
  7834. The actual Module Filter that will transform the enum into a class
  7835. dependencies:
  7836. Should run before ReflectionCFs, in order to enable proper reflection access.
  7837. Should run before TypeParams.RealTypeParams.RealTypeParamsModf, since generic enums must be first converted to generic classes
  7838. *)
  7839. module EnumToClassModf =
  7840. struct
  7841. let name = "enum_to_class_mod"
  7842. let priority = solve_deps name [DBefore ReflectionCFs.priority; DBefore TypeParams.RealTypeParams.RealTypeParamsModf.priority]
  7843. let pmap_exists fn pmap = try PMap.iter (fun a b -> if fn a b then raise Exit) pmap; false with | Exit -> true
  7844. let has_any_meta en =
  7845. let has_meta meta = List.exists (fun (m,_,_) -> match m with Meta.Custom _ -> true | _ -> false) meta in
  7846. has_meta en.e_meta || pmap_exists (fun _ ef -> has_meta ef.ef_meta) en.e_constrs
  7847. let convert gen t base_class en should_be_hxgen handle_type_params =
  7848. let basic = gen.gcon.basic in
  7849. let pos = en.e_pos in
  7850. (* create the class *)
  7851. let cl = mk_class en.e_module en.e_path pos in
  7852. Hashtbl.add t.ec_tbl en.e_path cl;
  7853. (match Codegen.build_metadata gen.gcon (TEnumDecl en) with
  7854. | Some expr ->
  7855. let cf = mk_class_field "__meta__" expr.etype false expr.epos (Var { v_read = AccNormal; v_write = AccNormal }) [] in
  7856. cf.cf_expr <- Some expr;
  7857. cl.cl_statics <- PMap.add "__meta__" cf cl.cl_statics;
  7858. cl.cl_ordered_statics <- cf :: cl.cl_ordered_statics
  7859. | _ -> ()
  7860. );
  7861. cl.cl_super <- Some(base_class,[]);
  7862. cl.cl_extern <- en.e_extern;
  7863. en.e_extern <- true;
  7864. en.e_meta <- (Meta.Class, [], pos) :: en.e_meta;
  7865. cl.cl_module <- en.e_module;
  7866. cl.cl_meta <- ( Meta.Enum, [], pos ) :: cl.cl_meta;
  7867. (match gen.gcon.platform with
  7868. | Cs when Common.defined gen.gcon Define.CoreApiSerialize ->
  7869. cl.cl_meta <- ( Meta.Meta, [ (EField( (EConst (Ident "System"), null_pos ), "Serializable" ), null_pos) ], null_pos ) :: cl.cl_meta
  7870. | _ -> ());
  7871. let c_types =
  7872. if handle_type_params then
  7873. List.map (fun (s,t) -> (s, TInst (map_param (get_cl_t t), []))) en.e_params
  7874. else
  7875. []
  7876. in
  7877. cl.cl_params <- c_types;
  7878. let i = ref 0 in
  7879. let cfs = List.map (fun name ->
  7880. let ef = PMap.find name en.e_constrs in
  7881. let pos = ef.ef_pos in
  7882. let old_i = !i in
  7883. incr i;
  7884. let cf = match follow ef.ef_type with
  7885. | TFun(params,ret) ->
  7886. let dup_types =
  7887. if handle_type_params then
  7888. List.map (fun (s,t) -> (s, TInst (map_param (get_cl_t t), []))) en.e_params
  7889. else
  7890. []
  7891. in
  7892. let ef_type =
  7893. let fn, types = if handle_type_params then snd, dup_types else (fun _ -> t_dynamic), en.e_params in
  7894. let t = apply_params en.e_params (List.map fn types) ef.ef_type in
  7895. apply_params ef.ef_params (List.map fn ef.ef_params) t
  7896. in
  7897. let params, ret = get_fun ef_type in
  7898. let cf_params = if handle_type_params then dup_types @ ef.ef_params else [] in
  7899. let cf = mk_class_field name ef_type true pos (Method MethNormal) cf_params in
  7900. cf.cf_meta <- [];
  7901. let tf_args = List.map (fun (name,opt,t) -> (alloc_var name t, if opt then Some TNull else None) ) params in
  7902. let arr_decl = { eexpr = TArrayDecl(List.map (fun (v,_) -> mk_local v pos) tf_args); etype = basic.tarray t_empty; epos = pos } in
  7903. let expr = {
  7904. eexpr = TFunction({
  7905. tf_args = tf_args;
  7906. tf_type = ret;
  7907. 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 } );
  7908. });
  7909. etype = ef_type;
  7910. epos = pos
  7911. } in
  7912. cf.cf_expr <- Some expr;
  7913. cf
  7914. | _ ->
  7915. let actual_t = match follow ef.ef_type with
  7916. | TEnum(e, p) -> TEnum(e, List.map (fun _ -> t_dynamic) p)
  7917. | _ -> assert false
  7918. in
  7919. let cf = mk_class_field name actual_t true pos (Var { v_read = AccNormal; v_write = AccNormal }) [] in
  7920. cf.cf_meta <- [];
  7921. cf.cf_expr <- Some {
  7922. eexpr = TNew(cl, List.map (fun _ -> t_empty) cl.cl_params, [mk_int gen old_i pos; { eexpr = TArrayDecl []; etype = basic.tarray t_empty; epos = pos }]);
  7923. etype = TInst(cl, List.map (fun _ -> t_empty) cl.cl_params);
  7924. epos = pos;
  7925. };
  7926. cf
  7927. in
  7928. cl.cl_statics <- PMap.add cf.cf_name cf cl.cl_statics;
  7929. cf
  7930. ) en.e_names in
  7931. let constructs_cf = mk_class_field "constructs" (basic.tarray basic.tstring) true pos (Var { v_read = AccNormal; v_write = AccNormal }) [] in
  7932. constructs_cf.cf_meta <- [];
  7933. constructs_cf.cf_expr <- Some {
  7934. eexpr = TArrayDecl (List.map (fun s -> { eexpr = TConst(TString s); etype = basic.tstring; epos = pos }) en.e_names);
  7935. etype = basic.tarray basic.tstring;
  7936. epos = pos;
  7937. };
  7938. cl.cl_ordered_statics <- constructs_cf :: cfs @ cl.cl_ordered_statics ;
  7939. cl.cl_statics <- PMap.add "constructs" constructs_cf cl.cl_statics;
  7940. let getTag_cf_type = tfun [] basic.tstring in
  7941. let getTag_cf = mk_class_field "getTag" getTag_cf_type true pos (Method MethNormal) [] in
  7942. getTag_cf.cf_meta <- [(Meta.Final, [], pos)];
  7943. getTag_cf.cf_expr <- Some {
  7944. eexpr = TFunction {
  7945. tf_args = [];
  7946. tf_type = basic.tstring;
  7947. tf_expr = {
  7948. eexpr = TReturn (Some (
  7949. let e_constructs = mk_static_field_access_infer cl "constructs" pos [] in
  7950. let e_this = mk (TConst TThis) (TInst (cl,[])) pos in
  7951. let e_index = mk_field_access gen e_this "index" pos in
  7952. let e_unsafe_get = mk_field_access gen e_constructs "__unsafe_get" pos in
  7953. {
  7954. eexpr = TCall (e_unsafe_get, [e_index]);
  7955. etype = basic.tstring;
  7956. epos = pos;
  7957. }
  7958. ));
  7959. epos = pos;
  7960. etype = basic.tvoid;
  7961. }
  7962. };
  7963. etype = getTag_cf_type;
  7964. epos = pos;
  7965. };
  7966. cl.cl_ordered_fields <- getTag_cf :: cl.cl_ordered_fields ;
  7967. cl.cl_fields <- PMap.add "getTag" getTag_cf cl.cl_fields;
  7968. cl.cl_overrides <- getTag_cf :: cl.cl_overrides;
  7969. (if should_be_hxgen then
  7970. cl.cl_meta <- (Meta.HxGen,[],cl.cl_pos) :: cl.cl_meta
  7971. else begin
  7972. (* create the constructor *)
  7973. let tf_args = [ alloc_var "index" basic.tint, None; alloc_var "params" (basic.tarray t_empty), None ] in
  7974. let ftype = TFun(fun_args tf_args, basic.tvoid) in
  7975. let ctor = mk_class_field "new" ftype true pos (Method MethNormal) [] in
  7976. let me = TInst(cl, List.map snd cl.cl_params) in
  7977. ctor.cf_expr <-
  7978. Some {
  7979. eexpr = TFunction(
  7980. {
  7981. tf_args = tf_args;
  7982. tf_type = basic.tvoid;
  7983. tf_expr = mk_block {
  7984. eexpr = TCall({ eexpr = TConst TSuper; etype = me; epos = pos }, List.map (fun (v,_) -> mk_local v pos) tf_args);
  7985. etype = basic.tvoid;
  7986. epos = pos;
  7987. }
  7988. });
  7989. etype = ftype;
  7990. epos = pos
  7991. };
  7992. cl.cl_constructor <- Some ctor
  7993. end);
  7994. gen.gadd_to_module (TClassDecl cl) (max_dep);
  7995. TEnumDecl en
  7996. (*
  7997. traverse
  7998. gen - gen context
  7999. convert_all : bool - should we convert all enums? If set, convert_if_has_meta will be ignored.
  8000. convert_if_has_meta : bool - should we convert only if it has meta?
  8001. enum_base_class : tclass - the enum base class.
  8002. should_be_hxgen : bool - should the created enum be hxgen?
  8003. *)
  8004. let traverse gen t convert_all convert_if_has_meta enum_base_class should_be_hxgen handle_tparams =
  8005. let convert e = convert gen t enum_base_class e should_be_hxgen handle_tparams in
  8006. let run md = match md with
  8007. | TEnumDecl e when is_hxgen md ->
  8008. if convert_all then
  8009. convert e
  8010. else if convert_if_has_meta && has_any_meta e then
  8011. convert e
  8012. else if not (Meta.has Meta.FlatEnum e.e_meta) then
  8013. convert e
  8014. else begin
  8015. (* take off the :hxgen meta from it, if there's any *)
  8016. e.e_meta <- List.filter (fun (n,_,_) -> not (n = Meta.HxGen)) e.e_meta;
  8017. md
  8018. end
  8019. | _ -> md
  8020. in
  8021. run
  8022. let configure gen (mapping_func:module_type->module_type) =
  8023. let map md = Some(mapping_func md) in
  8024. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  8025. end;;
  8026. (* ******************************************* *)
  8027. (* EnumToClassExprf *)
  8028. (* ******************************************* *)
  8029. (*
  8030. Enum to class Expression Filter
  8031. will convert TMatch into TSwitch
  8032. dependencies:
  8033. Should run before TArrayTransform, since it generates array access expressions
  8034. *)
  8035. module EnumToClassExprf =
  8036. struct
  8037. let name = "enum_to_class_exprf"
  8038. let priority = solve_deps name [DBefore TArrayTransform.priority]
  8039. let traverse gen t opt_get_native_enum_tag =
  8040. let rec run e =
  8041. let get_converted_enum_type et =
  8042. let en, eparams = match follow (gen.gfollow#run_f et) with
  8043. | TEnum(en,p) -> en, p
  8044. | _ -> raise Not_found
  8045. in
  8046. let cl = Hashtbl.find t.ec_tbl en.e_path in
  8047. TInst(cl, eparams)
  8048. in
  8049. match e.eexpr with
  8050. | TCall (({eexpr = TField(_, FStatic({cl_path=[],"Type"},{cf_name="enumIndex"}))} as left), [f]) ->
  8051. let f = run f in
  8052. (try
  8053. mk_field_access gen {f with etype = get_converted_enum_type f.etype} "index" e.epos
  8054. with Not_found ->
  8055. { e with eexpr = TCall(left, [f]) })
  8056. | TEnumParameter(f, _,i) ->
  8057. let f = run f in
  8058. (* check if en was converted to class *)
  8059. (* if it was, switch on tag field and change cond type *)
  8060. let f = try
  8061. { f with etype = get_converted_enum_type f.etype }
  8062. with Not_found ->
  8063. f
  8064. in
  8065. let cond_array = { (mk_field_access gen f "params" f.epos) with etype = gen.gcon.basic.tarray t_empty } in
  8066. { e with eexpr = TArray(cond_array, mk_int gen i cond_array.epos); }
  8067. | _ -> Type.map_expr run e
  8068. in
  8069. run
  8070. let configure gen (mapping_func:texpr->texpr) =
  8071. let map e = Some(mapping_func e) in
  8072. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority) map
  8073. end;;
  8074. let configure gen opt_get_native_enum_tag convert_all convert_if_has_meta enum_base_class should_be_hxgen handle_tparams =
  8075. let t = new_t () in
  8076. EnumToClassModf.configure gen (EnumToClassModf.traverse gen t convert_all convert_if_has_meta enum_base_class should_be_hxgen handle_tparams);
  8077. EnumToClassExprf.configure gen (EnumToClassExprf.traverse gen t opt_get_native_enum_tag)
  8078. end;;
  8079. (* ******************************************* *)
  8080. (* IteratorsInterface *)
  8081. (* ******************************************* *)
  8082. (*
  8083. This module will handle with Iterators, Iterables and TFor() expressions.
  8084. At first, a module filter will receive a Iterator<T> and Iterable<T> interface, which will be implemented
  8085. if hasNext(), next() or iterator() fields are detected with the correct type.
  8086. At this part a custom function will be called which can adequate the class fields so they are compatible with
  8087. native Iterators as well
  8088. The expression filter part of this module will look for TFor() expressions, and transform like that:
  8089. for (anInt in value.iterator())
  8090. {
  8091. }
  8092. {
  8093. var s:haxe.lang.Iterator<Int> = ExternalFunction.getIterator(value.iterator());
  8094. while (s.hasNext())
  8095. {
  8096. var anInt:Int = s.next();
  8097. }
  8098. }
  8099. dependencies:
  8100. None.
  8101. *)
  8102. module IteratorsInterface =
  8103. struct
  8104. let name = "iterators_interface"
  8105. (* TODO later
  8106. (* ******************************************* *)
  8107. (* IteratorsInterfaceModf *)
  8108. (* ******************************************* *)
  8109. (*
  8110. The module filter for Iterators Interface, which will implement the iterator/iterable interface on each
  8111. class that conforms with the typedefs Iterator<> and Iterable<>
  8112. It's a very simple module and it will rely on cast detection to work correctly. This is so that
  8113. when the
  8114. dependencies:
  8115. Must run at the Module Filters, so cast detection can detect a cast to the interface and we can
  8116. *)
  8117. module IteratorsInterfaceModf =
  8118. struct
  8119. let name = "iterators_interface_modf"
  8120. let conforms_cfs has_next next =
  8121. try (match follow has_next.cf_type with
  8122. | TFun([],ret) when
  8123. (match follow ret with | TAbstract({ a_path = ([], "Bool") }, []) -> () | _ -> raise Not_found) ->
  8124. ()
  8125. | _ -> raise Not_found);
  8126. (match follow next.cf_type with
  8127. | TFun([], ret) -> ret
  8128. | _ -> raise Not_found
  8129. )
  8130. let conforms_type_iterator t =
  8131. try match follow t with
  8132. | TInst(cl,params) ->
  8133. let has_next = PMap.find "hasNext" cl.cl_fields in
  8134. let next = PMap.find "next" cl.cl_fields in
  8135. Some (conforms_cfs has_next next)
  8136. | TAnon(anon) ->
  8137. let has_next = PMap.find "hasNext" anon.a_fields in
  8138. let next = PMap.find "next" anon.a_fields in
  8139. Some (conforms_cfs has_next next)
  8140. | _ -> None
  8141. with | Not_found -> None
  8142. let conforms_as_iterable cl =
  8143. try
  8144. let iterator = PMap.find "iterator" cl.cl_fields in
  8145. match follow iterator.cf_type with
  8146. | TFun([], ret) -> conforms_type_iterator ret
  8147. | _ -> None
  8148. with | Not_found -> None
  8149. let conforms_as_iterator cl =
  8150. try
  8151. let has_next = PMap.find "hasNext" cl.cl_fields in
  8152. let next = PMap.find "next" cl.cl_fields in
  8153. Some (conforms_cfs has_next next)
  8154. with | Not_found -> None
  8155. let priority = solve_deps name []
  8156. let traverse gen iterator_iface iterable_iface on_found_iterator on_found_iterable =
  8157. let rec run md =
  8158. match md with
  8159. | TClassDecl cl when not cl.cl_extern && is_hxgen cl ->
  8160. let conforms_iterator = conforms_as_iterator cl in
  8161. let conforms_iterable = conforms_as_iterable cl in
  8162. if is_some conforms_iterator then begin
  8163. let it_t = get conforms_iterator in
  8164. cl.cl_interfaces <- (iterator_iface, [it_t]);
  8165. on_found_iterator cl
  8166. end;
  8167. if is_some conforms_iterable then begin
  8168. let it_t = get conforms_iterable in
  8169. cl.cl_interfaces <- (iterable_iface, [it_t]);
  8170. on_found_iterable cl
  8171. end;
  8172. md
  8173. | _ -> md
  8174. in
  8175. run
  8176. let configure gen (mapping_func:texpr->texpr) =
  8177. let map e = Some(mapping_func e) in
  8178. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority) map
  8179. end;;
  8180. *)
  8181. (* ******************************************* *)
  8182. (* IteratorsInterfaceExprf *)
  8183. (* ******************************************* *)
  8184. (*
  8185. The expression filter for Iterators. Will look for TFor, transform it into
  8186. {
  8187. var iterator = // in expression here
  8188. while (iterator.hasNext())
  8189. {
  8190. var varName = iterator.next();
  8191. }
  8192. }
  8193. dependencies:
  8194. Must run before Dynamic fields access is run
  8195. *)
  8196. module IteratorsInterfaceExprf =
  8197. struct
  8198. let name = "iterators_interface_exprf"
  8199. let priority = solve_deps name [DBefore DynamicFieldAccess.priority]
  8200. let priority_as_synf = solve_deps name [DBefore DynamicFieldAccess.priority_as_synf]
  8201. let mk_access gen v name pos =
  8202. let field_t =
  8203. try match follow v.v_type with
  8204. | TInst(cl, params) ->
  8205. let field = PMap.find name cl.cl_fields in
  8206. apply_params cl.cl_params params field.cf_type
  8207. | TAnon(anon) ->
  8208. let field = PMap.find name anon.a_fields in
  8209. field.cf_type
  8210. | _ -> t_dynamic
  8211. with | Not_found -> t_dynamic
  8212. in
  8213. { (mk_field_access gen (mk_local v pos) name pos) with etype = field_t }
  8214. let traverse gen change_in_expr =
  8215. let basic = gen.gcon.basic in
  8216. let rec run e =
  8217. match e.eexpr with
  8218. | TFor(var, in_expr, block) ->
  8219. let in_expr = change_in_expr (run in_expr) in
  8220. let temp = mk_temp gen "iterator" in_expr.etype in
  8221. let block =
  8222. [
  8223. { eexpr = TVar(temp, Some(in_expr)); etype = basic.tvoid; epos = in_expr.epos };
  8224. {
  8225. eexpr = TWhile(
  8226. { eexpr = TCall(mk_access gen temp "hasNext" in_expr.epos, []); etype = basic.tbool; epos = in_expr.epos },
  8227. Type.concat ({
  8228. eexpr = TVar(var, Some({ eexpr = TCall(mk_access gen temp "next" in_expr.epos, []); etype = var.v_type; epos = in_expr.epos }));
  8229. etype = basic.tvoid;
  8230. epos = in_expr.epos
  8231. }) ( run block ),
  8232. Ast.NormalWhile);
  8233. etype = basic.tvoid;
  8234. epos = e.epos
  8235. }
  8236. ] in
  8237. { eexpr = TBlock(block); etype = e.etype; epos = e.epos }
  8238. | _ -> Type.map_expr run e
  8239. in
  8240. run
  8241. let configure gen (mapping_func:texpr->texpr) =
  8242. let map e = Some(mapping_func e) in
  8243. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority) map
  8244. let configure_as_synf gen (mapping_func:texpr->texpr) =
  8245. let map e = Some(mapping_func e) in
  8246. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority_as_synf) map
  8247. end;;
  8248. let configure gen change_in_expr =
  8249. IteratorsInterfaceExprf.configure gen (IteratorsInterfaceExprf.traverse gen change_in_expr)
  8250. let configure_as_synf gen change_in_expr =
  8251. IteratorsInterfaceExprf.configure_as_synf gen (IteratorsInterfaceExprf.traverse gen change_in_expr)
  8252. end;;
  8253. (* ******************************************* *)
  8254. (* SwitchToIf *)
  8255. (* ******************************************* *)
  8256. (*
  8257. Just a syntax filter which changes switch expressions to if() else if() else if() ...
  8258. It can be also an expression filter
  8259. dependencies:
  8260. *)
  8261. module SwitchToIf =
  8262. struct
  8263. let name = "switch_to_if"
  8264. let priority = solve_deps name []
  8265. let rec simplify_expr e = match e.eexpr with
  8266. | TParenthesis e
  8267. | TMeta(_,e) -> simplify_expr e
  8268. | _ -> e
  8269. let traverse gen (should_convert:texpr->bool) (handle_nullables:bool) =
  8270. let basic = gen.gcon.basic in
  8271. let rec run e =
  8272. match e.eexpr with
  8273. | TSwitch(cond,cases,default) when should_convert e ->
  8274. let cond_etype, should_cache = match handle_nullables, gen.gfollow#run_f cond.etype with
  8275. | true, TType({ t_path = ([], "Null") }, [t]) ->
  8276. let rec take_off_nullable t = match gen.gfollow#run_f t with
  8277. | TType({ t_path = ([], "Null") }, [t]) -> take_off_nullable t
  8278. | _ -> t
  8279. in
  8280. take_off_nullable t, true
  8281. | _, _ -> cond.etype, false
  8282. in
  8283. if should_cache && not (should_convert { e with eexpr = TSwitch({ cond with etype = cond_etype }, cases, default) }) then begin
  8284. { 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) }
  8285. end else begin
  8286. let local, fst_block = match cond.eexpr, should_cache with
  8287. | TLocal _, false -> cond, []
  8288. | _ ->
  8289. let var = mk_temp gen "switch" cond_etype in
  8290. let cond = run cond in
  8291. let cond = if should_cache then mk_cast cond_etype cond else cond in
  8292. mk_local var cond.epos, [ { eexpr = TVar(var,Some(cond)); etype = basic.tvoid; epos = cond.epos } ]
  8293. in
  8294. let mk_eq cond =
  8295. { eexpr = TBinop(Ast.OpEq, local, cond); etype = basic.tbool; epos = cond.epos }
  8296. in
  8297. let rec mk_many_cond conds =
  8298. match conds with
  8299. | cond :: [] ->
  8300. mk_eq cond
  8301. | cond :: tl ->
  8302. { eexpr = TBinop(Ast.OpBoolOr, mk_eq (run cond), mk_many_cond tl); etype = basic.tbool; epos = cond.epos }
  8303. | [] -> assert false
  8304. in
  8305. let mk_many_cond conds =
  8306. let ret = mk_many_cond conds in
  8307. (*
  8308. this might be considered a hack. But since we're on a syntax filter and
  8309. the condition is guaranteed to not have run twice, we can really run the
  8310. expr filters again for it (so to change e.g. OpEq accordingly
  8311. *)
  8312. gen.gexpr_filters#run_f ret
  8313. in
  8314. let rec loop cases = match cases with
  8315. | (conds,e) :: [] ->
  8316. { eexpr = TIf(mk_many_cond conds, run e, Option.map run default); etype = e.etype; epos = e.epos }
  8317. | (conds,e) :: tl ->
  8318. { eexpr = TIf(mk_many_cond conds, run e, Some(loop tl)); etype = e.etype; epos = e.epos }
  8319. | [] -> match default with
  8320. | None ->
  8321. raise Exit
  8322. | Some d -> run d
  8323. in
  8324. try
  8325. { e with eexpr = TBlock(fst_block @ [loop cases]) }
  8326. with | Exit ->
  8327. { e with eexpr = TBlock [] }
  8328. end
  8329. | TSwitch(cond,cases,default) -> (try
  8330. match (simplify_expr cond).eexpr with
  8331. | TCall( { eexpr = TField(_,FStatic({ cl_path = [],"Type" }, { cf_name = "enumIndex" })) }, [enum] ) ->
  8332. let real_enum = match enum.etype with
  8333. | TEnum(e,_) -> e
  8334. | _ -> raise Not_found
  8335. in
  8336. if Meta.has Meta.Class real_enum.e_meta then raise Not_found;
  8337. let enum_expr = mk_mt_access (TEnumDecl(real_enum)) e.epos in
  8338. let fields = Hashtbl.create (List.length real_enum.e_names) in
  8339. PMap.iter (fun _ ef -> Hashtbl.add fields ef.ef_index ef) real_enum.e_constrs;
  8340. let cases = List.map (fun (el,e) ->
  8341. List.map (fun e -> match e.eexpr with
  8342. | TConst(TInt i) ->
  8343. let ef = Hashtbl.find fields (Int32.to_int i) in
  8344. { e with eexpr = TField(enum_expr, FEnum(real_enum,ef)); etype = TEnum(real_enum,List.map (fun _ -> t_dynamic) real_enum.e_params) }
  8345. | _ -> raise Not_found) el, run e
  8346. ) cases in
  8347. { e with eexpr = TSwitch(enum,cases,Option.map run default) }
  8348. | _ -> raise Not_found
  8349. with Not_found -> Type.map_expr run e)
  8350. | _ -> Type.map_expr run e
  8351. in
  8352. run
  8353. let configure gen (mapping_func:texpr->texpr) =
  8354. let map e = Some(mapping_func e) in
  8355. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  8356. end;;
  8357. (* ******************************************* *)
  8358. (* Anonymous Class object handling *)
  8359. (* ******************************************* *)
  8360. (*
  8361. (syntax)
  8362. When we pass a class as an object, in some languages we will need a special construct to be able to
  8363. access its statics as if they were normal object fields. On C# and Java the way found to do that is
  8364. by handling statics reflection also by a normal instance. This also happens in hxcpp and neko, so I
  8365. guess it's a valid practice.
  8366. So if we want to handle the reflection of the static MyClass, here's roughly how it will be done:
  8367. var x = MyClass;
  8368. gets converted into
  8369. Haxe.Lang.Class x = Haxe.Lang.Runtime.GetType(typeof(MyClass).RuntimeHandle);
  8370. which will in turn look in its cache but roughly would do:
  8371. Haxe.Lang.Class x = new Haxe.Lang.Class(new MyClass(EmptyObject.EMPTY));
  8372. This module will of course let the caller choose how this will be implemented. It will just identify all
  8373. uses of class that will require it to be cast as an object.
  8374. dependencies:
  8375. *)
  8376. module ClassInstance =
  8377. struct
  8378. let priority = solve_deps "class_instance" []
  8379. let traverse gen (change_expr:texpr->module_type->texpr) =
  8380. let rec run e =
  8381. match e.eexpr with
  8382. | TCall( ({ eexpr = TLocal(v) } as local), calls ) when String.get v.v_name 0 = '_' && Hashtbl.mem gen.gspecial_vars v.v_name ->
  8383. { e with eexpr = TCall(local, List.map (fun e ->
  8384. match e.eexpr with
  8385. | TTypeExpr _ -> e
  8386. | _ -> run e) calls) }
  8387. | TField({ eexpr = TTypeExpr(mt) }, f) ->
  8388. e
  8389. | TField(ef, f) ->
  8390. (match anon_class ef.etype with
  8391. | None -> Type.map_expr run e
  8392. | Some t ->
  8393. { e with eexpr = TField( { ef with eexpr = TTypeExpr(t) }, f) }
  8394. )
  8395. | TTypeExpr(mt) -> change_expr e mt
  8396. | _ -> Type.map_expr run e
  8397. in
  8398. run
  8399. let configure gen (mapping_func:texpr->texpr) =
  8400. let map e = Some(mapping_func e) in
  8401. gen.gsyntax_filters#add ~name:"class_instance" ~priority:(PCustom priority) map
  8402. end;;
  8403. (* ******************************************* *)
  8404. (* HardNullableSynf *)
  8405. (* ******************************************* *)
  8406. (*
  8407. This module will handle Null<T> types for languages that offer a way of dealing with
  8408. stack-allocated structures or tuples and generics. Essentialy on those targets a Null<T>
  8409. will be a tuple ( 'a * bool ), where bool is whether the value is null or not.
  8410. At first (configure-time), we will modify the follow function so it can follow correctly nested Null<Null<T>>,
  8411. and do not follow Null<T> to its underlying type
  8412. Then we will run a syntax filter, which will look for casts to Null<T> and replace them by
  8413. a call to the new Null<T> creation;
  8414. Also casts from Null<T> to T or direct uses of Null<T> (call, field access, array access, closure)
  8415. will result in the actual value being accessed
  8416. For compatibility with the C# target, HardNullable will accept both Null<T> and haxe.lang.Null<T> types
  8417. dependencies:
  8418. Needs to be run after all cast detection modules
  8419. *)
  8420. module HardNullableSynf =
  8421. struct
  8422. let name = "hard_nullable"
  8423. let priority = solve_deps name [DAfter CastDetect.ReturnCast.priority]
  8424. let rec is_null_t gen t = match gen.greal_type t with
  8425. | TType( { t_path = ([], "Null") }, [of_t])
  8426. | TInst( { cl_path = (["haxe";"lang"], "Null") }, [of_t]) ->
  8427. let rec take_off_null t =
  8428. match is_null_t gen t with | None -> t | Some s -> take_off_null s
  8429. in
  8430. Some (take_off_null of_t)
  8431. | TMono r -> (match !r with | Some t -> is_null_t gen t | None -> None)
  8432. | TLazy f -> is_null_t gen (!f())
  8433. | TType (t, tl) ->
  8434. is_null_t gen (apply_params t.t_params tl t.t_type)
  8435. | _ -> None
  8436. let follow_addon gen t =
  8437. let rec strip_off_nullable t =
  8438. let t = gen.gfollow#run_f t in
  8439. match t with
  8440. (* haxe.lang.Null<haxe.lang.Null<>> wouldn't be a valid construct, so only follow Null<> *)
  8441. | TType ( { t_path = ([], "Null") }, [of_t] ) -> strip_off_nullable of_t
  8442. | _ -> t
  8443. in
  8444. match t with
  8445. | TType( ({ t_path = ([], "Null") } as tdef), [of_t]) ->
  8446. Some( TType(tdef, [ strip_off_nullable of_t ]) )
  8447. | _ -> None
  8448. let traverse gen unwrap_null wrap_val null_to_dynamic has_value opeq_handler handle_opeq handle_cast =
  8449. (* let unwrap_null e = *)
  8450. (* let ret = unwrap_null e in *)
  8451. (* { ret with eexpr = TParenthesis(ret) } *)
  8452. (* in *)
  8453. (* let wrap_val e t b = *)
  8454. (* let ret = wrap_val e t b in *)
  8455. (* { ret with eexpr = TParenthesis(ret) } *)
  8456. (* in *)
  8457. let is_string t = match gen.greal_type t with
  8458. | TInst({ cl_path=([],"String") },_) -> true
  8459. | _ -> false
  8460. in
  8461. let handle_unwrap to_t e =
  8462. let e_null_t = get (is_null_t gen e.etype) in
  8463. match gen.greal_type to_t with
  8464. | TDynamic _ | TMono _ | TAnon _ ->
  8465. (match e_null_t with
  8466. | TDynamic _ | TMono _ | TAnon _ ->
  8467. gen.ghandle_cast to_t e_null_t (unwrap_null e)
  8468. | _ -> null_to_dynamic e
  8469. )
  8470. | _ ->
  8471. gen.ghandle_cast to_t e_null_t (unwrap_null e)
  8472. in
  8473. let handle_wrap e t =
  8474. match e.eexpr with
  8475. | TConst(TNull) ->
  8476. wrap_val e t false
  8477. | _ ->
  8478. wrap_val e t true
  8479. in
  8480. let is_null_t = is_null_t gen in
  8481. let cur_block = ref [] in
  8482. let add_tmp v e p =
  8483. cur_block := { eexpr = TVar(v,e); etype = gen.gcon.basic.tvoid; epos = p } :: !cur_block
  8484. in
  8485. let get_local e = match e.eexpr with
  8486. | TLocal _ ->
  8487. e, e
  8488. | _ ->
  8489. let v = mk_temp gen "nulltmp" e.etype in
  8490. add_tmp v (Some (null e.etype e.epos)) e.epos;
  8491. let local = { e with eexpr = TLocal(v) } in
  8492. mk_paren { e with eexpr = TBinop(Ast.OpAssign, local, e) }, local
  8493. in
  8494. let rec run e =
  8495. match e.eexpr with
  8496. | TBlock(bl) ->
  8497. let lst = !cur_block in
  8498. cur_block := [];
  8499. List.iter (fun e ->
  8500. let e = run e in
  8501. cur_block := (e :: !cur_block)
  8502. ) bl;
  8503. let ret = !cur_block in
  8504. cur_block := lst;
  8505. { e with eexpr = TBlock(List.rev ret) }
  8506. | TCast(v, _) ->
  8507. let null_et = is_null_t e.etype in
  8508. let null_vt = is_null_t v.etype in
  8509. (match null_vt, null_et with
  8510. | Some(vt), None when is_string e.etype ->
  8511. let v = run v in
  8512. { e with eexpr = TCast(null_to_dynamic v,None) }
  8513. | Some(vt), None ->
  8514. (match v.eexpr with
  8515. (* is there an unnecessary cast to Nullable? *)
  8516. | TCast(v2, _) ->
  8517. run { v with etype = e.etype }
  8518. | _ ->
  8519. handle_unwrap e.etype (run v)
  8520. )
  8521. | None, Some(et) ->
  8522. handle_wrap (run v) et
  8523. | Some(vt), Some(et) when handle_cast ->
  8524. handle_wrap (gen.ghandle_cast et vt (handle_unwrap vt (run v))) et
  8525. | Some(vt), Some(et) when not (type_iseq (run_follow gen vt) (run_follow gen et)) ->
  8526. (* check if has value and convert *)
  8527. let vlocal_fst, vlocal = get_local (run v) in
  8528. {
  8529. eexpr = TIf(
  8530. has_value vlocal_fst,
  8531. handle_wrap (mk_cast et (unwrap_null vlocal)) et,
  8532. Some( handle_wrap (null et e.epos) et ));
  8533. etype = e.etype;
  8534. epos = e.epos
  8535. }
  8536. | _ ->
  8537. Type.map_expr run e
  8538. )
  8539. | TField(ef, field) when is_some (is_null_t ef.etype) ->
  8540. let to_t = get (is_null_t ef.etype) in
  8541. { e with eexpr = TField(handle_unwrap to_t (run ef), field) }
  8542. | TCall(ecall, params) when is_some (is_null_t ecall.etype) ->
  8543. let to_t = get (is_null_t ecall.etype) in
  8544. { e with eexpr = TCall(handle_unwrap to_t (run ecall), List.map run params) }
  8545. | TArray(earray, p) when is_some (is_null_t earray.etype) ->
  8546. let to_t = get (is_null_t earray.etype) in
  8547. { e with eexpr = TArray(handle_unwrap to_t (run earray), p) }
  8548. | TBinop(op, e1, e2) ->
  8549. let e1_t = is_null_t e1.etype in
  8550. let e2_t = is_null_t e2.etype in
  8551. (match op with
  8552. | Ast.OpAssign
  8553. | Ast.OpAssignOp _ ->
  8554. (match e1_t, e2_t with
  8555. | Some t1, Some t2 ->
  8556. (match op with
  8557. | Ast.OpAssign ->
  8558. Type.map_expr run e
  8559. | Ast.OpAssignOp op ->
  8560. (match e1.eexpr with
  8561. | TLocal _ ->
  8562. { e with eexpr = TBinop( Ast.OpAssign, e1, handle_wrap { e with eexpr = TBinop (op, handle_unwrap t1 e1, handle_unwrap t2 (run e2) ) } t1 ) }
  8563. | _ ->
  8564. let v, e1, evars = match e1.eexpr with
  8565. | TField(ef, f) ->
  8566. let v = mk_temp gen "nullbinop" ef.etype in
  8567. v, { e1 with eexpr = TField(mk_local v ef.epos, f) }, ef
  8568. | _ ->
  8569. let v = mk_temp gen "nullbinop" e1.etype in
  8570. v, mk_local v e1.epos, e1
  8571. in
  8572. { e with eexpr = TBlock([
  8573. { eexpr = TVar(v, Some evars); etype = gen.gcon.basic.tvoid; epos = e.epos };
  8574. { e with eexpr = TBinop( Ast.OpAssign, e1, handle_wrap { e with eexpr = TBinop (op, handle_unwrap t1 e1, handle_unwrap t2 (run e2) ) } t1 ) }
  8575. ]) }
  8576. )
  8577. | _ -> assert false
  8578. )
  8579. | _ ->
  8580. Type.map_expr run e (* casts are already dealt with normal CastDetection module *)
  8581. )
  8582. | Ast.OpEq | Ast.OpNotEq when not handle_opeq ->
  8583. Type.map_expr run e
  8584. | Ast.OpEq | Ast.OpNotEq ->
  8585. (match e1.eexpr, e2.eexpr with
  8586. | TConst(TNull), _ when is_some e2_t ->
  8587. let e = has_value (run e2) in
  8588. if op = Ast.OpEq then
  8589. { e with eexpr = TUnop(Ast.Not, Ast.Prefix, e) }
  8590. else
  8591. e
  8592. | _, TConst(TNull) when is_some e1_t ->
  8593. let e = has_value (run e1) in
  8594. if op = Ast.OpEq then
  8595. { e with eexpr = TUnop(Ast.Not, Ast.Prefix, e) }
  8596. else
  8597. e
  8598. | _ when is_some e1_t || is_some e2_t ->
  8599. let e1, e2 =
  8600. if not (is_some e1_t) then
  8601. run e2, handle_wrap (run e1) (get e2_t)
  8602. else if not (is_some e2_t) then
  8603. run e1, handle_wrap (run e2) (get e1_t)
  8604. else
  8605. run e1, run e2
  8606. in
  8607. let e = opeq_handler e1 e2 in
  8608. if op = Ast.OpEq then
  8609. { e with eexpr = TUnop(Ast.Not, Ast.Prefix, e) }
  8610. else
  8611. e
  8612. | _ ->
  8613. Type.map_expr run e
  8614. )
  8615. | Ast.OpAdd when is_string e1.etype || is_string e2.etype ->
  8616. let e1 = if is_some e1_t then
  8617. null_to_dynamic (run e1)
  8618. else
  8619. run e1
  8620. in
  8621. let e2 = if is_some e2_t then
  8622. null_to_dynamic (run e2)
  8623. else
  8624. run e2
  8625. in
  8626. let e_t = is_null_t e.etype in
  8627. if is_some e_t then
  8628. wrap_val { eexpr = TBinop(op,e1,e2); etype = get e_t; epos = e.epos } (get e_t) true
  8629. else
  8630. { e with eexpr = TBinop(op,e1,e2) }
  8631. | _ ->
  8632. let e1 = if is_some e1_t then
  8633. handle_unwrap (get e1_t) (run e1)
  8634. else run e1 in
  8635. let e2 = if is_some e2_t then
  8636. handle_unwrap (get e2_t) (run e2)
  8637. else
  8638. run e2 in
  8639. (* if it is Null<T>, we need to convert the result again to null *)
  8640. let e_t = (is_null_t e.etype) in
  8641. if is_some e_t then
  8642. wrap_val { eexpr = TBinop(op, e1, e2); etype = get e_t; epos = e.epos } (get e_t) true
  8643. else
  8644. { e with eexpr = TBinop(op, e1, e2) }
  8645. )
  8646. (*| TUnop( (Ast.Increment as op)*)
  8647. | _ -> Type.map_expr run e
  8648. in
  8649. let run e = match e.eexpr with
  8650. | TFunction tf ->
  8651. run { e with eexpr = TFunction { tf with tf_expr = mk_block tf.tf_expr } }
  8652. | TBlock _ ->
  8653. run e
  8654. | _ -> match run (mk_block e) with
  8655. | { eexpr = TBlock([e]) } -> e
  8656. | e -> e
  8657. in
  8658. run
  8659. let configure gen (mapping_func:texpr->texpr) =
  8660. gen.gfollow#add ~name:(name ^ "_follow") (follow_addon gen);
  8661. let map e = Some(mapping_func e) in
  8662. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  8663. end;;
  8664. (* ******************************************* *)
  8665. (* ArrayDeclSynf *)
  8666. (* ******************************************* *)
  8667. (*
  8668. A syntax filter that will change array declarations to the actual native array declarations plus
  8669. the haxe array initialization
  8670. dependencies:
  8671. Must run after ObjectDeclMap since it can add TArrayDecl expressions
  8672. *)
  8673. module ArrayDeclSynf =
  8674. struct
  8675. let name = "array_decl_synf"
  8676. let priority = solve_deps name [DAfter ObjectDeclMap.priority]
  8677. let default_implementation gen native_array_cl =
  8678. let rec run e =
  8679. match e.eexpr with
  8680. | TArrayDecl el ->
  8681. let cl, params = match follow e.etype with
  8682. | TInst(({ cl_path = ([], "Array") } as cl), ( _ :: _ as params)) -> cl, params
  8683. | TInst(({ cl_path = ([], "Array") } as cl), []) -> cl, [t_dynamic]
  8684. | _ -> assert false
  8685. in
  8686. let changed_params = gen.greal_type_param (TClassDecl cl) params in
  8687. { e with eexpr = TNew(cl, changed_params, [ { e with eexpr = TArrayDecl(List.map run el); etype = TInst(native_array_cl, changed_params) } ] ); }
  8688. | _ -> Type.map_expr run e
  8689. in
  8690. run
  8691. let configure gen (mapping_func:texpr->texpr) =
  8692. let map e = Some(mapping_func e) in
  8693. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  8694. end;;
  8695. (* ******************************************* *)
  8696. (* SwitchBreakSynf *)
  8697. (* ******************************************* *)
  8698. (*
  8699. In most languages, 'break' is used as a statement also to break from switch statements.
  8700. This generates an incompatibility with haxe code, as we can use break to break from loops from inside a switch
  8701. This script will detect 'breaks' inside switch statements, and will offer the opportunity to change both
  8702. when this pattern is found.
  8703. Some options are possible:
  8704. On languages that support goto, 'break' may mean goto " after the loop ". There also can be special labels for
  8705. loops, so you can write "break label" (javascript, java, d)
  8706. On languages that do not support goto, a custom solution must be enforced
  8707. dependencies:
  8708. Since UnreachableCodeElimination must run before it, and Unreachable should be one of the
  8709. very last filters to run, we will make a fixed value which runs after UnreachableCodeElimination
  8710. (meaning: it's the very last filter)
  8711. *)
  8712. module SwitchBreakSynf =
  8713. struct
  8714. let name = "switch_break_synf"
  8715. let priority = min_dep -. 150.0
  8716. type add_to_block_api = texpr->bool->unit
  8717. let traverse gen (change_loop:texpr->int->add_to_block_api->texpr) (change_break:texpr->int->add_to_block_api->texpr) =
  8718. let in_switch = ref false in
  8719. let cur_block = ref [] in
  8720. let to_add = ref [] in
  8721. let did_found = ref (-1) in
  8722. let api expr before =
  8723. if before then cur_block := expr :: !cur_block else to_add := expr :: !to_add
  8724. in
  8725. let num = ref 0 in
  8726. let cur_num = ref 0 in
  8727. let rec run e =
  8728. match e.eexpr with
  8729. | TFunction _ ->
  8730. let old_num = !num in
  8731. num := 0;
  8732. let ret = Type.map_expr run e in
  8733. num := old_num;
  8734. ret
  8735. | TFor _
  8736. | TWhile _ ->
  8737. let last_switch = !in_switch in
  8738. let last_found = !did_found in
  8739. let last_num = !cur_num in
  8740. in_switch := false;
  8741. incr num;
  8742. cur_num := !num;
  8743. did_found := -1;
  8744. let new_e = Type.map_expr run e in (* assuming that no loop will be found in the condition *)
  8745. let new_e = if !did_found <> -1 then change_loop new_e !did_found api else new_e in
  8746. did_found := last_found;
  8747. in_switch := last_switch;
  8748. cur_num := last_num;
  8749. new_e
  8750. | TSwitch _ ->
  8751. let last_switch = !in_switch in
  8752. in_switch := true;
  8753. let new_e = Type.map_expr run e in
  8754. in_switch := last_switch;
  8755. new_e
  8756. | TBlock bl ->
  8757. let last_block = !cur_block in
  8758. let last_toadd = !to_add in
  8759. to_add := [];
  8760. cur_block := [];
  8761. List.iter (fun e ->
  8762. let new_e = run e in
  8763. cur_block := new_e :: !cur_block;
  8764. match !to_add with
  8765. | [] -> ()
  8766. | _ -> cur_block := !to_add @ !cur_block; to_add := []
  8767. ) bl;
  8768. let ret = List.rev !cur_block in
  8769. cur_block := last_block;
  8770. to_add := last_toadd;
  8771. { e with eexpr = TBlock(ret) }
  8772. | TBreak ->
  8773. if !in_switch then (did_found := !cur_num; change_break e !cur_num api) else e
  8774. | _ -> Type.map_expr run e
  8775. in
  8776. run
  8777. let configure gen (mapping_func:texpr->texpr) =
  8778. let map e = Some(mapping_func e) in
  8779. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  8780. end;;
  8781. (* ******************************************* *)
  8782. (* Unreachable Code Elimination *)
  8783. (* ******************************************* *)
  8784. (*
  8785. In some source code platforms, the code won't compile if there is Unreachable code, so this filter will take off any unreachable code.
  8786. If the parameter "handle_switch_break" is set to true, it will already add a "break" statement on switch cases when suitable;
  8787. in order to not confuse with while break, it will be a special expression __sbreak__
  8788. 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.
  8789. (Will respect __fallback__ expressions)
  8790. If the parameter "java_mode" is set to true, some additional checks following the java unreachable specs
  8791. (http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21) will be added
  8792. dependencies:
  8793. This must run before SwitchBreakSynf (see SwitchBreakSynf dependecy value)
  8794. 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
  8795. *)
  8796. module UnreachableCodeEliminationSynf =
  8797. struct
  8798. let name = "unreachable_synf"
  8799. let priority = min_dep -. 100.0
  8800. type uexpr_kind =
  8801. | Normal
  8802. | BreaksLoop
  8803. | BreaksFunction
  8804. let aggregate_kind e1 e2 =
  8805. match e1, e2 with
  8806. | Normal, _
  8807. | _, Normal -> Normal
  8808. | BreaksLoop, _
  8809. | _, BreaksLoop -> BreaksLoop
  8810. | BreaksFunction, BreaksFunction -> BreaksFunction
  8811. let aggregate_constant op c1 c2=
  8812. match op, c1, c2 with
  8813. | OpEq, Some v1, Some v2 -> Some (TBool (v1 = v2))
  8814. | OpNotEq, Some v1, Some v2 -> Some (TBool (v1 <> v2))
  8815. | OpBoolOr, Some (TBool v1) , Some (TBool v2) -> Some (TBool (v1 || v2))
  8816. | OpBoolAnd, Some (TBool v1) , Some (TBool v2) -> Some (TBool (v1 && v2))
  8817. | OpAssign, _, Some v2 -> Some v2
  8818. | _ -> None
  8819. let rec get_constant_expr e =
  8820. match e.eexpr with
  8821. | TConst (v) -> Some v
  8822. | TBinop(op, v1, v2) -> aggregate_constant op (get_constant_expr v1) (get_constant_expr v2)
  8823. | TParenthesis(e) | TMeta(_,e) -> get_constant_expr e
  8824. | _ -> None
  8825. let traverse gen should_warn handle_switch_break handle_not_final_returns java_mode =
  8826. let basic = gen.gcon.basic in
  8827. let do_warn =
  8828. if should_warn then gen.gcon.warning "Unreachable code" else (fun pos -> ())
  8829. in
  8830. let return_loop expr kind =
  8831. match kind with
  8832. | Normal | BreaksLoop -> expr, Normal
  8833. | _ -> expr, kind
  8834. in
  8835. let sbreak = alloc_var "__sbreak__" t_dynamic in
  8836. let mk_sbreak = mk_local sbreak in
  8837. let rec has_fallback expr = match expr.eexpr with
  8838. | TBlock(bl) -> (match List.rev bl with
  8839. | { eexpr = TLocal { v_name = "__fallback__" } } :: _ -> true
  8840. | ({ eexpr = TBlock(_) } as bl) :: _ -> has_fallback bl
  8841. | _ -> false)
  8842. | TLocal { v_name = "__fallback__" } -> true
  8843. | _ -> false
  8844. in
  8845. let handle_case = if handle_switch_break then
  8846. (fun (expr,kind) ->
  8847. match kind with
  8848. | Normal when has_fallback expr -> expr
  8849. | Normal -> Type.concat expr (mk_sbreak expr.epos)
  8850. | BreaksLoop | BreaksFunction -> expr
  8851. )
  8852. else
  8853. fst
  8854. in
  8855. let has_break = ref false in
  8856. let rec process_expr expr =
  8857. match expr.eexpr with
  8858. | TReturn _ | TThrow _ -> expr, BreaksFunction
  8859. | TContinue -> expr, BreaksLoop
  8860. | TBreak -> has_break := true; expr, BreaksLoop
  8861. | TCall( { eexpr = TLocal { v_name = "__goto__" } }, _ ) -> expr, BreaksLoop
  8862. | TBlock bl ->
  8863. let new_block = ref [] in
  8864. let is_unreachable = ref false in
  8865. let ret_kind = ref Normal in
  8866. List.iter (fun e ->
  8867. if !is_unreachable then
  8868. do_warn e.epos
  8869. else begin
  8870. let changed_e, kind = process_expr e in
  8871. new_block := changed_e :: !new_block;
  8872. match kind with
  8873. | BreaksLoop | BreaksFunction ->
  8874. ret_kind := kind;
  8875. is_unreachable := true
  8876. | _ -> ()
  8877. end
  8878. ) bl;
  8879. { expr with eexpr = TBlock(List.rev !new_block) }, !ret_kind
  8880. | TFunction tf ->
  8881. let changed, kind = process_expr tf.tf_expr in
  8882. let changed = if handle_not_final_returns && not (is_void tf.tf_type) && kind <> BreaksFunction then
  8883. Type.concat changed { eexpr = TReturn( Some (null tf.tf_type expr.epos) ); etype = basic.tvoid; epos = expr.epos }
  8884. else
  8885. changed
  8886. in
  8887. { expr with eexpr = TFunction({ tf with tf_expr = changed }) }, Normal
  8888. | TFor(var, cond, block) ->
  8889. let last_has_break = !has_break in
  8890. has_break := false;
  8891. let changed_block, _ = process_expr block in
  8892. has_break := last_has_break;
  8893. let expr = { expr with eexpr = TFor(var, cond, changed_block) } in
  8894. return_loop expr Normal
  8895. | TIf(cond, eif, None) ->
  8896. if java_mode then
  8897. match get_constant_expr cond with
  8898. | Some (TBool true) ->
  8899. process_expr eif
  8900. | _ ->
  8901. { expr with eexpr = TIf(cond, fst (process_expr eif), None) }, Normal
  8902. else
  8903. { expr with eexpr = TIf(cond, fst (process_expr eif), None) }, Normal
  8904. | TIf(cond, eif, Some eelse) ->
  8905. let eif, eif_k = process_expr eif in
  8906. let eelse, eelse_k = process_expr eelse in
  8907. let k = aggregate_kind eif_k eelse_k in
  8908. { expr with eexpr = TIf(cond, eif, Some eelse) }, k
  8909. | TWhile(cond, block, flag) ->
  8910. let last_has_break = !has_break in
  8911. has_break := false;
  8912. let block, k = process_expr block in
  8913. if java_mode then
  8914. match get_constant_expr cond, flag, !has_break with
  8915. | Some (TBool true), _, false ->
  8916. has_break := last_has_break;
  8917. { expr with eexpr = TWhile(cond, block, flag) }, BreaksFunction
  8918. | Some (TBool false), NormalWhile, _ ->
  8919. has_break := last_has_break;
  8920. do_warn expr.epos;
  8921. null expr.etype expr.epos, Normal
  8922. | _ ->
  8923. has_break := last_has_break;
  8924. return_loop { expr with eexpr = TWhile(cond,block,flag) } Normal
  8925. else begin
  8926. has_break := last_has_break;
  8927. return_loop { expr with eexpr = TWhile(cond,block,flag) } Normal
  8928. end
  8929. | TSwitch(cond, el_e_l, None) ->
  8930. { expr with eexpr = TSwitch(cond, List.map (fun (el, e) -> (el, handle_case (process_expr e))) el_e_l, None) }, Normal
  8931. | TSwitch(cond, el_e_l, Some def) ->
  8932. let def, k = process_expr def in
  8933. let def = handle_case (def, k) in
  8934. let k = ref k in
  8935. let ret = { expr with eexpr = TSwitch(cond, List.map (fun (el, e) ->
  8936. let e, ek = process_expr e in
  8937. k := aggregate_kind !k ek;
  8938. (el, handle_case (e, ek))
  8939. ) el_e_l, Some def) } in
  8940. ret, !k
  8941. (* | TMatch(cond, ep, il_vopt_e_l, None) ->
  8942. { 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 *)
  8943. (* | TMatch(cond, ep, il_vopt_e_l, Some def) ->
  8944. let def, k = process_expr def in
  8945. let def = handle_case (def, k) in
  8946. let k = ref k in
  8947. let ret = { expr with eexpr = TMatch(cond, ep, List.map (fun (il, vopt, e) ->
  8948. let e, ek = process_expr e in
  8949. k := aggregate_kind !k ek;
  8950. (il, vopt, handle_case (e, ek))
  8951. ) il_vopt_e_l, Some def) } in
  8952. ret, !k *)
  8953. | TTry (e, catches) ->
  8954. let e, k = process_expr e in
  8955. let k = ref k in
  8956. let ret = { expr with eexpr = TTry(e, List.map (fun (v, e) ->
  8957. let e, ek = process_expr e in
  8958. k := aggregate_kind !k ek;
  8959. (v, e)
  8960. ) catches) } in
  8961. ret, !k
  8962. | _ -> expr, Normal
  8963. in
  8964. let run e = fst (process_expr e) in
  8965. run
  8966. let configure gen (mapping_func:texpr->texpr) =
  8967. let map e = Some(mapping_func e) in
  8968. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  8969. end;;
  8970. (* ******************************************* *)
  8971. (* DefaultArguments *)
  8972. (* ******************************************* *)
  8973. (*
  8974. This Module Filter will go through all defined functions in all modules and change them
  8975. so they set all default arguments to be of a Nullable type, and adds the unroll from nullable to
  8976. the not-nullable type in the beginning of the function.
  8977. dependencies:
  8978. It must run before OverloadingCtors, since OverloadingCtors will change optional structures behavior
  8979. *)
  8980. module DefaultArguments =
  8981. struct
  8982. let name = "default_arguments"
  8983. let priority = solve_deps name [ DBefore OverloadingConstructor.priority ]
  8984. let gen_check basic t nullable_var const pos =
  8985. let is_null t = match t with TType({t_path = ([],"Null")}, _) -> true | _ -> false in
  8986. let needs_cast t1 t2 = match is_null t1, is_null t2 with
  8987. | true, false | false, true -> true
  8988. | _ -> false
  8989. in
  8990. let const_t = match const with
  8991. | TString _ -> basic.tstring | TInt _ -> basic.tint | TFloat _ -> basic.tfloat
  8992. | TNull -> t | TBool _ -> basic.tbool | _ -> assert false
  8993. in
  8994. let const = { eexpr = TConst(const); etype = const_t; epos = pos } in
  8995. let const = if needs_cast t const_t then mk_cast t const else const in
  8996. let arg = mk_local nullable_var pos in
  8997. let arg = if needs_cast t nullable_var.v_type then mk_cast t arg else arg in
  8998. {
  8999. eexpr = TIf(
  9000. { eexpr = TBinop(Ast.OpEq, mk_local nullable_var pos, null nullable_var.v_type pos); etype = basic.tbool; epos = pos },
  9001. const,
  9002. Some(arg)
  9003. );
  9004. etype = t;
  9005. epos = pos;
  9006. }
  9007. let add_opt gen block pos (var,opt) =
  9008. match opt with
  9009. | None | Some TNull -> (var,opt)
  9010. | Some (TString str) ->
  9011. block := Codegen.set_default gen.gcon var (TString str) pos :: !block;
  9012. (var, opt)
  9013. | Some const ->
  9014. let basic = gen.gcon.basic in
  9015. let nullable_var = mk_temp gen var.v_name (basic.tnull var.v_type) in
  9016. let orig_name = var.v_name in
  9017. var.v_name <- nullable_var.v_name;
  9018. nullable_var.v_name <- orig_name;
  9019. (* var v = (temp_var == null) ? const : cast temp_var; *)
  9020. block :=
  9021. {
  9022. eexpr = TVar(var, Some(gen_check basic var.v_type nullable_var const pos));
  9023. etype = basic.tvoid;
  9024. epos = pos;
  9025. } :: !block;
  9026. (nullable_var, opt)
  9027. let rec change_func gen cf =
  9028. List.iter (change_func gen) cf.cf_overloads;
  9029. let is_ctor = cf.cf_name = "new" in
  9030. let basic = gen.gcon.basic in
  9031. match cf.cf_kind, follow cf.cf_type with
  9032. | Var _, _ | Method MethDynamic, _ -> ()
  9033. | _, TFun(args, ret) ->
  9034. let found = ref false in
  9035. let args = ref (List.map (fun (n,opt,t) ->
  9036. (n,opt, if opt then (found := true; basic.tnull t) else t)
  9037. ) args) in
  9038. (match !found, cf.cf_expr with
  9039. | true, Some ({ eexpr = TFunction tf } as texpr) ->
  9040. let block = ref [] in
  9041. let tf_args = List.map (add_opt gen block tf.tf_expr.epos) tf.tf_args in
  9042. let arg_assoc = List.map2 (fun (v,o) (v2,_) -> v,(v2,o) ) tf.tf_args tf_args in
  9043. let rec extract_super e = match e.eexpr with
  9044. | TBlock(({ eexpr = TCall({ eexpr = TConst TSuper }, _) } as e2) :: tl) ->
  9045. e2, tl
  9046. | TBlock(hd :: tl) ->
  9047. let e2, tl2 = extract_super hd in
  9048. e2, tl2 @ tl
  9049. | _ -> raise Not_found
  9050. in
  9051. let block = try
  9052. if not is_ctor then raise Not_found;
  9053. (* issue #2570 *)
  9054. (* check if the class really needs the super as the first statement -
  9055. just to make sure we don't inadvertently break any existing code *)
  9056. let rec check cl =
  9057. if not (is_hxgen (TClassDecl cl)) then
  9058. ()
  9059. else match cl.cl_super with
  9060. | None ->
  9061. raise Not_found
  9062. | Some (cl,_) ->
  9063. check cl
  9064. in
  9065. (match gen.gcurrent_class with
  9066. | Some cl -> check cl
  9067. | _ -> ());
  9068. let super, tl = extract_super tf.tf_expr in
  9069. (match super.eexpr with
  9070. | TCall({ eexpr = TConst TSuper } as e1, args) ->
  9071. (* any super argument will be replaced by an inlined version of the check *)
  9072. let found = ref false in
  9073. let rec replace_args e = match e.eexpr with
  9074. | TLocal(v) -> (try
  9075. let v2,o = List.assq v arg_assoc in
  9076. let o = match o with
  9077. | None -> raise Not_found
  9078. | Some o -> o
  9079. in
  9080. found := true;
  9081. gen_check gen.gcon.basic v.v_type v2 o e.epos
  9082. with | Not_found -> e)
  9083. | _ -> Type.map_expr replace_args e
  9084. in
  9085. let args = List.map (replace_args) args in
  9086. { tf.tf_expr with eexpr = TBlock((if !found then { super with eexpr = TCall(e1,args) } else super) :: !block @ tl) }
  9087. | _ -> assert false)
  9088. with | Not_found ->
  9089. Type.concat { tf.tf_expr with eexpr = TBlock(!block); etype = basic.tvoid } tf.tf_expr
  9090. in
  9091. args := fun_args tf_args;
  9092. cf.cf_expr <- Some( {texpr with eexpr = TFunction( { tf with
  9093. tf_args = tf_args;
  9094. tf_expr = block
  9095. } ); etype = TFun(!args, ret) } );
  9096. cf.cf_type <- TFun(!args, ret)
  9097. | _ -> ()
  9098. );
  9099. (if !found then cf.cf_type <- TFun(!args, ret))
  9100. | _, _ -> assert false
  9101. let traverse gen =
  9102. let run md = match md with
  9103. | TClassDecl cl ->
  9104. List.iter (change_func gen) cl.cl_ordered_fields;
  9105. List.iter (change_func gen) cl.cl_ordered_statics;
  9106. (match cl.cl_constructor with | None -> () | Some cf -> change_func gen cf);
  9107. md
  9108. | _ -> md
  9109. in
  9110. run
  9111. let configure gen (mapping_func:module_type->module_type) =
  9112. let map md = Some(mapping_func md) in
  9113. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  9114. end;;
  9115. (* ******************************************* *)
  9116. (* Interface Variables Removal Modf *)
  9117. (* ******************************************* *)
  9118. (*
  9119. This module filter will take care of sanitizing interfaces for targets that do not support
  9120. variables declaration in interfaces. By now this will mean that if anything is typed as the interface,
  9121. and a variable access is made, a FNotFound will be returned for the field_access, so
  9122. the field will be only accessible by reflection.
  9123. Speed-wise, ideally it would be best to create getProp/setProp functions in this case and change
  9124. the AST to call them when accessing by interface. (TODO)
  9125. But right now it will be accessed by reflection.
  9126. dependencies:
  9127. *)
  9128. module InterfaceVarsDeleteModf =
  9129. struct
  9130. let name = "interface_vars"
  9131. let priority = solve_deps name []
  9132. let run gen =
  9133. let run md = match md with
  9134. | TClassDecl ( { cl_interface = true } as cl ) ->
  9135. let to_add = ref [] in
  9136. let fields = List.filter (fun cf ->
  9137. match cf.cf_kind with
  9138. | Var _ when gen.gcon.platform = Cs && Meta.has Meta.Event cf.cf_meta ->
  9139. true
  9140. | Var vkind when not (Type.is_extern_field cf && Meta.has Meta.Property cf.cf_meta) ->
  9141. (match vkind.v_read with
  9142. | AccCall ->
  9143. let newcf = mk_class_field ("get_" ^ cf.cf_name) (TFun([],cf.cf_type)) true cf.cf_pos (Method MethNormal) [] in
  9144. to_add := newcf :: !to_add;
  9145. | _ -> ()
  9146. );
  9147. (match vkind.v_write with
  9148. | AccCall ->
  9149. 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
  9150. to_add := newcf :: !to_add;
  9151. | _ -> ()
  9152. );
  9153. cl.cl_fields <- PMap.remove cf.cf_name cl.cl_fields;
  9154. false
  9155. | Method MethDynamic ->
  9156. (* TODO OPTIMIZATION - add a `_dispatch` method to the interface which will call the dynamic function itself *)
  9157. cl.cl_fields <- PMap.remove cf.cf_name cl.cl_fields;
  9158. false
  9159. | _ -> true
  9160. ) cl.cl_ordered_fields in
  9161. cl.cl_ordered_fields <- fields;
  9162. List.iter (fun cf ->
  9163. match field_access gen (TInst(cl,List.map snd cl.cl_params)) cf.cf_name with
  9164. | FNotFound | FDynamicField _ ->
  9165. cl.cl_ordered_fields <- cf :: cl.cl_ordered_fields;
  9166. cl.cl_fields <- PMap.add cf.cf_name cf cl.cl_fields
  9167. | _ -> ()
  9168. ) !to_add;
  9169. md
  9170. | _ -> md
  9171. in
  9172. run
  9173. let configure gen =
  9174. let run = run gen in
  9175. let map md = Some(run md) in
  9176. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  9177. end;;
  9178. (* ******************************************* *)
  9179. (* InterfaceProps *)
  9180. (* ******************************************* *)
  9181. (*
  9182. This module filter will go through all declared properties, and see if they are conforming to a native interface.
  9183. If they are, it will add Meta.Property to it
  9184. dependencies:
  9185. *)
  9186. module InterfaceProps =
  9187. struct
  9188. let name = "interface_props"
  9189. let priority = solve_deps name []
  9190. let run gen =
  9191. let run md = match md with
  9192. | TClassDecl ( { cl_interface = false; cl_extern = false } as cl ) ->
  9193. let vars = List.fold_left (fun acc (iface,_) ->
  9194. if Meta.has Meta.CsNative iface.cl_meta then
  9195. List.filter (fun cf -> match cf.cf_kind with
  9196. | Var { v_read = AccCall } | Var { v_write = AccCall } ->
  9197. true
  9198. | _ -> false
  9199. ) iface.cl_ordered_fields @ acc
  9200. else
  9201. acc
  9202. ) [] cl.cl_implements in
  9203. let vars = List.map (fun cf -> cf.cf_name) vars in
  9204. if vars <> [] then
  9205. List.iter (fun cf -> match cf.cf_kind with
  9206. | Var { v_read = AccCall } | Var { v_write = AccCall } when List.mem cf.cf_name vars ->
  9207. cf.cf_meta <- (Meta.Property, [], Ast.null_pos) :: cf.cf_meta
  9208. | _ -> ()
  9209. ) cl.cl_ordered_fields;
  9210. md
  9211. | _ -> md
  9212. in
  9213. run
  9214. let configure gen =
  9215. let run = run gen in
  9216. let map md = Some(run md) in
  9217. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  9218. end;;
  9219. (* ******************************************* *)
  9220. (* Int Division Synf *)
  9221. (* ******************************************* *)
  9222. (*
  9223. On targets that support int division, this module will force a float division to be performed,
  9224. so compatibility with current haxe targets is ensured.
  9225. If catch_int_div is set to true, though, it will look for casts to int or use of Std.int() to optimize
  9226. this kind of operation.
  9227. dependencies:
  9228. since it depends on nothing, but many modules might generate division expressions,
  9229. it will be one of the last modules to run
  9230. *)
  9231. module IntDivisionSynf =
  9232. struct
  9233. let name = "int_division_synf"
  9234. let priority = solve_deps name [ DAfter ExpressionUnwrap.priority; DAfter ObjectDeclMap.priority; DAfter ArrayDeclSynf.priority ]
  9235. let is_int = like_int
  9236. let is_exactly_int t = match follow t with
  9237. | TAbstract ({ a_path=[],"Int" }, []) -> true
  9238. | _ -> false
  9239. let default_implementation gen catch_int_div =
  9240. let basic = gen.gcon.basic in
  9241. let rec run e =
  9242. match e.eexpr with
  9243. | TBinop((Ast.OpDiv as op), e1, e2) when is_int e1.etype && is_int e2.etype ->
  9244. { e with eexpr = TBinop(op, mk_cast basic.tfloat (run e1), run e2) }
  9245. | TCall(
  9246. { eexpr = TField(_, FStatic({ cl_path = ([], "Std") }, { cf_name = "int" })) },
  9247. [ ({ eexpr = TBinop((Ast.OpDiv as op), e1, e2) } as ebinop ) ]
  9248. ) when catch_int_div && is_int e1.etype && is_int e2.etype ->
  9249. let e = { ebinop with eexpr = TBinop(op, run e1, run e2); etype = basic.tint } in
  9250. if not (is_exactly_int e1.etype && is_exactly_int e2.etype) then
  9251. mk_cast basic.tint e
  9252. else
  9253. e
  9254. | TCast( ({ eexpr = TBinop((Ast.OpDiv as op), e1, e2) } as ebinop ), _ )
  9255. | 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 ->
  9256. let ret = { ebinop with eexpr = TBinop(op, run e1, run e2); etype = e.etype } in
  9257. if not (is_exactly_int e1.etype && is_exactly_int e2.etype) then
  9258. mk_cast e.etype ret
  9259. else
  9260. e
  9261. | _ -> Type.map_expr run e
  9262. in
  9263. run
  9264. let configure gen (mapping_func:texpr->texpr) =
  9265. let map e = Some(mapping_func e) in
  9266. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  9267. end;;
  9268. (* ******************************************* *)
  9269. (* UnnecessaryCastsRemoval *)
  9270. (* ******************************************* *)
  9271. (*
  9272. This module will take care of simplifying unnecessary casts, specially those made by the compiler
  9273. when inlining. Right now, it will only take care of casts used as a statement, which are always useless;
  9274. TODO: Take care of more cases, e.g. when the to and from types are the same
  9275. dependencies:
  9276. This must run after CastDetection, but before ExpressionUnwrap
  9277. *)
  9278. module UnnecessaryCastsRemoval =
  9279. struct
  9280. let name = "casts_removal"
  9281. let priority = solve_deps name [DAfter CastDetect.priority; DBefore ExpressionUnwrap.priority]
  9282. let rec take_off_cast run e =
  9283. match e.eexpr with
  9284. | TCast (c, _) ->
  9285. take_off_cast run c
  9286. | _ -> run e
  9287. let default_implementation gen =
  9288. let rec traverse e =
  9289. match e.eexpr with
  9290. | TBlock bl ->
  9291. let bl = List.map (fun e ->
  9292. take_off_cast traverse e
  9293. ) bl in
  9294. { e with eexpr = TBlock bl }
  9295. | TTry (block, catches) ->
  9296. { e with eexpr = TTry(traverse (mk_block block), List.map (fun (v,block) -> (v, traverse (mk_block block))) catches) }
  9297. (* | TMatch (cond,ep,il_vol_e_l,default) ->
  9298. { 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) } *)
  9299. | TSwitch (cond,el_e_l, default) ->
  9300. { 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) }
  9301. | TWhile (cond,block,flag) ->
  9302. {e with eexpr = TWhile(cond,traverse (mk_block block), flag) }
  9303. | TIf (cond, eif, eelse) ->
  9304. { e with eexpr = TIf(cond, traverse (mk_block eif), Option.map (fun e -> traverse (mk_block e)) eelse) }
  9305. | TFor (v,it,block) ->
  9306. { e with eexpr = TFor(v,it, traverse (mk_block block)) }
  9307. | TFunction (tfunc) ->
  9308. { e with eexpr = TFunction({ tfunc with tf_expr = traverse (mk_block tfunc.tf_expr) }) }
  9309. | _ -> e (* if expression doesn't have a block, we will exit *)
  9310. in
  9311. traverse
  9312. let configure gen =
  9313. let map e = Some(default_implementation gen e) in
  9314. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  9315. end;;
  9316. (* ******************************************* *)
  9317. (* OverrideFix *)
  9318. (* ******************************************* *)
  9319. (*
  9320. When DCE is on, sometimes a field is marked as override when it
  9321. really doesn't override anything. This module filter will take care of this.
  9322. dependencies:
  9323. No dependencies
  9324. *)
  9325. module OverrideFix =
  9326. struct
  9327. let name = "override_fix"
  9328. let priority = solve_deps name []
  9329. let default_implementation gen =
  9330. let rec run e =
  9331. match e.eexpr with
  9332. | _ -> Type.map_expr run e
  9333. in
  9334. run
  9335. let configure gen =
  9336. let map md =
  9337. match md with
  9338. | TClassDecl cl ->
  9339. cl.cl_overrides <- List.filter (fun s ->
  9340. let rec loop cl =
  9341. match cl.cl_super with
  9342. | Some (cl,_) when PMap.mem s.cf_name cl.cl_fields -> true
  9343. | Some (cl,_) -> loop cl
  9344. | None -> false
  9345. in
  9346. loop cl
  9347. ) cl.cl_overrides;
  9348. Some md
  9349. | _ -> Some md
  9350. in
  9351. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  9352. end;;
  9353. (* ******************************************* *)
  9354. (* AbstractImplementationFix *)
  9355. (* ******************************************* *)
  9356. (*
  9357. This module filter will map the compiler created classes from abstract
  9358. implementations to valid haxe code, as needed by gencommon
  9359. dependencies:
  9360. No dependencies
  9361. *)
  9362. module AbstractImplementationFix =
  9363. struct
  9364. let name = "abstract_implementation_fix"
  9365. let priority = solve_deps name []
  9366. let default_implementation gen =
  9367. let rec run md =
  9368. match md with
  9369. | TClassDecl ({ cl_kind = KAbstractImpl a } as c) ->
  9370. List.iter (function
  9371. | cf when Meta.has Meta.Impl cf.cf_meta ->
  9372. (* add type parameters to all implementation functions *)
  9373. cf.cf_params <- cf.cf_params @ a.a_params
  9374. | _ -> ()
  9375. ) c.cl_ordered_statics;
  9376. Some md
  9377. | _ -> Some md
  9378. in
  9379. run
  9380. let configure gen =
  9381. let map = default_implementation gen in
  9382. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  9383. end;;
  9384. (* ******************************************* *)
  9385. (* FixOverrides *)
  9386. (* ******************************************* *)
  9387. (*
  9388. Covariant return types, contravariant function arguments and applied type parameters may change
  9389. in a way that expected implementations / overrides aren't recognized as such.
  9390. This filter will fix that.
  9391. dependencies:
  9392. FixOverrides expects that the target platform is able to deal with overloaded functions
  9393. It must run after DefaultArguments, otherwise code added by the default arguments may be invalid
  9394. *)
  9395. module FixOverrides =
  9396. struct
  9397. let name = "fix_overrides"
  9398. let priority = solve_deps name [DAfter DefaultArguments.priority]
  9399. (*
  9400. if the platform allows explicit interface implementation (C#),
  9401. specify a explicit_fn_name function (tclass->string->string)
  9402. Otherwise, it expects the platform to be able to handle covariant return types
  9403. *)
  9404. let run ~explicit_fn_name gen =
  9405. let implement_explicitly = is_some explicit_fn_name in
  9406. let run md = match md with
  9407. | TClassDecl ( { cl_interface = true; cl_extern = false } as c ) ->
  9408. (* overrides can be removed from interfaces *)
  9409. c.cl_ordered_fields <- List.filter (fun f ->
  9410. try
  9411. if Meta.has Meta.Overload f.cf_meta then raise Not_found;
  9412. let f2 = Codegen.find_field gen.gcon c f in
  9413. if f2 == f then raise Not_found;
  9414. c.cl_fields <- PMap.remove f.cf_name c.cl_fields;
  9415. false;
  9416. with Not_found ->
  9417. true
  9418. ) c.cl_ordered_fields;
  9419. md
  9420. | TClassDecl({ cl_extern = false } as c) ->
  9421. let this = { eexpr = TConst TThis; etype = TInst(c,List.map snd c.cl_params); epos = c.cl_pos } in
  9422. (* look through all interfaces, and try to find a type that applies exactly *)
  9423. let rec loop_iface (iface:tclass) itl =
  9424. List.iter (fun (s,stl) -> loop_iface s (List.map (apply_params iface.cl_params itl) stl)) iface.cl_implements;
  9425. let real_itl = gen.greal_type_param (TClassDecl iface) itl in
  9426. let rec loop_f f =
  9427. List.iter loop_f f.cf_overloads;
  9428. let ftype = apply_params iface.cl_params itl f.cf_type in
  9429. let real_ftype = get_real_fun gen (apply_params iface.cl_params real_itl f.cf_type) in
  9430. replace_mono real_ftype;
  9431. let overloads = Typeload.get_overloads c f.cf_name in
  9432. try
  9433. let t2, f2 =
  9434. match overloads with
  9435. | (_, cf) :: _ when Meta.has Meta.Overload cf.cf_meta -> (* overloaded function *)
  9436. (* try to find exact function *)
  9437. List.find (fun (t,f2) ->
  9438. Typeload.same_overload_args ftype t f f2
  9439. ) overloads
  9440. | _ :: _ ->
  9441. (match field_access gen (TInst(c, List.map snd c.cl_params)) f.cf_name with
  9442. | FClassField(_,_,_,f2,false,t,_) -> t,f2 (* if it's not an overload, all functions should have the same signature *)
  9443. | _ -> raise Not_found)
  9444. | [] -> raise Not_found
  9445. in
  9446. replace_mono t2;
  9447. (* if we find a function with the exact type of real_ftype, it means this interface has already been taken care of *)
  9448. if not (type_iseq (get_real_fun gen (apply_params f2.cf_params (List.map snd f.cf_params) t2)) real_ftype) then begin
  9449. (match f.cf_kind with | Method (MethNormal | MethInline) -> () | _ -> raise Not_found);
  9450. let t2 = get_real_fun gen t2 in
  9451. if List.length f.cf_params <> List.length f2.cf_params then raise Not_found;
  9452. replace_mono t2;
  9453. match follow (apply_params f2.cf_params (List.map snd f.cf_params) t2), follow real_ftype with
  9454. | TFun(a1,r1), TFun(a2,r2) when not implement_explicitly && not (type_iseq r1 r2) && Typeload.same_overload_args real_ftype t2 f f2 ->
  9455. (* different return types are the trickiest cases to deal with *)
  9456. (* check for covariant return type *)
  9457. let is_covariant = match follow r1, follow r2 with
  9458. | _, TDynamic _ -> true
  9459. | r1, r2 -> try
  9460. unify r1 r2;
  9461. true
  9462. with | Unify_error _ -> false
  9463. in
  9464. (* we only have to worry about non-covariant issues *)
  9465. if not is_covariant then begin
  9466. (* override return type and cast implemented function *)
  9467. let args, newr = match follow t2, follow (apply_params f.cf_params (List.map snd f2.cf_params) real_ftype) with
  9468. | TFun(a,_), TFun(_,r) -> a,r
  9469. | _ -> assert false
  9470. in
  9471. f2.cf_type <- TFun(args,newr);
  9472. (match f2.cf_expr with
  9473. | Some ({ eexpr = TFunction tf } as e) ->
  9474. f2.cf_expr <- Some { e with eexpr = TFunction { tf with tf_type = newr } }
  9475. | _ -> ())
  9476. end
  9477. | TFun(a1,r1), TFun(a2,r2) ->
  9478. (* just implement a function that will call the main one *)
  9479. let name, is_explicit = match explicit_fn_name with
  9480. | Some fn when not (type_iseq r1 r2) && Typeload.same_overload_args real_ftype t2 f f2 ->
  9481. fn iface itl f.cf_name, true
  9482. | _ -> f.cf_name, false
  9483. in
  9484. let p = f2.cf_pos in
  9485. let newf = mk_class_field name real_ftype true f.cf_pos (Method MethNormal) f.cf_params in
  9486. let vars = List.map (fun (n,_,t) -> alloc_var n t) a2 in
  9487. let args = List.map2 (fun v (_,_,t) -> mk_cast t (mk_local v f2.cf_pos)) vars a1 in
  9488. let field = { eexpr = TField(this, FInstance(c,List.map snd c.cl_params,f2)); etype = TFun(a1,r1); epos = p } in
  9489. let call = { eexpr = TCall(field, args); etype = r1; epos = p } in
  9490. (* let call = gen.gparam_func_call call field (List.map snd f.cf_params) args in *)
  9491. let is_void = is_void r2 in
  9492. newf.cf_expr <- Some {
  9493. eexpr = TFunction({
  9494. tf_args = List.map (fun v -> v,None) vars;
  9495. tf_type = r2;
  9496. tf_expr = (if is_void then call else {
  9497. eexpr = TReturn (Some (mk_cast r2 call));
  9498. etype = r2;
  9499. epos = p
  9500. })
  9501. });
  9502. etype = real_ftype;
  9503. epos = p;
  9504. };
  9505. (* delayed: add to class *)
  9506. let delay () =
  9507. try
  9508. let fm = PMap.find f.cf_name c.cl_fields in
  9509. fm.cf_overloads <- newf :: fm.cf_overloads
  9510. with | Not_found ->
  9511. c.cl_fields <- PMap.add f.cf_name newf c.cl_fields;
  9512. c.cl_ordered_fields <- newf :: c.cl_ordered_fields
  9513. in
  9514. (* gen.gafter_filters_ended <- delay :: gen.gafter_filters_ended *)
  9515. delay();
  9516. | _ -> assert false
  9517. end
  9518. with | Not_found -> ()
  9519. in
  9520. List.iter (fun f -> match f.cf_kind with | Var _ -> () | _ -> loop_f f) iface.cl_ordered_fields
  9521. in
  9522. List.iter (fun (iface,itl) -> loop_iface iface itl) c.cl_implements;
  9523. (* now go through all overrides, *)
  9524. let rec check_f f =
  9525. (* find the first declared field *)
  9526. let is_overload = Meta.has Meta.Overload f.cf_meta in
  9527. let decl = if is_overload then
  9528. find_first_declared_field gen c ~exact_field:f f.cf_name
  9529. else
  9530. find_first_declared_field gen c f.cf_name
  9531. in
  9532. match decl with
  9533. | Some(f2,actual_t,_,t,declared_cl,_,_)
  9534. when not (Typeload.same_overload_args actual_t (get_real_fun gen f.cf_type) f2 f) ->
  9535. if Meta.has Meta.Overload f.cf_meta then begin
  9536. (* if it is overload, create another field with the requested type *)
  9537. let f3 = mk_class_field f.cf_name t f.cf_public f.cf_pos f.cf_kind f.cf_params in
  9538. let p = f.cf_pos in
  9539. let old_args, old_ret = get_fun f.cf_type in
  9540. let args, ret = get_fun t in
  9541. let tf_args = List.map (fun (n,o,t) -> alloc_var n t, None) args in
  9542. let f3_mk_return = if is_void ret then (fun e -> e) else (fun e -> mk_return (mk_cast ret e)) in
  9543. f3.cf_expr <- Some {
  9544. eexpr = TFunction({
  9545. tf_args = tf_args;
  9546. tf_type = ret;
  9547. tf_expr = mk_block (f3_mk_return {
  9548. eexpr = TCall(
  9549. {
  9550. eexpr = TField(
  9551. { eexpr = TConst TThis; etype = TInst(c, List.map snd c.cl_params); epos = p },
  9552. FInstance(c,List.map snd c.cl_params,f));
  9553. etype = f.cf_type;
  9554. epos = p
  9555. },
  9556. List.map2 (fun (v,_) (_,_,t) -> mk_cast t (mk_local v p)) tf_args old_args);
  9557. etype = old_ret;
  9558. epos = p
  9559. })
  9560. });
  9561. etype = t;
  9562. epos = p;
  9563. };
  9564. gen.gafter_filters_ended <- ((fun () ->
  9565. f.cf_overloads <- f3 :: f.cf_overloads;
  9566. ) :: gen.gafter_filters_ended);
  9567. f3
  9568. end else begin match f.cf_expr with
  9569. | Some({ eexpr = TFunction(tf) } as e) ->
  9570. (* if it's not overload, just cast the vars *)
  9571. let actual_args, _ = get_fun (get_real_fun gen actual_t) in
  9572. let new_args, vardecl = List.fold_left2 (fun (args,vdecl) (v,_) (_,_,t) ->
  9573. if not (type_iseq (gen.greal_type v.v_type) (gen.greal_type t)) then begin
  9574. let new_var = mk_temp gen v.v_name t in
  9575. (new_var,None) :: args, (v, Some(mk_cast v.v_type (mk_local new_var f.cf_pos))) :: vdecl
  9576. end else
  9577. (v,None) :: args, vdecl
  9578. ) ([],[]) tf.tf_args actual_args in
  9579. if vardecl <> [] then
  9580. f.cf_expr <- Some({ e with
  9581. eexpr = TFunction({ tf with
  9582. tf_args = List.rev new_args;
  9583. 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
  9584. });
  9585. });
  9586. f
  9587. | _ -> f
  9588. end
  9589. | _ -> f
  9590. in
  9591. if not c.cl_extern then
  9592. c.cl_overrides <- List.map (fun f -> check_f f) c.cl_overrides;
  9593. md
  9594. | _ -> md
  9595. in
  9596. run
  9597. let configure ?explicit_fn_name gen =
  9598. let delay () =
  9599. Hashtbl.clear gen.greal_field_types
  9600. in
  9601. gen.gafter_mod_filters_ended <- delay :: gen.gafter_mod_filters_ended;
  9602. let run = run ~explicit_fn_name:explicit_fn_name gen in
  9603. let map md = Some(run md) in
  9604. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  9605. end;;
  9606. (* ******************************************* *)
  9607. (* Normalize *)
  9608. (* ******************************************* *)
  9609. (*
  9610. - Filters out enum constructor type parameters from the AST; See Issue #1796
  9611. - Filters out monomorphs
  9612. - Filters out all non-whitelisted AST metadata
  9613. dependencies:
  9614. No dependencies; but it still should be one of the first filters to run,
  9615. as it will help normalize the AST
  9616. *)
  9617. module Normalize =
  9618. struct
  9619. let name = "normalize_type"
  9620. let priority = max_dep
  9621. let rec filter_param t = match t with
  9622. | TInst({ cl_kind = KTypeParameter _ } as c,_) when Meta.has Meta.EnumConstructorParam c.cl_meta ->
  9623. t_dynamic
  9624. | TMono r -> (match !r with
  9625. | None -> t_dynamic
  9626. | Some t -> filter_param t)
  9627. | TInst(_,[]) | TEnum(_,[]) | TType(_,[]) | TAbstract(_,[]) -> t
  9628. | TType(t,tl) -> TType(t,List.map filter_param tl)
  9629. | TInst(c,tl) -> TInst(c,List.map filter_param tl)
  9630. | TEnum(e,tl) -> TEnum(e,List.map filter_param tl)
  9631. | TAbstract(a,tl) when not (Meta.has Meta.CoreType a.a_meta) ->
  9632. filter_param (Abstract.get_underlying_type a tl)
  9633. | TAbstract(a,tl) -> TAbstract(a, List.map filter_param tl)
  9634. | TAnon a ->
  9635. TAnon {
  9636. a_fields = PMap.map (fun f -> { f with cf_type = filter_param f.cf_type }) a.a_fields;
  9637. a_status = a.a_status;
  9638. }
  9639. | TFun(args,ret) -> TFun(List.map (fun (n,o,t) -> (n,o,filter_param t)) args, filter_param ret)
  9640. | TDynamic _ -> t
  9641. | TLazy f -> filter_param (!f())
  9642. let default_implementation gen ~metas =
  9643. let rec run e =
  9644. match e.eexpr with
  9645. | TMeta(entry, e) when not (Hashtbl.mem metas entry) ->
  9646. run e
  9647. | _ ->
  9648. map_expr_type (fun e -> run e) filter_param (fun v -> v.v_type <- filter_param v.v_type; v) e
  9649. in
  9650. run
  9651. let default_implementation_module gen ~metas =
  9652. let rec run md = match md with
  9653. | TClassDecl cl ->
  9654. let rec map cf =
  9655. cf.cf_type <- filter_param cf.cf_type;
  9656. List.iter map cf.cf_overloads
  9657. in
  9658. List.iter map cl.cl_ordered_fields;
  9659. List.iter map cl.cl_ordered_statics;
  9660. Option.may map cl.cl_constructor;
  9661. md
  9662. | _ -> md
  9663. in
  9664. run
  9665. let configure gen ~metas =
  9666. let map e = Some(default_implementation gen e ~metas:metas) in
  9667. gen.gexpr_filters#add ~name:name ~priority:(PCustom priority) map;
  9668. let map md = Some(default_implementation_module gen ~metas md) in
  9669. gen.gmodule_filters#add ~name:name ~priority:(PCustom priority) map
  9670. end;;
  9671. (*
  9672. (* ******************************************* *)
  9673. (* Example *)
  9674. (* ******************************************* *)
  9675. (*
  9676. description
  9677. dependencies:
  9678. *)
  9679. module Example =
  9680. struct
  9681. let name = "example"
  9682. let priority = solve_deps name []
  9683. let default_implementation gen =
  9684. let rec run e =
  9685. match e.eexpr with
  9686. | _ -> Type.map_expr run e
  9687. in
  9688. run
  9689. let configure gen (mapping_func:texpr->texpr) =
  9690. let map e = Some(mapping_func e) in
  9691. gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
  9692. end;;
  9693. *)