BfCompiler.cpp 340 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041
  1. #pragma warning(disable:4996)
  2. #pragma warning(push)
  3. #pragma warning(disable:4800)
  4. #pragma warning(disable:4244)
  5. #pragma warning(disable:4141)
  6. #pragma warning(disable:4624)
  7. #pragma warning(disable:4146)
  8. #pragma warning(disable:4267)
  9. #pragma warning(disable:4291)
  10. #include "BeefySysLib/util/AllocDebug.h"
  11. #include "llvm/Support/Compiler.h"
  12. #include "BfCompiler.h"
  13. #include "BfSystem.h"
  14. #include "BfParser.h"
  15. #include "BfReducer.h"
  16. #include "BfExprEvaluator.h"
  17. #include "../Backend/BeLibManger.h"
  18. #include <fcntl.h>
  19. #include "BfConstResolver.h"
  20. #include "BfMangler.h"
  21. #include "BfDemangler.h"
  22. #include "BeefySysLib/util/PerfTimer.h"
  23. #include "BfSourceClassifier.h"
  24. #include "BfAutoComplete.h"
  25. #include "BfResolvePass.h"
  26. #include "BeefySysLib/util/BeefPerf.h"
  27. #include "BeefySysLib/util/ZipFile.h"
  28. #include "../LLVMUtils.h"
  29. #include "BfNamespaceVisitor.h"
  30. #include "CeMachine.h"
  31. #include "CeDebugger.h"
  32. #pragma warning(pop)
  33. namespace llvm
  34. {
  35. extern bool DebugFlag;
  36. }
  37. #define SPLIT_CONTEXTS
  38. Beefy::BfCompiler* gBfCompiler = NULL;
  39. void pt(llvm::Type* t)
  40. {
  41. //Beefy::OutputDebugStrF("pv((llvm::Type*)%p)\n", t);
  42. Beefy::debug_ostream os;
  43. t->print(os);
  44. os << "\n";
  45. os << " isSized: " << t->isSized() << "\n";
  46. os.flush();
  47. if (auto pointerType = llvm::dyn_cast<llvm::PointerType>(t))
  48. {
  49. Beefy::OutputDebugStrF("Element: ");
  50. pt(pointerType->getElementType());
  51. }
  52. }
  53. void ppt(llvm::Type* t)
  54. {
  55. auto pointerType = llvm::dyn_cast<llvm::PointerType>(t);
  56. if (pointerType == NULL)
  57. {
  58. Beefy::OutputDebugStrF("Not a pointer type");
  59. return;
  60. }
  61. pt(pointerType->getElementType());
  62. }
  63. void pt(llvm::DINode* t)
  64. {
  65. Beefy::debug_ostream os;
  66. t->print(os);
  67. os << "\n";
  68. os.flush();
  69. }
  70. void pt(llvm::Value* v)
  71. {
  72. pt(v->getType());
  73. }
  74. void pv(const llvm::Value* v)
  75. {
  76. Beefy::debug_ostream os;
  77. v->print(os);
  78. os << "\n";
  79. os.flush();
  80. pt(v->getType());
  81. }
  82. void ppt(llvm::Value* v)
  83. {
  84. ppt(v->getType());
  85. }
  86. void pmd(llvm::Metadata* md)
  87. {
  88. Beefy::debug_ostream os;
  89. md->print(os);
  90. os << "\n";
  91. os.flush();
  92. }
  93. void pdl(llvm::DebugLoc& dl)
  94. {
  95. Beefy::debug_ostream os;
  96. dl.print(os);
  97. os << "\n";
  98. os.flush();
  99. }
  100. void pm(llvm::Module* module)
  101. {
  102. Beefy::debug_ostream os;
  103. module->print(os, NULL);
  104. os << "\n";
  105. os.flush();
  106. }
  107. void PrintUsers(llvm::MDNode* md)
  108. {
  109. /*Beefy::debug_ostream os;
  110. //auto val = llvm::ReplaceableMetadataImpl::get(*md);
  111. auto val = md->Context.getReplaceableUses();
  112. if (val == NULL)
  113. {
  114. os << "Not replaceable\n";
  115. }
  116. else
  117. {
  118. //md->print(os);
  119. typedef std::pair<void *, std::pair<llvm::MetadataTracking::OwnerTy, uint64_t>> UseTy;
  120. llvm::SmallVector<UseTy, 8> Uses(val->UseMap.begin(), val->UseMap.end());
  121. std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
  122. return L.second.second < R.second.second;
  123. });
  124. for (const auto &Pair : Uses)
  125. {
  126. auto Owner = Pair.second.first;
  127. os << Beefy::StrFormat(" %d %p %d\n", Pair.second.first.isNull(), Pair.first, Pair.second.second, Pair).c_str();
  128. }
  129. os << "\n";
  130. }
  131. os.flush();*/
  132. }
  133. void ptbf(Beefy::BfType* bfType)
  134. {
  135. Beefy::OutputDebugStrF("%s\n", bfType->GetModule()->TypeToString(bfType).c_str());
  136. }
  137. void pt(const Beefy::BfTypedValue& val)
  138. {
  139. Beefy::OutputDebugStrF("%s\n", val.mType->GetModule()->TypeToString(val.mType).c_str());
  140. }
  141. void pt(llvm::SmallVectorImpl<llvm::Value*>& llvmArgs)
  142. {
  143. Beefy::debug_ostream os;
  144. for (int i = 0; i < (int)llvmArgs.size(); i++)
  145. {
  146. if (i > 0)
  147. os << ", ";
  148. llvmArgs[i]->getType()->print(os);
  149. }
  150. os << "\n";
  151. os.flush();
  152. }
  153. void PrintUsers(llvm::Value* v)
  154. {
  155. for (auto user : v->users())
  156. {
  157. pt(user);
  158. }
  159. }
  160. /*void PrintFunc(Beefy::BfMethodInstance* methodInstance)
  161. {
  162. Beefy::debug_ostream os;
  163. methodInstance->mIRFunction.mLLVMValue->print(os);
  164. os << "\n";
  165. os.flush();
  166. }*/
  167. USING_NS_BF;
  168. using namespace llvm;
  169. int Beefy::BfWorkListEntry::sCurReqId = 0;
  170. GlobalVariable* AllocGlobalVariable(Module &M, Type *Ty, bool isConstant,
  171. GlobalValue::LinkageTypes Linkage, Constant *Initializer,
  172. const Twine &Name = "", GlobalVariable *InsertBefore = nullptr,
  173. GlobalValue::ThreadLocalMode tlm = GlobalValue::NotThreadLocal, unsigned AddressSpace = 0,
  174. bool isExternallyInitialized = false);
  175. #include "BeefySysLib/util/AllocDebug.h"
  176. //////////////////////////////////////////////////////////////////////////
  177. BfCompiler::HotData::~HotData()
  178. {
  179. for (auto& kv : mMethodMap)
  180. {
  181. auto hotMethod = kv.mValue;
  182. hotMethod->Clear();
  183. }
  184. for (auto& kv : mThisType)
  185. kv.mValue->Deref();
  186. for (auto& kv : mAllocation)
  187. kv.mValue->Deref();
  188. for (auto& kv : mDevirtualizedMethods)
  189. kv.mValue->Deref();
  190. for (auto& kv : mFuncPtrs)
  191. kv.mValue->Deref();
  192. for (auto& kv : mVirtualDecls)
  193. kv.mValue->Deref();
  194. for (auto& kv : mInnerMethods)
  195. kv.mValue->Deref();
  196. for (auto& kv : mMethodMap)
  197. kv.mValue->Deref();
  198. }
  199. template <typename TDict>
  200. static void DeleteUnused(TDict& dict)
  201. {
  202. auto itr = dict.begin();
  203. while (itr != dict.end())
  204. {
  205. auto val = itr->mValue;
  206. BF_ASSERT(val->mRefCount >= 1);
  207. if (val->mRefCount == 1)
  208. {
  209. val->Deref();
  210. itr = dict.Remove(itr);
  211. }
  212. else
  213. ++itr;
  214. }
  215. }
  216. template <typename TDict, typename TElement>
  217. static typename TDict::value_type AllocFromMap(TDict& dict, TElement* elem)
  218. {
  219. typename TDict::value_type* valuePtr;
  220. if (dict.TryAdd(elem, NULL, &valuePtr))
  221. {
  222. auto val = new typename std::remove_pointer<typename TDict::value_type>::type(elem);
  223. val->mRefCount++;
  224. *valuePtr = val;
  225. }
  226. return *valuePtr;
  227. }
  228. void BfCompiler::HotData::ClearUnused(bool isHotCompile)
  229. {
  230. BP_ZONE("BfCompiler::HotData::ClearUnused");
  231. DeleteUnused(mThisType);
  232. DeleteUnused(mAllocation);
  233. DeleteUnused(mDevirtualizedMethods);
  234. DeleteUnused(mVirtualDecls);
  235. DeleteUnused(mInnerMethods);
  236. if (isHotCompile)
  237. {
  238. // We need to keep all function pointer references ever, since we can't tell if we still reference them or not
  239. DeleteUnused(mFuncPtrs);
  240. }
  241. }
  242. BfHotThisType* BfCompiler::HotData::GetThisType(BfHotTypeVersion* hotVersion)
  243. {
  244. return AllocFromMap(mThisType, hotVersion);
  245. }
  246. BfHotAllocation* BfCompiler::HotData::GetAllocation(BfHotTypeVersion* hotVersion)
  247. {
  248. return AllocFromMap(mAllocation, hotVersion);
  249. }
  250. BfHotDevirtualizedMethod* BfCompiler::HotData::GetDevirtualizedMethod(BfHotMethod* hotMethod)
  251. {
  252. return AllocFromMap(mDevirtualizedMethods, hotMethod);
  253. }
  254. BfHotFunctionReference* BfCompiler::HotData::GetFunctionReference(BfHotMethod* hotMethod)
  255. {
  256. return AllocFromMap(mFuncPtrs, hotMethod);
  257. }
  258. BfHotInnerMethod* BfCompiler::HotData::GetInnerMethod(BfHotMethod* hotMethod)
  259. {
  260. return AllocFromMap(mInnerMethods, hotMethod);
  261. }
  262. BfHotVirtualDeclaration* BfCompiler::HotData::GetVirtualDeclaration(BfHotMethod* hotMethod)
  263. {
  264. return AllocFromMap(mVirtualDecls, hotMethod);
  265. }
  266. BfCompiler::HotState::~HotState()
  267. {
  268. }
  269. bool BfCompiler::HotState::HasPendingChanges(BfTypeInstance* type)
  270. {
  271. return (type->mHotTypeData != NULL) && (type->mHotTypeData->mPendingDataChange);
  272. }
  273. void BfCompiler::HotState::RemovePendingChanges(BfTypeInstance* type)
  274. {
  275. BF_ASSERT(type->mHotTypeData->mPendingDataChange);
  276. if (!type->mHotTypeData->mPendingDataChange)
  277. return;
  278. type->mHotTypeData->mPendingDataChange = false;
  279. bool didRemove = mPendingDataChanges.Remove(type->mTypeId);
  280. BF_ASSERT(didRemove);
  281. }
  282. BfCompiler::HotResolveData::~HotResolveData()
  283. {
  284. for (auto hotMethod : mActiveMethods)
  285. hotMethod->Deref();
  286. for (auto kv : mReachableMethods)
  287. kv.mKey->Deref();
  288. }
  289. //////////////////////////////////////////////////////////////////////////
  290. BfCompiler::BfCompiler(BfSystem* bfSystem, bool isResolveOnly)
  291. {
  292. memset(&mStats, 0, sizeof(mStats));
  293. mCompletionPct = 0;
  294. mCanceling = false;
  295. mHasRequiredTypes = false;
  296. mNeedsFullRefresh = false;
  297. mFastFinish = false;
  298. mHasQueuedTypeRebuilds = false;
  299. mIsResolveOnly = isResolveOnly;
  300. mResolvePassData = NULL;
  301. mPassInstance = NULL;
  302. mRevision = 0;
  303. mUniqueId = 0;
  304. mLastRevisionAborted = false;
  305. gBfCompiler = this;
  306. mSystem = bfSystem;
  307. mCurTypeId = 1;
  308. mTypeInitCount = 0;
  309. //mMaxInterfaceSlots = 16;
  310. mMaxInterfaceSlots = -1;
  311. mInterfaceSlotCountChanged = false;
  312. mLastHadComptimeRebuilds = false;
  313. mHasComptimeRebuilds = false;
  314. mDepsMayHaveDeletedTypes = false;
  315. mHSPreserveIdx = 0;
  316. mCompileLogFP = NULL;
  317. mWantsDeferMethodDecls = false;
  318. mHadCancel = false;
  319. mCompileState = CompileState_None;
  320. //mMaxInterfaceSlots = 4;
  321. mHotData = NULL;
  322. mHotState = NULL;
  323. mHotResolveData = NULL;
  324. mBfObjectTypeDef = NULL;
  325. mChar32TypeDef = NULL;
  326. mFloatTypeDef = NULL;
  327. mDoubleTypeDef = NULL;
  328. mMathTypeDef = NULL;
  329. mArray1TypeDef = NULL;
  330. mArray2TypeDef = NULL;
  331. mArray3TypeDef = NULL;
  332. mArray4TypeDef = NULL;
  333. mSpanTypeDef = NULL;
  334. mRangeTypeDef = NULL;
  335. mClosedRangeTypeDef = NULL;
  336. mIndexTypeDef = NULL;
  337. mIndexRangeTypeDef = NULL;
  338. mAttributeTypeDef = NULL;
  339. mAttributeUsageAttributeTypeDef = NULL;
  340. mClassVDataTypeDef = NULL;
  341. mCLinkAttributeTypeDef = NULL;
  342. mImportAttributeTypeDef = NULL;
  343. mExportAttributeTypeDef = NULL;
  344. mCReprAttributeTypeDef = NULL;
  345. mUnderlyingArrayAttributeTypeDef = NULL;
  346. mAlignAttributeTypeDef = NULL;
  347. mAllowDuplicatesAttributeTypeDef = NULL;
  348. mNoDiscardAttributeTypeDef = NULL;
  349. mDisableChecksAttributeTypeDef = NULL;
  350. mDisableObjectAccessChecksAttributeTypeDef = NULL;
  351. mDbgRawAllocDataTypeDef = NULL;
  352. mDeferredCallTypeDef = NULL;
  353. mDelegateTypeDef = NULL;
  354. mFunctionTypeDef = NULL;
  355. mActionTypeDef = NULL;
  356. mEnumTypeDef = NULL;
  357. mFriendAttributeTypeDef = NULL;
  358. mComptimeAttributeTypeDef = NULL;
  359. mConstEvalAttributeTypeDef = NULL;
  360. mNoExtensionAttributeTypeDef = NULL;
  361. mCheckedAttributeTypeDef = NULL;
  362. mUncheckedAttributeTypeDef = NULL;
  363. mGCTypeDef = NULL;
  364. mGenericIEnumerableTypeDef = NULL;
  365. mGenericIEnumeratorTypeDef = NULL;
  366. mGenericIRefEnumeratorTypeDef = NULL;
  367. mInlineAttributeTypeDef = NULL;
  368. mThreadTypeDef = NULL;
  369. mInternalTypeDef = NULL;
  370. mPlatformTypeDef = NULL;
  371. mCompilerTypeDef = NULL;
  372. mCompilerGeneratorTypeDef = NULL;
  373. mDiagnosticsDebugTypeDef = NULL;
  374. mIDisposableTypeDef = NULL;
  375. mIIntegerTypeDef = NULL;
  376. mIPrintableTypeDef = NULL;
  377. mIHashableTypeDef = NULL;
  378. mIComptimeTypeApply = NULL;
  379. mIComptimeMethodApply = NULL;
  380. mIOnTypeInitTypeDef = NULL;
  381. mIOnTypeDoneTypeDef = NULL;
  382. mIOnFieldInitTypeDef = NULL;
  383. mIOnMethodInitTypeDef = NULL;
  384. mLinkNameAttributeTypeDef = NULL;
  385. mCallingConventionAttributeTypeDef = NULL;
  386. mMethodRefTypeDef = NULL;
  387. mNullableTypeDef = NULL;
  388. mOrderedAttributeTypeDef = NULL;
  389. mPointerTTypeDef = NULL;
  390. mPointerTypeDef = NULL;
  391. mReflectTypeIdTypeDef = NULL;
  392. mReflectArrayType = NULL;
  393. mReflectGenericParamType = NULL;
  394. mReflectFieldDataDef = NULL;
  395. mReflectFieldSplatDataDef = NULL;
  396. mReflectMethodDataDef = NULL;
  397. mReflectParamDataDef = NULL;
  398. mReflectInterfaceDataDef = NULL;
  399. mReflectPointerType = NULL;
  400. mReflectRefType = NULL;
  401. mReflectSizedArrayType = NULL;
  402. mReflectConstExprType = NULL;
  403. mReflectSpecializedGenericType = NULL;
  404. mReflectTypeInstanceTypeDef = NULL;
  405. mReflectUnspecializedGenericType = NULL;
  406. mReflectFieldInfoTypeDef = NULL;
  407. mReflectMethodInfoTypeDef = NULL;
  408. mSizedArrayTypeDef = NULL;
  409. mStaticInitAfterAttributeTypeDef = NULL;
  410. mStaticInitPriorityAttributeTypeDef = NULL;
  411. mStringTypeDef = NULL;
  412. mStringViewTypeDef = NULL;
  413. mThreadStaticAttributeTypeDef = NULL;
  414. mTypeTypeDef = NULL;
  415. mUnboundAttributeTypeDef = NULL;
  416. mValueTypeTypeDef = NULL;
  417. mResultTypeDef = NULL;
  418. mObsoleteAttributeTypeDef = NULL;
  419. mErrorAttributeTypeDef = NULL;
  420. mWarnAttributeTypeDef = NULL;
  421. mConstSkipAttributeTypeDef = NULL;
  422. mIgnoreErrorsAttributeTypeDef = NULL;
  423. mReflectAttributeTypeDef = NULL;
  424. mOnCompileAttributeTypeDef = NULL;
  425. mLastAutocompleteModule = NULL;
  426. mContext = new BfContext(this);
  427. mCeMachine = new CeMachine(this);
  428. mCurCEExecuteId = -1;
  429. mLastMidCompileRefreshRevision = -1;
  430. }
  431. BfCompiler::~BfCompiler()
  432. {
  433. delete mCeMachine;
  434. mCeMachine = NULL;
  435. delete mContext;
  436. delete mHotData;
  437. delete mHotState;
  438. delete mHotResolveData;
  439. }
  440. bool BfCompiler::IsTypeAccessible(BfType* checkType, BfProject* curProject)
  441. {
  442. if (checkType->IsBoxed())
  443. return IsTypeAccessible(((BfBoxedType*)checkType)->mElementType, curProject);
  444. BfTypeInstance* typeInst = checkType->ToTypeInstance();
  445. if (typeInst != NULL)
  446. {
  447. if (checkType->IsTuple())
  448. {
  449. for (auto&& fieldInst : typeInst->mFieldInstances)
  450. {
  451. if (!IsTypeAccessible(fieldInst.mResolvedType, curProject))
  452. return false;
  453. }
  454. }
  455. auto genericTypeInst = typeInst->ToGenericTypeInstance();
  456. if (genericTypeInst != NULL)
  457. {
  458. for (auto genericArg : genericTypeInst->mGenericTypeInfo->mTypeGenericArguments)
  459. if (!IsTypeAccessible(genericArg, curProject))
  460. return false;
  461. }
  462. return curProject->ContainsReference(typeInst->mTypeDef->mProject);
  463. }
  464. if (checkType->IsPointer())
  465. return IsTypeAccessible(((BfPointerType*)checkType)->mElementType, curProject);
  466. if (checkType->IsRef())
  467. return IsTypeAccessible(((BfPointerType*)checkType)->mElementType, curProject);
  468. return true;
  469. }
  470. bool BfCompiler::IsTypeUsed(BfType* checkType, BfProject* curProject)
  471. {
  472. if (mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  473. return IsTypeAccessible(checkType, curProject);
  474. BfTypeInstance* typeInst = checkType->ToTypeInstance();
  475. if (typeInst != NULL)
  476. {
  477. //TODO: Why was this here?
  478. // if ((typeInst->mTypeDef->mProject != NULL) && (typeInst->mTypeDef->mProject != curProject))
  479. // {
  480. // if (typeInst->mTypeDef->mProject->mTargetType == BfTargetType_BeefDynLib)
  481. // return false;
  482. // }
  483. if (checkType->IsInterface())
  484. return typeInst->mIsReified;
  485. //TODO: We could check to see if this project has any reified specialized instances...
  486. if (checkType->IsUnspecializedType())
  487. return typeInst->mIsReified;
  488. if (checkType->IsTuple())
  489. {
  490. for (auto&& fieldInst : typeInst->mFieldInstances)
  491. {
  492. if (!IsTypeUsed(fieldInst.mResolvedType, curProject))
  493. return false;
  494. }
  495. }
  496. auto genericTypeInst = typeInst->ToGenericTypeInstance();
  497. if (genericTypeInst != NULL)
  498. {
  499. for (auto genericArg : genericTypeInst->mGenericTypeInfo->mTypeGenericArguments)
  500. if (!IsTypeUsed(genericArg, curProject))
  501. return false;
  502. }
  503. if (checkType->IsFunction())
  504. {
  505. // These don't get their own modules so just assume "always used" at this point
  506. return true;
  507. }
  508. auto module = typeInst->GetModule();
  509. if (module == NULL)
  510. return true;
  511. return curProject->mUsedModules.Contains(module);
  512. }
  513. if (checkType->IsPointer())
  514. return IsTypeUsed(((BfPointerType*)checkType)->mElementType, curProject);
  515. if (checkType->IsRef())
  516. return IsTypeUsed(((BfRefType*)checkType)->mElementType, curProject);
  517. return true;
  518. }
  519. bool BfCompiler::IsModuleAccessible(BfModule* module, BfProject* curProject)
  520. {
  521. for (auto checkType : module->mOwnedTypeInstances)
  522. {
  523. if (!IsTypeAccessible(checkType, curProject))
  524. return false;
  525. }
  526. return curProject->ContainsReference(module->mProject);
  527. }
  528. void BfCompiler::FixVDataHash(BfModule* bfModule)
  529. {
  530. // We recreate the actual vdata hash now that we're done creating new string literals
  531. /*for (auto context : mContexts)
  532. HASH128_MIXIN(bfModule->mDataHash, bfModule->mHighestUsedStringId);*/
  533. }
  534. void BfCompiler::CheckModuleStringRefs(BfModule* module, BfVDataModule* vdataModule, int lastModuleRevision, HashSet<int>& foundStringIds, HashSet<int>& dllNameSet, Array<BfMethodInstance*>& dllMethods, Array<BfCompiler::StringValueEntry>& stringValueEntries)
  535. {
  536. for (int stringId : module->mStringPoolRefs)
  537. {
  538. if (foundStringIds.Add(stringId))
  539. {
  540. BfStringPoolEntry& stringPoolEntry = module->mContext->mStringObjectIdMap[stringId];
  541. if (IsHotCompile())
  542. {
  543. if (vdataModule->mDefinedStrings.Contains(stringId))
  544. continue;
  545. }
  546. StringValueEntry stringEntry;
  547. stringEntry.mId = stringId;
  548. vdataModule->mDefinedStrings.Add(stringId);
  549. stringEntry.mStringVal = vdataModule->CreateStringObjectValue(stringPoolEntry.mString, stringId, true);
  550. stringValueEntries.Add(stringEntry);
  551. CompileLog("String %d %s\n", stringId, stringPoolEntry.mString.c_str());
  552. }
  553. }
  554. for (auto dllNameId : module->mImportFileNames)
  555. dllNameSet.Add(dllNameId);
  556. for (auto& dllImportEntry : module->mDllImportEntries)
  557. dllMethods.push_back(dllImportEntry.mMethodInstance);
  558. auto altModule = module->mNextAltModule;
  559. while (altModule != NULL)
  560. {
  561. CheckModuleStringRefs(altModule, vdataModule, lastModuleRevision, foundStringIds, dllNameSet, dllMethods, stringValueEntries);
  562. altModule = altModule->mNextAltModule;
  563. }
  564. for (auto& specModulePair : module->mSpecializedMethodModules)
  565. CheckModuleStringRefs(specModulePair.mValue, vdataModule, lastModuleRevision, foundStringIds, dllNameSet, dllMethods, stringValueEntries);
  566. }
  567. void BfCompiler::HashModuleVData(BfModule* module, HashContext& vdataHash)
  568. {
  569. BP_ZONE("BfCompiler::HashModuleVData");
  570. if (module->mStringPoolRefs.size() > 0)
  571. {
  572. module->mStringPoolRefs.Sort([](int lhs, int rhs) { return lhs < rhs; });
  573. vdataHash.Mixin(&module->mStringPoolRefs[0], (int)module->mStringPoolRefs.size() * (int)sizeof(int));
  574. }
  575. if (module->mImportFileNames.size() > 0)
  576. {
  577. module->mImportFileNames.Sort([](int lhs, int rhs) { return lhs < rhs; });
  578. vdataHash.Mixin(&module->mImportFileNames[0], (int)module->mImportFileNames.size() * (int)sizeof(int));
  579. }
  580. auto altModule = module->mNextAltModule;
  581. while (altModule != NULL)
  582. {
  583. HashModuleVData(altModule, vdataHash);
  584. altModule = altModule->mNextAltModule;
  585. }
  586. for (auto& specModulePair : module->mSpecializedMethodModules)
  587. {
  588. HashModuleVData(specModulePair.mValue, vdataHash);
  589. }
  590. }
  591. BfIRFunction BfCompiler::CreateLoadSharedLibraries(BfVDataModule* bfModule, Array<BfMethodInstance*>& dllMethods)
  592. {
  593. BfIRType nullPtrType = bfModule->mBfIRBuilder->MapType(bfModule->GetPrimitiveType(BfTypeCode_NullPtr));
  594. BfIRType nullPtrPtrType = bfModule->mBfIRBuilder->MapType(bfModule->CreatePointerType(bfModule->GetPrimitiveType(BfTypeCode_NullPtr)));
  595. BfIRType voidType = bfModule->mBfIRBuilder->MapType(bfModule->GetPrimitiveType(BfTypeCode_None));
  596. SmallVector<BfIRType, 2> paramTypes;
  597. auto loadSharedLibrariesFuncType = bfModule->mBfIRBuilder->CreateFunctionType(voidType, paramTypes, false);
  598. auto loadSharedLibFunc = bfModule->mBfIRBuilder->CreateFunction(loadSharedLibrariesFuncType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  599. bfModule->SetupIRMethod(NULL, loadSharedLibFunc, false);
  600. bfModule->mBfIRBuilder->SetActiveFunction(loadSharedLibFunc);
  601. auto entryBlock = bfModule->mBfIRBuilder->CreateBlock("entry", true);
  602. bfModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  603. HashSet<int> dllNameSet;
  604. auto internalType = bfModule->ResolveTypeDef(mInternalTypeDef);
  605. bfModule->PopulateType(internalType);
  606. auto getSharedProcAddressInstance = bfModule->GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddressInto");
  607. auto loadSharedLibraryProc = bfModule->GetMethodByName(internalType->ToTypeInstance(), "LoadSharedLibraryInto");
  608. BF_ASSERT(getSharedProcAddressInstance);
  609. BF_ASSERT(loadSharedLibraryProc);
  610. if (!getSharedProcAddressInstance)
  611. {
  612. bfModule->Fail("Missing Internal.GetSharedProcAddressInto");
  613. return loadSharedLibFunc;
  614. }
  615. if (!loadSharedLibraryProc)
  616. {
  617. bfModule->Fail("Missing Internal.LoadSharedLibraryInto");
  618. return loadSharedLibFunc;
  619. }
  620. Dictionary<int, BfIRValue> dllHandleMap;
  621. for (auto methodInstance : dllMethods)
  622. {
  623. auto typeInstance = methodInstance->GetOwner();
  624. auto methodDef = methodInstance->mMethodDef;
  625. BF_ASSERT(methodInstance->GetCustomAttributes() != NULL);
  626. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  627. {
  628. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  629. {
  630. bool doCLink = false;
  631. bool undecorated = false;
  632. BfCallingConvention callingConvention = methodDef->mCallingConvention;
  633. for (auto fieldSet : customAttr.mSetField)
  634. {
  635. BfFieldDef* fieldDef = fieldSet.mFieldRef;
  636. if (fieldDef->mName == "CLink")
  637. {
  638. auto constant = typeInstance->mConstHolder->GetConstant(fieldSet.mParam.mValue);
  639. if (constant != NULL)
  640. doCLink = constant->mBool;
  641. }
  642. if (fieldDef->mName == "Undecorated")
  643. {
  644. auto constant = typeInstance->mConstHolder->GetConstant(fieldSet.mParam.mValue);
  645. if (constant != NULL)
  646. undecorated = constant->mBool;
  647. }
  648. if (fieldDef->mName == "CallingConvention")
  649. {
  650. auto constant = typeInstance->mConstHolder->GetConstant(fieldSet.mParam.mValue);
  651. if (constant != NULL)
  652. {
  653. int callingConventionVal = (int)constant->mInt32;
  654. if ((callingConventionVal == 3) || (callingConventionVal == 1))
  655. callingConvention = BfCallingConvention_Stdcall;
  656. else if (callingConventionVal == 2)
  657. callingConvention = BfCallingConvention_Cdecl;
  658. }
  659. }
  660. }
  661. if (customAttr.mCtorArgs.size() == 1)
  662. {
  663. auto fileNameArg = customAttr.mCtorArgs[0];
  664. int strNum = 0;
  665. auto constant = typeInstance->mConstHolder->GetConstant(fileNameArg);
  666. if (constant != NULL)
  667. {
  668. if (constant->IsNull())
  669. continue; // Invalid
  670. strNum = constant->mInt32;
  671. }
  672. else
  673. {
  674. strNum = bfModule->GetStringPoolIdx(fileNameArg, typeInstance->mConstHolder);
  675. }
  676. BfIRValue dllHandleVar;
  677. if (!dllHandleMap.TryGetValue(strNum, &dllHandleVar))
  678. {
  679. String dllHandleName = StrFormat("bf_hs_preserve@dllHandle%d", strNum);
  680. dllHandleVar = bfModule->mBfIRBuilder->CreateGlobalVariable(nullPtrType, false, BfIRLinkageType_External,
  681. bfModule->GetDefaultValue(bfModule->GetPrimitiveType(BfTypeCode_NullPtr)), dllHandleName);
  682. BfIRValue namePtr = bfModule->GetStringCharPtr(strNum);
  683. SmallVector<BfIRValue, 2> args;
  684. args.push_back(namePtr);
  685. args.push_back(dllHandleVar);
  686. BfIRValue dllHandleValue = bfModule->mBfIRBuilder->CreateCall(loadSharedLibraryProc.mFunc, args);
  687. dllHandleMap[strNum] = dllHandleVar;
  688. }
  689. String methodImportName;
  690. if (undecorated)
  691. {
  692. methodImportName = methodInstance->mMethodDef->mName;
  693. }
  694. else if (doCLink)
  695. {
  696. methodImportName = methodInstance->mMethodDef->mName;
  697. if ((mSystem->mPtrSize == 4) && (callingConvention == BfCallingConvention_Stdcall))
  698. {
  699. int argSize = (int)methodDef->mParams.size() * mSystem->mPtrSize;
  700. methodImportName = StrFormat("_%s$%d", methodImportName.c_str(), argSize);
  701. }
  702. }
  703. else
  704. BfMangler::Mangle(methodImportName, GetMangleKind(), methodInstance);
  705. BfIRValue methodNameValue = bfModule->mBfIRBuilder->CreateGlobalStringPtr(methodImportName);
  706. //auto moduleMethodInstance = bfModule->ReferenceExternalMethodInstance(methodInstance);
  707. //auto globalVarPtr = bfModule->mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, nullPtrPtrType);
  708. auto func = bfModule->CreateDllImportGlobalVar(methodInstance, false);
  709. auto globalVarPtr = bfModule->mBfIRBuilder->CreateBitCast(func, nullPtrPtrType);
  710. BfSizedVector<BfIRValue, 2> args;
  711. args.push_back(bfModule->mBfIRBuilder->CreateLoad(dllHandleVar));
  712. args.push_back(methodNameValue);
  713. args.push_back(globalVarPtr);
  714. BfIRValue dllFuncValVoidPtr = bfModule->mBfIRBuilder->CreateCall(getSharedProcAddressInstance.mFunc, args);
  715. }
  716. }
  717. }
  718. }
  719. bfModule->mBfIRBuilder->CreateRetVoid();
  720. return loadSharedLibFunc;
  721. }
  722. void BfCompiler::GetTestMethods(BfVDataModule* bfModule, Array<TestMethod>& testMethods, HashContext& vdataHashCtx)
  723. {
  724. vdataHashCtx.Mixin(0xBEEF0001); // Marker
  725. auto _CheckMethod = [&](BfTypeInstance* typeInstance, BfMethodInstance* methodInstance)
  726. {
  727. auto project = methodInstance->mMethodDef->mDeclaringType->mProject;
  728. if (project->mTargetType != BfTargetType_BeefTest)
  729. return;
  730. if (project != bfModule->mProject)
  731. return;
  732. bool isTest = false;
  733. if ((methodInstance->GetCustomAttributes() != NULL) &&
  734. (methodInstance->GetCustomAttributes()->Contains(mTestAttributeTypeDef)))
  735. isTest = true;
  736. if (!isTest)
  737. return;
  738. if (methodInstance->mIsUnspecialized)
  739. {
  740. if (!typeInstance->IsSpecializedType())
  741. {
  742. bfModule->Fail(StrFormat("Method '%s' cannot be used for testing because it's generic", bfModule->MethodToString(methodInstance).c_str()),
  743. methodInstance->mMethodDef->GetRefNode());
  744. }
  745. bfModule->mHadBuildError = true;
  746. return;
  747. }
  748. if (!methodInstance->mMethodDef->mIsStatic)
  749. {
  750. if (!typeInstance->IsSpecializedType())
  751. {
  752. bfModule->Fail(StrFormat("Method '%s' cannot be used for testing because it's not static", bfModule->MethodToString(methodInstance).c_str()),
  753. methodInstance->mMethodDef->GetRefNode());
  754. }
  755. bfModule->mHadBuildError = true;
  756. return;
  757. }
  758. if (methodInstance->GetParamCount() > 0)
  759. {
  760. if ((methodInstance->GetParamInitializer(0) == NULL) &&
  761. (methodInstance->GetParamKind(0) != BfParamKind_Params))
  762. {
  763. if (!typeInstance->IsSpecializedType())
  764. {
  765. bfModule->Fail(StrFormat("Method '%s' cannot be used for testing because it contains parameters without defaults", bfModule->MethodToString(methodInstance).c_str()),
  766. methodInstance->mMethodDef->GetRefNode());
  767. }
  768. bfModule->mHadBuildError = true;
  769. return;
  770. }
  771. }
  772. BF_ASSERT(typeInstance->IsReified());
  773. TestMethod testMethod;
  774. testMethod.mMethodInstance = methodInstance;
  775. testMethods.Add(testMethod);
  776. BF_ASSERT_REL(!typeInstance->mModule->mIsDeleting);
  777. if (!bfModule->mProject->mUsedModules.Contains(typeInstance->mModule))
  778. {
  779. bfModule->mProject->mUsedModules.Add(typeInstance->mModule);
  780. }
  781. vdataHashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  782. vdataHashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  783. };
  784. for (auto type : mContext->mResolvedTypes)
  785. {
  786. auto typeInstance = type->ToTypeInstance();
  787. if (typeInstance == NULL)
  788. continue;
  789. if (typeInstance->IsUnspecializedType())
  790. continue;
  791. for (auto& methodInstanceGroup : typeInstance->mMethodInstanceGroups)
  792. {
  793. if (methodInstanceGroup.mDefault != NULL)
  794. _CheckMethod(typeInstance, methodInstanceGroup.mDefault);
  795. }
  796. }
  797. }
  798. void BfCompiler::EmitTestMethod(BfVDataModule* bfModule, Array<TestMethod>& testMethods, BfIRValue& retValue)
  799. {
  800. for (auto& testMethod : testMethods)
  801. {
  802. auto methodInstance = testMethod.mMethodInstance;
  803. auto typeInstance = methodInstance->GetOwner();
  804. testMethod.mName += bfModule->TypeToString(typeInstance);
  805. if (!testMethod.mName.IsEmpty())
  806. testMethod.mName += ".";
  807. testMethod.mName += methodInstance->mMethodDef->mName;
  808. testMethod.mName += "\t";
  809. auto testAttribute = methodInstance->GetCustomAttributes()->Get(mTestAttributeTypeDef);
  810. for (auto& field : testAttribute->mSetField)
  811. {
  812. auto constant = typeInstance->mConstHolder->GetConstant(field.mParam.mValue);
  813. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_Boolean) && (constant->mBool))
  814. {
  815. BfFieldDef* fieldDef = field.mFieldRef;
  816. if (fieldDef->mName == "ShouldFail")
  817. {
  818. testMethod.mName += "Sf";
  819. }
  820. else if (fieldDef->mName == "Profile")
  821. {
  822. testMethod.mName += "Pr";
  823. }
  824. else if (fieldDef->mName == "Ignore")
  825. {
  826. testMethod.mName += "Ig";
  827. }
  828. }
  829. }
  830. bfModule->UpdateSrcPos(methodInstance->mMethodDef->GetRefNode(), (BfSrcPosFlags)(BfSrcPosFlag_NoSetDebugLoc | BfSrcPosFlag_Force));
  831. testMethod.mName += StrFormat("\t%s\t%d\t%d", bfModule->mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), bfModule->mCurFilePosition.mCurLine, bfModule->mCurFilePosition.mCurColumn);
  832. }
  833. std::stable_sort(testMethods.begin(), testMethods.end(),
  834. [](const TestMethod& lhs, const TestMethod& rhs)
  835. {
  836. return lhs.mName < rhs.mName;
  837. });
  838. String methodData;
  839. for (int methodIdx = 0; methodIdx < (int)testMethods.size(); methodIdx++)
  840. {
  841. String& methodName = testMethods[methodIdx].mName;
  842. if (!methodData.IsEmpty())
  843. methodData += "\n";
  844. methodData += methodName;
  845. }
  846. //////////////////////////////////////////////////////////////////////////
  847. auto testInitMethod = bfModule->GetInternalMethod("Test_Init");
  848. auto testQueryMethod = bfModule->GetInternalMethod("Test_Query");
  849. auto testFinishMethod = bfModule->GetInternalMethod("Test_Finish");
  850. auto char8PtrType = bfModule->CreatePointerType(bfModule->GetPrimitiveType(BfTypeCode_Char8));
  851. BfIRType strCharType = bfModule->mBfIRBuilder->GetSizedArrayType(bfModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_Char8), (int)methodData.length() + 1);
  852. BfIRValue strConstant = bfModule->mBfIRBuilder->CreateConstString(methodData);
  853. BfIRValue gv = bfModule->mBfIRBuilder->CreateGlobalVariable(strCharType,
  854. true, BfIRLinkageType_External,
  855. strConstant, "__bfTestData");
  856. BfIRValue strPtrVal = bfModule->mBfIRBuilder->CreateBitCast(gv, bfModule->mBfIRBuilder->MapType(char8PtrType));
  857. SizedArray<BfIRValue, 4> irArgs;
  858. irArgs.Add(strPtrVal);
  859. bfModule->mBfIRBuilder->CreateCall(testInitMethod.mFunc, irArgs);
  860. BfIRBlock testHeadBlock = bfModule->mBfIRBuilder->CreateBlock("testHead");
  861. BfIRBlock testEndBlock = bfModule->mBfIRBuilder->CreateBlock("testEnd");
  862. bfModule->mBfIRBuilder->CreateBr(testHeadBlock);
  863. bfModule->mBfIRBuilder->AddBlock(testHeadBlock);
  864. bfModule->mBfIRBuilder->SetInsertPoint(testHeadBlock);
  865. irArgs.clear();
  866. auto testVal = bfModule->mBfIRBuilder->CreateCall(testQueryMethod.mFunc, irArgs);
  867. auto switchVal = bfModule->mBfIRBuilder->CreateSwitch(testVal, testEndBlock, (int)testMethods.size());
  868. for (int methodIdx = 0; methodIdx < (int)testMethods.size(); methodIdx++)
  869. {
  870. auto methodInstance = testMethods[methodIdx].mMethodInstance;
  871. String& methodName = testMethods[methodIdx].mName;
  872. auto testBlock = bfModule->mBfIRBuilder->CreateBlock(StrFormat("test%d", methodIdx));
  873. bfModule->mBfIRBuilder->AddSwitchCase(switchVal, bfModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, methodIdx), testBlock);
  874. bfModule->mBfIRBuilder->AddBlock(testBlock);
  875. bfModule->mBfIRBuilder->SetInsertPoint(testBlock);
  876. auto moduleMethodInstance = bfModule->ReferenceExternalMethodInstance(methodInstance);
  877. irArgs.clear();
  878. if (methodInstance->GetParamCount() > 0)
  879. {
  880. if (methodInstance->GetParamKind(0) == BfParamKind_Params)
  881. {
  882. auto paramType = methodInstance->GetParamType(0);
  883. auto paramTypeInst = paramType->ToTypeInstance();
  884. BfTypedValue paramVal = BfTypedValue(bfModule->mBfIRBuilder->CreateAlloca(bfModule->mBfIRBuilder->MapTypeInst(paramTypeInst)), paramType);
  885. bfModule->InitTypeInst(paramVal, NULL, false, BfIRValue());
  886. //TODO: Assert 'length' var is at slot 1
  887. auto arrayBits = bfModule->mBfIRBuilder->CreateBitCast(paramVal.mValue, bfModule->mBfIRBuilder->MapType(paramTypeInst->mBaseType));
  888. auto addr = bfModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, 1);
  889. auto storeInst = bfModule->mBfIRBuilder->CreateAlignedStore(bfModule->GetConstValue(0), addr, 4);
  890. irArgs.Add(paramVal.mValue);
  891. }
  892. else
  893. {
  894. for (int defaultIdx = 0; defaultIdx < (int)methodInstance->mDefaultValues.size(); defaultIdx++)
  895. {
  896. auto constHolder = methodInstance->GetOwner()->mConstHolder;
  897. auto defaultTypedValue = methodInstance->mDefaultValues[defaultIdx];
  898. auto defaultVal = bfModule->ConstantToCurrent(constHolder->GetConstant(defaultTypedValue.mValue), constHolder, defaultTypedValue.mType);
  899. auto castedVal = bfModule->Cast(methodInstance->mMethodDef->GetRefNode(), BfTypedValue(defaultVal, defaultTypedValue.mType), methodInstance->GetParamType(defaultIdx));
  900. if (castedVal)
  901. {
  902. BfExprEvaluator exprEvaluator(bfModule);
  903. exprEvaluator.PushArg(castedVal, irArgs);
  904. }
  905. }
  906. }
  907. }
  908. BfExprEvaluator exprEvaluator(bfModule);
  909. exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  910. bfModule->mBfIRBuilder->CreateBr(testHeadBlock);
  911. }
  912. bfModule->mBfIRBuilder->AddBlock(testEndBlock);
  913. bfModule->mBfIRBuilder->SetInsertPoint(testEndBlock);
  914. irArgs.clear();
  915. bfModule->mBfIRBuilder->CreateCall(testFinishMethod.mFunc, irArgs);
  916. retValue = bfModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 0);
  917. }
  918. void BfCompiler::CreateVData(BfVDataModule* bfModule)
  919. {
  920. bool isHotCompile = IsHotCompile();
  921. if ((isHotCompile) && (bfModule->mProject != mOptions.mHotProject))
  922. return;
  923. BP_ZONE("BfCompiler::CreateVData");
  924. BfLogSysM("CreateVData %s\n", bfModule->mProject->mName.c_str());
  925. CompileLog("CreateVData %s\n", bfModule->mProject->mName.c_str());
  926. BF_ASSERT_REL(!bfModule->mIsDeleting);
  927. bfModule->mProject->mUsedModules.Add(bfModule);
  928. auto project = bfModule->mProject;
  929. auto vdataContext = bfModule->mContext;
  930. BF_ASSERT(bfModule->mModuleName == "vdata");
  931. //////////////////////////////////////////////////////////////////////////
  932. mContext->ReflectInit();
  933. // Create types we'll need for vdata, so we won't change the vdata hash afterward
  934. // bfModule->CreatePointerType(bfModule->GetPrimitiveType(BfTypeCode_NullPtr));
  935. //
  936. // ///
  937. //
  938. // auto typeDefType = bfModule->ResolveTypeDef(mTypeTypeDef)->ToTypeInstance();
  939. // if (!typeDefType)
  940. // return;
  941. // BF_ASSERT(typeDefType != NULL);
  942. // vdataContext->mBfTypeType = typeDefType->ToTypeInstance();
  943. //
  944. // auto typeInstanceDefType = bfModule->ResolveTypeDef(mReflectTypeInstanceTypeDef);
  945. // if (!typeInstanceDefType)
  946. // return;
  947. // auto typeInstanceDefTypeInstance = typeInstanceDefType->ToTypeInstance();
  948. //
  949. // auto typeDef = mSystem->FindTypeDef("System.ClassVData");
  950. // BF_ASSERT(typeDef != NULL);
  951. // auto bfClassVDataType = bfModule->ResolveTypeDef(typeDef)->ToTypeInstance();
  952. // vdataContext->mBfClassVDataPtrType = bfModule->CreatePointerType(bfClassVDataType);
  953. //////////////////////////////////////////////////////////////////////////
  954. int numEntries = 0;
  955. int numConcreteTypes = 0;
  956. Array<BfType*> orderedTypes;
  957. for (auto type : mContext->mResolvedTypes)
  958. {
  959. numEntries++;
  960. BF_ASSERT((type != NULL) || (mPassInstance->HasFailed()));
  961. if (!type->IsReified())
  962. continue;
  963. orderedTypes.Add(type);
  964. CompileLog("TypeId:%d %s\n", type->mTypeId, bfModule->TypeToString(type).c_str());
  965. if ((type != NULL) && (type->IsObjectOrInterface()))
  966. {
  967. numConcreteTypes++;
  968. auto typeInst = type->ToTypeInstance();
  969. if (typeInst->mModule == NULL)
  970. {
  971. BF_ASSERT(mPassInstance->HasFailed());
  972. continue;
  973. }
  974. }
  975. }
  976. {
  977. BP_ZONE("BfCompiler::CreateVData sort orderedTypes");
  978. orderedTypes.Sort([](BfType* lhs, BfType* rhs)
  979. {
  980. return lhs->mTypeId < rhs->mTypeId;
  981. });
  982. }
  983. BfLogSysM("TypeEntries: %d ConcreteTypes: %d\n", numEntries, numConcreteTypes);
  984. HashContext vdataHashCtx;
  985. //vdataHashCtx.mDbgViz = true;
  986. vdataHashCtx.Mixin(bfModule->mProject->mVDataConfigHash);
  987. Array<TestMethod> testMethods;
  988. if (project->mTargetType == BfTargetType_BeefTest)
  989. GetTestMethods(bfModule, testMethods, vdataHashCtx);
  990. Array<String*> typeNameList;
  991. defer(
  992. {
  993. for (auto str : typeNameList)
  994. delete str;
  995. });
  996. struct _SortedTypeEntry
  997. {
  998. BfTypeInstance* mTypeInstance;
  999. String* mTypeName;
  1000. int mPriority;
  1001. _SortedTypeEntry()
  1002. {
  1003. mPriority = 0;
  1004. mTypeInstance = NULL;
  1005. mTypeName = NULL;
  1006. }
  1007. _SortedTypeEntry(BfModule* module, BfTypeInstance* typeInstance, Array<String*>& nameList, String*& namePtr)
  1008. {
  1009. if (namePtr == NULL)
  1010. {
  1011. namePtr = new String(module->TypeToString(typeInstance));
  1012. nameList.Add(namePtr);
  1013. }
  1014. mTypeName = namePtr;
  1015. mTypeInstance = typeInstance;
  1016. mPriority = 0;
  1017. }
  1018. static void Sort(Array<_SortedTypeEntry>& list)
  1019. {
  1020. list.Sort(
  1021. [](const _SortedTypeEntry& lhs, const _SortedTypeEntry& rhs)
  1022. {
  1023. if (lhs.mPriority != rhs.mPriority)
  1024. return lhs.mPriority > rhs.mPriority;
  1025. return *lhs.mTypeName < *rhs.mTypeName;
  1026. });
  1027. }
  1028. static void SortRev(Array<_SortedTypeEntry>& list)
  1029. {
  1030. list.Sort(
  1031. [](const _SortedTypeEntry& lhs, const _SortedTypeEntry& rhs)
  1032. {
  1033. if (lhs.mPriority != rhs.mPriority)
  1034. return lhs.mPriority < rhs.mPriority;
  1035. return *lhs.mTypeName > *rhs.mTypeName;
  1036. });
  1037. }
  1038. };
  1039. Array<_SortedTypeEntry> preStaticInitList;
  1040. Array<_SortedTypeEntry> staticMarkList;
  1041. Array<_SortedTypeEntry> staticTLSList;
  1042. Array<BfType*> vdataTypeList;
  1043. HashSet<BfModule*> usedModuleSet;
  1044. HashSet<BfType*> reflectTypeSet;
  1045. HashSet<BfType*> reflectFieldTypeSet;
  1046. vdataHashCtx.MixinStr(project->mStartupObject);
  1047. vdataHashCtx.Mixin(project->mTargetType);
  1048. for (auto type : orderedTypes)
  1049. {
  1050. if (type == NULL)
  1051. continue;
  1052. if (type->IsTemporary())
  1053. continue;
  1054. if ((type->IsGenericParam()) || (type->IsUnspecializedTypeVariation()))
  1055. continue;
  1056. auto typeInst = type->ToTypeInstance();
  1057. if ((typeInst != NULL) && (!typeInst->IsReified()) && (!typeInst->IsUnspecializedType()))
  1058. continue;
  1059. if (!IsTypeUsed(type, project))
  1060. continue;
  1061. vdataTypeList.push_back(type);
  1062. vdataHashCtx.Mixin(type->mTypeId);
  1063. BF_ASSERT((type != NULL) || (mPassInstance->HasFailed()));
  1064. if ((type != NULL) && (typeInst != NULL))
  1065. {
  1066. auto module = typeInst->mModule;
  1067. if (module == NULL)
  1068. continue;
  1069. if (type->IsEnum())
  1070. {
  1071. for (auto& fieldInst : typeInst->mFieldInstances)
  1072. {
  1073. auto fieldDef = fieldInst.GetFieldDef();
  1074. if (fieldDef == NULL)
  1075. continue;
  1076. if (!fieldDef->IsEnumCaseEntry())
  1077. continue;
  1078. if (fieldInst.mResolvedType->IsTuple())
  1079. reflectFieldTypeSet.Add(fieldInst.mResolvedType);
  1080. }
  1081. }
  1082. if (type->IsInterface())
  1083. vdataHashCtx.Mixin(typeInst->mSlotNum);
  1084. vdataHashCtx.Mixin(typeInst->mAlwaysIncludeFlags);
  1085. vdataHashCtx.Mixin(typeInst->mHasBeenInstantiated);
  1086. if (!module->mIsScratchModule)
  1087. {
  1088. BF_ASSERT(module->mIsReified);
  1089. if (usedModuleSet.Add(module))
  1090. {
  1091. CompileLog("UsedModule %p %s\n", module, module->mModuleName.c_str());
  1092. HashModuleVData(module, vdataHashCtx);
  1093. }
  1094. }
  1095. vdataHashCtx.MixinStr(module->mModuleName);
  1096. vdataHashCtx.Mixin(typeInst->mTypeDef->mSignatureHash);
  1097. vdataHashCtx.Mixin(module->mHasForceLinkMarker);
  1098. for (auto iface : typeInst->mInterfaces)
  1099. {
  1100. vdataHashCtx.Mixin(iface.mInterfaceType->mTypeId);
  1101. vdataHashCtx.Mixin(iface.mDeclaringType->mTypeCode);
  1102. vdataHashCtx.Mixin(iface.mDeclaringType->mProject);
  1103. }
  1104. if (!typeInst->IsUnspecializedType())
  1105. {
  1106. for (auto& methodInstGroup : typeInst->mMethodInstanceGroups)
  1107. {
  1108. bool isImplementedAndReified = (methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  1109. (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mIsUnspecialized);
  1110. vdataHashCtx.Mixin(isImplementedAndReified);
  1111. }
  1112. }
  1113. // Could be necessary if a base type in another project adds new virtual methods (for example)
  1114. auto baseType = typeInst->mBaseType;
  1115. while (baseType != NULL)
  1116. {
  1117. vdataHashCtx.Mixin(baseType->mTypeDef->mSignatureHash);
  1118. baseType = baseType->mBaseType;
  1119. }
  1120. //TODO: What was this for?
  1121. // if (module->mProject != bfModule->mProject)
  1122. // {
  1123. // if ((module->mProject != NULL) && (module->mProject->mTargetType == BfTargetType_BeefDynLib))
  1124. // continue;
  1125. // }
  1126. String* typeName = NULL;
  1127. if ((typeInst->mHasStaticInitMethod) || (typeInst->mHasStaticDtorMethod))
  1128. preStaticInitList.Add(_SortedTypeEntry(bfModule, typeInst, typeNameList, typeName));
  1129. if ((typeInst->mHasStaticMarkMethod) && (mOptions.mEnableRealtimeLeakCheck))
  1130. staticMarkList.Add(_SortedTypeEntry(bfModule, typeInst, typeNameList, typeName));
  1131. if ((typeInst->mHasTLSFindMethod) && (mOptions.mEnableRealtimeLeakCheck))
  1132. staticTLSList.Add(_SortedTypeEntry(bfModule, typeInst, typeNameList, typeName));
  1133. }
  1134. }
  1135. int lastModuleRevision = bfModule->mRevision;
  1136. Val128 vdataHash = vdataHashCtx.Finish128();
  1137. bool wantsRebuild = vdataHash != bfModule->mDataHash;
  1138. if (bfModule->mHadBuildError)
  1139. wantsRebuild = true;
  1140. // If we did one of those 'hot compile' partial vdata builds, now build the whole thing
  1141. if ((!IsHotCompile()) && (bfModule->mHadHotObjectWrites))
  1142. wantsRebuild = true;
  1143. if (mOptions.mHotProject != NULL)
  1144. {
  1145. HashContext vdataHashCtxEx;
  1146. vdataHashCtxEx.Mixin(mOptions.mHotProject->mName);
  1147. vdataHashCtxEx.Mixin((int)mHotState->mNewlySlottedTypeIds.size());
  1148. for (auto typeId : mHotState->mNewlySlottedTypeIds)
  1149. vdataHashCtxEx.Mixin(typeId);
  1150. vdataHashCtxEx.Mixin((int)mHotState->mSlotDefineTypeIds.size());
  1151. for (auto typeId : mHotState->mSlotDefineTypeIds)
  1152. vdataHashCtxEx.Mixin(typeId);
  1153. Val128 vdataHashEx = vdataHashCtxEx.Finish128();
  1154. if (mHotState->mVDataHashEx.IsZero())
  1155. {
  1156. if (!mHotState->mNewlySlottedTypeIds.IsEmpty())
  1157. wantsRebuild = true;
  1158. if (!mHotState->mSlotDefineTypeIds.IsEmpty())
  1159. wantsRebuild = true;
  1160. }
  1161. else
  1162. {
  1163. if (vdataHashEx != mHotState->mVDataHashEx)
  1164. wantsRebuild = true;
  1165. }
  1166. mHotState->mVDataHashEx = vdataHashEx;
  1167. }
  1168. if ((wantsRebuild) || (bfModule->mIsModuleMutable))
  1169. {
  1170. bfModule->StartNewRevision();
  1171. if (bfModule->mAwaitingInitFinish)
  1172. bfModule->FinishInit();
  1173. }
  1174. // We add the string hash into vdata hash later
  1175. bfModule->mDataHash = vdataHash;//vdataPreStringHash;
  1176. // This handles "no StartNewRevision" 'else' case, but also handles if vdata failed to complete from a previous compilation
  1177. if (!bfModule->mIsModuleMutable)
  1178. {
  1179. CompileLog("VData unchanged, skipping\n");
  1180. return;
  1181. }
  1182. BfTypeInstance* stringType = bfModule->ResolveTypeDef(mStringTypeDef, BfPopulateType_Data)->ToTypeInstance();
  1183. BfTypeInstance* stringViewType = bfModule->ResolveTypeDef(mStringViewTypeDef, BfPopulateType_Data)->ToTypeInstance();
  1184. BfTypeInstance* reflectSpecializedTypeInstance = bfModule->ResolveTypeDef(mReflectSpecializedGenericType)->ToTypeInstance();
  1185. BfTypeInstance* reflectUnspecializedTypeInstance = bfModule->ResolveTypeDef(mReflectUnspecializedGenericType)->ToTypeInstance();
  1186. BfTypeInstance* reflectArrayTypeInstance = bfModule->ResolveTypeDef(mReflectArrayType)->ToTypeInstance();
  1187. bool madeBfTypeData = false;
  1188. auto typeDefType = mContext->mBfTypeType;
  1189. bool needsTypeList = bfModule->IsMethodImplementedAndReified(typeDefType, "GetType");
  1190. bool needsObjectTypeData = needsTypeList || bfModule->IsMethodImplementedAndReified(vdataContext->mBfObjectType, "RawGetType") || bfModule->IsMethodImplementedAndReified(vdataContext->mBfObjectType, "GetType");
  1191. bool needsTypeNames = bfModule->IsMethodImplementedAndReified(typeDefType, "GetName") || bfModule->IsMethodImplementedAndReified(typeDefType, "GetFullName");
  1192. bool needsStringLiteralList = (mOptions.mAllowHotSwapping) || (bfModule->IsMethodImplementedAndReified(stringType, "Intern")) || (bfModule->IsMethodImplementedAndReified(stringViewType, "Intern"));
  1193. Dictionary<int, int> usedStringIdMap;
  1194. reflectTypeSet.Add(vdataContext->mUnreifiedModule->ResolveTypeDef(mReflectTypeInstanceTypeDef));
  1195. reflectTypeSet.Add(vdataContext->mUnreifiedModule->ResolveTypeDef(mReflectSpecializedGenericType));
  1196. reflectTypeSet.Add(vdataContext->mUnreifiedModule->ResolveTypeDef(mReflectUnspecializedGenericType));
  1197. reflectTypeSet.Add(vdataContext->mUnreifiedModule->ResolveTypeDef(mReflectArrayType));
  1198. reflectTypeSet.Add(vdataContext->mUnreifiedModule->ResolveTypeDef(mReflectGenericParamType));
  1199. SmallVector<BfIRValue, 256> typeDataVector;
  1200. for (auto type : vdataTypeList)
  1201. {
  1202. if (type->IsTypeAlias())
  1203. continue;
  1204. if (type->IsTypeInstance())
  1205. BF_ASSERT(!type->IsIncomplete());
  1206. auto typeInst = type->ToTypeInstance();
  1207. if ((typeInst != NULL) && (!typeInst->IsReified()) && (!typeInst->IsUnspecializedType()))
  1208. continue;
  1209. bool needsTypeData = (needsTypeList) || ((type->IsObject()) && (needsObjectTypeData));
  1210. bool needsVData = (type->IsObject()) && (typeInst->HasBeenInstantiated());
  1211. bool forceReflectFields = false;
  1212. if (bfModule->mProject->mReferencedTypeData.Contains(type))
  1213. {
  1214. needsTypeData = true;
  1215. if (type->IsEnum())
  1216. forceReflectFields = true;
  1217. }
  1218. BfIRValue typeVariable;
  1219. if ((needsTypeData) || (needsVData))
  1220. {
  1221. if (reflectFieldTypeSet.Contains(type))
  1222. {
  1223. needsTypeData = true;
  1224. forceReflectFields = true;
  1225. }
  1226. else if (reflectTypeSet.Contains(type))
  1227. {
  1228. needsTypeData = true;
  1229. needsVData = true;
  1230. }
  1231. typeVariable = bfModule->CreateTypeData(type, usedStringIdMap, forceReflectFields, needsTypeData, needsTypeNames, needsVData);
  1232. }
  1233. type->mDirty = false;
  1234. if (needsTypeList)
  1235. {
  1236. int typeId = type->mTypeId;
  1237. if (typeId == -1)
  1238. continue;
  1239. if (typeId >= (int)typeDataVector.size())
  1240. typeDataVector.resize(typeId + 1);
  1241. typeDataVector[typeId] = typeVariable;
  1242. }
  1243. }
  1244. for (int typeId = 0; typeId < (int)typeDataVector.size(); typeId++)
  1245. {
  1246. if (!typeDataVector[typeId])
  1247. typeDataVector[typeId] = bfModule->GetDefaultValue(typeDefType);
  1248. }
  1249. // We only need 'sTypes' if we actually reference it
  1250. //
  1251. {
  1252. auto typeDefPtrType = bfModule->CreatePointerType(typeDefType);
  1253. StringT<128> typesVariableName;
  1254. BfMangler::MangleStaticFieldName(typesVariableName, GetMangleKind(), typeDefType->ToTypeInstance(), "sTypes", typeDefPtrType);
  1255. auto arrayType = bfModule->mBfIRBuilder->GetSizedArrayType(bfModule->mBfIRBuilder->MapType(typeDefType), (int)typeDataVector.size());
  1256. auto typeDataConst = bfModule->mBfIRBuilder->CreateConstAgg_Value(arrayType, typeDataVector);
  1257. BfIRValue typeDataArray = bfModule->mBfIRBuilder->CreateGlobalVariable(arrayType, true, BfIRLinkageType_External,
  1258. typeDataConst, typesVariableName);
  1259. StringT<128> typeCountVariableName;
  1260. BfMangler::MangleStaticFieldName(typeCountVariableName, GetMangleKind(), typeDefType->ToTypeInstance(), "sTypeCount", bfModule->GetPrimitiveType(BfTypeCode_Int32));
  1261. bfModule->mBfIRBuilder->CreateGlobalVariable(bfModule->mBfIRBuilder->MapType(bfModule->GetPrimitiveType(BfTypeCode_Int32)), true, BfIRLinkageType_External,
  1262. bfModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, (int)typeDataVector.size()), typeCountVariableName);
  1263. }
  1264. HashSet<int> foundStringIds;
  1265. for (int stringId : bfModule->mStringPoolRefs)
  1266. foundStringIds.Add(stringId);
  1267. Array<BfModule*> orderedUsedModules;
  1268. for (auto module : usedModuleSet)
  1269. orderedUsedModules.push_back(module);
  1270. std::sort(orderedUsedModules.begin(), orderedUsedModules.end(), [] (BfModule* lhs, BfModule* rhs)
  1271. {
  1272. return lhs->mModuleName < rhs->mModuleName;
  1273. });
  1274. Array<BfMethodInstance*> dllMethods;
  1275. Array<BfIRValue> forceLinkValues;
  1276. HashSet<int> dllNameSet;
  1277. Array<BfCompiler::StringValueEntry> stringValueEntries;
  1278. for (auto module : orderedUsedModules)
  1279. {
  1280. CheckModuleStringRefs(module, bfModule, lastModuleRevision, foundStringIds, dllNameSet, dllMethods, stringValueEntries);
  1281. if ((module->mHasForceLinkMarker) &&
  1282. ((!isHotCompile) || (module->mHadHotObjectWrites)) &&
  1283. (mOptions.mPlatformType != BfPlatformType_Wasm))
  1284. forceLinkValues.Add(bfModule->CreateForceLinkMarker(module, NULL));
  1285. }
  1286. if (!forceLinkValues.IsEmpty())
  1287. {
  1288. auto elemType = bfModule->CreatePointerType(bfModule->GetPrimitiveType(BfTypeCode_Int8));
  1289. auto arrayType = bfModule->mBfIRBuilder->GetSizedArrayType(bfModule->mBfIRBuilder->MapType(elemType), (int)forceLinkValues.size());
  1290. auto typeDataConst = bfModule->mBfIRBuilder->CreateConstAgg_Value(arrayType, forceLinkValues);
  1291. BfIRValue typeDataArray = bfModule->mBfIRBuilder->CreateGlobalVariable(arrayType, true, BfIRLinkageType_Internal,
  1292. typeDataConst, "FORCELINK_MODULES");
  1293. }
  1294. // Generate strings array
  1295. {
  1296. if (!needsStringLiteralList)
  1297. {
  1298. stringValueEntries.Clear();
  1299. }
  1300. std::sort(stringValueEntries.begin(), stringValueEntries.end(),
  1301. [](const StringValueEntry& lhs, const StringValueEntry& rhs)
  1302. {
  1303. return lhs.mId < rhs.mId;
  1304. });
  1305. auto stringPtrType = bfModule->CreatePointerType(stringType);
  1306. auto stringPtrIRType = bfModule->mBfIRBuilder->MapTypeInstPtr(stringType);
  1307. StringT<128> stringsVariableName;
  1308. BfMangler::MangleStaticFieldName(stringsVariableName, GetMangleKind(), stringType->ToTypeInstance(), "sStringLiterals", stringPtrType);
  1309. Array<BfIRValue> stringList;
  1310. stringList.Add(bfModule->mBfIRBuilder->CreateConstNull(stringPtrIRType));
  1311. for (auto& stringValueEntry : stringValueEntries)
  1312. stringList.Add(stringValueEntry.mStringVal);
  1313. stringList.Add(bfModule->mBfIRBuilder->CreateConstNull(stringPtrIRType));
  1314. BfIRType stringArrayType = bfModule->mBfIRBuilder->GetSizedArrayType(stringPtrIRType, (int)stringList.size());
  1315. auto stringArray = bfModule->mBfIRBuilder->CreateConstAgg_Value(stringArrayType, stringList);
  1316. auto stringArrayVar = bfModule->mBfIRBuilder->CreateGlobalVariable(stringArrayType, true, BfIRLinkageType_External, stringArray, stringsVariableName);
  1317. if (bfModule->mBfIRBuilder->DbgHasInfo())
  1318. {
  1319. auto dbgArrayType = bfModule->mBfIRBuilder->DbgCreateArrayType(stringList.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, bfModule->mBfIRBuilder->DbgGetType(stringPtrType), (int)stringList.size());
  1320. bfModule->mBfIRBuilder->DbgCreateGlobalVariable(bfModule->mDICompileUnit, stringsVariableName, stringsVariableName, BfIRMDNode(), 0, dbgArrayType, false, stringArrayVar);
  1321. }
  1322. }
  1323. // Generate string ID array
  1324. {
  1325. auto stringType = bfModule->ResolveTypeDef(mStringTypeDef, BfPopulateType_Data)->ToTypeInstance();
  1326. auto stringPtrType = bfModule->CreatePointerType(stringType);
  1327. auto stringPtrIRType = bfModule->mBfIRBuilder->MapTypeInstPtr(stringType);
  1328. StringT<128> stringsVariableName;
  1329. BfMangler::MangleStaticFieldName(stringsVariableName, GetMangleKind(), stringType->ToTypeInstance(), "sIdStringLiterals", stringPtrType);
  1330. Array<BfIRValue> stringList;
  1331. stringList.Resize(usedStringIdMap.size());
  1332. for (auto& kv : usedStringIdMap)
  1333. {
  1334. stringList[kv.mValue] = bfModule->mStringObjectPool[kv.mKey];
  1335. }
  1336. BfIRType stringArrayType = bfModule->mBfIRBuilder->GetSizedArrayType(stringPtrIRType, (int)usedStringIdMap.size());
  1337. auto stringArray = bfModule->mBfIRBuilder->CreateConstAgg_Value(stringArrayType, stringList);
  1338. auto stringArrayVar = bfModule->mBfIRBuilder->CreateGlobalVariable(stringArrayType, true, BfIRLinkageType_External, stringArray, stringsVariableName);
  1339. if (bfModule->mBfIRBuilder->DbgHasInfo())
  1340. {
  1341. auto dbgArrayType = bfModule->mBfIRBuilder->DbgCreateArrayType(stringList.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, bfModule->mBfIRBuilder->DbgGetType(stringPtrType), (int)stringList.size());
  1342. bfModule->mBfIRBuilder->DbgCreateGlobalVariable(bfModule->mDICompileUnit, stringsVariableName, stringsVariableName, BfIRMDNode(), 0, dbgArrayType, false, stringArrayVar);
  1343. }
  1344. }
  1345. BfIRFunction loadSharedLibFunc = CreateLoadSharedLibraries(bfModule, dllMethods);
  1346. BfIRType nullPtrType = bfModule->mBfIRBuilder->MapType(bfModule->GetPrimitiveType(BfTypeCode_NullPtr));
  1347. BfIRType voidType = bfModule->mBfIRBuilder->MapType(bfModule->GetPrimitiveType(BfTypeCode_None));
  1348. BfIRType int32Type = bfModule->mBfIRBuilder->MapType(bfModule->GetPrimitiveType(BfTypeCode_Int32));
  1349. Array<_SortedTypeEntry> staticInitList;
  1350. // Populate staticInitList
  1351. {
  1352. Dictionary<int, BfTypeInstance*> pendingIDToInstanceMap;
  1353. HashSet<BfTypeInstance*> handledTypes;
  1354. BfType* staticInitPriorityAttributeType = vdataContext->mUnreifiedModule->ResolveTypeDef(mStaticInitPriorityAttributeTypeDef);
  1355. BfType* staticInitAfterAttributeType = vdataContext->mUnreifiedModule->ResolveTypeDef(mStaticInitAfterAttributeTypeDef);
  1356. bool forceAdd = false;
  1357. for (int pass = 0; true; pass++)
  1358. {
  1359. bool hadAdd = false;
  1360. for (auto& mapEntry : preStaticInitList)
  1361. {
  1362. auto typeInst = mapEntry.mTypeInstance;
  1363. if ((typeInst != NULL) && (!typeInst->IsUnspecializedType()))
  1364. {
  1365. if (pass == 0)
  1366. {
  1367. int priority = 0;
  1368. bool hadInitAfterAttribute = false;
  1369. if (typeInst->mCustomAttributes != NULL)
  1370. {
  1371. for (auto& customAttr : typeInst->mCustomAttributes->mAttributes)
  1372. {
  1373. if (customAttr.mType == staticInitAfterAttributeType)
  1374. hadInitAfterAttribute = true;
  1375. if (customAttr.mType == staticInitPriorityAttributeType)
  1376. {
  1377. if (customAttr.mCtorArgs.size() == 1)
  1378. {
  1379. auto constant = typeInst->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  1380. if (constant != NULL)
  1381. priority = constant->mInt32;
  1382. }
  1383. }
  1384. }
  1385. }
  1386. if (!hadInitAfterAttribute)
  1387. {
  1388. mapEntry.mPriority = priority;
  1389. staticInitList.Add(mapEntry);
  1390. mapEntry.mTypeInstance = NULL;
  1391. }
  1392. else
  1393. {
  1394. pendingIDToInstanceMap.TryAdd(typeInst->mTypeId, typeInst);
  1395. }
  1396. }
  1397. else
  1398. {
  1399. if (pendingIDToInstanceMap.ContainsKey(typeInst->mTypeId))
  1400. {
  1401. bool doAdd = true;
  1402. if (!forceAdd)
  1403. {
  1404. for (auto& customAttr : typeInst->mCustomAttributes->mAttributes)
  1405. {
  1406. if (customAttr.mType == staticInitAfterAttributeType)
  1407. {
  1408. if (customAttr.mCtorArgs.size() == 0)
  1409. {
  1410. doAdd = false;
  1411. }
  1412. else
  1413. {
  1414. auto ctorArg = customAttr.mCtorArgs[0];
  1415. auto constant = typeInst->mConstHolder->GetConstant(ctorArg);
  1416. if (constant != NULL)
  1417. {
  1418. int refTypeId = constant->mInt32;
  1419. if (pendingIDToInstanceMap.ContainsKey(refTypeId))
  1420. doAdd = false;
  1421. }
  1422. }
  1423. }
  1424. }
  1425. }
  1426. if (doAdd)
  1427. {
  1428. staticInitList.Add(mapEntry);
  1429. pendingIDToInstanceMap.Remove(typeInst->mTypeId);
  1430. hadAdd = true;
  1431. }
  1432. }
  1433. }
  1434. }
  1435. }
  1436. if (pass == 0)
  1437. {
  1438. _SortedTypeEntry::Sort(staticInitList);
  1439. }
  1440. if ((pass > 0) && (!hadAdd) && (pendingIDToInstanceMap.size() > 0)) // Circular ref?
  1441. forceAdd = true;
  1442. if (pendingIDToInstanceMap.size() == 0)
  1443. break;
  1444. }
  1445. }
  1446. /// Generate "BfCallAllStaticDtors"
  1447. BfIRFunction dtorFunc;
  1448. {
  1449. SmallVector<BfIRType, 2> paramTypes;
  1450. auto dtorFuncType = bfModule->mBfIRBuilder->CreateFunctionType(voidType, paramTypes, false);
  1451. String dtorName = (mOptions.mPlatformType == BfPlatformType_Wasm) ? "BeefDone" : "BfCallAllStaticDtors";
  1452. dtorFunc = bfModule->mBfIRBuilder->CreateFunction(dtorFuncType, BfIRLinkageType_External, dtorName);
  1453. bfModule->SetupIRMethod(NULL, dtorFunc, false);
  1454. bfModule->mBfIRBuilder->SetActiveFunction(dtorFunc);
  1455. auto entryBlock = bfModule->mBfIRBuilder->CreateBlock("entry", true);
  1456. bfModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  1457. for (int i = staticInitList.mSize - 1; i >= 0; i--)
  1458. {
  1459. auto typeInst = staticInitList[i].mTypeInstance;
  1460. if (!typeInst->mHasStaticDtorMethod)
  1461. continue;
  1462. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1463. {
  1464. auto methodInstance = methodGroup.mDefault;
  1465. if ((methodInstance != NULL) &&
  1466. (methodInstance->mMethodDef->mIsStatic) &&
  1467. (methodInstance->mMethodDef->mMethodType == BfMethodType_Dtor) &&
  1468. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  1469. {
  1470. if (!typeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, bfModule->mProject))
  1471. continue;
  1472. if (methodInstance->mHotMethod != NULL)
  1473. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_AlwaysCalled);
  1474. auto methodModule = bfModule->GetMethodInstanceAtIdx(typeInst, methodInstance->mMethodDef->mIdx);
  1475. bfModule->mBfIRBuilder->CreateCall(methodModule.mFunc, SmallVector<BfIRValue, 0>());
  1476. }
  1477. }
  1478. }
  1479. bfModule->mBfIRBuilder->CreateRetVoid();
  1480. }
  1481. auto targetType = project->mTargetType;
  1482. if ((targetType == BfTargetType_BeefWindowsApplication) && (mOptions.mPlatformType != BfPlatformType_Windows))
  1483. targetType = BfTargetType_BeefConsoleApplication;
  1484. bool isConsoleApplication = (targetType == BfTargetType_BeefConsoleApplication) || (targetType == BfTargetType_BeefTest);
  1485. if ((targetType == BfTargetType_BeefWindowsApplication) && (mOptions.mPlatformType != BfPlatformType_Windows))
  1486. isConsoleApplication = true;
  1487. bool isDllMain = (targetType == BfTargetType_BeefLib_DynamicLib) && (mOptions.mPlatformType == BfPlatformType_Windows);
  1488. bool isPosixDynLib = ((targetType == BfTargetType_BeefLib_DynamicLib) || (targetType == BfTargetType_BeefLib_StaticLib)) &&
  1489. (mOptions.mPlatformType != BfPlatformType_Windows);
  1490. bool mainHasArgs = (targetType != BfTargetType_BeefLib_DynamicLib) && (targetType != BfTargetType_BeefLib_StaticLib) &&
  1491. (mOptions.mPlatformType != BfPlatformType_Wasm);
  1492. bool mainHasRet = ((targetType != BfTargetType_BeefLib_DynamicLib) && (targetType != BfTargetType_BeefLib_StaticLib)) || (isDllMain);
  1493. // Generate "main"
  1494. if (!IsHotCompile())
  1495. {
  1496. int rtFlags = 0;
  1497. BfIRFunctionType mainFuncType;
  1498. BfIRFunction mainFunc;
  1499. BfIRFunctionType shutdownFuncType;
  1500. BfIRFunction shutdownFunc;
  1501. if (isConsoleApplication)
  1502. {
  1503. SmallVector<BfIRType, 2> paramTypes;
  1504. paramTypes.push_back(int32Type);
  1505. paramTypes.push_back(nullPtrType);
  1506. mainFuncType = bfModule->mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, false);
  1507. mainFunc = bfModule->mBfIRBuilder->CreateFunction(mainFuncType, BfIRLinkageType_External, "main");
  1508. bfModule->SetupIRMethod(NULL, mainFunc, false);
  1509. }
  1510. else if (isDllMain)
  1511. {
  1512. SmallVector<BfIRType, 4> paramTypes;
  1513. paramTypes.push_back(nullPtrType); // hinstDLL
  1514. paramTypes.push_back(int32Type); // fdwReason
  1515. paramTypes.push_back(nullPtrType); // lpvReserved
  1516. mainFuncType = bfModule->mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, false);
  1517. mainFunc = bfModule->mBfIRBuilder->CreateFunction(mainFuncType, BfIRLinkageType_External, "DllMain");
  1518. if (mOptions.mMachineType == BfMachineType_x86)
  1519. bfModule->mBfIRBuilder->SetFuncCallingConv(mainFunc, BfIRCallingConv_StdCall);
  1520. bfModule->SetupIRMethod(NULL, mainFunc, false);
  1521. rtFlags = 0x10; // BfRtFlags_NoThreadExitWait
  1522. }
  1523. else if (targetType == BfTargetType_BeefWindowsApplication)
  1524. {
  1525. SmallVector<BfIRType, 4> paramTypes;
  1526. paramTypes.push_back(nullPtrType); // hInstance
  1527. paramTypes.push_back(nullPtrType); // hPrevInstance
  1528. paramTypes.push_back(nullPtrType); // lpCmdLine
  1529. paramTypes.push_back(int32Type); // nCmdShow
  1530. mainFuncType = bfModule->mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, false);
  1531. mainFunc = bfModule->mBfIRBuilder->CreateFunction(mainFuncType, BfIRLinkageType_External, "WinMain");
  1532. if (mOptions.mMachineType == BfMachineType_x86)
  1533. bfModule->mBfIRBuilder->SetFuncCallingConv(mainFunc, BfIRCallingConv_StdCall);
  1534. bfModule->SetupIRMethod(NULL, mainFunc, false);
  1535. }
  1536. else
  1537. {
  1538. BfIRFunction combinedFunc;
  1539. SmallVector<BfIRType, 2> paramTypes;
  1540. if (mainHasArgs)
  1541. {
  1542. paramTypes.push_back(int32Type);
  1543. paramTypes.push_back(nullPtrType);
  1544. }
  1545. mainFuncType = bfModule->mBfIRBuilder->CreateFunctionType(mainHasRet ? int32Type : voidType, paramTypes, false);
  1546. mainFunc = bfModule->mBfIRBuilder->CreateFunction(mainFuncType, BfIRLinkageType_External, "BeefStart");
  1547. bfModule->SetupIRMethod(NULL, mainFunc, false);
  1548. combinedFunc = bfModule->mBfIRBuilder->CreateFunction(mainFuncType, BfIRLinkageType_External, "BeefMain");
  1549. bfModule->SetupIRMethod(NULL, combinedFunc, false);
  1550. paramTypes.clear();
  1551. shutdownFuncType = bfModule->mBfIRBuilder->CreateFunctionType(voidType, paramTypes, false);
  1552. shutdownFunc = bfModule->mBfIRBuilder->CreateFunction(shutdownFuncType, BfIRLinkageType_External, "BeefStop");
  1553. bfModule->SetupIRMethod(NULL, shutdownFunc, false);
  1554. bfModule->mBfIRBuilder->SetActiveFunction(combinedFunc);
  1555. auto entryBlock = bfModule->mBfIRBuilder->CreateBlock("entry", true);
  1556. bfModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  1557. SmallVector<BfIRValue, 1> args;
  1558. if (mainHasArgs)
  1559. {
  1560. args.push_back(bfModule->mBfIRBuilder->GetArgument(0));
  1561. args.push_back(bfModule->mBfIRBuilder->GetArgument(1));
  1562. }
  1563. auto res = bfModule->mBfIRBuilder->CreateCall(mainFunc, args);
  1564. args.clear();
  1565. bfModule->mBfIRBuilder->CreateCall(shutdownFunc, args);
  1566. if (mainHasRet)
  1567. bfModule->mBfIRBuilder->CreateRet(res);
  1568. else
  1569. bfModule->mBfIRBuilder->CreateRetVoid();
  1570. }
  1571. bfModule->mBfIRBuilder->SetActiveFunction(mainFunc);
  1572. auto entryBlock = bfModule->mBfIRBuilder->CreateBlock("entry", true);
  1573. bfModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  1574. if (rtFlags != 0)
  1575. {
  1576. auto addRtFlagMethod = bfModule->GetInternalMethod("AddRtFlags", 1);
  1577. if (addRtFlagMethod)
  1578. {
  1579. SmallVector<BfIRValue, 1> args;
  1580. args.push_back(bfModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, rtFlags));
  1581. bfModule->mBfIRBuilder->CreateCall(addRtFlagMethod.mFunc, args);
  1582. }
  1583. }
  1584. if ((mOptions.mPlatformType != BfPlatformType_Windows) && (mainHasArgs) &&
  1585. ((targetType == BfTargetType_BeefConsoleApplication) || (targetType == BfTargetType_BeefApplication_StaticLib) ||
  1586. (targetType == BfTargetType_BeefApplication_DynamicLib) || (targetType == BfTargetType_BeefTest)))
  1587. {
  1588. SmallVector<BfIRType, 2> paramTypes;
  1589. paramTypes.push_back(int32Type);
  1590. paramTypes.push_back(nullPtrType);
  1591. auto setCmdLineFuncType = bfModule->mBfIRBuilder->CreateFunctionType(voidType, paramTypes, false);
  1592. auto setCmdLineFunc = bfModule->mBfIRBuilder->CreateFunction(setCmdLineFuncType, BfIRLinkageType_External, "BfpSystem_SetCommandLine");
  1593. bfModule->SetupIRMethod(NULL, setCmdLineFunc, false);
  1594. SmallVector<BfIRValue, 2> args;
  1595. args.push_back(bfModule->mBfIRBuilder->GetArgument(0));
  1596. args.push_back(bfModule->mBfIRBuilder->GetArgument(1));
  1597. bfModule->mBfIRBuilder->CreateCall(setCmdLineFunc, args);
  1598. }
  1599. BfIRBlock initSkipBlock;
  1600. if (isDllMain)
  1601. {
  1602. auto initBlock = bfModule->mBfIRBuilder->CreateBlock("doInit", false);
  1603. initSkipBlock = bfModule->mBfIRBuilder->CreateBlock("skipInit", false);
  1604. auto cmpResult = bfModule->mBfIRBuilder->CreateCmpEQ(bfModule->mBfIRBuilder->GetArgument(1), bfModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1));
  1605. bfModule->mBfIRBuilder->CreateCondBr(cmpResult, initBlock, initSkipBlock);
  1606. bfModule->mBfIRBuilder->AddBlock(initBlock);
  1607. bfModule->mBfIRBuilder->SetInsertPoint(initBlock);
  1608. auto moduleMethodInstance = bfModule->GetInternalMethod("SetModuleHandle", 1);
  1609. if (moduleMethodInstance)
  1610. {
  1611. SmallVector<BfIRValue, 1> args;
  1612. args.push_back(bfModule->mBfIRBuilder->GetArgument(0));
  1613. bfModule->mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, args);
  1614. }
  1615. }
  1616. // Do the LoadLibrary calls below priority 100
  1617. bool didSharedLibLoad = false;
  1618. auto _CheckSharedLibLoad = [&]()
  1619. {
  1620. if (!didSharedLibLoad)
  1621. {
  1622. bfModule->mBfIRBuilder->CreateCall(loadSharedLibFunc, SmallVector<BfIRValue, 0>());
  1623. didSharedLibLoad = true;
  1624. }
  1625. };
  1626. for (auto& staticInitEntry : staticInitList)
  1627. {
  1628. auto typeInst = staticInitEntry.mTypeInstance;
  1629. if (!typeInst->mHasStaticInitMethod)
  1630. continue;
  1631. if (staticInitEntry.mPriority < 100)
  1632. _CheckSharedLibLoad();
  1633. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1634. {
  1635. auto methodInstance = methodGroup.mDefault;
  1636. if ((methodInstance != NULL) &&
  1637. (methodInstance->mMethodDef->mIsStatic) &&
  1638. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  1639. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  1640. {
  1641. if (!typeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, bfModule->mProject))
  1642. continue;
  1643. auto methodModule = bfModule->GetMethodInstanceAtIdx(typeInst, methodInstance->mMethodDef->mIdx);
  1644. if (methodInstance->mHotMethod != NULL)
  1645. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_AlwaysCalled);
  1646. bfModule->mBfIRBuilder->CreateCall(methodModule.mFunc, SmallVector<BfIRValue, 0>());
  1647. }
  1648. }
  1649. }
  1650. _CheckSharedLibLoad();
  1651. if (initSkipBlock)
  1652. {
  1653. bfModule->mBfIRBuilder->CreateBr(initSkipBlock);
  1654. bfModule->mBfIRBuilder->AddBlock(initSkipBlock);
  1655. bfModule->mBfIRBuilder->SetInsertPoint(initSkipBlock);
  1656. }
  1657. BfIRValue retValue;
  1658. if ((targetType == BfTargetType_BeefConsoleApplication) || (targetType == BfTargetType_BeefWindowsApplication) ||
  1659. (targetType == BfTargetType_BeefApplication_StaticLib) || (targetType == BfTargetType_BeefApplication_DynamicLib))
  1660. {
  1661. bool hadRet = false;
  1662. String entryClassName = project->mStartupObject;
  1663. auto typeDef = mSystem->FindTypeDef(entryClassName, 0, bfModule->mProject, {}, NULL, BfFindTypeDefFlag_AllowGlobal);
  1664. if (typeDef != NULL)
  1665. {
  1666. auto type = bfModule->ResolveTypeDef(typeDef);
  1667. BF_ASSERT((type != NULL) || (mPassInstance->HasFailed()));
  1668. if (type != NULL)
  1669. {
  1670. BfType* stringType = vdataContext->mUnreifiedModule->ResolveTypeDef(mStringTypeDef);
  1671. BfType* int32Type = bfModule->GetPrimitiveType(BfTypeCode_Int32);
  1672. BfType* intType = bfModule->GetPrimitiveType(BfTypeCode_IntPtr);
  1673. BfType* voidType = bfModule->GetPrimitiveType(BfTypeCode_None);
  1674. bool hadValidMainMethod = false;
  1675. BfModuleMethodInstance moduleMethodInst;
  1676. for (auto methodDef : typeDef->mMethods)
  1677. {
  1678. if (methodDef->mName == "Main")
  1679. {
  1680. hadValidMainMethod = true;
  1681. moduleMethodInst = bfModule->GetMethodInstanceAtIdx(type->ToTypeInstance(), methodDef->mIdx);
  1682. if (!methodDef->mIsStatic)
  1683. {
  1684. mPassInstance->Fail("Main method must be static", methodDef->GetRefNode());
  1685. hadValidMainMethod = false;
  1686. }
  1687. if ((moduleMethodInst.mMethodInstance->mReturnType != int32Type) &&
  1688. (moduleMethodInst.mMethodInstance->mReturnType != intType) &&
  1689. (moduleMethodInst.mMethodInstance->mReturnType != voidType))
  1690. {
  1691. mPassInstance->Fail("Main method must return void, int, or int32", methodDef->GetRefNode());
  1692. hadValidMainMethod = false;
  1693. }
  1694. if (moduleMethodInst.mMethodInstance->GetParamCount() == 0)
  1695. {
  1696. // No params
  1697. }
  1698. else
  1699. {
  1700. auto paramType = moduleMethodInst.mMethodInstance->GetParamType(0);
  1701. if ((moduleMethodInst.mMethodInstance->GetParamCount() != 1) || (!paramType->IsArray()) || (paramType->GetUnderlyingType() != stringType))
  1702. {
  1703. mPassInstance->Fail("Main method must be declared with either no parameters or a single String[] parameter", methodDef->GetRefNode());
  1704. hadValidMainMethod = false;
  1705. }
  1706. }
  1707. }
  1708. }
  1709. if (moduleMethodInst)
  1710. {
  1711. if (hadValidMainMethod)
  1712. {
  1713. bool hasArgs = moduleMethodInst.mMethodInstance->GetParamCount() != 0;
  1714. BfIRType intType = bfModule->mBfIRBuilder->MapType(bfModule->GetPrimitiveType(BfTypeCode_IntPtr));
  1715. BfIRType int32Type = bfModule->mBfIRBuilder->MapType(bfModule->GetPrimitiveType(BfTypeCode_Int32));
  1716. // Create BeefEntry thunk
  1717. SmallVector<BfIRType, 1> paramTypes;
  1718. if (hasArgs)
  1719. {
  1720. paramTypes.push_back(bfModule->mBfIRBuilder->MapType(moduleMethodInst.mMethodInstance->GetParamType(0)));
  1721. }
  1722. BfIRFunctionType thunkFuncType = bfModule->mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, false);
  1723. BfIRFunction thunkMainFunc = bfModule->mBfIRBuilder->CreateFunction(thunkFuncType, BfIRLinkageType_External, "BeefStartProgram");
  1724. bfModule->SetupIRMethod(NULL, thunkMainFunc, false);
  1725. bfModule->mBfIRBuilder->SetActiveFunction(thunkMainFunc);
  1726. auto thunkEntryBlock = bfModule->mBfIRBuilder->CreateBlock("entry", true);
  1727. bfModule->mBfIRBuilder->SetInsertPoint(thunkEntryBlock);
  1728. SmallVector<BfIRValue, 1> args;
  1729. if (hasArgs)
  1730. args.push_back(bfModule->mBfIRBuilder->GetArgument(0));
  1731. auto methodInstance = moduleMethodInst.mMethodInstance;
  1732. if (methodInstance->mHotMethod != NULL)
  1733. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_AlwaysCalled);
  1734. auto retVal = bfModule->mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  1735. if (moduleMethodInst.mMethodInstance->mReturnType->IsVoid())
  1736. {
  1737. bfModule->mBfIRBuilder->CreateRet(bfModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 0));
  1738. }
  1739. else
  1740. {
  1741. retVal = bfModule->mBfIRBuilder->CreateNumericCast(retVal, true, BfTypeCode_Int32);
  1742. bfModule->mBfIRBuilder->CreateRet(retVal);
  1743. }
  1744. hadRet = true;
  1745. auto internalType = bfModule->ResolveTypeDef(mInternalTypeDef);
  1746. args.clear();
  1747. // Call BeefEntry thunk
  1748. bfModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  1749. if (hasArgs)
  1750. {
  1751. auto createParamsMethodInstance = bfModule->GetMethodByName(internalType->ToTypeInstance(), "CreateParamsArray");
  1752. auto callValue = bfModule->mBfIRBuilder->CreateCall(createParamsMethodInstance.mFunc, SmallVector<BfIRValue, 0>());
  1753. args.push_back(callValue);
  1754. }
  1755. retValue = bfModule->mBfIRBuilder->CreateCall(thunkMainFunc, args);
  1756. if (hasArgs)
  1757. {
  1758. auto deleteStringArrayMethodInstance = bfModule->GetMethodByName(internalType->ToTypeInstance(), "DeleteStringArray");
  1759. bfModule->mBfIRBuilder->CreateCall(deleteStringArrayMethodInstance.mFunc, args);
  1760. }
  1761. }
  1762. }
  1763. else
  1764. {
  1765. if (entryClassName.IsEmpty())
  1766. mPassInstance->Fail("Unable to find Main method in global namespace. Consider specifying a Startup Object in the project properties.");
  1767. else
  1768. mPassInstance->Fail(StrFormat("Unable to find Main method in specified Startup Object '%s'", entryClassName.c_str()));
  1769. }
  1770. }
  1771. }
  1772. else
  1773. {
  1774. if (entryClassName.empty())
  1775. mPassInstance->Fail(StrFormat("No entry point class specified for executable in project '%s'", project->mName.c_str()));
  1776. else
  1777. mPassInstance->Fail(StrFormat("Unable to find entry point class '%s' in project '%s'", entryClassName.c_str(), project->mName.c_str()));
  1778. bfModule->mHadBuildError = true;
  1779. }
  1780. if (!hadRet)
  1781. retValue = bfModule->GetConstValue32(0);
  1782. }
  1783. else
  1784. {
  1785. if (mainHasRet)
  1786. retValue = bfModule->GetConstValue32(1);
  1787. }
  1788. if (targetType == BfTargetType_BeefTest)
  1789. EmitTestMethod(bfModule, testMethods, retValue);
  1790. BfIRBlock deinitSkipBlock;
  1791. if (isDllMain)
  1792. {
  1793. auto deinitBlock = bfModule->mBfIRBuilder->CreateBlock("doDeinit", false);
  1794. deinitSkipBlock = bfModule->mBfIRBuilder->CreateBlock("skipDeinit", false);
  1795. auto cmpResult = bfModule->mBfIRBuilder->CreateCmpEQ(bfModule->mBfIRBuilder->GetArgument(1), bfModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 0));
  1796. bfModule->mBfIRBuilder->CreateCondBr(cmpResult, deinitBlock, deinitSkipBlock);
  1797. bfModule->mBfIRBuilder->AddBlock(deinitBlock);
  1798. bfModule->mBfIRBuilder->SetInsertPoint(deinitBlock);
  1799. }
  1800. if (mOptions.mPlatformType != BfPlatformType_Wasm)
  1801. {
  1802. auto prevBlock = bfModule->mBfIRBuilder->GetInsertBlock();
  1803. if (shutdownFunc)
  1804. {
  1805. bfModule->mBfIRBuilder->SetActiveFunction(shutdownFunc);
  1806. auto entryBlock = bfModule->mBfIRBuilder->CreateBlock("entry", true);
  1807. bfModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  1808. }
  1809. bfModule->mBfIRBuilder->CreateCall(dtorFunc, SizedArray<BfIRValue, 0>());
  1810. BfModuleMethodInstance shutdownMethod = bfModule->GetInternalMethod("Shutdown");
  1811. if (shutdownMethod)
  1812. {
  1813. bfModule->mBfIRBuilder->CreateCall(shutdownMethod.mFunc, SizedArray<BfIRValue, 0>());
  1814. }
  1815. if (shutdownFunc)
  1816. {
  1817. bfModule->mBfIRBuilder->CreateRetVoid();
  1818. bfModule->mBfIRBuilder->SetActiveFunction(mainFunc);
  1819. bfModule->mBfIRBuilder->SetInsertPoint(prevBlock);
  1820. }
  1821. }
  1822. if (deinitSkipBlock)
  1823. {
  1824. bfModule->mBfIRBuilder->CreateBr(deinitSkipBlock);
  1825. bfModule->mBfIRBuilder->AddBlock(deinitSkipBlock);
  1826. bfModule->mBfIRBuilder->SetInsertPoint(deinitSkipBlock);
  1827. }
  1828. if (retValue)
  1829. bfModule->mBfIRBuilder->CreateRet(retValue);
  1830. else
  1831. bfModule->mBfIRBuilder->CreateRetVoid();
  1832. if ((mOptions.mAllowHotSwapping) && (bfModule->mHasFullDebugInfo))
  1833. {
  1834. auto int8Type = bfModule->GetPrimitiveType(BfTypeCode_Int8);
  1835. int dataSize = 16*1024;
  1836. auto irArrType = bfModule->mBfIRBuilder->GetSizedArrayType(bfModule->mBfIRBuilder->MapType(int8Type), dataSize);
  1837. String name = "__BFTLS_EXTRA";
  1838. auto irVal = bfModule->mBfIRBuilder->CreateGlobalVariable(irArrType, false, BfIRLinkageType_External, bfModule->mBfIRBuilder->CreateConstAggZero(irArrType), name, true);
  1839. BfIRMDNode dbgArrayType = bfModule->mBfIRBuilder->DbgCreateArrayType(dataSize * 8, 8, bfModule->mBfIRBuilder->DbgGetType(int8Type), dataSize);
  1840. bfModule->mBfIRBuilder->DbgCreateGlobalVariable(bfModule->mDICompileUnit, name, name, BfIRMDNode(), 0, dbgArrayType, false, irVal);
  1841. }
  1842. if (isPosixDynLib)
  1843. {
  1844. auto voidType = bfModule->mBfIRBuilder->MapType(bfModule->GetPrimitiveType(BfTypeCode_None));
  1845. SizedArray<BfIRType, 4> paramTypes;
  1846. BfIRFunctionType funcType = bfModule->mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  1847. BfIRFunction func = bfModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "BfDynLib__Startup");
  1848. bfModule->mBfIRBuilder->SetActiveFunction(func);
  1849. bfModule->mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_Constructor);
  1850. auto entryBlock = bfModule->mBfIRBuilder->CreateBlock("main", true);
  1851. bfModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  1852. SmallVector<BfIRValue, 2> startArgs;
  1853. bfModule->mBfIRBuilder->CreateCall(mainFunc, startArgs);
  1854. bfModule->mBfIRBuilder->CreateRetVoid();
  1855. //////////////////////////////////////////////////////////////////////////
  1856. func = bfModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "BfDynLib__Shutdown");
  1857. bfModule->mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_Destructor);
  1858. bfModule->mBfIRBuilder->SetActiveFunction(func);
  1859. entryBlock = bfModule->mBfIRBuilder->CreateBlock("main", true);
  1860. bfModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  1861. SmallVector<BfIRValue, 2> stopArgs;
  1862. bfModule->mBfIRBuilder->CreateCall(shutdownFunc, startArgs);
  1863. bfModule->mBfIRBuilder->CreateRetVoid();
  1864. }
  1865. }
  1866. // Generate "System.GC.MarkAllStaticMembers"
  1867. auto gcType = vdataContext->mUnreifiedModule->ResolveTypeDef(mGCTypeDef);
  1868. if (bfModule->IsMethodImplementedAndReified(gcType->ToTypeInstance(), "MarkAllStaticMembers"))
  1869. {
  1870. bfModule->PopulateType(gcType);
  1871. auto moduleMethodInstance = bfModule->GetMethodByName(gcType->ToTypeInstance(), "MarkAllStaticMembers");
  1872. bfModule->mBfIRBuilder->SetActiveFunction(moduleMethodInstance.mFunc);
  1873. if (!moduleMethodInstance)
  1874. {
  1875. bfModule->Fail("Internal error: System.GC doesn't contain MarkAllStaticMembers method");
  1876. }
  1877. else
  1878. {
  1879. auto entryBlock = bfModule->mBfIRBuilder->CreateBlock("entry", true);
  1880. bfModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  1881. _SortedTypeEntry::Sort(staticMarkList);
  1882. for (auto& mapEntry : staticMarkList)
  1883. {
  1884. auto typeInst = mapEntry.mTypeInstance;
  1885. if (typeInst->IsUnspecializedType())
  1886. continue;
  1887. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1888. {
  1889. auto methodInstance = methodGroup.mDefault;
  1890. if ((methodInstance != NULL) &&
  1891. (methodInstance->mMethodDef->mIsStatic) &&
  1892. (methodInstance->mMethodDef->mMethodType == BfMethodType_Normal) &&
  1893. (methodInstance->mMethodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) &&
  1894. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  1895. {
  1896. if (!typeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, bfModule->mProject))
  1897. continue;
  1898. auto methodModule = bfModule->GetMethodInstanceAtIdx(typeInst, methodInstance->mMethodDef->mIdx);
  1899. if (methodInstance->mHotMethod != NULL)
  1900. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_AlwaysCalled);
  1901. bfModule->mBfIRBuilder->CreateCall(methodModule.mFunc, SmallVector<BfIRValue, 0>());
  1902. }
  1903. }
  1904. }
  1905. bfModule->mBfIRBuilder->CreateRetVoid();
  1906. }
  1907. }
  1908. // Generate "System.GC.FindAllTLSMembers"
  1909. if (bfModule->IsMethodImplementedAndReified(gcType->ToTypeInstance(), "FindAllTLSMembers"))
  1910. {
  1911. bfModule->PopulateType(gcType);
  1912. auto moduleMethodInstance = bfModule->GetMethodByName(gcType->ToTypeInstance(), "FindAllTLSMembers");
  1913. bfModule->mBfIRBuilder->SetActiveFunction(moduleMethodInstance.mFunc);
  1914. if (!moduleMethodInstance)
  1915. {
  1916. bfModule->Fail("Internal error: System.GC doesn't contain FindAllTLSMembers method");
  1917. }
  1918. else
  1919. {
  1920. auto entryBlock = bfModule->mBfIRBuilder->CreateBlock("entry", true);
  1921. bfModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  1922. _SortedTypeEntry::Sort(staticTLSList);
  1923. for (auto& mapEntry : staticTLSList)
  1924. {
  1925. auto typeInst = mapEntry.mTypeInstance;
  1926. if (typeInst->IsUnspecializedType())
  1927. continue;
  1928. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1929. {
  1930. auto methodInstance = methodGroup.mDefault;
  1931. if ((methodInstance != NULL) &&
  1932. (methodInstance->mMethodDef->mIsStatic) &&
  1933. (methodInstance->mMethodDef->mMethodType == BfMethodType_Normal) &&
  1934. (methodInstance->mMethodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS) &&
  1935. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  1936. {
  1937. if (!typeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, bfModule->mProject))
  1938. continue;
  1939. auto methodModule = bfModule->GetMethodInstanceAtIdx(typeInst, methodInstance->mMethodDef->mIdx);
  1940. bfModule->mBfIRBuilder->CreateCall(methodModule.mFunc, SmallVector<BfIRValue, 0>());
  1941. }
  1942. }
  1943. }
  1944. bfModule->mBfIRBuilder->CreateRetVoid();
  1945. }
  1946. }
  1947. if (bfModule->mHadBuildError)
  1948. {
  1949. bfModule->mDataHash = 0;
  1950. }
  1951. }
  1952. // This method clears out unused generic types AFTER compilation of reified types has occurred
  1953. void BfCompiler::UpdateDependencyMap(bool deleteUnusued, bool& didWork)
  1954. {
  1955. BP_ZONE("BfCompiler::UpdateDependencyMap");
  1956. BfLogSysM("Compiler::UpdateDependencyMap %d\n", deleteUnusued);
  1957. bool madeFullPass = true;
  1958. if (mCanceling)
  1959. madeFullPass = false;
  1960. if ((mResolvePassData != NULL) && (!mResolvePassData->mParsers.IsEmpty()))
  1961. madeFullPass = false;
  1962. SetAndRestoreValue<bool> prevAssertOnPopulateType(mContext->mAssertOnPopulateType, deleteUnusued && madeFullPass);
  1963. if ((deleteUnusued) && (madeFullPass))
  1964. {
  1965. // Work queues should be empty if we're not canceling
  1966. BF_ASSERT(mContext->mPopulateTypeWorkList.size() == 0);
  1967. BF_ASSERT(mContext->mMethodWorkList.size() == 0);
  1968. }
  1969. // Remove old data in dependency maps, and find types which don't have any references (direct or indirect)
  1970. // to a non-generic type and remove them
  1971. for (int pass = 0; true; pass++)
  1972. {
  1973. // This assert can fail if we have a dependency error, where deleting a type causes a dependent type
  1974. // to be rebuilt
  1975. BF_ASSERT(pass < 100);
  1976. bool foundNew = false;
  1977. for (auto type : mContext->mResolvedTypes)
  1978. {
  1979. if (type != NULL)
  1980. {
  1981. auto depType = type->ToDependedType();
  1982. auto typeInst = type->ToTypeInstance();
  1983. if (depType != NULL)
  1984. {
  1985. extern BfModule* gLastCreatedModule;
  1986. #ifdef _DEBUG
  1987. for (auto itr = depType->mDependencyMap.begin(); itr != depType->mDependencyMap.end(); ++itr)
  1988. {
  1989. auto dependentType = itr->mKey;
  1990. if (dependentType->IsIncomplete())
  1991. {
  1992. BF_ASSERT(dependentType->IsDeleting() || dependentType->IsOnDemand() || !dependentType->HasBeenReferenced() || mCanceling || !madeFullPass || dependentType->IsSpecializedByAutoCompleteMethod());
  1993. }
  1994. }
  1995. #endif
  1996. depType->mDependencyMap.mFlagsUnion = BfDependencyMap::DependencyFlag_None;
  1997. // Not combined with previous loop because PopulateType could modify typeInst->mDependencyMap
  1998. for (auto itr = depType->mDependencyMap.begin(); itr != depType->mDependencyMap.end();)
  1999. {
  2000. auto dependentType = itr->mKey;
  2001. auto depTypeInst = dependentType->ToTypeInstance();
  2002. auto& depData = itr->mValue;
  2003. bool isInvalidVersion = (dependentType->mRevision > depData.mRevision);// && (deleteUnusued) && (madeFullPass);
  2004. //TODO: Just to cause crash if dependentType is deleted
  2005. bool isIncomplete = dependentType->IsIncomplete();
  2006. if ((isInvalidVersion) && (!dependentType->IsDeleting()))
  2007. {
  2008. if (!dependentType->HasBeenReferenced())
  2009. {
  2010. BfLogSysM("Skipping remove of old dependent %p from %p\n", dependentType, typeInst);
  2011. //BF_ASSERT(dependentType->IsGenericTypeInstance());
  2012. // We have a pending type rebuild but we're not sure whether we're being deleted or not yet...
  2013. ++itr;
  2014. continue;
  2015. }
  2016. }
  2017. if ((dependentType->IsDeleting()) || (isInvalidVersion))
  2018. {
  2019. if (dependentType->IsDeleting() || ((deleteUnusued) && (madeFullPass)))
  2020. {
  2021. // If we're deleting the type, OR the dependency of the type has been removed.
  2022. // We detect a removed dependency by the dependent type changing but the dependency revision
  2023. // is older than the dependent type.
  2024. BfLogSysM("Removing old dependent %p from %p\n", dependentType, depType);
  2025. itr = depType->mDependencyMap.erase(itr);
  2026. }
  2027. else
  2028. ++itr;
  2029. }
  2030. else
  2031. {
  2032. // There needs to be more usage than just being used as part of the method specialization's MethodGenericArg.
  2033. // Keep in mind that actually invoking a generic method creates a DependencyFlag_LocalUsage dependency. The
  2034. // DependencyFlag_MethodGenericArg is just used by the owner during creation of the method specialization
  2035. bool isDependentUsage = (depData.mFlags & BfDependencyMap::DependencyFlag_DependentUsageMask) != 0;
  2036. // We need to consider specialized generic types separately, to remove unused specializations
  2037. if (typeInst != NULL)
  2038. {
  2039. bool isDirectReference = (depTypeInst != NULL) && (!depTypeInst->IsOnDemand()) && (!dependentType->IsGenericTypeInstance());
  2040. if ((depTypeInst != NULL) && (typeInst->mLastNonGenericUsedRevision != mRevision) && (isDependentUsage) &&
  2041. ((isDirectReference) || (dependentType->IsUnspecializedType()) || (depTypeInst->mLastNonGenericUsedRevision == mRevision)))
  2042. {
  2043. typeInst->mLastNonGenericUsedRevision = mRevision;
  2044. foundNew = true;
  2045. if (!typeInst->HasBeenReferenced())
  2046. {
  2047. mContext->AddTypeToWorkList(typeInst);
  2048. foundNew = true;
  2049. }
  2050. }
  2051. }
  2052. ++itr;
  2053. }
  2054. depType->mDependencyMap.mFlagsUnion = (BfDependencyMap::DependencyFlags)(depType->mDependencyMap.mFlagsUnion | depData.mFlags);
  2055. }
  2056. if ((!depType->IsGenericTypeInstance() && (!depType->IsBoxed())) ||
  2057. (depType->IsUnspecializedType()) ||
  2058. ((typeInst != NULL) && (typeInst->mLastNonGenericUsedRevision == mRevision)))
  2059. {
  2060. if ((depType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2061. {
  2062. mContext->MarkAsReferenced(depType);
  2063. }
  2064. }
  2065. }
  2066. }
  2067. }
  2068. if (mCanceling)
  2069. madeFullPass = false;
  2070. if (!madeFullPass)
  2071. {
  2072. // We can't delete types based on the dependency map when we're canceling, because we may still
  2073. // have items in the work queues (particularly the mMethodWorkList) that will create
  2074. // new dependencies -- things may unduly be thought to be deleted.
  2075. return;
  2076. }
  2077. if (foundNew)
  2078. {
  2079. // This will work through generic method specializations for the types referenced above, clearing out AwaitingReference flags for
  2080. // newly-referenced generics, and queuing up their method specializations as well
  2081. didWork |= DoWorkLoop(false, false);
  2082. }
  2083. else if (deleteUnusued)
  2084. {
  2085. // Work queues should be empty if we're not canceling
  2086. BF_ASSERT(mContext->mPopulateTypeWorkList.size() == 0);
  2087. BF_ASSERT(mContext->mMethodWorkList.size() == 0);
  2088. // We need to use a delete queue because we trigger a RebuildType for dependent types,
  2089. // but we need to make sure we don't rebuild any types that may be next in line for
  2090. // deletion, so we must set BfTypeRebuildFlag_DeleteQueued first to avoid that
  2091. Array<BfDependedType*> deleteQueue;
  2092. // We bubble out
  2093. for (auto type : mContext->mResolvedTypes)
  2094. {
  2095. auto depType = type->ToDependedType();
  2096. // Delete if we're a generic
  2097. if ((depType != NULL) && (!depType->IsDeleting()))
  2098. {
  2099. auto typeInst = depType->ToTypeInstance();
  2100. bool wantDelete = false;
  2101. if (typeInst != NULL)
  2102. {
  2103. wantDelete = (typeInst->mLastNonGenericUsedRevision != mRevision) &&
  2104. (typeInst->IsGenericTypeInstance() || typeInst->IsBoxed()) && (!typeInst->IsUnspecializedType());
  2105. }
  2106. wantDelete |= (depType->IsOnDemand()) && (depType->mDependencyMap.IsEmpty());
  2107. if (wantDelete)
  2108. {
  2109. deleteQueue.push_back(depType);
  2110. depType->mRebuildFlags = (BfTypeRebuildFlags)(depType->mRebuildFlags | BfTypeRebuildFlag_DeleteQueued);
  2111. foundNew = true;
  2112. }
  2113. }
  2114. }
  2115. for (auto depType : deleteQueue)
  2116. {
  2117. BfLogSysM("Deleting type from deleteQueue in UpdateDependencyMap %p\n", depType);
  2118. mContext->DeleteType(depType, true);
  2119. }
  2120. if (deleteQueue.size() != 0)
  2121. {
  2122. mContext->ValidateDependencies();
  2123. mContext->UpdateAfterDeletingTypes();
  2124. mContext->ValidateDependencies();
  2125. }
  2126. }
  2127. if (!foundNew)
  2128. break;
  2129. }
  2130. #ifdef _DEBUG
  2131. if (deleteUnusued)
  2132. {
  2133. for (auto type : mContext->mResolvedTypes)
  2134. {
  2135. // This flag should be handled by now
  2136. BF_ASSERT((type->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) == 0);
  2137. }
  2138. }
  2139. #endif
  2140. BP_ZONE("UpdateDependencyMap QueuedSpecializedMethodRebuildTypes");
  2141. HashSet<BfTypeInstance*> specializerSet;
  2142. for (auto rebuildType : mContext->mQueuedSpecializedMethodRebuildTypes)
  2143. {
  2144. if (rebuildType->mRevision != mRevision)
  2145. {
  2146. mContext->RebuildType(rebuildType);
  2147. rebuildType->mRebuildFlags = (BfTypeRebuildFlags)(rebuildType->mRebuildFlags | BfTypeRebuildFlag_SpecializedMethodRebuild);
  2148. for (auto& dep : rebuildType->mDependencyMap)
  2149. {
  2150. auto depType = dep.mKey;
  2151. auto& depData = dep.mValue;
  2152. auto depTypeInst = depType->ToTypeInstance();
  2153. if (depTypeInst == NULL)
  2154. continue;
  2155. if ((depData.mFlags & BfDependencyMap::DependencyFlag_Calls) != 0)
  2156. {
  2157. specializerSet.Add(depTypeInst);
  2158. }
  2159. }
  2160. }
  2161. }
  2162. for (auto depType : specializerSet)
  2163. {
  2164. mContext->QueueMethodSpecializations(depType, true);
  2165. }
  2166. for (auto rebuildType : mContext->mQueuedSpecializedMethodRebuildTypes)
  2167. {
  2168. rebuildType->mRebuildFlags = (BfTypeRebuildFlags)(rebuildType->mRebuildFlags & ~BfTypeRebuildFlag_SpecializedMethodRebuild);
  2169. }
  2170. mContext->mQueuedSpecializedMethodRebuildTypes.Clear();
  2171. mDepsMayHaveDeletedTypes = false;
  2172. }
  2173. void BfCompiler::SanitizeDependencyMap()
  2174. {
  2175. BfLogSysM("SanitizeDependencyMap\n");
  2176. for (auto type : mContext->mResolvedTypes)
  2177. {
  2178. if (type == NULL)
  2179. continue;
  2180. auto depType = type->ToDependedType();
  2181. if (depType == NULL)
  2182. continue;
  2183. // Not combined with previous loop because PopulateType could modify typeInst->mDependencyMap
  2184. for (auto itr = depType->mDependencyMap.begin(); itr != depType->mDependencyMap.end();)
  2185. {
  2186. auto dependentType = itr->mKey;
  2187. auto depTypeInst = dependentType->ToTypeInstance();
  2188. if (dependentType->IsDeleting())
  2189. {
  2190. BfLogSysM("SanitizeDependencyMap removing old dependent %p from %p\n", dependentType, depType);
  2191. itr = depType->mDependencyMap.erase(itr);
  2192. }
  2193. else
  2194. ++itr;
  2195. }
  2196. }
  2197. mContext->RemoveInvalidWorkItems();
  2198. mDepsMayHaveDeletedTypes = false;
  2199. }
  2200. // When we are unsure of whether an old generic instance will survive, we RebuildType but don't put it in any worklist.
  2201. // One of three things happens:
  2202. // 1) It gets built on demand
  2203. // 2) It gets deleted in UpdateDependencyMap
  2204. // 3) It stays undefined and we need to build it here
  2205. bool BfCompiler::ProcessPurgatory(bool reifiedOnly)
  2206. {
  2207. BP_ZONE("BfCompiler::ProcessPurgatory");
  2208. bool didWork = false;
  2209. while (true)
  2210. {
  2211. mContext->RemoveInvalidWorkItems();
  2212. //for (auto type : mGenericInstancePurgatory)
  2213. for (int i = 0; i < (int)mGenericInstancePurgatory.size(); i++)
  2214. {
  2215. auto type = mGenericInstancePurgatory[i];
  2216. if ((reifiedOnly) && (!type->IsReified()))
  2217. continue;
  2218. if ((reifiedOnly) && ((type->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0))
  2219. continue;
  2220. if (!type->IsDeleting())
  2221. {
  2222. auto module = type->GetModule();
  2223. if (module != NULL)
  2224. {
  2225. if (!module->mIsModuleMutable)
  2226. module->StartExtension();
  2227. module->PopulateType(type, BfPopulateType_Full);
  2228. }
  2229. }
  2230. if (reifiedOnly)
  2231. {
  2232. mGenericInstancePurgatory.RemoveAtFast(i);
  2233. i--;
  2234. }
  2235. }
  2236. if (!reifiedOnly)
  2237. mGenericInstancePurgatory.Clear();
  2238. int prevPurgatorySize = (int)mGenericInstancePurgatory.size();
  2239. if (mContext->ProcessWorkList(reifiedOnly, reifiedOnly))
  2240. didWork = true;
  2241. if (prevPurgatorySize == (int)mGenericInstancePurgatory.size())
  2242. break;
  2243. }
  2244. return didWork;
  2245. }
  2246. bool BfCompiler::VerifySlotNums()
  2247. {
  2248. BP_ZONE("BfCompiler::VerifySlotNums");
  2249. SmallVector<BfTypeInstance*, 16> isSlotUsed;
  2250. for (auto type : mContext->mResolvedTypes)
  2251. {
  2252. if (!type->IsReified())
  2253. continue;
  2254. auto typeInst = type->ToTypeInstance();
  2255. if (typeInst == NULL)
  2256. continue;
  2257. if (typeInst->IsUnspecializedType())
  2258. continue;
  2259. if (typeInst->IsInterface())
  2260. {
  2261. if (typeInst->mSlotNum == -2)
  2262. continue; // Not used
  2263. if ((typeInst->mVirtualMethodTableSize > 0) && (typeInst->mSlotNum == -1))
  2264. {
  2265. // Slot not assigned yet
  2266. return false;
  2267. }
  2268. continue;
  2269. }
  2270. isSlotUsed.clear();
  2271. isSlotUsed.resize(mMaxInterfaceSlots);
  2272. auto checkType = typeInst;
  2273. while (checkType != NULL)
  2274. {
  2275. for (auto iface : checkType->mInterfaces)
  2276. {
  2277. int slotNum = iface.mInterfaceType->mSlotNum;
  2278. if (slotNum >= 0)
  2279. {
  2280. if ((isSlotUsed[slotNum] != NULL) && (isSlotUsed[slotNum] != iface.mInterfaceType))
  2281. return false; // Collision
  2282. isSlotUsed[slotNum] = iface.mInterfaceType;
  2283. }
  2284. }
  2285. checkType = checkType->mBaseType;
  2286. }
  2287. }
  2288. return true;
  2289. }
  2290. bool BfCompiler::QuickGenerateSlotNums()
  2291. {
  2292. /*SmallVector<bool, 16> isSlotUsed;
  2293. for (auto globalTypeEntry : mResolvedTypes)
  2294. {
  2295. BfType* type = globalTypeEntry->mType;
  2296. auto typeInst = type->ToTypeInstance();
  2297. if (typeInst == NULL)
  2298. continue;
  2299. if (typeInst->IsInterface())
  2300. {
  2301. if ((typeInst->mVirtualMethodTableSize > 0) && (typeInst->mSlotNum == -1))
  2302. {
  2303. // Slot not assigned yet
  2304. return false;
  2305. }
  2306. continue;
  2307. }
  2308. }
  2309. return VerifySlotNums();*/
  2310. // Implement later
  2311. return false;
  2312. }
  2313. class BfSlotEntry
  2314. {
  2315. public:
  2316. BfTypeInstance* mTypeInstance;
  2317. int mRefCount;
  2318. Array<BfTypeInstance*> mConcurrentRefs;
  2319. };
  2320. typedef std::pair<BfTypeInstance*, BfTypeInstance*> InterfacePair;
  2321. typedef Dictionary<BfTypeInstance*, BfSlotEntry*> SlotEntryMap;
  2322. static BfSlotEntry* GetSlotEntry(SlotEntryMap& slotEntryMap, BfTypeInstance* typeInst)
  2323. {
  2324. BF_ASSERT(typeInst->IsReified());
  2325. BfSlotEntry** slotEntryPtr = NULL;
  2326. if (!slotEntryMap.TryAdd(typeInst, NULL, &slotEntryPtr))
  2327. return *slotEntryPtr;
  2328. BfSlotEntry* slotEntry = new BfSlotEntry();
  2329. slotEntry->mTypeInstance = typeInst;
  2330. slotEntry->mRefCount = 0;
  2331. //insertPair.first->second = slotEntry;
  2332. *slotEntryPtr = slotEntry;
  2333. return slotEntry;
  2334. }
  2335. static InterfacePair MakeInterfacePair(BfTypeInstance* iface1, BfTypeInstance* iface2)
  2336. {
  2337. if (iface1->mTypeId < iface2->mTypeId)
  2338. return InterfacePair(iface1, iface2);
  2339. return InterfacePair(iface2, iface1);
  2340. }
  2341. struct InterfacePairHash
  2342. {
  2343. size_t operator()(const InterfacePair& val) const
  2344. {
  2345. return (((size_t)val.first) >> 2) ^ ((size_t)val.second);
  2346. }
  2347. };
  2348. bool BfCompiler::SlowGenerateSlotNums()
  2349. {
  2350. BP_ZONE("BfCompiler::SlowGenerateSlotNums");
  2351. SlotEntryMap ifaceUseMap;
  2352. std::unordered_set<InterfacePair, InterfacePairHash> concurrentInterfaceSet;
  2353. HashSet<BfTypeInstance*> foundIFaces;
  2354. if (mMaxInterfaceSlots < 0)
  2355. {
  2356. mMaxInterfaceSlots = 0;
  2357. }
  2358. bool isHotCompile = IsHotCompile();
  2359. for (auto type : mContext->mResolvedTypes)
  2360. {
  2361. if (!type->IsReified())
  2362. continue;
  2363. auto typeInst = type->ToTypeInstance();
  2364. if (typeInst == NULL)
  2365. continue;
  2366. if (typeInst->IsUnspecializedType())
  2367. continue;
  2368. if (typeInst->IsInterface())
  2369. {
  2370. if (typeInst->mSlotNum == -2) // Not needed
  2371. continue;
  2372. if (!isHotCompile) // Hot compiles cannot remap slot numbers
  2373. typeInst->mSlotNum = -1;
  2374. if (typeInst->mVirtualMethodTableSize > 0)
  2375. {
  2376. GetSlotEntry(ifaceUseMap, typeInst);
  2377. }
  2378. continue;
  2379. }
  2380. foundIFaces.Clear();
  2381. auto checkTypeInst = typeInst;
  2382. while (checkTypeInst != NULL)
  2383. {
  2384. for (auto iface : checkTypeInst->mInterfaces)
  2385. {
  2386. auto interfaceType = iface.mInterfaceType;
  2387. if (interfaceType->mSlotNum == -2)
  2388. continue; // Not needed
  2389. if ((isHotCompile) && (interfaceType->mSlotNum == -1))
  2390. checkTypeInst->mDirty = true; // We're about to slot an interface here
  2391. if (interfaceType->mVirtualMethodTableSize > 0)
  2392. {
  2393. BfSlotEntry* slotEntry = GetSlotEntry(ifaceUseMap, interfaceType);
  2394. slotEntry->mRefCount++;
  2395. foundIFaces.Add(iface.mInterfaceType);
  2396. }
  2397. }
  2398. checkTypeInst = checkTypeInst->mBaseType;
  2399. }
  2400. for (auto itr1 = foundIFaces.begin(); itr1 != foundIFaces.end(); ++itr1)
  2401. {
  2402. auto itr2 = itr1;
  2403. ++itr2;
  2404. for ( ; itr2 != foundIFaces.end(); ++itr2)
  2405. {
  2406. auto iface1 = *itr1;
  2407. auto iface2 = *itr2;
  2408. InterfacePair ifacePair = MakeInterfacePair(iface1, iface2);
  2409. if (concurrentInterfaceSet.insert(ifacePair).second)
  2410. {
  2411. BfSlotEntry* entry1 = GetSlotEntry(ifaceUseMap, iface1);
  2412. BfSlotEntry* entry2 = GetSlotEntry(ifaceUseMap, iface2);
  2413. entry1->mConcurrentRefs.push_back(iface2);
  2414. entry2->mConcurrentRefs.push_back(iface1);
  2415. }
  2416. }
  2417. }
  2418. }
  2419. Array<BfSlotEntry*> sortedIfaceUseMap;
  2420. for (auto& entry : ifaceUseMap)
  2421. {
  2422. if (!isHotCompile)
  2423. BF_ASSERT(entry.mValue->mTypeInstance->mSlotNum == -1);
  2424. sortedIfaceUseMap.push_back(entry.mValue);
  2425. }
  2426. std::sort(sortedIfaceUseMap.begin(), sortedIfaceUseMap.end(), [] (BfSlotEntry* lhs, BfSlotEntry* rhs)
  2427. {
  2428. if (lhs->mRefCount != rhs->mRefCount)
  2429. return lhs->mRefCount > rhs->mRefCount;
  2430. return lhs->mTypeInstance->mTypeId < rhs->mTypeInstance->mTypeId;
  2431. });
  2432. bool failed = false;
  2433. SmallVector<bool, 16> isSlotUsed;
  2434. for (auto slotEntry : sortedIfaceUseMap)
  2435. {
  2436. BfTypeInstance* iface = slotEntry->mTypeInstance;
  2437. if (iface->mSlotNum >= 0)
  2438. {
  2439. BF_ASSERT(isHotCompile);
  2440. continue;
  2441. }
  2442. isSlotUsed.clear();
  2443. if (mMaxInterfaceSlots > 0)
  2444. isSlotUsed.resize(mMaxInterfaceSlots);
  2445. BF_ASSERT(iface->mSlotNum == -1);
  2446. BF_ASSERT(iface->IsInterface());
  2447. for (auto iface2 : slotEntry->mConcurrentRefs)
  2448. {
  2449. int slotNum2 = iface2->mSlotNum;
  2450. if (slotNum2 != -1)
  2451. isSlotUsed[slotNum2] = true;
  2452. }
  2453. for (int checkSlot = 0; checkSlot < mMaxInterfaceSlots; checkSlot++)
  2454. {
  2455. if (!isSlotUsed[checkSlot])
  2456. {
  2457. iface->mSlotNum = checkSlot;
  2458. break;
  2459. }
  2460. }
  2461. if (iface->mSlotNum == -1)
  2462. {
  2463. if (isHotCompile)
  2464. {
  2465. failed = true;
  2466. mPassInstance->Fail("Interface slot numbering overflow. Restart the program or revert changes.");
  2467. break;
  2468. }
  2469. iface->mSlotNum = mMaxInterfaceSlots;
  2470. if (mOptions.mIncrementalBuild)
  2471. {
  2472. // Allocate more than enough interface slots
  2473. mMaxInterfaceSlots += 3;
  2474. }
  2475. else
  2476. mMaxInterfaceSlots++;
  2477. // failed = true;
  2478. // mPassInstance->Fail(StrFormat("Interface slot numbering overflow, increase the maximum slot number from '%d'", mMaxInterfaceSlots));
  2479. // break;
  2480. }
  2481. // if (iface->mSlotNum == -1)
  2482. // {
  2483. // failed = true;
  2484. // mPassInstance->Fail(StrFormat("Interface slot numbering overflow, increase the maximum slot number from '%d'", mMaxInterfaceSlots));
  2485. // break;
  2486. // }
  2487. if (isHotCompile)
  2488. {
  2489. mHotState->mNewlySlottedTypeIds.Add(iface->mTypeId);
  2490. mHotState->mSlotDefineTypeIds.Add(iface->mTypeId);
  2491. }
  2492. }
  2493. if (!failed)
  2494. {
  2495. bool success = VerifySlotNums();
  2496. if ((!success) && (!isHotCompile))
  2497. {
  2498. BF_DBG_FATAL("Failed!");
  2499. }
  2500. }
  2501. for (auto& entry : ifaceUseMap)
  2502. delete entry.mValue;
  2503. return true;
  2504. }
  2505. void BfCompiler::GenerateSlotNums()
  2506. {
  2507. BP_ZONE("BfCompiler::GenerateSlotNums");
  2508. if (mMaxInterfaceSlots < 0)
  2509. {
  2510. if (mOptions.mIncrementalBuild)
  2511. mMaxInterfaceSlots = 3;
  2512. else
  2513. mMaxInterfaceSlots = 0;
  2514. }
  2515. bool isHotCompile = IsHotCompile();
  2516. for (auto type : mContext->mResolvedTypes)
  2517. {
  2518. if (!type->IsInterface())
  2519. continue;
  2520. auto typeInstance = type->ToTypeInstance();
  2521. if ((typeInstance->mSlotNum <= 0) || (!isHotCompile))
  2522. {
  2523. if ((mContext->mReferencedIFaceSlots.Contains(typeInstance)) ||
  2524. (typeInstance->mHasBeenInstantiated) || (typeInstance->IncludeAllMethods()))
  2525. {
  2526. if (typeInstance->mSlotNum == -2)
  2527. typeInstance->mSlotNum = -1;
  2528. }
  2529. else
  2530. typeInstance->mSlotNum = -2; // Not needed
  2531. }
  2532. }
  2533. if (VerifySlotNums())
  2534. return;
  2535. if (!QuickGenerateSlotNums())
  2536. SlowGenerateSlotNums();
  2537. BfLogSysM("GenerateSlotNums mMaxInterfaceSlots: %d\n", mMaxInterfaceSlots);
  2538. }
  2539. void BfCompiler::GenerateDynCastData()
  2540. {
  2541. BP_ZONE("BfCompiler::GenerateDynCastData");
  2542. Array<int> firstDerivedIds;
  2543. Array<int> nextSiblingIds;
  2544. firstDerivedIds.Resize(mCurTypeId);
  2545. nextSiblingIds.Resize(mCurTypeId);
  2546. for (auto type : mContext->mResolvedTypes)
  2547. {
  2548. if (type->IsBoxed())
  2549. continue;
  2550. auto typeInst = type->ToTypeInstance();
  2551. if (typeInst == NULL)
  2552. continue;
  2553. if (typeInst->mBaseType == NULL)
  2554. continue;
  2555. int baseId = typeInst->mBaseType->mTypeId;
  2556. int firstDerivedId = firstDerivedIds[baseId];
  2557. nextSiblingIds[typeInst->mTypeId] = firstDerivedIds[baseId];
  2558. firstDerivedIds[baseId] = typeInst->mTypeId;
  2559. }
  2560. int curInheritanceId = 1;
  2561. std::function<void(BfTypeInstance*)> _AddTypeInfo = [&](BfTypeInstance* typeInst)
  2562. {
  2563. if (typeInst->mInheritanceId != curInheritanceId)
  2564. {
  2565. typeInst->mInheritanceId = curInheritanceId;
  2566. typeInst->mDirty = true;
  2567. }
  2568. curInheritanceId++;
  2569. int childId = firstDerivedIds[typeInst->mTypeId];
  2570. while (childId != 0)
  2571. {
  2572. auto childType = mContext->mTypes[childId]->ToTypeInstance();
  2573. _AddTypeInfo(childType);
  2574. childId = nextSiblingIds[childId];
  2575. }
  2576. int inheritanceCount = curInheritanceId - typeInst->mInheritanceId - 1;
  2577. if (typeInst->mInheritanceCount != inheritanceCount)
  2578. {
  2579. typeInst->mInheritanceCount = inheritanceCount;
  2580. typeInst->mDirty = true;
  2581. }
  2582. };
  2583. _AddTypeInfo(mContext->mBfObjectType);
  2584. auto valueTypeInst = mContext->mScratchModule->ResolveTypeDef(mValueTypeTypeDef)->ToTypeInstance();
  2585. _AddTypeInfo(valueTypeInst);
  2586. }
  2587. void BfCompiler::UpdateRevisedTypes()
  2588. {
  2589. BfLogSysM("BfCompiler::UpdateRevisedTypes\n");
  2590. BP_ZONE("BfCompiler::UpdateRevisedTypes");
  2591. // See if we have any name conflicts and remove those
  2592. auto typeDefItr = mSystem->mTypeDefs.begin();
  2593. while (typeDefItr != mSystem->mTypeDefs.end())
  2594. {
  2595. auto typeDef = *typeDefItr;
  2596. auto origTypeDef = typeDef;
  2597. if (typeDef->mNextRevision != NULL)
  2598. typeDef = typeDef->mNextRevision;
  2599. if (typeDef->mDupDetectedRevision == mRevision)
  2600. {
  2601. ++typeDefItr;
  2602. continue;
  2603. }
  2604. typeDef->mDupDetectedRevision = -1;
  2605. if ((typeDef->mIsCombinedPartial) || (typeDef->mDefState == BfTypeDef::DefState_Deleted) || (typeDef->mTypeCode == BfTypeCode_Extension))
  2606. {
  2607. ++typeDefItr;
  2608. continue;
  2609. }
  2610. if ((!typeDef->IsGlobalsContainer()) && (mSystem->ContainsNamespace(typeDef->mFullName, typeDef->mProject)))
  2611. {
  2612. mPassInstance->Fail(StrFormat("The name '%s' is already defined to be a namespace name", typeDef->mFullName.ToString().c_str()), typeDef->mTypeDeclaration->mNameNode);
  2613. }
  2614. bool removedElement = false;
  2615. auto nextTypeDefItr = typeDefItr;
  2616. nextTypeDefItr.MoveToNextHashMatch();
  2617. while (nextTypeDefItr)
  2618. {
  2619. auto nextTypeDef = *nextTypeDefItr;
  2620. if (nextTypeDef->mNextRevision != NULL)
  2621. nextTypeDef = nextTypeDef->mNextRevision;
  2622. if ((nextTypeDef->mIsCombinedPartial) || (nextTypeDef->mDefState == BfTypeDef::DefState_Deleted) || (nextTypeDef->mTypeCode == BfTypeCode_Extension) ||
  2623. (typeDef->mFullNameEx != nextTypeDef->mFullNameEx) || (typeDef->mGenericParamDefs.size() != nextTypeDef->mGenericParamDefs.size()))
  2624. {
  2625. nextTypeDefItr.MoveToNextHashMatch();
  2626. continue;
  2627. }
  2628. if ((typeDef->mIsPartial) && (nextTypeDef->mIsPartial) &&
  2629. (!typeDef->IsGlobalsContainer()) &&
  2630. (typeDef->mProject != nextTypeDef->mProject))
  2631. {
  2632. BfTypeDef* typeA = NULL;
  2633. BfTypeDef* typeB = NULL;
  2634. BfError* error = NULL;
  2635. if (typeDef->mProject->ReferencesOrReferencedBy(nextTypeDef->mProject))
  2636. {
  2637. typeA = typeDef;
  2638. typeB = nextTypeDef;
  2639. }
  2640. else if (nextTypeDef->mProject->ReferencesOrReferencedBy(typeDef->mProject))
  2641. {
  2642. typeA = nextTypeDef;
  2643. typeB = typeDef;
  2644. }
  2645. if (typeA != NULL)
  2646. {
  2647. error = mPassInstance->Fail(StrFormat("Partial type in project '%s' cannot extend a type from a referenced project", typeA->mProject->mName.c_str()).c_str(),
  2648. typeA->mTypeDeclaration->mNameNode);
  2649. mPassInstance->MoreInfo(StrFormat("Previous definition in project '%s'", typeB->mProject->mName.c_str()),
  2650. typeB->mTypeDeclaration->mNameNode);
  2651. }
  2652. if (error != NULL)
  2653. error->mIsPersistent = true;
  2654. }
  2655. if (((!typeDef->mIsPartial) || (!nextTypeDef->mIsPartial)) &&
  2656. (!typeDef->IsGlobalsContainer()) && (!nextTypeDef->IsGlobalsContainer()) &&
  2657. (typeDef->mProject->ReferencesOrReferencedBy(nextTypeDef->mProject)))
  2658. {
  2659. nextTypeDef->mDupDetectedRevision = mRevision;
  2660. BfError* error = NULL;
  2661. /*if ((typeDef->mIsPartial) && (typeDef->mTypeCode != BfTypeCode_Extension))
  2662. {
  2663. error = mPassInstance->Fail("Missing 'partial' modifier; another partial definition of this type exists", nextTypeDef->mTypeDeclaration->mNameNode);
  2664. mPassInstance->MoreInfo("Previous definition", typeDef->mTypeDeclaration->mNameNode);
  2665. }
  2666. else if ((nextTypeDef->mIsPartial) && (nextTypeDef->mTypeCode != BfTypeCode_Extension))
  2667. {
  2668. error = mPassInstance->Fail("Missing 'partial' modifier; another partial definition of this type exists", typeDef->mTypeDeclaration->mNameNode);
  2669. mPassInstance->MoreInfo("Previous definition", nextTypeDef->mTypeDeclaration->mNameNode);
  2670. }
  2671. else */if (nextTypeDef->mOuterType != NULL)
  2672. {
  2673. error = mPassInstance->Fail(StrFormat("The type '%s.%s' already has a definition for '%s'", nextTypeDef->mOuterType->mNamespace.ToString().c_str(), nextTypeDef->mOuterType->mName->mString.mPtr,
  2674. nextTypeDef->mName->mString.mPtr), nextTypeDef->mTypeDeclaration->mNameNode);
  2675. mPassInstance->MoreInfo("Previous definition", typeDef->mTypeDeclaration->mNameNode);
  2676. }
  2677. else if (!nextTypeDef->mNamespace.IsEmpty())
  2678. {
  2679. error = mPassInstance->Fail(StrFormat("The namespace '%s' already has a definition for '%s'", nextTypeDef->mNamespace.ToString().c_str(),
  2680. nextTypeDef->mName->mString.mPtr), nextTypeDef->mTypeDeclaration->mNameNode);
  2681. mPassInstance->MoreInfo("Previous definition", typeDef->mTypeDeclaration->mNameNode);
  2682. }
  2683. else
  2684. {
  2685. error = mPassInstance->Fail(StrFormat("The global namespace already has a definition for '%s'",
  2686. nextTypeDef->mName->mString.mPtr), nextTypeDef->mTypeDeclaration->mNameNode);
  2687. mPassInstance->MoreInfo("Previous definition", typeDef->mTypeDeclaration->mNameNode);
  2688. }
  2689. if (error != NULL)
  2690. error->mIsPersistent = true;
  2691. }
  2692. nextTypeDefItr.MoveToNextHashMatch();
  2693. }
  2694. ++typeDefItr;
  2695. }
  2696. mContext->PreUpdateRevisedTypes();
  2697. // If we missed out on required types previously, now we should be 'okay'
  2698. mInInvalidState = false;
  2699. // We can't do any yields in here - the compiler state is invalid from the time we inject a new
  2700. // typedef revision up until we finish the associated RebuildType
  2701. int compositeBucket = 0;
  2702. // These are "extension" defs that were unmatched last run through
  2703. Array<BfTypeDef*> prevSoloExtensions;
  2704. mSystem->mTypeDefs.CheckRehash();
  2705. Array<BfProject*> corlibProjects;
  2706. //
  2707. {
  2708. BfAtomComposite objectName;
  2709. if (mSystem->ParseAtomComposite("System.Object", objectName))
  2710. {
  2711. for (auto itr = mSystem->mTypeDefs.TryGet(objectName); itr != mSystem->mTypeDefs.end(); ++itr)
  2712. {
  2713. BfTypeDef* typeDef = *itr;
  2714. if ((typeDef->mFullName == objectName) && (typeDef->mTypeCode == BfTypeCode_Object))
  2715. corlibProjects.Add(typeDef->mProject);
  2716. }
  2717. }
  2718. }
  2719. // Process the typedefs one bucket at a time. When we are combining extensions or partials (globals) into a single definition then
  2720. // we will be making multiple passes over the bucket that contains that name
  2721. for (int bucketIdx = 0; bucketIdx < mSystem->mTypeDefs.mHashSize; bucketIdx++)
  2722. {
  2723. bool hadPartials = false;
  2724. bool hadChanges = false;
  2725. if (mSystem->mTypeDefs.mHashHeads == NULL)
  2726. break;
  2727. // Partials combiner
  2728. auto outerTypeDefEntryIdx = mSystem->mTypeDefs.mHashHeads[bucketIdx];
  2729. while (outerTypeDefEntryIdx != -1)
  2730. {
  2731. // Make sure we can fit a composite without reallocating
  2732. mSystem->mTypeDefs.EnsureFreeCount(1);
  2733. auto outerTypeDefEntry = &mSystem->mTypeDefs.mEntries[outerTypeDefEntryIdx];
  2734. auto outerTypeDef = outerTypeDefEntry->mValue;
  2735. if (outerTypeDef->mDefState == BfTypeDef::DefState_Deleted)
  2736. {
  2737. hadChanges = true;
  2738. outerTypeDefEntryIdx = mSystem->mTypeDefs.mEntries[outerTypeDefEntryIdx].mNext;
  2739. continue;
  2740. }
  2741. if (outerTypeDef->mNextRevision != NULL)
  2742. hadChanges = true;
  2743. BfTypeDefMap::Entry* rootTypeDefEntry = NULL;
  2744. BfTypeDef* rootTypeDef = NULL;
  2745. BfTypeDef* compositeTypeDef = NULL;
  2746. BfProject* compositeProject = NULL;
  2747. auto latestOuterTypeDef = outerTypeDef->GetLatest();
  2748. if ((outerTypeDef->mTypeCode == BfTypeCode_Extension) && (!outerTypeDef->mIsPartial))
  2749. {
  2750. prevSoloExtensions.Add(outerTypeDef);
  2751. outerTypeDef->mIsPartial = true;
  2752. }
  2753. if ((outerTypeDef->mIsPartial) || (outerTypeDef->mIsCombinedPartial))
  2754. {
  2755. // Initialize mPartialUsed flags
  2756. if (!hadPartials)
  2757. {
  2758. auto checkTypeDefEntryIdx = mSystem->mTypeDefs.mHashHeads[bucketIdx];
  2759. while (checkTypeDefEntryIdx != -1)
  2760. {
  2761. // This clears the mPartialUsed flag for the whole bucket
  2762. auto checkTypeDef = mSystem->mTypeDefs.mEntries[checkTypeDefEntryIdx].mValue;
  2763. if ((checkTypeDef->mIsPartial) || (checkTypeDef->mIsCombinedPartial))
  2764. checkTypeDef->mPartialUsed = false;
  2765. checkTypeDefEntryIdx = mSystem->mTypeDefs.mEntries[checkTypeDefEntryIdx].mNext;
  2766. }
  2767. hadPartials = true;
  2768. }
  2769. }
  2770. bool isExplicitPartial = outerTypeDef->mIsExplicitPartial;
  2771. bool failedToFindRootType = false;
  2772. if ((outerTypeDef->mTypeCode == BfTypeCode_Extension) && (!outerTypeDef->mPartialUsed))
  2773. {
  2774. // Find root type, and we assume the composite type follows this
  2775. auto checkTypeDefEntryIdx = mSystem->mTypeDefs.mHashHeads[bucketIdx];
  2776. while (checkTypeDefEntryIdx != -1)
  2777. {
  2778. auto checkTypeDefEntry = &mSystem->mTypeDefs.mEntries[checkTypeDefEntryIdx];
  2779. auto checkTypeDef = checkTypeDefEntry->mValue;
  2780. if ((checkTypeDefEntry->mHashCode != outerTypeDefEntry->mHashCode) ||
  2781. (checkTypeDef->mIsCombinedPartial) ||
  2782. (checkTypeDef->mTypeCode == BfTypeCode_Extension) ||
  2783. (checkTypeDef->mDefState == BfTypeDef::DefState_Deleted) ||
  2784. (checkTypeDef->mPartialUsed) ||
  2785. (!checkTypeDef->NameEquals(outerTypeDef)) ||
  2786. (checkTypeDef->mGenericParamDefs.size() != outerTypeDef->mGenericParamDefs.size()) ||
  2787. (!outerTypeDef->mProject->ContainsReference(checkTypeDef->mProject)))
  2788. {
  2789. checkTypeDefEntryIdx = checkTypeDefEntry->mNext;
  2790. continue;
  2791. }
  2792. // Only allow extending structs, objects, and interfaces
  2793. if ((checkTypeDef->mTypeCode == BfTypeCode_Struct) ||
  2794. (checkTypeDef->mTypeCode == BfTypeCode_Object) ||
  2795. (checkTypeDef->mTypeCode == BfTypeCode_Enum) ||
  2796. (checkTypeDef->mTypeCode == BfTypeCode_Interface))
  2797. {
  2798. rootTypeDef = checkTypeDef;
  2799. rootTypeDefEntry = checkTypeDefEntry;
  2800. compositeProject = rootTypeDef->mProject;
  2801. }
  2802. checkTypeDefEntryIdx = checkTypeDefEntry->mNext;
  2803. if (compositeTypeDef != NULL)
  2804. {
  2805. BF_ASSERT(rootTypeDef->mFullNameEx == compositeTypeDef->mFullNameEx);
  2806. }
  2807. }
  2808. if (rootTypeDef == NULL)
  2809. {
  2810. failedToFindRootType = true;
  2811. isExplicitPartial = true;
  2812. }
  2813. }
  2814. if ((isExplicitPartial) && (!outerTypeDef->mPartialUsed))
  2815. {
  2816. // For explicit partials there is no 'root type' so we want to select any partial in the 'innermost' project
  2817. rootTypeDef = outerTypeDef;
  2818. rootTypeDefEntry = outerTypeDefEntry;
  2819. compositeProject = rootTypeDef->mProject;
  2820. // Find composite type, there is no explicit position for this
  2821. auto checkTypeDefEntryIdx = mSystem->mTypeDefs.mHashHeads[bucketIdx];
  2822. while (checkTypeDefEntryIdx != -1)
  2823. {
  2824. auto checkTypeDefEntry = &mSystem->mTypeDefs.mEntries[checkTypeDefEntryIdx];
  2825. auto checkTypeDef = checkTypeDefEntry->mValue;
  2826. if ((checkTypeDefEntry->mHashCode != outerTypeDefEntry->mHashCode) ||
  2827. (checkTypeDef->mPartialUsed) ||
  2828. (checkTypeDef->mDefState == BfTypeDef::DefState_Deleted) ||
  2829. (!checkTypeDef->NameEquals(outerTypeDef)) ||
  2830. (checkTypeDef->mGenericParamDefs.size() != outerTypeDef->mGenericParamDefs.size()))
  2831. {
  2832. checkTypeDefEntryIdx = checkTypeDefEntry->mNext;
  2833. continue;
  2834. }
  2835. if (!checkTypeDef->mIsCombinedPartial)
  2836. {
  2837. // Select the innermost project for the composite project def
  2838. if (compositeProject != checkTypeDef->mProject)
  2839. {
  2840. if (checkTypeDef->mProject->ContainsReference(compositeProject))
  2841. {
  2842. // Fine, already contains it
  2843. }
  2844. else if (compositeProject->ContainsReference(checkTypeDef->mProject))
  2845. {
  2846. rootTypeDef = checkTypeDef;
  2847. rootTypeDefEntry = checkTypeDefEntry;
  2848. compositeProject = rootTypeDef->mProject;
  2849. }
  2850. else
  2851. {
  2852. // Try 'corlib'
  2853. for (auto corlibProject : corlibProjects)
  2854. {
  2855. if ((rootTypeDef->mProject->ContainsReference(corlibProject)) &&
  2856. (checkTypeDef->mProject->ContainsReference(corlibProject)))
  2857. compositeProject = corlibProject;
  2858. }
  2859. }
  2860. }
  2861. checkTypeDefEntryIdx = checkTypeDefEntry->mNext;
  2862. continue;
  2863. }
  2864. if (!rootTypeDef->mProject->ContainsReference(checkTypeDef->mProject))
  2865. {
  2866. checkTypeDefEntryIdx = checkTypeDefEntry->mNext;
  2867. continue;
  2868. }
  2869. compositeTypeDef = checkTypeDef;
  2870. if (rootTypeDef != NULL)
  2871. {
  2872. BF_ASSERT(rootTypeDef->mFullNameEx == compositeTypeDef->mFullNameEx);
  2873. }
  2874. if (compositeTypeDef->mNextRevision != NULL)
  2875. {
  2876. // This is an old 'next revision'
  2877. delete compositeTypeDef->mNextRevision;
  2878. compositeTypeDef->mNextRevision = NULL;
  2879. if (compositeTypeDef->mDefState != BfTypeDef::DefState_Deleted)
  2880. compositeTypeDef->mDefState = BfTypeDef::DefState_Defined;
  2881. }
  2882. checkTypeDefEntryIdx = checkTypeDefEntry->mNext;
  2883. }
  2884. }
  2885. // Now find extensions to apply to the rootTypeDef
  2886. if (rootTypeDef != NULL)
  2887. {
  2888. bool partialsHadChanges = false;
  2889. bool hadSignatureChange = false;
  2890. bool compositeIsNew = false;
  2891. if (compositeTypeDef == NULL)
  2892. {
  2893. BfTypeDefMap::Entry* nextEntry = NULL;
  2894. if (rootTypeDefEntry->mNext != -1)
  2895. nextEntry = &mSystem->mTypeDefs.mEntries[rootTypeDefEntry->mNext];
  2896. if ((rootTypeDef->mIsExplicitPartial) || (nextEntry == NULL) ||
  2897. (!nextEntry->mValue->mIsCombinedPartial) ||
  2898. (nextEntry->mValue->mTypeCode != rootTypeDef->mTypeCode) ||
  2899. (nextEntry->mValue->mIsFunction != rootTypeDef->mIsFunction) ||
  2900. (nextEntry->mValue->mIsDelegate != rootTypeDef->mIsDelegate) ||
  2901. (nextEntry->mValue->mGenericParamDefs.size() != rootTypeDef->mGenericParamDefs.size()))
  2902. {
  2903. compositeTypeDef = new BfTypeDef();
  2904. compositeTypeDef->mSystem = rootTypeDef->mSystem;
  2905. compositeTypeDef->mProject = compositeProject;
  2906. compositeTypeDef->mName = rootTypeDef->mName;
  2907. compositeTypeDef->mName->mRefCount++;
  2908. mSystem->TrackName(compositeTypeDef);
  2909. compositeTypeDef->mNameEx = rootTypeDef->mNameEx;
  2910. compositeTypeDef->mNameEx->Ref();
  2911. compositeTypeDef->mProtection = rootTypeDef->mProtection;
  2912. compositeTypeDef->mNamespace = rootTypeDef->mNamespace;
  2913. if (rootTypeDef->mTypeCode == BfTypeCode_Extension)
  2914. compositeTypeDef->mTypeCode = BfTypeCode_Struct;
  2915. else
  2916. compositeTypeDef->mTypeCode = rootTypeDef->mTypeCode;
  2917. compositeTypeDef->mFullName = rootTypeDef->mFullName;
  2918. compositeTypeDef->mFullNameEx = rootTypeDef->mFullNameEx;
  2919. compositeTypeDef->mIsFunction = rootTypeDef->mIsFunction;
  2920. compositeTypeDef->mIsDelegate = rootTypeDef->mIsDelegate;
  2921. compositeTypeDef->mIsCombinedPartial = true;
  2922. for (auto prevGenericParam : rootTypeDef->mGenericParamDefs)
  2923. {
  2924. BfGenericParamDef* copiedGenericParam = new BfGenericParamDef();
  2925. *copiedGenericParam = *prevGenericParam;
  2926. compositeTypeDef->mGenericParamDefs.Add(copiedGenericParam);
  2927. }
  2928. mSystem->mTypeDefs.AddAfter(compositeTypeDef, rootTypeDefEntry);
  2929. partialsHadChanges = true;
  2930. hadSignatureChange = true;
  2931. compositeIsNew = true;
  2932. BfLogSysM("Creating compositeTypeDef %p\n", compositeTypeDef);
  2933. }
  2934. else
  2935. {
  2936. BF_ASSERT(nextEntry->mValue->NameEquals(rootTypeDef));
  2937. compositeTypeDef = nextEntry->mValue;
  2938. if (rootTypeDef != NULL)
  2939. {
  2940. BF_ASSERT(rootTypeDef->mFullNameEx == compositeTypeDef->mFullNameEx);
  2941. }
  2942. if (compositeTypeDef->mNextRevision != NULL)
  2943. {
  2944. // This is an old 'next revision'
  2945. mSystem->InjectNewRevision(compositeTypeDef);
  2946. BF_ASSERT(compositeTypeDef->mNextRevision == NULL);
  2947. }
  2948. }
  2949. }
  2950. else
  2951. {
  2952. // These may not get caught below if the composite project changes
  2953. for (auto checkTypeDef : compositeTypeDef->mPartials)
  2954. {
  2955. if (checkTypeDef->mDefState == BfTypeDef::DefState_Deleted)
  2956. {
  2957. partialsHadChanges = true;
  2958. hadSignatureChange = true;
  2959. }
  2960. }
  2961. }
  2962. // Collect the partials
  2963. BfSizedVector<BfTypeDef*, 8> typeParts;
  2964. typeParts.push_back(rootTypeDef);
  2965. auto checkTypeDefEntryIdx = mSystem->mTypeDefs.mHashHeads[bucketIdx];
  2966. while (checkTypeDefEntryIdx != -1)
  2967. {
  2968. auto checkTypeDefEntry = &mSystem->mTypeDefs.mEntries[checkTypeDefEntryIdx];
  2969. auto checkTypeDef = checkTypeDefEntry->mValue;
  2970. bool isValidProject = checkTypeDef->mProject->ContainsReference(compositeProject);
  2971. if (checkTypeDef != rootTypeDef)
  2972. {
  2973. if ((checkTypeDef->mIsCombinedPartial) ||
  2974. ((!checkTypeDef->mIsPartial) && (checkTypeDef->mTypeCode != BfTypeCode_Extension)) ||
  2975. (checkTypeDef->mPartialUsed) ||
  2976. (!checkTypeDef->NameEquals(rootTypeDef)) ||
  2977. (checkTypeDef->mGenericParamDefs.size() != rootTypeDef->mGenericParamDefs.size()) ||
  2978. (!isValidProject))
  2979. {
  2980. checkTypeDefEntryIdx = checkTypeDefEntry->mNext;
  2981. continue;
  2982. }
  2983. }
  2984. if (checkTypeDef->mTypeCode == BfTypeCode_Extension)
  2985. {
  2986. // This was an extension that was orphaned but now we're taking it back
  2987. checkTypeDef->mIsPartial = true;
  2988. }
  2989. compositeTypeDef->mPartialUsed = true;
  2990. checkTypeDef->mPartialUsed = true;
  2991. if (checkTypeDef->mDefState == BfTypeDef::DefState_Deleted)
  2992. {
  2993. partialsHadChanges = true;
  2994. hadSignatureChange = true;
  2995. }
  2996. else
  2997. {
  2998. if (checkTypeDef != rootTypeDef)
  2999. typeParts.push_back(checkTypeDef);
  3000. if (checkTypeDef->mNextRevision != NULL)
  3001. {
  3002. partialsHadChanges = true;
  3003. BF_ASSERT(checkTypeDef->mNextRevision->mGenericParamDefs.size() == rootTypeDef->mGenericParamDefs.size());
  3004. //mSystem->InjectNewRevision(checkTypeDef);
  3005. //BF_ASSERT(checkTypeDef->mGenericParamDefs.size() == rootTypeDef->mGenericParamDefs.size());
  3006. }
  3007. else if (checkTypeDef->mDefState == BfTypeDef::DefState_New)
  3008. partialsHadChanges = true;
  3009. }
  3010. checkTypeDefEntryIdx = checkTypeDefEntry->mNext;
  3011. }
  3012. // Set this down here, because the InjectNewRevision will clear this flag
  3013. rootTypeDef->mIsPartial = true;
  3014. if (partialsHadChanges)
  3015. {
  3016. BF_ASSERT(compositeTypeDef->mNextRevision == NULL);
  3017. mSystem->VerifyTypeDef(compositeTypeDef);
  3018. for (auto checkTypeDef : typeParts)
  3019. {
  3020. mSystem->VerifyTypeDef(checkTypeDef);
  3021. // Apply any def state that is more conservative
  3022. if (checkTypeDef->mDefState == BfTypeDef::DefState_Signature_Changed)
  3023. compositeTypeDef->mDefState = BfTypeDef::DefState_Signature_Changed;
  3024. else if (checkTypeDef->mDefState == BfTypeDef::DefState_InlinedInternals_Changed)
  3025. {
  3026. if (compositeTypeDef->mDefState != BfTypeDef::DefState_Signature_Changed)
  3027. compositeTypeDef->mDefState = BfTypeDef::DefState_InlinedInternals_Changed;
  3028. }
  3029. else if (checkTypeDef->mDefState == BfTypeDef::DefState_Internals_Changed)
  3030. {
  3031. if ((compositeTypeDef->mDefState != BfTypeDef::DefState_Signature_Changed) &&
  3032. (compositeTypeDef->mDefState != BfTypeDef::DefState_InlinedInternals_Changed))
  3033. compositeTypeDef->mDefState = BfTypeDef::DefState_Internals_Changed;
  3034. }
  3035. else if (checkTypeDef->mDefState == BfTypeDef::DefState_Refresh)
  3036. {
  3037. if ((compositeTypeDef->mDefState != BfTypeDef::DefState_Signature_Changed) &&
  3038. (compositeTypeDef->mDefState != BfTypeDef::DefState_InlinedInternals_Changed) &&
  3039. (compositeTypeDef->mDefState != BfTypeDef::DefState_Internals_Changed))
  3040. compositeTypeDef->mDefState = BfTypeDef::DefState_Refresh;
  3041. }
  3042. BF_ASSERT(checkTypeDef->mIsPartial);
  3043. if (checkTypeDef->mNextRevision != NULL)
  3044. {
  3045. mSystem->VerifyTypeDef(checkTypeDef->mNextRevision);
  3046. mSystem->InjectNewRevision(checkTypeDef);
  3047. }
  3048. checkTypeDef->mIsPartial = true;
  3049. checkTypeDef->mDefState = BfTypeDef::DefState_Defined;
  3050. mSystem->AddToCompositePartial(mPassInstance, compositeTypeDef, checkTypeDef);
  3051. BfLogSysM("AddToCompositePartial %p added to %p\n", checkTypeDef, compositeTypeDef);
  3052. }
  3053. mSystem->FinishCompositePartial(compositeTypeDef);
  3054. if (!compositeIsNew)
  3055. {
  3056. if (compositeTypeDef->mNextRevision != NULL)
  3057. {
  3058. BF_ASSERT(compositeTypeDef->mPartials.size() != 0);
  3059. }
  3060. }
  3061. // We use the root typedef's namespace search for the composite, but this should only be
  3062. // used for cases where we CANNOT specify a typeref on an extension. IE: custom attributes
  3063. // for a type can only be added on the root typedef. If this changes then we need to make
  3064. // sure that we attach a definingType to attributes
  3065. for (auto name : compositeTypeDef->mNamespaceSearch)
  3066. mSystem->ReleaseAtomComposite(name);
  3067. compositeTypeDef->mNamespaceSearch = rootTypeDef->mNamespaceSearch;
  3068. for (auto name : compositeTypeDef->mNamespaceSearch)
  3069. mSystem->RefAtomComposite(name);
  3070. if (rootTypeDef != NULL)
  3071. compositeTypeDef->mNamespaceSearch = rootTypeDef->mNamespaceSearch;
  3072. else
  3073. compositeTypeDef->mNamespaceSearch.Clear();
  3074. //BfLogSysM("Composite type %p updating. isNew: %d\n", compositeTypeDef, compositeIsNew);
  3075. if (compositeIsNew)
  3076. {
  3077. compositeTypeDef->mDefState = BfTypeDef::DefState_New;
  3078. if (compositeTypeDef->mNextRevision->mTypeCode != BfTypeCode_Extension)
  3079. compositeTypeDef->mTypeCode = compositeTypeDef->mNextRevision->mTypeCode;
  3080. else
  3081. compositeTypeDef->mNextRevision->mTypeCode = compositeTypeDef->mTypeCode;
  3082. mSystem->InjectNewRevision(compositeTypeDef);
  3083. // Reset 'New' state
  3084. compositeTypeDef->mDefState = BfTypeDef::DefState_New;
  3085. }
  3086. else
  3087. {
  3088. if (compositeTypeDef->mNextRevision->mTypeCode == BfTypeCode_Extension)
  3089. compositeTypeDef->mNextRevision->mTypeCode = compositeTypeDef->mTypeCode;
  3090. if (hadSignatureChange)
  3091. compositeTypeDef->mDefState = BfTypeDef::DefState_Signature_Changed;
  3092. }
  3093. if (compositeTypeDef->mDefState == BfTypeDef::DefState_Defined)
  3094. {
  3095. // No changes, just inject
  3096. mSystem->InjectNewRevision(compositeTypeDef);
  3097. }
  3098. /*if (compositeTypeDef->mTypeCode == BfTypeCode_Extension)
  3099. {
  3100. BF_ASSERT(rootTypeDef == NULL);
  3101. compositeTypeDef->mTypeCode = BfTypeCode_Object;
  3102. }*/
  3103. auto latestCompositeTypeDef = compositeTypeDef->GetLatest();
  3104. if (latestCompositeTypeDef->mTypeCode == BfTypeCode_Extension)
  3105. {
  3106. BF_ASSERT(rootTypeDef == NULL);
  3107. latestCompositeTypeDef->mTypeCode = BfTypeCode_Struct;
  3108. }
  3109. BfLogSysM("Partial combined type typedef %p updated from parser %p\n", compositeTypeDef, latestCompositeTypeDef->mTypeDeclaration->GetSourceData());
  3110. }
  3111. if (failedToFindRootType)
  3112. {
  3113. for (auto partialTypeDef : compositeTypeDef->GetLatest()->mPartials)
  3114. {
  3115. if (partialTypeDef->IsExtension())
  3116. {
  3117. // Couldn't find a root type def, treat ourselves as an explicit partial
  3118. auto error = mPassInstance->Fail(StrFormat("Unable to find root type definition for extension '%s'", BfTypeUtils::TypeToString(partialTypeDef->GetLatest()).c_str()),
  3119. partialTypeDef->GetLatest()->mTypeDeclaration->mNameNode);
  3120. if (error != NULL)
  3121. error->mIsPersistent = true;
  3122. }
  3123. }
  3124. }
  3125. }
  3126. outerTypeDefEntryIdx = outerTypeDefEntry->mNext;
  3127. }
  3128. // Handle unused partials, apply any new revisions, process pending deletes
  3129. if ((hadPartials) || (hadChanges))
  3130. {
  3131. BfTypeDef* checkMasterTypeDef = NULL;
  3132. BfTypeDef* deletedCombinedPartial = NULL;
  3133. outerTypeDefEntryIdx = mSystem->mTypeDefs.mHashHeads[bucketIdx];
  3134. while (outerTypeDefEntryIdx != -1)
  3135. {
  3136. auto outerTypeDefEntry = &mSystem->mTypeDefs.mEntries[outerTypeDefEntryIdx];
  3137. auto outerTypeDef = outerTypeDefEntry->mValue;
  3138. auto nextTypeDefEntryIdx = outerTypeDefEntry->mNext;
  3139. BfTypeDefMap::Entry* nextTypeDefEntry = NULL;
  3140. if (nextTypeDefEntryIdx != -1)
  3141. nextTypeDefEntry = &mSystem->mTypeDefs.mEntries[nextTypeDefEntryIdx];
  3142. if ((outerTypeDef->mIsPartial) && (!outerTypeDef->mIsExplicitPartial) && (outerTypeDef->mTypeCode != BfTypeCode_Extension) &&
  3143. (nextTypeDefEntry != NULL) && (!nextTypeDefEntry->mValue->mPartialUsed))
  3144. {
  3145. // This is a root type that we've removed all extensions from, so now we go back to treating it as the actual definition
  3146. // instead of using the composite that immediately follows it
  3147. BF_ASSERT(outerTypeDef->mTypeCode != BfTypeCode_Extension);
  3148. outerTypeDef->mIsPartial = false;
  3149. outerTypeDef->mPartialIdx = -1;
  3150. }
  3151. if (outerTypeDef->mDefState == BfTypeDef::DefState_Deleted)
  3152. {
  3153. BfLogSysM("UpdateRevisedTypes deleting outerTypeDef %p\n", outerTypeDef);
  3154. outerTypeDef->mDefState = BfTypeDef::DefState_Deleted;
  3155. mSystem->RemoveTypeDef(outerTypeDef);
  3156. }
  3157. else if (!outerTypeDef->mPartialUsed)
  3158. {
  3159. if (outerTypeDef->mIsCombinedPartial)
  3160. {
  3161. BfLogSysM("UpdateRevisedTypes deleting combinedPartial type %p\n", outerTypeDef);
  3162. deletedCombinedPartial = outerTypeDef;
  3163. outerTypeDef->mDefState = BfTypeDef::DefState_Deleted;
  3164. mSystem->RemoveTypeDef(outerTypeDef);
  3165. }
  3166. else if (outerTypeDef->mTypeCode == BfTypeCode_Extension)
  3167. {
  3168. auto error = mPassInstance->Fail(StrFormat("Unable to find root type definition for extension '%s'", outerTypeDef->GetLatest()->mFullName.ToString().c_str()),
  3169. outerTypeDef->GetLatest()->mTypeDeclaration->mNameNode);
  3170. if (error != NULL)
  3171. error->mIsPersistent = true;
  3172. if (outerTypeDef->mIsPartial)
  3173. {
  3174. // Allow this typeDef be a full solo type by itself
  3175. //outerTypeDef->mTypeCode = BfTypeCode_Struct;
  3176. outerTypeDef->mIsPartial = false;
  3177. if (outerTypeDef->mNextRevision != NULL)
  3178. outerTypeDef->mNextRevision->mIsPartial = false;
  3179. if (outerTypeDef->mPartialIdx != -1)
  3180. {
  3181. outerTypeDef->mPartialIdx = -1;
  3182. outerTypeDef->mDefState = BfTypeDef::DefState_New;
  3183. }
  3184. }
  3185. }
  3186. }
  3187. outerTypeDefEntryIdx = nextTypeDefEntryIdx;
  3188. }
  3189. }
  3190. }
  3191. for (auto typeDef : prevSoloExtensions)
  3192. {
  3193. // If this got added to a composite partial then delete the previous solo type
  3194. if (typeDef->mIsPartial)
  3195. {
  3196. BfLogSysM("Solo partial going back to normal partial %p\n", typeDef);
  3197. typeDef->mIsPartial = false;
  3198. auto type = mContext->mScratchModule->ResolveTypeDef(typeDef, BfPopulateType_Identity);
  3199. mContext->DeleteType(type);
  3200. typeDef->mIsPartial = true;
  3201. }
  3202. }
  3203. mContext->UpdateRevisedTypes();
  3204. mContext->VerifyTypeLookups();
  3205. mContext->ValidateDependencies();
  3206. if (mStats.mTypesDeleted != 0)
  3207. {
  3208. mContext->UpdateAfterDeletingTypes();
  3209. mContext->ValidateDependencies();
  3210. }
  3211. mContext->RemoveInvalidWorkItems();
  3212. mSystem->mNeedsTypesHandledByCompiler = false;
  3213. //TODO:
  3214. //Sleep(300);
  3215. //mSystem->CheckLockYield();
  3216. }
  3217. BfTypeDef* BfCompiler::GetArrayTypeDef(int dimensions)
  3218. {
  3219. BF_ASSERT(dimensions <= 4);
  3220. if (dimensions == 1)
  3221. return mArray1TypeDef;
  3222. if (dimensions == 2)
  3223. return mArray2TypeDef;
  3224. if (dimensions == 3)
  3225. return mArray3TypeDef;
  3226. return mArray4TypeDef;
  3227. }
  3228. void BfCompiler::VisitAutocompleteExteriorIdentifiers()
  3229. {
  3230. for (auto checkNode : mResolvePassData->mExteriorAutocompleteCheckNodes)
  3231. {
  3232. bool isUsingDirective = false;
  3233. BfIdentifierNode* checkIdentifier = NULL;
  3234. if (auto usingDirective = BfNodeDynCast<BfUsingDirective>(checkNode))
  3235. {
  3236. checkIdentifier = usingDirective->mNamespace;
  3237. }
  3238. else if (auto usingDirective = BfNodeDynCast<BfUsingModDirective>(checkNode))
  3239. {
  3240. if (usingDirective->mTypeRef != NULL)
  3241. {
  3242. BF_ASSERT(mContext->mScratchModule->mCurTypeInstance == NULL);
  3243. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInstance(mContext->mScratchModule->mCurTypeInstance, NULL);
  3244. SetAndRestoreValue<bool> prevIgnoreErrors(mContext->mScratchModule->mIgnoreErrors, true);
  3245. mContext->mScratchModule->ResolveTypeRef(usingDirective->mTypeRef, NULL);
  3246. if (mResolvePassData->mAutoComplete != NULL)
  3247. mResolvePassData->mAutoComplete->CheckTypeRef(usingDirective->mTypeRef, false, isUsingDirective);
  3248. continue;
  3249. }
  3250. }
  3251. else
  3252. checkIdentifier = BfNodeDynCast<BfIdentifierNode>(checkNode);
  3253. if (checkIdentifier == NULL)
  3254. continue;
  3255. if (mResolvePassData->mAutoComplete != NULL)
  3256. mResolvePassData->mAutoComplete->CheckIdentifier(checkIdentifier, false, isUsingDirective);
  3257. if (auto sourceClassifier = mResolvePassData->GetSourceClassifier(checkIdentifier))
  3258. {
  3259. if (isUsingDirective)
  3260. {
  3261. while (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(checkIdentifier))
  3262. {
  3263. sourceClassifier->SetElementType(qualifiedNameNode->mRight, BfSourceElementType_Namespace);
  3264. checkIdentifier = qualifiedNameNode->mLeft;
  3265. }
  3266. if (checkIdentifier != NULL)
  3267. sourceClassifier->SetElementType(checkIdentifier, BfSourceElementType_Namespace);
  3268. }
  3269. }
  3270. }
  3271. mResolvePassData->mExteriorAutocompleteCheckNodes.Clear();
  3272. }
  3273. void BfCompiler::VisitSourceExteriorNodes()
  3274. {
  3275. BP_ZONE("BfCompiler::VisitSourceExteriorNodes");
  3276. String str;
  3277. Array<BfAtom*> namespaceParts;
  3278. Array<BfAstNode*> srcNodes;
  3279. std::function<bool(BfAstNode*, bool)> _AddName = [&](BfAstNode* node, bool wantErrors)
  3280. {
  3281. if (node == NULL)
  3282. return false;
  3283. if (auto qualifiedName = BfNodeDynCast<BfQualifiedNameNode>(node))
  3284. {
  3285. if (!_AddName(qualifiedName->mLeft, wantErrors))
  3286. return false;
  3287. if (!_AddName(qualifiedName->mRight, wantErrors))
  3288. return false;
  3289. return true;
  3290. }
  3291. else if (auto qualifedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(node))
  3292. {
  3293. if (!_AddName(qualifedTypeRef->mLeft, wantErrors))
  3294. return false;
  3295. if (!_AddName(qualifedTypeRef->mRight, wantErrors))
  3296. return false;
  3297. return true;
  3298. }
  3299. else if ((node->IsA<BfIdentifierNode>()) || (node->IsA<BfNamedTypeReference>()))
  3300. {
  3301. srcNodes.Add(node);
  3302. str.Clear();
  3303. node->ToString(str);
  3304. auto atom = mSystem->FindAtom(str);
  3305. if (atom == NULL)
  3306. {
  3307. String prevNamespace;
  3308. for (auto part : namespaceParts)
  3309. {
  3310. if (!prevNamespace.IsEmpty())
  3311. prevNamespace += ".";
  3312. prevNamespace += part->mString;
  3313. }
  3314. if (wantErrors)
  3315. {
  3316. if (prevNamespace.IsEmpty())
  3317. mPassInstance->Fail(StrFormat("The namespace '%s' does not exist", str.c_str()), node);
  3318. else
  3319. mPassInstance->Fail(StrFormat("The namespace '%s' does not exist in the namespace '%s'", str.c_str(), prevNamespace.c_str()), node);
  3320. }
  3321. return false;
  3322. }
  3323. namespaceParts.Add(atom);
  3324. return true;
  3325. }
  3326. return false;
  3327. };
  3328. auto _CheckNamespace = [&](BfParser* parser, bool wantErrors, bool& failed)
  3329. {
  3330. for (int i = 0; i < (int)namespaceParts.size(); i++)
  3331. {
  3332. BfAtomComposite checkNamespace;
  3333. checkNamespace.mParts = &namespaceParts[0];
  3334. checkNamespace.mSize = i + 1;
  3335. if (!mSystem->ContainsNamespace(checkNamespace, parser->mProject))
  3336. {
  3337. failed = true;
  3338. BfAtomComposite prevNamespace;
  3339. prevNamespace.mParts = &namespaceParts[0];
  3340. prevNamespace.mSize = i;
  3341. if (wantErrors)
  3342. {
  3343. if (i == 0)
  3344. mPassInstance->Fail(StrFormat("The namespace '%s' does not exist", namespaceParts[i]->mString.ToString().c_str()), srcNodes[i]);
  3345. else
  3346. mPassInstance->Fail(StrFormat("The namespace '%s' does not exist in the namespace '%s'", namespaceParts[i]->mString.ToString().c_str(), prevNamespace.ToString().c_str()), srcNodes[i]);
  3347. }
  3348. return false;
  3349. }
  3350. }
  3351. return true;
  3352. };
  3353. auto _CheckParser = [&](BfParser* parser)
  3354. {
  3355. while (parser->mNextRevision != NULL)
  3356. parser = parser->mNextRevision;
  3357. if (parser->mAwaitingDelete)
  3358. return;
  3359. if (parser->mParserData == NULL)
  3360. return;
  3361. if (parser->mParserData->mExteriorNodesCheckIdx == mSystem->mTypeMapVersion)
  3362. return;
  3363. bool failed = false;
  3364. for (auto& node : parser->mParserData->mExteriorNodes)
  3365. {
  3366. SetAndRestoreValue<BfSizedArray<BfNamespaceDeclaration*>*> prevCurNamespaceNodes(mContext->mCurNamespaceNodes, &node.mNamespaceNodes);
  3367. auto exteriorAstNode = node.mNode;
  3368. if (auto usingDirective = BfNodeDynCast<BfUsingDirective>(exteriorAstNode))
  3369. {
  3370. srcNodes.Clear();
  3371. namespaceParts.Clear();
  3372. bool success = _AddName(usingDirective->mNamespace, true);
  3373. _CheckNamespace(parser, true, failed);
  3374. }
  3375. else if (auto usingDirective = BfNodeDynCast<BfUsingModDirective>(exteriorAstNode))
  3376. {
  3377. if (usingDirective->mTypeRef != NULL)
  3378. {
  3379. BF_ASSERT(mContext->mScratchModule->mCurTypeInstance == NULL);
  3380. bool wasNamespace = false;
  3381. if (usingDirective->mModToken->mToken == BfToken_Internal)
  3382. {
  3383. srcNodes.Clear();
  3384. namespaceParts.Clear();
  3385. if (_AddName(usingDirective->mTypeRef, false))
  3386. {
  3387. wasNamespace = _CheckNamespace(parser, false, failed);
  3388. }
  3389. }
  3390. if (!wasNamespace)
  3391. {
  3392. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInstance(mContext->mScratchModule->mCurTypeInstance, NULL);
  3393. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(usingDirective->mTypeRef))
  3394. {
  3395. mContext->mScratchModule->ResolveTypeRefAllowUnboundGenerics(usingDirective->mTypeRef, BfPopulateType_Identity);
  3396. }
  3397. else
  3398. mContext->mScratchModule->ResolveTypeRef(usingDirective->mTypeRef, BfPopulateType_Identity);
  3399. if ((mResolvePassData != NULL) && (mResolvePassData->mAutoComplete != NULL))
  3400. mResolvePassData->mAutoComplete->CheckTypeRef(usingDirective->mTypeRef, false, false);
  3401. }
  3402. }
  3403. }
  3404. }
  3405. if (!failed)
  3406. parser->mParserData->mExteriorNodesCheckIdx = mSystem->mTypeMapVersion;
  3407. };
  3408. if (mResolvePassData != NULL)
  3409. {
  3410. for (auto parser : mResolvePassData->mParsers)
  3411. _CheckParser(parser);
  3412. }
  3413. else
  3414. {
  3415. for (auto parser : mSystem->mParsers)
  3416. {
  3417. _CheckParser(parser);
  3418. }
  3419. }
  3420. }
  3421. void BfCompiler::ProcessAutocompleteTempType()
  3422. {
  3423. BP_ZONE_F("BfCompiler::ProcessAutocompleteTempType %d", mResolvePassData->mResolveType);
  3424. String& autoCompleteResultString = *gTLStrReturn.Get();
  3425. autoCompleteResultString.clear();
  3426. if (mContext->mBfObjectType == NULL)
  3427. return; // Not initialized yet
  3428. auto module = mContext->mScratchModule;
  3429. auto autoComplete = mResolvePassData->mAutoComplete;
  3430. BfLogSysM("ProcessAutocompleteTempType %d\n", autoComplete->mResolveType);
  3431. SetAndRestoreValue<bool> prevCanceling(mCanceling, false);
  3432. BF_ASSERT(mResolvePassData->mAutoComplete->mDefMethod == NULL);
  3433. if (autoComplete->mResolveType == BfResolveType_GetNavigationData)
  3434. {
  3435. for (auto parser : mResolvePassData->mParsers)
  3436. {
  3437. for (auto node : parser->mSidechannelRootNode->mChildArr)
  3438. {
  3439. if (auto preprocNode = BfNodeDynCast<BfPreprocessorNode>(node))
  3440. {
  3441. if (preprocNode->mCommand->Equals("region"))
  3442. {
  3443. if (!autoCompleteResultString.empty())
  3444. autoCompleteResultString += "\n";
  3445. autoCompleteResultString += "#";
  3446. preprocNode->mArgument->ToString(autoCompleteResultString);
  3447. mContext->mScratchModule->UpdateSrcPos(preprocNode, (BfSrcPosFlags)(BfSrcPosFlag_NoSetDebugLoc | BfSrcPosFlag_Force));
  3448. autoCompleteResultString += StrFormat("\tregion\t%d\t%d", module->mCurFilePosition.mCurLine, module->mCurFilePosition.mCurColumn);
  3449. }
  3450. }
  3451. }
  3452. }
  3453. for (auto tempTypeDef : mResolvePassData->mAutoCompleteTempTypes)
  3454. {
  3455. String typeName = tempTypeDef->ToString();
  3456. BfLogSysM("BfResolveType_GetNavigationData TypeDef:%p %s\n", tempTypeDef, typeName.c_str());
  3457. auto refNode = tempTypeDef->GetRefNode();
  3458. if ((refNode != NULL) && (!tempTypeDef->IsGlobalsContainer()))
  3459. {
  3460. if (!autoCompleteResultString.empty())
  3461. autoCompleteResultString += "\n";
  3462. String typeName = BfTypeUtils::TypeToString(tempTypeDef, BfTypeNameFlag_OmitNamespace);
  3463. module->UpdateSrcPos(refNode, (BfSrcPosFlags)(BfSrcPosFlag_NoSetDebugLoc | BfSrcPosFlag_Force));
  3464. autoCompleteResultString += typeName;
  3465. if (tempTypeDef->mTypeCode == BfTypeCode_Object)
  3466. autoCompleteResultString += "\tclass";
  3467. else if (tempTypeDef->mTypeCode == BfTypeCode_Enum)
  3468. autoCompleteResultString += "\tenum";
  3469. else if (tempTypeDef->mTypeCode == BfTypeCode_Struct)
  3470. autoCompleteResultString += "\tstruct";
  3471. else if (tempTypeDef->mTypeCode == BfTypeCode_TypeAlias)
  3472. autoCompleteResultString += "\ttypealias";
  3473. else
  3474. autoCompleteResultString += "\t";
  3475. autoCompleteResultString += StrFormat("\t%d\t%d", module->mCurFilePosition.mCurLine, module->mCurFilePosition.mCurColumn);
  3476. }
  3477. String methodText;
  3478. for (auto methodDef : tempTypeDef->mMethods)
  3479. {
  3480. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Operator) ||
  3481. (methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_Dtor) ||
  3482. (methodDef->mMethodType == BfMethodType_Mixin) || (methodDef->mMethodType == BfMethodType_Extension)) &&
  3483. (methodDef->mMethodDeclaration != NULL))
  3484. {
  3485. methodText = methodDef->ToString();
  3486. if (typeName != "@")
  3487. methodText = typeName + "." + methodText;
  3488. if (!autoCompleteResultString.empty())
  3489. autoCompleteResultString += "\n";
  3490. auto methodDeclaration = methodDef->GetMethodDeclaration();
  3491. BfAstNode* refNode = methodDeclaration;
  3492. if (methodDeclaration->mBody != NULL)
  3493. refNode = methodDeclaration->mBody;
  3494. else if (methodDeclaration->mNameNode != NULL)
  3495. refNode = methodDeclaration->mNameNode;
  3496. module->UpdateSrcPos(refNode, (BfSrcPosFlags)(BfSrcPosFlag_NoSetDebugLoc | BfSrcPosFlag_Force));
  3497. const char* typeStr = (methodDef->mMethodType == BfMethodType_Extension) ? "extmethod" : "method";
  3498. methodText += StrFormat("\t%s\t%d\t%d", typeStr, module->mCurFilePosition.mCurLine, module->mCurFilePosition.mCurColumn);
  3499. autoCompleteResultString += methodText;
  3500. }
  3501. }
  3502. for (auto fieldDef : tempTypeDef->mFields)
  3503. {
  3504. auto fieldDeclaration = BfNodeDynCast<BfFieldDeclaration>(fieldDef->mFieldDeclaration);
  3505. if ((fieldDeclaration == NULL) || (fieldDeclaration->mNameNode == NULL) || (BfNodeIsA<BfPropertyDeclaration>(fieldDef->mFieldDeclaration)))
  3506. continue;
  3507. String fieldText = fieldDef->mName;
  3508. if (typeName != "@")
  3509. fieldText = typeName + "." + fieldText;
  3510. if (!autoCompleteResultString.empty())
  3511. autoCompleteResultString += "\n";
  3512. BfAstNode* refNode = fieldDeclaration->mNameNode;
  3513. module->UpdateSrcPos(refNode, (BfSrcPosFlags)(BfSrcPosFlag_NoSetDebugLoc | BfSrcPosFlag_Force));
  3514. fieldText += StrFormat("\tfield\t%d\t%d", module->mCurFilePosition.mCurLine, module->mCurFilePosition.mCurColumn);
  3515. autoCompleteResultString += fieldText;
  3516. }
  3517. for (auto propDef : tempTypeDef->mProperties)
  3518. {
  3519. auto propDeclaration = BfNodeDynCast<BfPropertyDeclaration>(propDef->mFieldDeclaration);
  3520. if ((propDeclaration == NULL) || (propDeclaration->mNameNode == NULL))
  3521. continue;
  3522. String propText = propDef->mName;
  3523. if (typeName != "@")
  3524. propText = typeName + "." + propText;
  3525. if (!autoCompleteResultString.empty())
  3526. autoCompleteResultString += "\n";
  3527. BfAstNode* refNode = propDeclaration->mNameNode;
  3528. module->UpdateSrcPos(refNode, (BfSrcPosFlags)(BfSrcPosFlag_NoSetDebugLoc | BfSrcPosFlag_Force));
  3529. propText += StrFormat("\tproperty\t%d\t%d", module->mCurFilePosition.mCurLine, module->mCurFilePosition.mCurColumn);
  3530. autoCompleteResultString += propText;
  3531. }
  3532. }
  3533. module->CleanupFileInstances();
  3534. return;
  3535. }
  3536. if (autoComplete->mResolveType == BfResolveType_GetCurrentLocation)
  3537. {
  3538. for (auto tempTypeDef : mResolvePassData->mAutoCompleteTempTypes)
  3539. {
  3540. String typeName = tempTypeDef->mNamespace.ToString();
  3541. if (!typeName.empty())
  3542. typeName += ".";
  3543. typeName += tempTypeDef->ToString();
  3544. autoCompleteResultString = typeName;
  3545. for (auto methodDef : tempTypeDef->mMethods)
  3546. {
  3547. BfAstNode* defNode = methodDef->mMethodDeclaration;
  3548. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  3549. defNode = propertyDeclaration;
  3550. if (defNode == NULL)
  3551. continue;
  3552. auto parser = defNode->GetParser();
  3553. if ((parser == NULL) || (parser->mCursorIdx == -1))
  3554. continue;
  3555. if ((defNode != NULL) &&
  3556. (defNode->Contains(parser->mCursorIdx)))
  3557. {
  3558. String methodText = methodDef->ToString();
  3559. if (typeName != "@")
  3560. methodText = typeName + "." + methodText;
  3561. autoCompleteResultString = methodText;
  3562. break;
  3563. }
  3564. }
  3565. }
  3566. if (mResolvePassData->mAutoCompleteTempTypes.IsEmpty())
  3567. {
  3568. for (auto& kv : mResolvePassData->mEmitEmbedEntries)
  3569. {
  3570. if (kv.mValue.mCursorIdx < 0)
  3571. continue;
  3572. String typeName = kv.mKey;
  3573. auto type = GetType(typeName);
  3574. if (type == NULL)
  3575. continue;
  3576. auto typeInst = type->ToTypeInstance();
  3577. if (typeInst == NULL)
  3578. continue;
  3579. if (mResolvePassData->mParsers.IsEmpty())
  3580. break;
  3581. autoCompleteResultString = mContext->mScratchModule->TypeToString(typeInst);
  3582. for (auto methodDef : typeInst->mTypeDef->mMethods)
  3583. {
  3584. BfAstNode* defNode = methodDef->mMethodDeclaration;
  3585. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  3586. defNode = propertyDeclaration;
  3587. if (defNode == NULL)
  3588. continue;
  3589. if ((defNode != NULL) &&
  3590. (defNode->Contains(kv.mValue.mCursorIdx)))
  3591. {
  3592. auto defParser = defNode->GetParser();
  3593. if (defParser == NULL)
  3594. continue;
  3595. if (!defParser->mIsEmitted)
  3596. continue;
  3597. autoCompleteResultString += ".";
  3598. autoCompleteResultString += methodDef->ToString();
  3599. break;
  3600. }
  3601. }
  3602. }
  3603. }
  3604. module->CleanupFileInstances();
  3605. return;
  3606. }
  3607. mFastFinish = false;
  3608. SetAndRestoreValue<BfMethodState*> prevMethodState(module->mCurMethodState, NULL);
  3609. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(module->mCurTypeInstance, NULL);
  3610. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(module->mCurMethodInstance, NULL);
  3611. SetAndRestoreValue<BfTypeState*> prevTypeState(module->mContext->mCurTypeState, NULL);
  3612. // >>> VisitExteriorIdentifiers
  3613. mResolvePassData->mAutoComplete->SetModule(module);
  3614. {
  3615. BP_ZONE("VisitExteriorIdentifiers");
  3616. VisitAutocompleteExteriorIdentifiers();
  3617. }
  3618. VisitSourceExteriorNodes();
  3619. if (autoComplete->mResolveType == BfResolveType_GetFixits)
  3620. {
  3621. BfAstNode* conflictStart = NULL;
  3622. BfAstNode* conflictSplit = NULL;
  3623. for (auto parser : mResolvePassData->mParsers)
  3624. {
  3625. auto src = parser->mSrc;
  3626. for (int checkIdx = 0; checkIdx < (int)parser->mSidechannelRootNode->mChildArr.mSize; checkIdx++)
  3627. {
  3628. auto sideNode = parser->mSidechannelRootNode->mChildArr.mVals[checkIdx];
  3629. if (autoComplete->CheckFixit(sideNode))
  3630. {
  3631. if (src[sideNode->mSrcStart] == '<')
  3632. {
  3633. conflictStart = sideNode;
  3634. conflictSplit = NULL;
  3635. }
  3636. }
  3637. else
  3638. {
  3639. if (src[sideNode->mSrcStart] == '<')
  3640. {
  3641. conflictStart = NULL;
  3642. conflictSplit = NULL;
  3643. }
  3644. else if (src[sideNode->mSrcStart] == '=')
  3645. {
  3646. if (conflictStart != NULL)
  3647. conflictSplit = sideNode;
  3648. }
  3649. else if (src[sideNode->mSrcStart] == '>')
  3650. {
  3651. if (conflictSplit != NULL)
  3652. {
  3653. autoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("Accept First\tdelete|%s-%d|\x01""delete|%s-%d|",
  3654. autoComplete->FixitGetLocation(parser->mParserData, conflictSplit->mSrcStart).c_str(), sideNode->mSrcEnd - conflictSplit->mSrcStart + 1,
  3655. autoComplete->FixitGetLocation(parser->mParserData, conflictStart->mSrcStart).c_str(), conflictStart->mSrcEnd - conflictStart->mSrcStart + 1).c_str()));
  3656. autoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("Accept Second\tdelete|%s-%d|\x01""delete|%s-%d|",
  3657. autoComplete->FixitGetLocation(parser->mParserData, sideNode->mSrcStart).c_str(), sideNode->mSrcEnd - sideNode->mSrcStart + 1,
  3658. autoComplete->FixitGetLocation(parser->mParserData, conflictStart->mSrcStart).c_str(), conflictSplit->mSrcEnd - conflictStart->mSrcStart + 1).c_str()));
  3659. autoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("Accept Both\tdelete|%s-%d|\x01""delete|%s-%d|\x01""delete|%s-%d|",
  3660. autoComplete->FixitGetLocation(parser->mParserData, sideNode->mSrcStart).c_str(), sideNode->mSrcEnd - sideNode->mSrcStart + 1,
  3661. autoComplete->FixitGetLocation(parser->mParserData, conflictSplit->mSrcStart).c_str(), conflictSplit->mSrcEnd - conflictSplit->mSrcStart + 1,
  3662. autoComplete->FixitGetLocation(parser->mParserData, conflictStart->mSrcStart).c_str(), conflictStart->mSrcEnd - conflictStart->mSrcStart + 1).c_str()));
  3663. conflictStart = NULL;
  3664. conflictSplit = NULL;
  3665. }
  3666. }
  3667. }
  3668. }
  3669. }
  3670. }
  3671. if (autoComplete->mResolveType == BfResolveType_GetSymbolInfo)
  3672. {
  3673. BfNamespaceVisitor namespaceVisitor;
  3674. namespaceVisitor.mResolvePassData = mResolvePassData;
  3675. namespaceVisitor.mSystem = mSystem;
  3676. for (auto parser : mResolvePassData->mParsers)
  3677. namespaceVisitor.Visit(parser->mRootNode);
  3678. }
  3679. auto _FindAcutalTypeDef = [&](BfTypeDef* tempTypeDef)
  3680. {
  3681. auto typeName = tempTypeDef->mFullName;
  3682. int wantNumGenericParams = (int)tempTypeDef->mGenericParamDefs.size();
  3683. auto actualTypeDefItr = mSystem->mTypeDefs.TryGet(typeName);
  3684. while (actualTypeDefItr)
  3685. {
  3686. auto checkTypeDef = *actualTypeDefItr;
  3687. if ((!checkTypeDef->mIsPartial) /*&& (checkTypeDef->mTypeCode != BfTypeCode_Extension)*/ &&
  3688. ((checkTypeDef->mTypeCode == tempTypeDef->mTypeCode) || (tempTypeDef->mTypeCode == BfTypeCode_Extension)))
  3689. {
  3690. if ((checkTypeDef->NameEquals(tempTypeDef)) && (checkTypeDef->mIsCombinedPartial) &&
  3691. (checkTypeDef->mGenericParamDefs.size() == tempTypeDef->mGenericParamDefs.size()) &&
  3692. (tempTypeDef->mProject->ContainsReference(checkTypeDef->mProject)))
  3693. {
  3694. return mSystem->FilterDeletedTypeDef(checkTypeDef);
  3695. }
  3696. if ((checkTypeDef->mGenericParamDefs.size() == wantNumGenericParams) &&
  3697. (FileNameEquals(tempTypeDef->mSource->mSourceData->ToParserData()->mFileName, checkTypeDef->mSource->mSourceData->ToParserData()->mFileName)) &&
  3698. (tempTypeDef->mProject == checkTypeDef->mProject))
  3699. {
  3700. return mSystem->FilterDeletedTypeDef(checkTypeDef);
  3701. }
  3702. }
  3703. actualTypeDefItr.MoveToNextHashMatch();
  3704. }
  3705. return (BfTypeDef*)NULL;
  3706. };
  3707. BfTypeDef* tempTypeDef = NULL;
  3708. BfTypeDef* actualTypeDef = NULL;
  3709. for (auto checkTempType : mResolvePassData->mAutoCompleteTempTypes)
  3710. {
  3711. if (mResolvePassData->mAutoComplete->IsAutocompleteNode(checkTempType->mTypeDeclaration))
  3712. {
  3713. BfTypeDef* checkActualTypeDef = _FindAcutalTypeDef(checkTempType);
  3714. if ((actualTypeDef == NULL) || (checkActualTypeDef != NULL))
  3715. {
  3716. actualTypeDef = checkActualTypeDef;
  3717. tempTypeDef = checkTempType;
  3718. }
  3719. mContext->HandleChangedTypeDef(checkTempType, true);
  3720. }
  3721. auto sourceClassifier = mResolvePassData->GetSourceClassifier(checkTempType->mTypeDeclaration->mNameNode);
  3722. if (sourceClassifier == NULL)
  3723. continue;
  3724. BfSourceElementType elemType = BfSourceElementType_Type;
  3725. if (checkTempType->mTypeCode == BfTypeCode_Interface)
  3726. elemType = BfSourceElementType_Interface;
  3727. else if (checkTempType->mTypeCode == BfTypeCode_Object)
  3728. elemType = BfSourceElementType_RefType;
  3729. else if (checkTempType->mTypeCode == BfTypeCode_Struct)
  3730. elemType = BfSourceElementType_Struct;
  3731. sourceClassifier->SetElementType(checkTempType->mTypeDeclaration->mNameNode, elemType);
  3732. }
  3733. if (tempTypeDef == NULL)
  3734. {
  3735. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GoToDefinition))
  3736. {
  3737. autoComplete->SetModule(NULL);
  3738. for (auto& kv : mResolvePassData->mEmitEmbedEntries)
  3739. {
  3740. String typeName = kv.mKey;
  3741. auto type = GetType(typeName);
  3742. if (type == NULL)
  3743. continue;
  3744. auto typeInst = type->ToTypeInstance();
  3745. if (typeInst == NULL)
  3746. continue;
  3747. mContext->RebuildType(typeInst);
  3748. if (!typeInst->mModule->mIsModuleMutable)
  3749. typeInst->mModule->StartNewRevision(BfModule::RebuildKind_All, true);
  3750. mContext->mScratchModule->PopulateType(typeInst, Beefy::BfPopulateType_Full_Force);
  3751. }
  3752. DoWorkLoop();
  3753. autoComplete->SetModule(mContext->mScratchModule);
  3754. }
  3755. GenerateAutocompleteInfo();
  3756. BfLogSysM("ProcessAutocompleteTempType - no tempTypeDef\n");
  3757. return;
  3758. }
  3759. if (tempTypeDef->mProject->mDisabled)
  3760. {
  3761. BfLogSysM("ProcessAutocompleteTempType - project disabled\n");
  3762. return;
  3763. }
  3764. BfTypeState typeState;
  3765. typeState.mCurTypeDef = tempTypeDef;
  3766. module->mContext->mCurTypeState = &typeState;
  3767. BfStaticSearch* staticSearch = NULL;
  3768. if (mResolvePassData->mStaticSearchMap.TryAdd(tempTypeDef, NULL, &staticSearch))
  3769. {
  3770. for (auto typeRef : tempTypeDef->mStaticSearch)
  3771. {
  3772. auto type = module->ResolveTypeRef(typeRef, NULL, BfPopulateType_Declaration);
  3773. if (type != NULL)
  3774. {
  3775. auto typeInst = type->ToTypeInstance();
  3776. if (typeInst != NULL)
  3777. staticSearch->mStaticTypes.Add(typeInst);
  3778. }
  3779. }
  3780. }
  3781. BfInternalAccessSet* internalAccessSet = NULL;
  3782. if (mResolvePassData->mInternalAccessMap.TryAdd(tempTypeDef, NULL, &internalAccessSet))
  3783. {
  3784. for (auto typeRef : tempTypeDef->mInternalAccessSet)
  3785. {
  3786. if ((typeRef->IsA<BfNamedTypeReference>()) ||
  3787. (typeRef->IsA<BfQualifiedTypeReference>()))
  3788. {
  3789. String checkNamespaceStr;
  3790. typeRef->ToString(checkNamespaceStr);
  3791. BfAtomComposite checkNamespace;
  3792. if (mSystem->ParseAtomComposite(checkNamespaceStr, checkNamespace))
  3793. {
  3794. if (mSystem->ContainsNamespace(checkNamespace, tempTypeDef->mProject))
  3795. {
  3796. internalAccessSet->mNamespaces.Add(checkNamespace);
  3797. continue;
  3798. }
  3799. }
  3800. }
  3801. BfType* type;
  3802. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  3803. type = mContext->mScratchModule->ResolveTypeRefAllowUnboundGenerics(typeRef, BfPopulateType_Identity);
  3804. else
  3805. type = module->ResolveTypeRef(typeRef, NULL, BfPopulateType_Identity);
  3806. if (type != NULL)
  3807. {
  3808. auto typeInst = type->ToTypeInstance();
  3809. if (typeInst != NULL)
  3810. internalAccessSet->mTypes.Add(typeInst);
  3811. }
  3812. }
  3813. }
  3814. if (tempTypeDef->mTypeCode == BfTypeCode_Extension)
  3815. {
  3816. BfTypeInstance* outerTypeInstance = NULL;
  3817. if (tempTypeDef->mOuterType != NULL)
  3818. {
  3819. auto outerTypeDef = _FindAcutalTypeDef(tempTypeDef->mOuterType);
  3820. if (outerTypeDef != NULL)
  3821. {
  3822. outerTypeInstance = (BfTypeInstance*)module->ResolveTypeDef(outerTypeDef, BfPopulateType_IdentityNoRemapAlias);
  3823. if ((outerTypeInstance != NULL) && (outerTypeInstance->IsIncomplete()))
  3824. module->PopulateType(outerTypeInstance, BfPopulateType_Full);
  3825. }
  3826. }
  3827. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInstance(module->mCurTypeInstance, outerTypeInstance);
  3828. auto autoComplete = mResolvePassData->mAutoComplete;
  3829. if (autoComplete->IsAutocompleteNode(tempTypeDef->mTypeDeclaration->mNameNode))
  3830. {
  3831. BfIdentifierNode* nameNode = tempTypeDef->mTypeDeclaration->mNameNode;
  3832. autoComplete->AddTopLevelNamespaces(nameNode);
  3833. autoComplete->AddTopLevelTypes(nameNode);
  3834. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  3835. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  3836. }
  3837. }
  3838. // while (actualTypeDef == NULL)
  3839. // {
  3840. // checkT
  3841. // }
  3842. if ((actualTypeDef == NULL) || (actualTypeDef->mTypeDeclaration == NULL))
  3843. {
  3844. GenerateAutocompleteInfo();
  3845. return;
  3846. }
  3847. auto sourceClassifier = mResolvePassData->GetSourceClassifier(tempTypeDef->mTypeDeclaration);
  3848. if (tempTypeDef->mTypeCode == BfTypeCode_Extension)
  3849. sourceClassifier->SetElementType(tempTypeDef->mTypeDeclaration->mNameNode, actualTypeDef->mTypeCode);
  3850. if (tempTypeDef->mTypeDeclaration->mAttributes != NULL)
  3851. sourceClassifier->VisitChild(tempTypeDef->mTypeDeclaration->mAttributes);
  3852. BfTypeInstance* typeInst;
  3853. {
  3854. BP_ZONE("ProcessAutocompleteTempType.ResolveTypeDef");
  3855. typeInst = (BfTypeInstance*)module->ResolveTypeDef(actualTypeDef, BfPopulateType_IdentityNoRemapAlias);
  3856. if ((typeInst != NULL) && (typeInst->IsIncomplete()))
  3857. module->PopulateType(typeInst, BfPopulateType_Full);
  3858. }
  3859. if (typeInst == NULL)
  3860. {
  3861. return;
  3862. }
  3863. BF_ASSERT((typeInst->mSize != -1) || (typeInst->IsTypeAlias()));
  3864. #ifdef _DEBUG
  3865. if ((typeInst->mModule != NULL) && (!typeInst->mModule->mIsScratchModule))
  3866. mLastAutocompleteModule = typeInst->mModule;
  3867. #endif
  3868. SetAndRestoreValue<BfTypeInstance*> prevType(module->mCurTypeInstance, typeInst);
  3869. typeState.mType = typeInst;
  3870. BfGenericExtensionEntry* genericExEntry = NULL;
  3871. bool hadTempExtensionInfo = false;
  3872. if ((tempTypeDef->IsExtension()) && (actualTypeDef->mIsCombinedPartial) && (typeInst->IsGenericTypeInstance()))
  3873. {
  3874. // Add to our extension info map and then take it out at the end...
  3875. auto genericTypeInst = (BfTypeInstance*)typeInst;
  3876. module->BuildGenericExtensionInfo(genericTypeInst, tempTypeDef);
  3877. genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.TryGetValue(tempTypeDef, &genericExEntry);
  3878. BF_ASSERT(genericExEntry != NULL);
  3879. hadTempExtensionInfo = true;
  3880. }
  3881. if ((typeInst->IsUnspecializedType()) || (!typeInst->IsGenericTypeInstance()))
  3882. {
  3883. auto autoComplete = mResolvePassData->mAutoComplete;
  3884. if (autoComplete->IsAutocompleteNode(tempTypeDef->mTypeDeclaration->mNameNode))
  3885. {
  3886. BfIdentifierNode* nameNode;
  3887. nameNode = tempTypeDef->mTypeDeclaration->mNameNode;
  3888. if ((actualTypeDef->mIsCombinedPartial) && (tempTypeDef->mTypeCode == BfTypeCode_Extension))
  3889. {
  3890. autoComplete->AddTopLevelNamespaces(tempTypeDef->mTypeDeclaration->mNameNode);
  3891. autoComplete->AddTopLevelTypes(tempTypeDef->mTypeDeclaration->mNameNode);
  3892. autoComplete->SetDefinitionLocation(actualTypeDef->mTypeDeclaration->mNameNode);
  3893. }
  3894. else
  3895. autoComplete->SetDefinitionLocation(nameNode);
  3896. autoComplete->mDefType = actualTypeDef;
  3897. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  3898. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  3899. if (autoComplete->mResolveType == BfResolveType_GetResultString)
  3900. {
  3901. autoComplete->mResultString = ":";
  3902. autoComplete->mResultString += module->TypeToString(typeInst, (BfTypeNameFlags)(BfTypeNameFlag_ExtendedInfo | BfTypeNameFlag_ResolveGenericParamNames));
  3903. }
  3904. }
  3905. }
  3906. autoComplete->CheckInterfaceFixit(typeInst, tempTypeDef->mTypeDeclaration->mNameNode);
  3907. if (tempTypeDef->mTypeCode == BfTypeCode_TypeAlias)
  3908. {
  3909. auto typeAliasDecl = (BfTypeAliasDeclaration*)tempTypeDef->mTypeDeclaration;
  3910. if (typeAliasDecl->mAliasToType != NULL)
  3911. {
  3912. autoComplete->CheckTypeRef(typeAliasDecl->mAliasToType, false);
  3913. module->ResolveTypeRef(typeAliasDecl->mAliasToType);
  3914. }
  3915. }
  3916. // Save and restore mFieldResolveReentrys, we could fire off autocomplete while resolving a field
  3917. SetAndRestoreValue<decltype (module->mContext->mFieldResolveReentrys)> prevTypeResolveReentry(module->mContext->mFieldResolveReentrys);
  3918. module->mContext->mFieldResolveReentrys.Clear();
  3919. if (tempTypeDef->mTypeDeclaration->mAttributes != NULL)
  3920. {
  3921. auto customAttrs = module->GetCustomAttributes(tempTypeDef);
  3922. delete customAttrs;
  3923. }
  3924. for (int genericParamIdx = 0; genericParamIdx < (int)tempTypeDef->mGenericParamDefs.size(); genericParamIdx++)
  3925. {
  3926. auto genericParamDef = tempTypeDef->mGenericParamDefs[genericParamIdx];
  3927. auto genericParamInstance = new BfGenericTypeParamInstance(tempTypeDef, genericParamIdx);
  3928. genericParamInstance->mExternType = module->GetGenericParamType(BfGenericParamKind_Type, genericParamIdx);
  3929. module->ResolveGenericParamConstraints(genericParamInstance, true);
  3930. delete genericParamInstance;
  3931. for (auto nameNode : genericParamDef->mNameNodes)
  3932. module->HandleTypeGenericParamRef(nameNode, tempTypeDef, genericParamIdx);
  3933. }
  3934. //TODO: Do extern constraint stuff here
  3935. for (auto fieldDef : tempTypeDef->mFields)
  3936. {
  3937. BP_ZONE("ProcessAutocompleteTempType.CheckField");
  3938. if (BfNodeIsA<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  3939. continue; // Don't process auto-generated property fields
  3940. if (fieldDef->mTypeRef != NULL)
  3941. {
  3942. BfResolveTypeRefFlags flags = BfResolveTypeRefFlag_None;
  3943. if (fieldDef->GetInitializer() != NULL)
  3944. flags = (BfResolveTypeRefFlags)(flags | BfResolveTypeRefFlag_AllowInferredSizedArray);
  3945. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) &&
  3946. (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  3947. module->ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, flags);
  3948. }
  3949. mResolvePassData->mAutoComplete->CheckTypeRef(fieldDef->mTypeRef, true);
  3950. actualTypeDef->PopulateMemberSets();
  3951. BfFieldDef* actualFieldDef = NULL;
  3952. BfMemberSetEntry* memberSetEntry = NULL;
  3953. if (actualTypeDef->mFieldSet.TryGetWith((StringImpl&)fieldDef->mName, &memberSetEntry))
  3954. {
  3955. auto checkFieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  3956. if ((checkFieldDef->mIsConst == fieldDef->mIsConst) &&
  3957. (checkFieldDef->mIsStatic == fieldDef->mIsStatic))
  3958. {
  3959. actualFieldDef = checkFieldDef;
  3960. }
  3961. }
  3962. if (actualFieldDef != NULL)
  3963. {
  3964. auto fieldInstance = &typeInst->mFieldInstances[actualFieldDef->mIdx];
  3965. autoComplete->CheckVarResolution(fieldDef->mTypeRef, fieldInstance->mResolvedType);
  3966. }
  3967. auto nameNode = fieldDef->GetNameNode();
  3968. if (((autoComplete->mIsGetDefinition) || (autoComplete->mResolveType == BfResolveType_GetResultString)) &&
  3969. (fieldDef->mFieldDeclaration != NULL) && (autoComplete->IsAutocompleteNode(nameNode)))
  3970. {
  3971. for (int i = 0; i < (int)actualTypeDef->mFields.size(); i++)
  3972. {
  3973. auto actualFieldDef = actualTypeDef->mFields[i];
  3974. if (actualFieldDef->mName == fieldDef->mName)
  3975. {
  3976. if (autoComplete->mIsGetDefinition)
  3977. {
  3978. autoComplete->mDefType = actualTypeDef;
  3979. autoComplete->mDefField = actualFieldDef;
  3980. autoComplete->SetDefinitionLocation(nameNode);
  3981. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  3982. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  3983. }
  3984. else if (autoComplete->mResolveType == BfResolveType_GetResultString)
  3985. {
  3986. auto fieldInstance = &typeInst->mFieldInstances[actualFieldDef->mIdx];
  3987. if (fieldInstance->mConstIdx != -1)
  3988. {
  3989. auto constant = typeInst->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  3990. auto retVal = module->ConstantToCurrent(constant, typeInst->mConstHolder, fieldInstance->mResolvedType);
  3991. BfTypedValue typedValue = BfTypedValue(retVal, fieldInstance->mResolvedType);
  3992. autoComplete->CheckResult(fieldDef->GetRefNode(), typedValue);
  3993. }
  3994. }
  3995. break;
  3996. }
  3997. }
  3998. }
  3999. BfFieldDeclaration* fieldDecl = fieldDef->GetFieldDeclaration();
  4000. if ((fieldDecl != NULL) && (fieldDecl->mAttributes != NULL))
  4001. {
  4002. auto customAttrs = module->GetCustomAttributes(fieldDecl->mAttributes, fieldDef->mIsStatic ? BfAttributeTargets_StaticField : BfAttributeTargets_Field);
  4003. delete customAttrs;
  4004. }
  4005. if (fieldDef->mIsConst)
  4006. {
  4007. module->ResolveConstField(typeInst, NULL, fieldDef);
  4008. }
  4009. if (fieldDef->GetInitializer() == NULL)
  4010. {
  4011. if (BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef))
  4012. {
  4013. if ((fieldDef->mTypeRef->IsA<BfVarTypeReference>()) || (fieldDef->mTypeRef->IsA<BfLetTypeReference>()))
  4014. mPassInstance->Fail("Implicitly-typed fields must be initialized", fieldDef->GetRefNode());
  4015. }
  4016. }
  4017. }
  4018. auto checkTypeDef = tempTypeDef;
  4019. while (checkTypeDef != NULL)
  4020. {
  4021. for (auto baseType : checkTypeDef->mBaseTypes)
  4022. {
  4023. autoComplete->CheckTypeRef(baseType, false);
  4024. module->ResolveTypeRef(baseType);
  4025. }
  4026. checkTypeDef = checkTypeDef->mOuterType;
  4027. }
  4028. for (auto propDef : tempTypeDef->mProperties)
  4029. {
  4030. auto fieldDecl = propDef->GetFieldDeclaration();
  4031. if ((fieldDecl != NULL) && (fieldDecl->mAttributes != NULL))
  4032. {
  4033. BfAttributeTargets target = BfAttributeTargets_Property;
  4034. if (propDef->IsExpressionBodied())
  4035. target = (BfAttributeTargets)(target | BfAttributeTargets_Method);
  4036. auto customAttrs = module->GetCustomAttributes(fieldDecl->mAttributes, target);
  4037. delete customAttrs;
  4038. }
  4039. auto propDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDecl);
  4040. if (propDeclaration != NULL)
  4041. autoComplete->CheckProperty(propDeclaration);
  4042. if (BfNodeIsA<BfVarTypeReference>(propDef->mTypeRef))
  4043. {
  4044. // This is only valid for ConstEval properties
  4045. }
  4046. else
  4047. module->ResolveTypeRef(propDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowRef);
  4048. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propDef->mFieldDeclaration))
  4049. {
  4050. for (auto paramDecl : indexerDeclaration->mParams)
  4051. {
  4052. module->ResolveTypeRef(paramDecl->mTypeRef, BfPopulateType_Identity);
  4053. }
  4054. }
  4055. if ((autoComplete->mIsGetDefinition) && (fieldDecl != NULL) && (autoComplete->IsAutocompleteNode(fieldDecl->mNameNode)))
  4056. {
  4057. auto checkType = typeInst;
  4058. while (checkType != NULL)
  4059. {
  4060. for (auto checkProp : checkType->mTypeDef->mProperties)
  4061. {
  4062. if (checkProp->mName == propDef->mName)
  4063. {
  4064. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  4065. if ((checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  4066. {
  4067. autoComplete->SetDefinitionLocation(checkPropDeclaration->mNameNode);
  4068. autoComplete->mDefType = checkType->mTypeDef;
  4069. autoComplete->mDefProp = checkProp;
  4070. checkType = NULL;
  4071. break;
  4072. }
  4073. }
  4074. }
  4075. if (checkType != NULL)
  4076. checkType = checkType->mBaseType;
  4077. }
  4078. }
  4079. }
  4080. Array<BfMethodInstance*> methodInstances;
  4081. for (auto methodDef : tempTypeDef->mMethods)
  4082. {
  4083. auto methodDeclaration = methodDef->GetMethodDeclaration();
  4084. if (methodDeclaration != NULL)
  4085. autoComplete->CheckMethod(methodDeclaration, false);
  4086. if (!methodDef->mWantsBody)
  4087. {
  4088. if (methodDeclaration != NULL)
  4089. {
  4090. if (methodDeclaration->mAttributes != NULL)
  4091. {
  4092. auto customAttrs = module->GetCustomAttributes(methodDeclaration->mAttributes, (methodDef->mMethodType == BfMethodType_Ctor) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method);
  4093. delete customAttrs;
  4094. }
  4095. }
  4096. else if (auto methodPropertyDeclaration = methodDef->GetPropertyMethodDeclaration())
  4097. {
  4098. if (methodPropertyDeclaration->mAttributes != NULL)
  4099. {
  4100. auto customAttrs = module->GetCustomAttributes(methodPropertyDeclaration->mAttributes, BfAttributeTargets_Method);
  4101. delete customAttrs;
  4102. }
  4103. }
  4104. continue;
  4105. }
  4106. BP_ZONE("ProcessAutocompleteTempType.CheckMethod");
  4107. BfMethodInstanceGroup methodInstanceGroup;
  4108. methodInstanceGroup.mOwner = typeInst;
  4109. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  4110. BfMethodInstance* methodInstance = new BfMethodInstance();
  4111. methodInstances.push_back(methodInstance);
  4112. methodInstance->mMethodDef = methodDef;
  4113. methodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  4114. methodInstance->mIsAutocompleteMethod = true;
  4115. methodInstanceGroup.mDefault = methodInstance;
  4116. defer(methodInstanceGroup.mDefault = NULL);
  4117. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  4118. {
  4119. auto genericParamType = module->GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  4120. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.push_back(genericParamType);
  4121. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  4122. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  4123. }
  4124. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  4125. {
  4126. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  4127. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  4128. }
  4129. bool wantsProcess = !actualTypeDef->mIsFunction;
  4130. SetAndRestoreValue<BfFilePosition> prevFilePos(module->mCurFilePosition);
  4131. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(module->mCurMethodInstance, methodInstance);
  4132. module->DoMethodDeclaration(methodDeclaration, true, wantsProcess);
  4133. if (wantsProcess)
  4134. {
  4135. module->mIncompleteMethodCount++;
  4136. module->ProcessMethod(methodInstance);
  4137. }
  4138. if (methodInstance->mIRFunction)
  4139. {
  4140. BfLogSysM("Autocomplete removing IRFunction %d\n", methodInstance->mIRFunction.mId);
  4141. module->mBfIRBuilder->Func_DeleteBody(methodInstance->mIRFunction);
  4142. module->mBfIRBuilder->Func_SafeRename(methodInstance->mIRFunction);
  4143. }
  4144. }
  4145. if ((mResolvePassData->mAutoComplete->mDefType != NULL) && (mResolvePassData->mAutoComplete->mDefType->GetDefinition() == actualTypeDef) &&
  4146. (mResolvePassData->mAutoComplete->mDefMethod != NULL))
  4147. {
  4148. BfMethodDef* tempDefMethod = NULL;
  4149. for (auto checkMethod : tempTypeDef->mMethods)
  4150. {
  4151. if (checkMethod == mResolvePassData->mAutoComplete->mDefMethod)
  4152. tempDefMethod = checkMethod;
  4153. }
  4154. if (tempDefMethod != NULL)
  4155. {
  4156. BfMethodDef* actualReplaceMethodDef = NULL;
  4157. for (auto checkMethodDef : actualTypeDef->mMethods)
  4158. {
  4159. if ((checkMethodDef->mMethodType == tempDefMethod->mMethodType) &&
  4160. (checkMethodDef->mMethodDeclaration != NULL) && (tempDefMethod->mMethodDeclaration != NULL) &&
  4161. (checkMethodDef->mMethodDeclaration->GetSrcStart() == tempDefMethod->mMethodDeclaration->GetSrcStart()))
  4162. actualReplaceMethodDef = checkMethodDef;
  4163. }
  4164. if (actualReplaceMethodDef == NULL)
  4165. {
  4166. autoComplete->mReplaceLocalId = -1;
  4167. autoComplete->mDefType = NULL;
  4168. autoComplete->mDefField = NULL;
  4169. autoComplete->mDefMethod = NULL;
  4170. autoComplete->mDefProp = NULL;
  4171. autoComplete->mDefMethodGenericParamIdx = -1;
  4172. autoComplete->mDefTypeGenericParamIdx = -1;
  4173. }
  4174. else
  4175. autoComplete->mDefMethod = actualReplaceMethodDef;
  4176. }
  4177. }
  4178. if (hadTempExtensionInfo)
  4179. {
  4180. auto genericTypeInst = (BfTypeInstance*)typeInst;
  4181. genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.Remove(tempTypeDef);
  4182. }
  4183. for (auto checkNode : mResolvePassData->mExteriorAutocompleteCheckNodes)
  4184. {
  4185. BP_ZONE("ProcessAutocompleteTempType.CheckIdentifier");
  4186. bool isUsingDirective = false;
  4187. BfIdentifierNode* checkIdentifier = NULL;
  4188. if (auto usingDirective = BfNodeDynCast<BfUsingDirective>(checkNode))
  4189. {
  4190. isUsingDirective = true;
  4191. checkIdentifier = usingDirective->mNamespace;
  4192. }
  4193. else
  4194. checkIdentifier = BfNodeDynCast<BfIdentifierNode>(checkNode);
  4195. mResolvePassData->mAutoComplete->CheckIdentifier(checkIdentifier, false, isUsingDirective);
  4196. }
  4197. GenerateAutocompleteInfo();
  4198. for (auto methodInstance : methodInstances)
  4199. delete methodInstance;
  4200. methodInstances.Clear();
  4201. module->CleanupFileInstances();
  4202. prevTypeInstance.Restore();
  4203. if (module->mCurTypeInstance == NULL)
  4204. module->ClearConstData();
  4205. BfLogSysM("ProcessAutocompleteTempType end\n");
  4206. }
  4207. BfType* BfCompiler::CheckSymbolReferenceTypeRef(BfModule* module, BfTypeReference* typeRef)
  4208. {
  4209. //auto resolvedType = module->ResolveTypeRef(typeRef, BfPopulateType_Declaration,
  4210. //(BfResolveTypeRefFlags)(BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue | BfResolveTypeRefFlag_AllowGenericTypeParamConstValue));
  4211. auto resolvedType = module->ResolveTypeRef(typeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowRef);
  4212. if ((resolvedType != NULL) && (resolvedType->IsTypeInstance()))
  4213. {
  4214. auto typeInst = resolvedType->ToTypeInstance();
  4215. //TODO: Did we need this?
  4216. // The ResolveTypeRef call already does mResolvePassData->HandleTypeReference, so we were adding double entries
  4217. //mResolvePassData->HandleTypeReference(typeRef, typeInst->mTypeDef);
  4218. }
  4219. return resolvedType;
  4220. }
  4221. void BfCompiler::AddToRebuildTypeList(BfTypeInstance* typeInst, HashSet<BfTypeInstance*>& rebuildTypeInstList)
  4222. {
  4223. if (!mResolvePassData->mParsers.IsEmpty())
  4224. {
  4225. bool found = false;
  4226. for (auto parser : mResolvePassData->mParsers)
  4227. {
  4228. // Only find references within the current file
  4229. if (typeInst->mTypeDef->GetDefinition()->HasSource(parser))
  4230. found = true;
  4231. }
  4232. if (!found)
  4233. return;
  4234. }
  4235. bool allowRebuild = ((!typeInst->IsGenericTypeInstance()) ||
  4236. ((typeInst->IsUnspecializedType()) && (!typeInst->IsUnspecializedTypeVariation())));
  4237. if ((typeInst->IsClosure()) || (typeInst->IsConcreteInterfaceType()) || (typeInst->IsModifiedTypeType()))
  4238. allowRebuild = false;
  4239. if (allowRebuild)
  4240. rebuildTypeInstList.Add(typeInst);
  4241. }
  4242. void BfCompiler::AddDepsToRebuildTypeList(BfTypeInstance* replaceTypeInst, HashSet<BfTypeInstance*>& rebuildTypeInstList)
  4243. {
  4244. for (auto& dep : replaceTypeInst->mDependencyMap)
  4245. {
  4246. auto depType = dep.mKey;
  4247. auto depTypeInst = depType->ToTypeInstance();
  4248. if (depTypeInst == NULL)
  4249. continue;
  4250. AddToRebuildTypeList(depTypeInst, rebuildTypeInstList);
  4251. }
  4252. }
  4253. void BfCompiler::GetSymbolReferences()
  4254. {
  4255. BfLogSysM("GetSymbolReferences\n");
  4256. if (mInInvalidState)
  4257. return; // Don't even try
  4258. auto context = mContext;
  4259. if (context->mBfObjectType == NULL)
  4260. return; // Not initialized yet
  4261. auto module = context->mScratchModule;
  4262. if (mResolvePassData->mAutoComplete != NULL)
  4263. mResolvePassData->mAutoComplete->SetModule(module);
  4264. BfTypeDef* typeDef = NULL;
  4265. HashSet<BfTypeInstance*> rebuildTypeInstList;
  4266. if (!mResolvePassData->mQueuedSymbolReferenceNamespace.IsEmpty())
  4267. {
  4268. if (!mSystem->ParseAtomComposite(mResolvePassData->mQueuedSymbolReferenceNamespace, mResolvePassData->mSymbolReferenceNamespace))
  4269. return;
  4270. for (auto type : mContext->mResolvedTypes)
  4271. {
  4272. auto typeInst = type->ToTypeInstance();
  4273. if (typeInst == NULL)
  4274. continue;
  4275. for (auto& lookupKV : typeInst->mLookupResults)
  4276. {
  4277. auto typeDef = lookupKV.mValue.mTypeDef;
  4278. if ((typeDef != NULL) && (typeDef->mNamespace.StartsWith(mResolvePassData->mSymbolReferenceNamespace)))
  4279. {
  4280. AddToRebuildTypeList(typeInst, rebuildTypeInstList);
  4281. }
  4282. }
  4283. }
  4284. for (auto parser : mSystem->mParsers)
  4285. {
  4286. BfNamespaceVisitor namespaceVisitor;
  4287. namespaceVisitor.mResolvePassData = mResolvePassData;
  4288. namespaceVisitor.mSystem = mSystem;
  4289. namespaceVisitor.Visit(parser->mRootNode);
  4290. }
  4291. }
  4292. else
  4293. {
  4294. const char* strPtr = mResolvePassData->mQueuedReplaceTypeDef.c_str();
  4295. typeDef = mSystem->FindTypeDefEx(strPtr);
  4296. if ((typeDef == NULL) || (typeDef->mTypeDeclaration == NULL))
  4297. return;
  4298. typeDef = typeDef->GetLatest();
  4299. mResolvePassData->mSymbolReferenceTypeDef = typeDef;
  4300. auto replaceType = module->ResolveTypeDef(typeDef, BfPopulateType_IdentityNoRemapAlias);
  4301. module->PopulateType(replaceType);
  4302. auto replaceTypeInst = replaceType->ToTypeInstance();
  4303. if (mResolvePassData->mGetSymbolReferenceKind != BfGetSymbolReferenceKind_Local)
  4304. {
  4305. AddDepsToRebuildTypeList(replaceTypeInst, rebuildTypeInstList);
  4306. // For generic types, add all references from all specialized versions
  4307. if (replaceTypeInst->IsGenericTypeInstance())
  4308. {
  4309. for (auto type : mContext->mResolvedTypes)
  4310. {
  4311. auto typeInst = type->ToTypeInstance();
  4312. if ((typeInst != replaceTypeInst) && (typeInst != NULL) && (typeInst->mTypeDef->GetLatest() == typeDef))
  4313. AddDepsToRebuildTypeList(typeInst, rebuildTypeInstList);
  4314. }
  4315. }
  4316. }
  4317. AddToRebuildTypeList(replaceTypeInst, rebuildTypeInstList);
  4318. }
  4319. //TODO: Did we need this to be rebuildTypeInst->mModule??? Why?
  4320. //auto rebuildModule = rebuildTypeInst->mModule;
  4321. auto rebuildModule = context->mScratchModule;
  4322. auto _CheckAttributes = [&](BfAttributeDirective* attrib, BfTypeDef* declaringType)
  4323. {
  4324. if ((mResolvePassData->mGetSymbolReferenceKind != BfGetSymbolReferenceKind_Type) &&
  4325. (mResolvePassData->mGetSymbolReferenceKind != BfGetSymbolReferenceKind_Field) &&
  4326. (mResolvePassData->mGetSymbolReferenceKind != BfGetSymbolReferenceKind_Property))
  4327. return;
  4328. while (attrib != NULL)
  4329. {
  4330. if (attrib->mAttributeTypeRef != NULL)
  4331. {
  4332. auto attrType = module->ResolveTypeRef(attrib->mAttributeTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_Attribute);
  4333. BfTypeDef* attrTypeDef = NULL;
  4334. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  4335. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  4336. if (attrTypeDef != NULL)
  4337. {
  4338. mResolvePassData->HandleTypeReference(attrib->mAttributeTypeRef, attrTypeDef);
  4339. attrTypeDef->PopulateMemberSets();
  4340. for (auto argExpr : attrib->mArguments)
  4341. {
  4342. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(argExpr))
  4343. {
  4344. auto propName = assignExpr->mLeft->ToString();
  4345. BfMemberSetEntry* propDefEntry;
  4346. if (attrTypeDef->mPropertySet.TryGetWith(propName, &propDefEntry))
  4347. {
  4348. mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, (BfPropertyDef*)propDefEntry->mMemberDef);
  4349. }
  4350. else if (attrTypeDef->mFieldSet.TryGetWith(propName, &propDefEntry))
  4351. {
  4352. mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, (BfFieldDef*)propDefEntry->mMemberDef);
  4353. }
  4354. }
  4355. }
  4356. }
  4357. }
  4358. attrib = attrib->mNextAttribute;
  4359. }
  4360. };
  4361. for (auto rebuildTypeInst : rebuildTypeInstList)
  4362. {
  4363. // These never have a definition. Also note that BfGenericDelegateType does not have proper generic defs
  4364. if (rebuildTypeInst->IsOnDemand())
  4365. continue;
  4366. auto context = mContext;
  4367. auto module = context->mScratchModule;
  4368. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(module->mCurTypeInstance, rebuildTypeInst);
  4369. SetAndRestoreValue<bool> prevIgnoreErrors(module->mIgnoreErrors, true);
  4370. // Run through base types for type renames
  4371. auto typeDef = rebuildTypeInst->mTypeDef;
  4372. if ((typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mNameNode != NULL))
  4373. {
  4374. if (typeDef->mIsCombinedPartial)
  4375. {
  4376. for (auto checkTypeDef : typeDef->mPartials)
  4377. {
  4378. auto nameNode = checkTypeDef->mTypeDeclaration->mNameNode;
  4379. for (auto parser : mResolvePassData->mParsers)
  4380. {
  4381. if (nameNode->IsFromParser(parser))
  4382. {
  4383. mResolvePassData->HandleTypeReference(nameNode, typeDef);
  4384. break;
  4385. }
  4386. }
  4387. if (mResolvePassData->mParsers.IsEmpty())
  4388. mResolvePassData->HandleTypeReference(nameNode, typeDef);
  4389. if (checkTypeDef->IsExtension())
  4390. {
  4391. if (mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Type)
  4392. {
  4393. BfTypeState typeState;
  4394. typeState.mCurTypeDef = checkTypeDef;
  4395. SetAndRestoreValue<BfTypeState*> prevTypeState(module->mContext->mCurTypeState, &typeState);
  4396. for (auto baseTypeRef : checkTypeDef->mBaseTypes)
  4397. CheckSymbolReferenceTypeRef(module, baseTypeRef);
  4398. for (auto genericParam : checkTypeDef->mGenericParamDefs)
  4399. {
  4400. for (auto constraint : genericParam->mConstraints)
  4401. {
  4402. if (auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint))
  4403. {
  4404. module->ResolveTypeRef(constraintTypeRef, BfPopulateType_Identity);
  4405. }
  4406. else if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  4407. {
  4408. module->ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Identity);
  4409. module->ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Identity);
  4410. }
  4411. }
  4412. }
  4413. }
  4414. }
  4415. }
  4416. }
  4417. else
  4418. {
  4419. mResolvePassData->HandleTypeReference(typeDef->mTypeDeclaration->mNameNode, typeDef);
  4420. }
  4421. }
  4422. if (!typeDef->mPartials.IsEmpty())
  4423. {
  4424. for (auto partialDef : typeDef->mPartials)
  4425. {
  4426. if ((partialDef->mTypeDeclaration != NULL) && (partialDef->mTypeDeclaration->mAttributes != NULL))
  4427. _CheckAttributes(partialDef->mTypeDeclaration->mAttributes, typeDef);
  4428. }
  4429. }
  4430. else
  4431. {
  4432. if ((typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mAttributes != NULL))
  4433. _CheckAttributes(typeDef->mTypeDeclaration->mAttributes, typeDef);
  4434. }
  4435. if (auto typeAliasDeclaration = BfNodeDynCast<BfTypeAliasDeclaration>(typeDef->mTypeDeclaration))
  4436. {
  4437. CheckSymbolReferenceTypeRef(module, typeAliasDeclaration->mAliasToType);
  4438. }
  4439. if (mResolvePassData != NULL)
  4440. {
  4441. if (rebuildTypeInst->IsGenericTypeInstance())
  4442. {
  4443. auto genericTypeInstance = (BfTypeInstance*)rebuildTypeInst;
  4444. for (int genericParamIdx = 0; genericParamIdx < (int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(); genericParamIdx++)
  4445. {
  4446. BfGenericTypeParamInstance genericParamInstance(genericTypeInstance->mTypeDef, genericParamIdx);
  4447. auto genericParamDef = typeDef->mGenericParamDefs[genericParamIdx];
  4448. if (mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_TypeGenericParam)
  4449. {
  4450. for (auto nameNode : genericParamDef->mNameNodes)
  4451. if (nameNode != NULL)
  4452. mResolvePassData->HandleTypeGenericParam(nameNode, typeDef, genericParamIdx);
  4453. }
  4454. rebuildModule->ResolveGenericParamConstraints(&genericParamInstance, genericTypeInstance->IsGenericTypeInstance());
  4455. }
  4456. }
  4457. }
  4458. if (mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Type)
  4459. {
  4460. for (auto baseTypeRef : typeDef->mBaseTypes)
  4461. CheckSymbolReferenceTypeRef(module, baseTypeRef);
  4462. }
  4463. BfTypeState typeState;
  4464. SetAndRestoreValue<BfTypeState*> prevTypeState(module->mContext->mCurTypeState, &typeState);
  4465. if (mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Property)
  4466. {
  4467. for (auto propDef : typeDef->mProperties)
  4468. {
  4469. BfPropertyDef* checkPropDef = propDef;
  4470. BfTypeInstance* checkTypeInst = rebuildTypeInst;
  4471. typeState.mCurTypeDef = propDef->mDeclaringType;
  4472. module->GetBasePropertyDef(checkPropDef, checkTypeInst);
  4473. if (auto fieldDecl = propDef->GetFieldDeclaration())
  4474. mResolvePassData->HandlePropertyReference(fieldDecl->mNameNode, checkTypeInst->mTypeDef, checkPropDef);
  4475. }
  4476. }
  4477. if (mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field)
  4478. {
  4479. for (auto fieldDef : typeDef->mFields)
  4480. {
  4481. if (auto nameNode = fieldDef->GetNameNode())
  4482. {
  4483. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  4484. mResolvePassData->HandleFieldReference(nameNode, typeDef, fieldDef);
  4485. }
  4486. }
  4487. }
  4488. for (auto& fieldInst : rebuildTypeInst->mFieldInstances)
  4489. {
  4490. auto fieldDef = fieldInst.GetFieldDef();
  4491. if (fieldDef != NULL)
  4492. {
  4493. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  4494. if (fieldDef->mTypeRef != NULL)
  4495. CheckSymbolReferenceTypeRef(module, fieldDef->mTypeRef);
  4496. if ((fieldDef->mIsConst) && (fieldDef->GetInitializer() != NULL))
  4497. {
  4498. BfMethodState methodState;
  4499. methodState.mTempKind = BfMethodState::TempKind_Static;
  4500. SetAndRestoreValue<BfMethodState*> prevMethodState(module->mCurMethodState, &methodState);
  4501. BfConstResolver constResolver(module);
  4502. constResolver.Resolve(fieldDef->GetInitializer());
  4503. }
  4504. if (auto fieldDecl = fieldDef->GetFieldDeclaration())
  4505. {
  4506. if (fieldDecl->mAttributes != NULL)
  4507. _CheckAttributes(fieldDecl->mAttributes, fieldDef->mDeclaringType);
  4508. }
  4509. }
  4510. }
  4511. for (auto& propDef : rebuildTypeInst->mTypeDef->mProperties)
  4512. {
  4513. typeState.mCurTypeDef = propDef->mDeclaringType;
  4514. if (propDef->mTypeRef != NULL)
  4515. CheckSymbolReferenceTypeRef(module, propDef->mTypeRef);
  4516. }
  4517. if (rebuildModule == NULL)
  4518. continue;
  4519. rebuildModule->EnsureIRBuilder();
  4520. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance2(rebuildModule->mCurTypeInstance, rebuildTypeInst);
  4521. for (auto& methodInstGroup : rebuildTypeInst->mMethodInstanceGroups)
  4522. {
  4523. // Run through all methods
  4524. bool isDefault = true;
  4525. BfMethodInstanceGroup::MapType::iterator methodItr;
  4526. if (methodInstGroup.mMethodSpecializationMap != NULL)
  4527. methodItr = methodInstGroup.mMethodSpecializationMap->begin();
  4528. while (true)
  4529. {
  4530. BfMethodInstance* rebuildMethodInstance;
  4531. if (isDefault)
  4532. {
  4533. rebuildMethodInstance = methodInstGroup.mDefault;
  4534. if (rebuildMethodInstance == NULL)
  4535. break;
  4536. isDefault = false;
  4537. }
  4538. else
  4539. {
  4540. //TODO: Why did we process specialized methods?
  4541. // This caused renaming of types picking up 'T' usage from generic methods
  4542. break;
  4543. // if (methodInstGroup.mMethodSpecializationMap == NULL)
  4544. // break;
  4545. // if (methodItr == methodInstGroup.mMethodSpecializationMap->end())
  4546. // break;
  4547. // rebuildMethodInstance = methodItr->mValue;
  4548. // ++methodItr;
  4549. }
  4550. if ((rebuildMethodInstance->IsOrInUnspecializedVariation()) || (rebuildMethodInstance->IsSpecializedGenericMethod()))
  4551. continue;
  4552. SetAndRestoreValue<BfMethodInstance*> prevTypeInstance(rebuildModule->mCurMethodInstance, rebuildMethodInstance);
  4553. auto methodDef = rebuildMethodInstance->mMethodDef;
  4554. auto methodDeclaration = methodDef->GetMethodDeclaration();
  4555. typeState.mCurTypeDef = methodDef->mDeclaringType;
  4556. if ((methodDeclaration != NULL) && (methodDeclaration->mAttributes != NULL))
  4557. _CheckAttributes(methodDeclaration->mAttributes, methodDef->mDeclaringType);
  4558. if ((mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Type) ||
  4559. (mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_MethodGenericParam) ||
  4560. (mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_TypeGenericParam))
  4561. {
  4562. if (methodDef->mExplicitInterface != NULL)
  4563. CheckSymbolReferenceTypeRef(rebuildModule, methodDef->mExplicitInterface);
  4564. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size(); paramIdx++)
  4565. {
  4566. auto param = methodDef->mParams[paramIdx];
  4567. CheckSymbolReferenceTypeRef(rebuildModule, param->mTypeRef);
  4568. }
  4569. if (methodDef->mReturnTypeRef != NULL)
  4570. CheckSymbolReferenceTypeRef(rebuildModule, methodDef->mReturnTypeRef);
  4571. }
  4572. if (rebuildMethodInstance->mIgnoreBody)
  4573. {
  4574. auto methodDeclaration = methodDef->GetMethodDeclaration();
  4575. if (methodDeclaration != NULL)
  4576. mResolvePassData->HandleMethodReference(methodDeclaration->mNameNode, typeDef, methodDef);
  4577. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size(); paramIdx++)
  4578. {
  4579. auto param = methodDef->mParams[paramIdx];
  4580. if (param->mParamDeclaration != NULL)
  4581. {
  4582. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(param->mParamDeclaration->mNameNode))
  4583. mResolvePassData->HandleLocalReference(identifierNode, rebuildTypeInst->mTypeDef, rebuildMethodInstance->mMethodDef, paramIdx + 1);
  4584. else if (auto tupleExprNode = BfNodeDynCast<BfTupleExpression>(param->mParamDeclaration->mNameNode))
  4585. {
  4586. for (int fieldIdx = 0; fieldIdx < (int)tupleExprNode->mValues.size(); fieldIdx++)
  4587. {
  4588. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(tupleExprNode->mValues[fieldIdx]))
  4589. mResolvePassData->HandleLocalReference(identifierNode, rebuildTypeInst->mTypeDef, rebuildMethodInstance->mMethodDef, paramIdx + 1);
  4590. }
  4591. }
  4592. }
  4593. }
  4594. }
  4595. else
  4596. {
  4597. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size(); paramIdx++)
  4598. {
  4599. auto param = methodDef->mParams[paramIdx];
  4600. if ((param->mParamDeclaration != NULL) && (param->mParamDeclaration->mInitializer != NULL))
  4601. {
  4602. auto paramType = rebuildMethodInstance->GetParamType(paramIdx);
  4603. BfConstResolver constResolver(rebuildModule);
  4604. constResolver.Resolve(param->mParamDeclaration->mInitializer, paramType);
  4605. }
  4606. }
  4607. if (rebuildMethodInstance->mHasBeenProcessed)
  4608. {
  4609. if (rebuildMethodInstance->mIRFunction)
  4610. rebuildModule->mBfIRBuilder->Func_DeleteBody(rebuildMethodInstance->mIRFunction);
  4611. rebuildMethodInstance->mHasBeenProcessed = false;
  4612. rebuildModule->mIncompleteMethodCount++;
  4613. }
  4614. else
  4615. {
  4616. if ((rebuildModule->mIncompleteMethodCount == 0) && (!rebuildModule->mIsScratchModule))
  4617. {
  4618. BF_FATAL("Shouldn't be processing this method");
  4619. }
  4620. }
  4621. for (int genericParamIdx = 0; genericParamIdx < (int)rebuildMethodInstance->GetNumGenericArguments(); genericParamIdx++)
  4622. {
  4623. BfGenericMethodParamInstance genericParamInstance(rebuildMethodInstance->mMethodDef, genericParamIdx);
  4624. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  4625. if (mResolvePassData != NULL)
  4626. {
  4627. for (auto nameNode : genericParamDef->mNameNodes)
  4628. if (nameNode != NULL)
  4629. mResolvePassData->HandleMethodGenericParam(nameNode, typeDef, methodDef, genericParamIdx);
  4630. }
  4631. rebuildModule->ResolveGenericParamConstraints(&genericParamInstance, rebuildMethodInstance->mIsUnspecialized);
  4632. }
  4633. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  4634. {
  4635. BfGenericMethodParamInstance genericParamInstance(rebuildMethodInstance->mMethodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  4636. auto& externConstraintDef = methodDef->mExternalConstraints[externConstraintIdx];
  4637. CheckSymbolReferenceTypeRef(module, externConstraintDef.mTypeRef);
  4638. rebuildModule->ResolveGenericParamConstraints(&genericParamInstance, rebuildMethodInstance->mIsUnspecialized);
  4639. }
  4640. rebuildModule->ProcessMethod(rebuildMethodInstance);
  4641. }
  4642. }
  4643. }
  4644. }
  4645. }
  4646. void BfCompiler::UpdateCompletion()
  4647. {
  4648. if (mIsResolveOnly)
  4649. return;
  4650. float typeScale = 10.0f;
  4651. float methodScale = 1.0f;
  4652. float queueModuleScale = 50.0f;
  4653. float genModuleScale = 50.0f;
  4654. mCodeGen.UpdateStats();
  4655. BF_ASSERT(mCodeGen.mQueuedCount >= mCodeGen.mCompletionCount);
  4656. BF_ASSERT(mStats.mModulesFinished <= mStats.mModulesStarted);
  4657. BF_ASSERT(mCodeGen.mCompletionCount <= mStats.mModulesStarted);
  4658. float numerator = ((mStats.mQueuedTypesProcessed * typeScale) + //(mStats.mMethodsProcessed * methodScale) +
  4659. (mStats.mModulesFinished * queueModuleScale) + (mCodeGen.mCompletionCount * genModuleScale));
  4660. float divisor = ((mStats.mTypesQueued * typeScale) + //(mStats.mMethodsQueued * methodScale) +
  4661. (mStats.mModulesStarted * queueModuleScale) + (mStats.mReifiedModuleCount * genModuleScale));
  4662. float checkPct = 0;
  4663. if (divisor > 0)
  4664. {
  4665. checkPct = numerator / divisor;
  4666. BF_ASSERT(checkPct >= 0);
  4667. if (checkPct > mCompletionPct)
  4668. mCompletionPct = checkPct;
  4669. }
  4670. else
  4671. mCompletionPct = 0;
  4672. if (!mHadCancel)
  4673. BF_ASSERT(mCompletionPct <= 1.0f);
  4674. if (mCompletionPct > 1.0f)
  4675. mCompletionPct = 1.0f;
  4676. }
  4677. void BfCompiler::MarkStringPool(BfModule* module)
  4678. {
  4679. for (int stringId : module->mStringPoolRefs)
  4680. {
  4681. BfStringPoolEntry& stringPoolEntry = module->mContext->mStringObjectIdMap[stringId];
  4682. stringPoolEntry.mLastUsedRevision = mRevision;
  4683. }
  4684. for (int stringId : module->mUnreifiedStringPoolRefs)
  4685. {
  4686. BfStringPoolEntry& stringPoolEntry = module->mContext->mStringObjectIdMap[stringId];
  4687. stringPoolEntry.mLastUsedRevision = mRevision;
  4688. }
  4689. for (int stringId : module->mImportFileNames)
  4690. {
  4691. BfStringPoolEntry& stringPoolEntry = module->mContext->mStringObjectIdMap[stringId];
  4692. stringPoolEntry.mLastUsedRevision = mRevision;
  4693. }
  4694. /*if (module->mOptModule != NULL)
  4695. MarkStringPool(module->mOptModule);*/
  4696. auto altModule = module->mNextAltModule;
  4697. while (altModule != NULL)
  4698. {
  4699. MarkStringPool(altModule);
  4700. altModule = altModule->mNextAltModule;
  4701. }
  4702. for (auto& specModulePair : module->mSpecializedMethodModules)
  4703. MarkStringPool(specModulePair.mValue);
  4704. }
  4705. void BfCompiler::MarkStringPool(BfIRConstHolder* constHolder, BfIRValue irValue)
  4706. {
  4707. auto constant = constHolder->GetConstant(irValue);
  4708. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  4709. {
  4710. BfStringPoolEntry& stringPoolEntry = mContext->mStringObjectIdMap[constant->mInt32];
  4711. stringPoolEntry.mLastUsedRevision = mRevision;
  4712. }
  4713. }
  4714. void BfCompiler::ClearUnusedStringPoolEntries()
  4715. {
  4716. BF_ASSERT(!IsHotCompile());
  4717. for (auto module : mContext->mModules)
  4718. {
  4719. MarkStringPool(module);
  4720. }
  4721. for (auto type : mContext->mResolvedTypes)
  4722. {
  4723. auto typeInstance = type->ToTypeInstance();
  4724. if (typeInstance == NULL)
  4725. continue;
  4726. if (typeInstance->mCustomAttributes == NULL)
  4727. continue;
  4728. for (auto& attribute : typeInstance->mCustomAttributes->mAttributes)
  4729. {
  4730. for (auto arg : attribute.mCtorArgs)
  4731. MarkStringPool(typeInstance->mConstHolder, arg);
  4732. for (auto setValue : attribute.mSetProperties)
  4733. MarkStringPool(typeInstance->mConstHolder, setValue.mParam.mValue);
  4734. for (auto setValue : attribute.mSetField)
  4735. MarkStringPool(typeInstance->mConstHolder, setValue.mParam.mValue);
  4736. }
  4737. }
  4738. for (auto itr = mContext->mStringObjectIdMap.begin(); itr != mContext->mStringObjectIdMap.end(); )
  4739. {
  4740. int strId = itr->mKey;
  4741. BfStringPoolEntry& stringPoolEntry = itr->mValue;
  4742. if (stringPoolEntry.mLastUsedRevision != mRevision)
  4743. {
  4744. CompileLog("Clearing unused string: %d %s\n", itr->mKey, stringPoolEntry.mString.c_str());
  4745. mContext->mStringObjectPool.Remove(stringPoolEntry.mString);
  4746. itr = mContext->mStringObjectIdMap.Remove(itr);
  4747. }
  4748. else
  4749. ++itr;
  4750. }
  4751. }
  4752. void BfCompiler::ClearBuildCache()
  4753. {
  4754. mCodeGen.ClearBuildCache();
  4755. for (auto project : mSystem->mProjects)
  4756. {
  4757. String libPath = mOutputDirectory + "/" + project->mName + "/" + project->mName + "__.lib";
  4758. BfpFile_Delete(libPath.c_str(), NULL);
  4759. }
  4760. }
  4761. int BfCompiler::GetDynCastVDataCount()
  4762. {
  4763. int dynElements = 1 + mMaxInterfaceSlots;
  4764. return ((dynElements * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  4765. }
  4766. bool BfCompiler::IsAutocomplete()
  4767. {
  4768. return (mResolvePassData != NULL) && (mResolvePassData->mAutoComplete != NULL);
  4769. }
  4770. bool BfCompiler::IsDataResolvePass()
  4771. {
  4772. return (mResolvePassData != NULL) && (mResolvePassData->mResolveType == BfResolveType_GetResultString);
  4773. }
  4774. bool BfCompiler::WantsClassifyNode(BfAstNode* node)
  4775. {
  4776. return (mResolvePassData != NULL) && (mResolvePassData->GetSourceClassifier(node) != NULL);
  4777. }
  4778. BfAutoComplete* BfCompiler::GetAutoComplete()
  4779. {
  4780. if (mResolvePassData != NULL)
  4781. return mResolvePassData->mAutoComplete;
  4782. return NULL;
  4783. }
  4784. bool BfCompiler::IsHotCompile()
  4785. {
  4786. return mOptions.mHotProject != NULL;
  4787. }
  4788. bool BfCompiler::IsSkippingExtraResolveChecks()
  4789. {
  4790. return mIsResolveOnly && !mOptions.mExtraResolveChecks;
  4791. }
  4792. int BfCompiler::GetVTableMethodOffset()
  4793. {
  4794. if (mOptions.mHasVDataExtender)
  4795. return 1;
  4796. return 0;
  4797. }
  4798. bool BfCompiler::DoWorkLoop(bool onlyReifiedTypes, bool onlyReifiedMethods)
  4799. {
  4800. bool hadAnyWork = false;
  4801. while (true)
  4802. {
  4803. bool didWork = false;
  4804. didWork |= mContext->ProcessWorkList(onlyReifiedTypes, onlyReifiedMethods);
  4805. if (!didWork)
  4806. break;
  4807. hadAnyWork = true;
  4808. }
  4809. return hadAnyWork;
  4810. }
  4811. BfMangler::MangleKind BfCompiler::GetMangleKind()
  4812. {
  4813. if (mOptions.mToolsetType == BfToolsetType_GNU)
  4814. return BfMangler::MangleKind_GNU;
  4815. return (mSystem->mPtrSize == 8) ? BfMangler::MangleKind_Microsoft_64 : BfMangler::MangleKind_Microsoft_32;
  4816. }
  4817. //////////////////////////////////////////////////////////////////////////
  4818. int ArrTest()
  4819. {
  4820. //SizedArray<int, 8> intArr;
  4821. //Array<int> intArr;
  4822. //std::vector<int> intArr;
  4823. BfSizedVector<int, 8> intArr;
  4824. //int val = intArr.GetLastSafe();
  4825. intArr.push_back(123);
  4826. intArr.pop_back();
  4827. intArr.push_back(234);
  4828. intArr.push_back(345);
  4829. //intArr.push_back(567);
  4830. //auto itr = std::find(intArr.begin(), intArr.end(), 234);
  4831. //intArr.erase(itr);
  4832. for (auto itr = intArr.begin(); itr != intArr.end(); )
  4833. {
  4834. if (*itr == 234)
  4835. itr = intArr.erase(itr);
  4836. else
  4837. itr++;
  4838. }
  4839. return (int)intArr.size();
  4840. //intArr.RemoveAt(2);
  4841. }
  4842. //////////////////////////////////////////////////////////////////////////
  4843. void BfCompiler::PopulateReified()
  4844. {
  4845. BfLogSysM("BfCompiler::PopulateReified\n");
  4846. BP_ZONE("PopulateReified");
  4847. BfContext* context = mContext;
  4848. bool hasTests = mSystem->HasTestProjects();
  4849. Array<BfMethodInstance*> impChainHeadMethods;
  4850. // Types can pull in new dependencies, so fully populate types until they stop
  4851. bool reifiedOnly = mOptions.mCompileOnDemandKind != BfCompileOnDemandKind_AlwaysInclude;
  4852. while (true)
  4853. {
  4854. BP_ZONE("Compile_PopulateTypes");
  4855. int startTypeInitCount = mTypeInitCount;
  4856. bool didWork = false;
  4857. BfLogSysM("PopulateReified iteration start\n");
  4858. Array<BfType*> typeList;
  4859. typeList.Reserve(context->mResolvedTypes.GetCount());
  4860. for (auto type : context->mResolvedTypes)
  4861. typeList.Add(type);
  4862. int typeCount = 0;
  4863. for (auto type : typeList)
  4864. {
  4865. auto module = type->GetModule();
  4866. typeCount++;
  4867. if (module == NULL)
  4868. continue;
  4869. if (!type->IsReified())
  4870. {
  4871. // On compiles, only handle reified types in this loop. This fixes cases where our first instance of a dependent type
  4872. // is found to be unreified and then we have to reify it later. It's not an error, just a compile perf issue
  4873. continue;
  4874. }
  4875. // We have to not populate generic type instances because that may force us to populate a type that SHOULD be deleted
  4876. if ((type->IsIncomplete()) && (type->IsTypeInstance()) && (!type->IsGenericTypeInstance()))
  4877. {
  4878. mSystem->CheckLockYield();
  4879. module->PopulateType(type, BfPopulateType_Full);
  4880. }
  4881. auto typeInst = type->ToTypeInstance();
  4882. if ((typeInst != NULL) && (typeInst->IsGenericTypeInstance()) && (!typeInst->IsUnspecializedType()) &&
  4883. (!typeInst->IsDelegateFromTypeRef()) && (!typeInst->IsFunctionFromTypeRef()) && (!typeInst->IsTuple()))
  4884. {
  4885. auto unspecializedType = module->GetUnspecializedTypeInstance(typeInst);
  4886. if (!unspecializedType->mIsReified)
  4887. unspecializedType->mIsReified = true;
  4888. }
  4889. if ((type->IsValueType()) && (!type->IsUnspecializedType()))
  4890. {
  4891. bool dynamicBoxing = false;
  4892. if ((typeInst != NULL) && (typeInst->mTypeOptionsIdx != -2))
  4893. {
  4894. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  4895. if (typeOptions != NULL)
  4896. {
  4897. if (typeOptions->Apply(false, BfOptionFlags_ReflectBoxing))
  4898. dynamicBoxing = true;
  4899. }
  4900. }
  4901. auto reflectKind = module->GetReflectKind(BfReflectKind_None, typeInst);
  4902. if ((reflectKind & BfReflectKind_DynamicBoxing) != 0)
  4903. dynamicBoxing = true;
  4904. if (dynamicBoxing)
  4905. {
  4906. auto boxedType = module->CreateBoxedType(typeInst);
  4907. module->AddDependency(boxedType, typeInst, BfDependencyMap::DependencyFlag_Allocates);
  4908. boxedType->mHasBeenInstantiated = true;
  4909. }
  4910. }
  4911. // Check reifications forced by virtuals or interfaces
  4912. if ((typeInst != NULL) && (typeInst->mIsReified) && (!typeInst->IsUnspecializedType()) && (!typeInst->IsInterface()) &&
  4913. (!typeInst->IsIncomplete()))
  4914. {
  4915. // If we have chained methods, make sure we implement the chain members if the chain head is implemented and reified
  4916. if (typeInst->mTypeDef->mIsCombinedPartial)
  4917. {
  4918. typeInst->mTypeDef->PopulateMemberSets();
  4919. bool hasUnimpChainMembers = false;
  4920. impChainHeadMethods.Clear();
  4921. for (auto& methodInstanceGroup : typeInst->mMethodInstanceGroups)
  4922. {
  4923. auto methodInstance = methodInstanceGroup.mDefault;
  4924. if (methodInstance == NULL)
  4925. continue;
  4926. if (methodInstance->mChainType == BfMethodChainType_ChainHead)
  4927. {
  4928. if (methodInstance->IsReifiedAndImplemented())
  4929. impChainHeadMethods.Add(methodInstance);
  4930. }
  4931. else if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  4932. {
  4933. if (!methodInstance->IsReifiedAndImplemented())
  4934. hasUnimpChainMembers = true;
  4935. }
  4936. else if ((methodInstance->mChainType == BfMethodChainType_None) && (methodInstance->mMethodDef->IsDefaultCtor()))
  4937. {
  4938. if (!methodInstance->IsReifiedAndImplemented())
  4939. hasUnimpChainMembers = true;
  4940. }
  4941. else if (methodInstance->mIsInnerOverride)
  4942. {
  4943. if (!methodInstance->IsReifiedAndImplemented())
  4944. {
  4945. bool forceMethod = false;
  4946. BfMemberSetEntry* memberSetEntry;
  4947. if (typeInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &memberSetEntry))
  4948. {
  4949. BfMethodDef* checkMethodDef = (BfMethodDef*)memberSetEntry->mMemberDef;
  4950. while (checkMethodDef != NULL)
  4951. {
  4952. auto& checkMethodInstanceGroup = typeInst->mMethodInstanceGroups[checkMethodDef->mIdx];
  4953. auto checkMethodInstance = checkMethodInstanceGroup.mDefault;
  4954. if (checkMethodInstance != NULL)
  4955. {
  4956. if ((checkMethodDef->mIsExtern) && (checkMethodInstance->IsReifiedAndImplemented()))
  4957. forceMethod = true;
  4958. }
  4959. checkMethodDef = checkMethodDef->mNextWithSameName;
  4960. }
  4961. }
  4962. if (forceMethod)
  4963. {
  4964. typeInst->mModule->GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(),
  4965. (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass));
  4966. }
  4967. }
  4968. }
  4969. }
  4970. if ((hasUnimpChainMembers) && (!impChainHeadMethods.IsEmpty()))
  4971. {
  4972. for (auto& methodInstanceGroup : typeInst->mMethodInstanceGroups)
  4973. {
  4974. auto methodInstance = methodInstanceGroup.mDefault;
  4975. if (methodInstance == NULL)
  4976. continue;
  4977. bool forceMethod = false;
  4978. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  4979. {
  4980. if (!methodInstance->IsReifiedAndImplemented())
  4981. {
  4982. for (auto impMethodInstance : impChainHeadMethods)
  4983. {
  4984. if (typeInst->mModule->CompareMethodSignatures(methodInstance, impMethodInstance))
  4985. {
  4986. forceMethod = true;
  4987. }
  4988. }
  4989. }
  4990. }
  4991. else if (methodInstance->mMethodDef->IsDefaultCtor())
  4992. {
  4993. if (!methodInstance->IsReifiedAndImplemented())
  4994. forceMethod = true;
  4995. }
  4996. if (forceMethod)
  4997. {
  4998. typeInst->mModule->GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(),
  4999. (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass));
  5000. }
  5001. }
  5002. }
  5003. }
  5004. // Only check virtual stuff if we have been instantiated
  5005. if ((typeInst->HasBeenInstantiated()) && (!mCanceling))
  5006. {
  5007. // If we have any virtual methods overrides that are unreified but the declaring virtual method is reified then we also need to reify
  5008. for (int virtIdx = 0; virtIdx < typeInst->mVirtualMethodTable.mSize; virtIdx++)
  5009. {
  5010. auto& vEntry = typeInst->mVirtualMethodTable[virtIdx];
  5011. if ((vEntry.mDeclaringMethod.mTypeInstance == NULL) ||
  5012. (vEntry.mDeclaringMethod.mTypeInstance->IsIncomplete()) ||
  5013. (vEntry.mImplementingMethod.mTypeInstance == NULL) ||
  5014. (vEntry.mImplementingMethod.mTypeInstance->IsIncomplete()))
  5015. continue;
  5016. BfMethodInstance* declaringMethod = vEntry.mDeclaringMethod;
  5017. if (declaringMethod == NULL)
  5018. continue;
  5019. if ((declaringMethod->mIsReified) && (declaringMethod->mMethodInstanceGroup->IsImplemented()))
  5020. {
  5021. if (vEntry.mImplementingMethod.mKind == BfMethodRefKind_AmbiguousRef)
  5022. {
  5023. auto checkTypeInst = typeInst;
  5024. while (checkTypeInst != NULL)
  5025. {
  5026. BfMemberSetEntry* memberSetEntry;
  5027. if (checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String(declaringMethod->mMethodDef->mName), &memberSetEntry))
  5028. {
  5029. BfMethodDef* methodDef = (BfMethodDef*)memberSetEntry->mMemberDef;
  5030. while (methodDef != NULL)
  5031. {
  5032. if ((methodDef->mIsOverride) && (methodDef->mParams.mSize == declaringMethod->mMethodDef->mParams.mSize))
  5033. {
  5034. auto implMethod = typeInst->mModule->GetRawMethodInstance(typeInst, methodDef);
  5035. if (typeInst->mModule->CompareMethodSignatures(declaringMethod, implMethod))
  5036. {
  5037. if ((implMethod != NULL) && ((!implMethod->mMethodInstanceGroup->IsImplemented()) || (!implMethod->mIsReified)))
  5038. {
  5039. didWork = true;
  5040. if (!typeInst->mModule->mIsModuleMutable)
  5041. typeInst->mModule->StartExtension();
  5042. typeInst->mModule->GetMethodInstance(implMethod);
  5043. }
  5044. }
  5045. }
  5046. methodDef = methodDef->mNextWithSameName;
  5047. }
  5048. }
  5049. if (checkTypeInst == declaringMethod->GetOwner())
  5050. break;
  5051. checkTypeInst = checkTypeInst->mBaseType;
  5052. }
  5053. }
  5054. else
  5055. {
  5056. BfMethodInstance* implMethod = vEntry.mImplementingMethod;
  5057. if ((implMethod != NULL) && ((!implMethod->mMethodInstanceGroup->IsImplemented()) || (!implMethod->mIsReified)))
  5058. {
  5059. didWork = true;
  5060. if (!typeInst->mModule->mIsModuleMutable)
  5061. typeInst->mModule->StartExtension();
  5062. typeInst->mModule->GetMethodInstance(implMethod);
  5063. }
  5064. }
  5065. }
  5066. }
  5067. auto checkType = typeInst;
  5068. while (checkType != NULL)
  5069. {
  5070. if ((checkType != typeInst) && (checkType->HasBeenInstantiated()))
  5071. {
  5072. // We will already check this type here in its own loop
  5073. break;
  5074. }
  5075. if (checkType->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  5076. break;
  5077. for (auto& ifaceTypeInst : checkType->mInterfaces)
  5078. {
  5079. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  5080. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  5081. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  5082. auto declTypeDef = ifaceTypeInst.mDeclaringType;
  5083. for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  5084. {
  5085. auto& ifaceMethodInstGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  5086. auto ifaceMethodInst = ifaceMethodInstGroup.mDefault;
  5087. if (typeInst->IsObject())
  5088. {
  5089. // If the implementor is an object then this can be dynamically dispatched
  5090. }
  5091. else
  5092. {
  5093. // If this method is explicitly reflected then a struct's implementation may be invoked with reflection
  5094. if (!ifaceMethodInstGroup.mExplicitlyReflected)
  5095. continue;
  5096. }
  5097. if ((ifaceMethodInst == NULL) || (!ifaceMethodInst->IsReifiedAndImplemented()))
  5098. continue;
  5099. auto implMethodRef = &checkType->mInterfaceMethodTable[iMethodIdx + startIdx].mMethodRef;
  5100. BfMethodInstance* implMethod = *implMethodRef;
  5101. if (implMethod == NULL)
  5102. continue;
  5103. // Reify any interface methods that could be called dynamically
  5104. if ((!implMethod->IsReifiedAndImplemented()) && (implMethod->GetNumGenericParams() == 0) && (!implMethod->mMethodDef->mIsStatic) &&
  5105. (!implMethod->mReturnType->IsConcreteInterfaceType()))
  5106. {
  5107. didWork = true;
  5108. checkType->mModule->GetMethodInstance(implMethod);
  5109. }
  5110. }
  5111. }
  5112. checkType = checkType->mBaseType;
  5113. }
  5114. for (auto& reifyDep : typeInst->mReifyMethodDependencies)
  5115. {
  5116. if ((reifyDep.mDepMethod.mTypeInstance == NULL) ||
  5117. (reifyDep.mDepMethod.mTypeInstance->IsIncomplete()))
  5118. continue;
  5119. BfMethodInstance* depMethod = reifyDep.mDepMethod;
  5120. if (depMethod == NULL)
  5121. continue;
  5122. if ((depMethod->mIsReified) && (depMethod->mMethodInstanceGroup->IsImplemented()))
  5123. {
  5124. auto methodDef = typeInst->mTypeDef->mMethods[reifyDep.mMethodIdx];
  5125. typeInst->mModule->GetMethodInstance(typeInst, methodDef, BfTypeVector());
  5126. }
  5127. }
  5128. }
  5129. }
  5130. }
  5131. if (mOptions.mCompileOnDemandKind != BfCompileOnDemandKind_AlwaysInclude)
  5132. {
  5133. BfLogSysM("BfCompiler::PopulateReified finding Main\n");
  5134. for (auto project : mSystem->mProjects)
  5135. {
  5136. String entryClassName = project->mStartupObject;
  5137. auto typeDef = mSystem->FindTypeDef(entryClassName, 0, project, {}, NULL, BfFindTypeDefFlag_AllowGlobal);
  5138. if (typeDef != NULL)
  5139. {
  5140. typeDef->mIsAlwaysInclude = true;
  5141. auto resolvedType = mContext->mScratchModule->ResolveTypeDef(typeDef);
  5142. if (resolvedType != NULL)
  5143. {
  5144. auto resolvedTypeInst = resolvedType->ToTypeInstance();
  5145. if (resolvedTypeInst != NULL)
  5146. {
  5147. auto module = resolvedTypeInst->GetModule();
  5148. if (!module->mIsReified)
  5149. module->ReifyModule();
  5150. mContext->mScratchModule->PopulateType(resolvedType, BfPopulateType_Full);
  5151. BfMemberSetEntry* memberSetEntry;
  5152. if (resolvedTypeInst->mTypeDef->mMethodSet.TryGetWith(String("Main"), &memberSetEntry))
  5153. {
  5154. BfMethodDef* methodDef = (BfMethodDef*)memberSetEntry->mMemberDef;
  5155. while (methodDef != NULL)
  5156. {
  5157. auto moduleMethodInstance = mContext->mScratchModule->GetMethodInstanceAtIdx(resolvedTypeInst, methodDef->mIdx);
  5158. auto methodInstance = moduleMethodInstance.mMethodInstance;
  5159. if (methodInstance->GetParamCount() != 0)
  5160. {
  5161. mContext->mScratchModule->GetInternalMethod("CreateParamsArray");
  5162. mContext->mScratchModule->GetInternalMethod("DeleteStringArray");
  5163. }
  5164. methodDef = methodDef->mNextWithSameName;
  5165. }
  5166. }
  5167. }
  5168. }
  5169. }
  5170. }
  5171. }
  5172. BfLogSysM("PopulateReified iteration done\n");
  5173. didWork |= DoWorkLoop(reifiedOnly, reifiedOnly);
  5174. if (reifiedOnly)
  5175. didWork |= DoWorkLoop(false, reifiedOnly);
  5176. if (startTypeInitCount != mTypeInitCount)
  5177. didWork = true;
  5178. if (didWork)
  5179. continue;
  5180. // We get everything on the first pass through
  5181. if (mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  5182. break;
  5183. if (mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_SkipUnused)
  5184. break;
  5185. if (startTypeInitCount == mTypeInitCount)
  5186. break;
  5187. }
  5188. }
  5189. bool BfCompiler::IsCePaused()
  5190. {
  5191. return (mCeMachine != NULL) && (mCeMachine->mDbgPaused);
  5192. }
  5193. bool BfCompiler::EnsureCeUnpaused(BfType* refType)
  5194. {
  5195. if ((mCeMachine == NULL) || (!mCeMachine->mDbgPaused))
  5196. return true;
  5197. mCeMachine->mDebugger->mCurDbgState->mReferencedIncompleteTypes = true;
  5198. //mPassInstance->Fail(StrFormat("Use of incomplete type '%s'", mCeMachine->mCeModule->TypeToString(refType).c_str()));
  5199. return false;
  5200. }
  5201. void BfCompiler::HotCommit()
  5202. {
  5203. if (mHotState == NULL)
  5204. return;
  5205. mHotState->mCommittedHotCompileIdx = mOptions.mHotCompileIdx;
  5206. for (auto type : mContext->mResolvedTypes)
  5207. {
  5208. auto typeInst = type->ToTypeInstance();
  5209. if (typeInst == NULL)
  5210. continue;
  5211. if (typeInst->mHotTypeData == NULL)
  5212. continue;
  5213. for (int typeIdx = (int)typeInst->mHotTypeData->mTypeVersions.size() - 1; typeIdx >= 0; typeIdx--)
  5214. {
  5215. auto hotVersion = typeInst->mHotTypeData->mTypeVersions[typeIdx];
  5216. if (hotVersion->mCommittedHotCompileIdx != -1)
  5217. break;
  5218. hotVersion->mCommittedHotCompileIdx = mHotState->mCommittedHotCompileIdx;
  5219. if ((!hotVersion->mInterfaceMapping.IsEmpty()) && (typeIdx > 0))
  5220. {
  5221. auto hotVersionHead = typeInst->mHotTypeData->GetLatestVersionHead();
  5222. if ((hotVersionHead != hotVersion) && (hotVersionHead->mDataHash == hotVersion->mDataHash))
  5223. {
  5224. // When we have a slot failure, the data hash will match but we actually do need to use the new mInterfaceMapping entries
  5225. // So we copy them over to the
  5226. hotVersionHead->mInterfaceMapping = hotVersion->mInterfaceMapping;
  5227. }
  5228. }
  5229. }
  5230. }
  5231. }
  5232. void BfCompiler::HotResolve_Start(HotResolveFlags flags)
  5233. {
  5234. BfLogSysM("BfCompiler::HotResolve_Start\n");
  5235. delete mHotResolveData;
  5236. mHotResolveData = new HotResolveData();
  5237. mHotResolveData->mFlags = flags;
  5238. mHotResolveData->mHotTypeIdFlags.Resize(mCurTypeId);
  5239. mHotResolveData->mReasons.Resize(mCurTypeId);
  5240. if ((mHotResolveData->mFlags & HotResolveFlag_HadDataChanges) != 0)
  5241. {
  5242. HotResolve_AddReachableMethod("BfCallAllStaticDtors");
  5243. for (auto& kv : mHotData->mFuncPtrs)
  5244. {
  5245. auto funcRef = kv.mValue;
  5246. HotResolve_AddReachableMethod(funcRef->mMethod, HotTypeFlag_FuncPtr, true);
  5247. }
  5248. }
  5249. }
  5250. //#define HOT_DEBUG_NAME
  5251. bool BfCompiler::HotResolve_AddReachableMethod(BfHotMethod* hotMethod, HotTypeFlags flags, bool devirtualized, bool forceProcess)
  5252. {
  5253. #ifdef HOT_DEBUG_NAME
  5254. HotResolve_PopulateMethodNameMap();
  5255. String* namePtr = NULL;
  5256. if (mHotData->mMethodNameMap.TryGetValue(hotMethod, &namePtr))
  5257. {
  5258. }
  5259. #endif
  5260. HotReachableData* hotReachableData;
  5261. if (mHotResolveData->mReachableMethods.TryAdd(hotMethod, NULL, &hotReachableData))
  5262. {
  5263. hotMethod->mRefCount++;
  5264. }
  5265. else
  5266. {
  5267. hotReachableData->mTypeFlags = (HotTypeFlags)(hotReachableData->mTypeFlags | flags);
  5268. if ((!devirtualized) && (!hotReachableData->mHadNonDevirtualizedCall))
  5269. {
  5270. hotReachableData->mHadNonDevirtualizedCall = true;
  5271. if (!forceProcess)
  5272. return true;
  5273. }
  5274. if (!forceProcess)
  5275. return false;
  5276. }
  5277. hotReachableData->mTypeFlags = (HotTypeFlags)(hotReachableData->mTypeFlags | flags);
  5278. if (!devirtualized)
  5279. hotReachableData->mHadNonDevirtualizedCall = true;
  5280. for (auto hotDepData : hotMethod->mReferences)
  5281. {
  5282. if (hotDepData->mDataKind == BfHotDepDataKind_ThisType)
  5283. {
  5284. auto hotThisType = (BfHotThisType*)hotDepData;
  5285. auto hotTypeVersion = hotThisType->mTypeVersion;
  5286. HotTypeFlags hotTypeFlags = mHotResolveData->mHotTypeIdFlags[hotTypeVersion->mTypeId];
  5287. bool isAllocated = (hotTypeFlags & (HotTypeFlag_Heap | HotTypeFlag_CanAllocate)) != 0;
  5288. if (!isAllocated)
  5289. {
  5290. if (mHotResolveData->mDeferredThisCheckMethods.Add(hotMethod))
  5291. {
  5292. return true;
  5293. }
  5294. else
  5295. {
  5296. return false;
  5297. }
  5298. }
  5299. else
  5300. {
  5301. mHotResolveData->mDeferredThisCheckMethods.Remove(hotMethod);
  5302. }
  5303. }
  5304. else if (hotDepData->mDataKind == BfHotDepDataKind_Allocation)
  5305. {
  5306. auto hotAllocation = (BfHotAllocation*)hotDepData;
  5307. auto hotTypeVersion = hotAllocation->mTypeVersion;
  5308. HotResolve_ReportType(hotTypeVersion, flags, hotMethod);
  5309. HotResolve_ReportType(hotTypeVersion, HotTypeFlag_CanAllocate, hotMethod);
  5310. }
  5311. else if (hotDepData->mDataKind == BfHotDepDataKind_TypeVersion)
  5312. {
  5313. auto hotTypeVersion = (BfHotTypeVersion*)hotDepData;
  5314. HotResolve_ReportType(hotTypeVersion, flags, hotMethod);
  5315. }
  5316. else if (hotDepData->mDataKind == BfHotDepDataKind_Method)
  5317. {
  5318. auto checkMethod = (BfHotMethod*)hotDepData;
  5319. HotResolve_AddReachableMethod(checkMethod, flags, false);
  5320. }
  5321. else if (hotDepData->mDataKind == BfHotDepDataKind_DevirtualizedMethod)
  5322. {
  5323. auto checkMethod = (BfHotDevirtualizedMethod*)hotDepData;
  5324. HotResolve_AddReachableMethod(checkMethod->mMethod, flags, true);
  5325. }
  5326. else if (hotDepData->mDataKind == BfHotDepDataKind_DupMethod)
  5327. {
  5328. auto checkMethod = (BfHotDupMethod*)hotDepData;
  5329. HotResolve_AddReachableMethod(checkMethod->mMethod, flags, true);
  5330. }
  5331. }
  5332. return true;
  5333. }
  5334. void BfCompiler::HotResolve_AddReachableMethod(const StringImpl& methodName)
  5335. {
  5336. BfLogSysM("HotResolve_AddReachableMethod %s\n", methodName.c_str());
  5337. String mangledName = methodName;
  5338. BfHotMethod** hotMethodPtr;
  5339. if (!mHotData->mMethodMap.TryGetValue(mangledName, &hotMethodPtr))
  5340. {
  5341. BfLogSysM("Hot method not found\n");
  5342. return;
  5343. }
  5344. BfHotMethod* hotMethod = *hotMethodPtr;
  5345. while (hotMethod->mPrevVersion != NULL)
  5346. {
  5347. if (hotMethod->mSrcTypeVersion->mCommittedHotCompileIdx != -1)
  5348. break;
  5349. hotMethod = hotMethod->mPrevVersion;
  5350. }
  5351. HotResolve_AddReachableMethod(hotMethod, HotTypeFlag_ActiveFunction, true);
  5352. }
  5353. void BfCompiler::HotResolve_AddActiveMethod(BfHotMethod* hotMethod)
  5354. {
  5355. #ifdef HOT_DEBUG_NAME
  5356. HotResolve_PopulateMethodNameMap();
  5357. String* namePtr = NULL;
  5358. if (mHotData->mMethodNameMap.TryGetValue(hotMethod, &namePtr))
  5359. {
  5360. }
  5361. #endif
  5362. if (mHotResolveData->mActiveMethods.Add(hotMethod))
  5363. {
  5364. hotMethod->mRefCount++;
  5365. }
  5366. // We don't need to mark reachable methods unless we had data changes
  5367. if ((mHotResolveData->mFlags & HotResolveFlag_HadDataChanges) != 0)
  5368. {
  5369. HotResolve_AddReachableMethod(hotMethod, HotTypeFlag_ActiveFunction, true);
  5370. }
  5371. if ((hotMethod->mFlags & BfHotDepDataFlag_HasDup) != 0)
  5372. {
  5373. for (auto depData : hotMethod->mReferences)
  5374. {
  5375. if (depData->mDataKind != BfHotDepDataKind_DupMethod)
  5376. continue;
  5377. auto hotDupMethod = (BfHotDupMethod*)depData;
  5378. HotResolve_AddActiveMethod(hotDupMethod->mMethod);
  5379. }
  5380. }
  5381. }
  5382. void BfCompiler::HotResolve_AddActiveMethod(const StringImpl& methodName)
  5383. {
  5384. BfLogSysM("HotResolve_AddActiveMethod %s\n", methodName.c_str());
  5385. StringT<512> mangledName;
  5386. int hotCompileIdx = 0;
  5387. int tabIdx = (int)methodName.IndexOf('\t');
  5388. if (tabIdx != -1)
  5389. {
  5390. mangledName = methodName.Substring(0, tabIdx);
  5391. hotCompileIdx = atoi(methodName.c_str() + tabIdx + 1);
  5392. }
  5393. else
  5394. mangledName = methodName;
  5395. bool isDelegateRef = false;
  5396. BfHotMethod** hotMethodPtr;
  5397. if (!mHotData->mMethodMap.TryGetValue(mangledName, &hotMethodPtr))
  5398. {
  5399. BfLogSysM("Hot method not found\n");
  5400. return;
  5401. }
  5402. BfHotMethod* hotMethod = *hotMethodPtr;
  5403. while (hotMethod->mPrevVersion != NULL)
  5404. {
  5405. if ((hotMethod->mSrcTypeVersion->mCommittedHotCompileIdx != -1) && (hotCompileIdx < hotMethod->mSrcTypeVersion->mCommittedHotCompileIdx))
  5406. break;
  5407. hotMethod = hotMethod->mPrevVersion;
  5408. }
  5409. HotResolve_AddActiveMethod(hotMethod);
  5410. }
  5411. void BfCompiler::HotResolve_AddDelegateMethod(const StringImpl& methodName)
  5412. {
  5413. BfLogSysM("HotResolve_HotResolve_AddDelegateMethod %s\n", methodName.c_str());
  5414. String mangledName = methodName;
  5415. BfHotMethod** hotMethodPtr;
  5416. if (!mHotData->mMethodMap.TryGetValue(mangledName, &hotMethodPtr))
  5417. {
  5418. BfLogSysM("Hot method not found\n");
  5419. return;
  5420. }
  5421. BfHotMethod* hotMethod = *hotMethodPtr;
  5422. HotResolve_AddReachableMethod(hotMethod, HotTypeFlag_Delegate, true);
  5423. }
  5424. void BfCompiler::HotResolve_ReportType(BfHotTypeVersion* hotTypeVersion, HotTypeFlags flags, BfHotDepData* reason)
  5425. {
  5426. auto& flagsRef = mHotResolveData->mHotTypeFlags[hotTypeVersion];
  5427. if (flagsRef == (flagsRef | flags))
  5428. return;
  5429. flagsRef = (HotTypeFlags)(flags | flagsRef);
  5430. bool applyFlags = true;
  5431. if ((flags & (BfCompiler::HotTypeFlag_ActiveFunction | BfCompiler::HotTypeFlag_Delegate | BfCompiler::HotTypeFlag_FuncPtr)) != 0)
  5432. {
  5433. applyFlags = (hotTypeVersion->mCommittedHotCompileIdx != -1) && (mHotState->mPendingDataChanges.Contains(hotTypeVersion->mTypeId));
  5434. if ((!applyFlags) && (hotTypeVersion->mCommittedHotCompileIdx != -1))
  5435. applyFlags = mHotState->mPendingFailedSlottings.Contains(hotTypeVersion->mTypeId);
  5436. if (applyFlags)
  5437. {
  5438. if (reason != NULL)
  5439. mHotResolveData->mReasons[hotTypeVersion->mTypeId] = reason;
  5440. }
  5441. }
  5442. if (applyFlags)
  5443. {
  5444. auto& flagsIdRef = mHotResolveData->mHotTypeIdFlags[hotTypeVersion->mTypeId];
  5445. flagsIdRef = (HotTypeFlags)(flags | flagsIdRef);
  5446. }
  5447. BfLogSysM("HotResolve_ReportType %p %s Flags:%X DeclHotIdx:%d\n", hotTypeVersion, mContext->TypeIdToString(hotTypeVersion->mTypeId).c_str(), flags, hotTypeVersion->mDeclHotCompileIdx);
  5448. for (auto member : hotTypeVersion->mMembers)
  5449. {
  5450. HotResolve_ReportType(member, flags, reason);
  5451. }
  5452. }
  5453. void BfCompiler::HotResolve_ReportType(int typeId, HotTypeFlags flags)
  5454. {
  5455. if ((uint)typeId >= mHotResolveData->mHotTypeIdFlags.size())
  5456. {
  5457. BF_DBG_FATAL("Invalid typeId");
  5458. return;
  5459. }
  5460. if (mHotResolveData->mHotTypeIdFlags[typeId] == (mHotResolveData->mHotTypeIdFlags[typeId] | flags))
  5461. return;
  5462. auto hotTypeData = mContext->GetHotTypeData(typeId);
  5463. if (hotTypeData != NULL)
  5464. {
  5465. auto hotTypeVersion = hotTypeData->GetTypeVersion(mHotState->mCommittedHotCompileIdx);
  5466. BF_ASSERT(hotTypeVersion != NULL);
  5467. if (hotTypeVersion != NULL)
  5468. HotResolve_ReportType(hotTypeVersion, flags, NULL);
  5469. }
  5470. mHotResolveData->mHotTypeIdFlags[typeId] = (HotTypeFlags)(flags | mHotResolveData->mHotTypeIdFlags[typeId]);
  5471. }
  5472. void BfCompiler::HotResolve_PopulateMethodNameMap()
  5473. {
  5474. if (!mHotData->mMethodNameMap.IsEmpty())
  5475. return;
  5476. for (auto& kv : mHotData->mMethodMap)
  5477. {
  5478. auto hotMethod = kv.mValue;
  5479. while (hotMethod != NULL)
  5480. {
  5481. mHotData->mMethodNameMap[hotMethod] = &kv.mKey;
  5482. hotMethod = hotMethod->mPrevVersion;
  5483. }
  5484. }
  5485. }
  5486. String BfCompiler::HotResolve_Finish()
  5487. {
  5488. BfLogSysM("HotResolve_Finish\n");
  5489. if (mHotState == NULL)
  5490. {
  5491. // It's possible we did a HotCompile with no file changes and therefore didn't actually do a compile
  5492. return "";
  5493. }
  5494. String result;
  5495. if ((mHotResolveData->mFlags & HotResolveFlag_HadDataChanges) != 0)
  5496. {
  5497. BF_ASSERT(!mHotState->mPendingDataChanges.IsEmpty() || !mHotState->mPendingFailedSlottings.IsEmpty());
  5498. }
  5499. else
  5500. {
  5501. BF_ASSERT(mHotState->mPendingDataChanges.IsEmpty() && mHotState->mPendingFailedSlottings.IsEmpty());
  5502. }
  5503. if ((mHotResolveData->mFlags & HotResolveFlag_HadDataChanges) != 0)
  5504. {
  5505. auto _AddUsedType = [&](BfTypeDef* typeDef)
  5506. {
  5507. auto type = mContext->mUnreifiedModule->ResolveTypeDef(mReflectTypeInstanceTypeDef);
  5508. if (type != NULL)
  5509. HotResolve_ReportType(type->mTypeId, BfCompiler::HotTypeFlag_Heap);
  5510. };
  5511. // We have some types that can be allocated in a read-only section- pretend they are on the heap
  5512. _AddUsedType(mReflectTypeInstanceTypeDef);
  5513. _AddUsedType(mStringTypeDef);
  5514. // Find any virtual method overrides that may have been called.
  5515. // These can cause new reachable virtual methods to be called, which may take more than one iteration to fully resolve
  5516. for (int methodPass = 0; true; methodPass++)
  5517. {
  5518. bool didWork = false;
  5519. for (auto hotMethod : mHotResolveData->mDeferredThisCheckMethods)
  5520. {
  5521. if (HotResolve_AddReachableMethod(hotMethod, BfCompiler::HotTypeFlag_ActiveFunction, true, true))
  5522. didWork = true;
  5523. }
  5524. HotTypeFlags typeFlags = HotTypeFlag_None;
  5525. for (auto& kv : mHotData->mMethodMap)
  5526. {
  5527. String& methodName = kv.mKey;
  5528. auto hotMethod = kv.mValue;
  5529. bool doCall = false;
  5530. bool forceAdd = false;
  5531. if (mHotResolveData->mReachableMethods.ContainsKey(hotMethod))
  5532. continue;
  5533. for (auto ref : hotMethod->mReferences)
  5534. {
  5535. if (ref->mDataKind == BfHotDepDataKind_ThisType)
  5536. continue;
  5537. if (ref->mDataKind != BfHotDepDataKind_VirtualDecl)
  5538. break;
  5539. auto hotVirtualDecl = (BfHotVirtualDeclaration*)ref;
  5540. HotReachableData* hotReachableData;
  5541. if (mHotResolveData->mReachableMethods.TryGetValue(hotVirtualDecl->mMethod, &hotReachableData))
  5542. {
  5543. #ifdef HOT_DEBUG_NAME
  5544. HotResolve_PopulateMethodNameMap();
  5545. String* namePtr = NULL;
  5546. if (mHotData->mMethodNameMap.TryGetValue(hotVirtualDecl->mMethod, &namePtr))
  5547. {
  5548. }
  5549. #endif
  5550. if (hotReachableData->mHadNonDevirtualizedCall)
  5551. {
  5552. typeFlags = hotReachableData->mTypeFlags;
  5553. doCall = true;
  5554. }
  5555. }
  5556. }
  5557. if (!doCall)
  5558. {
  5559. if ((hotMethod->mFlags & BfHotDepDataFlag_AlwaysCalled) != 0)
  5560. {
  5561. typeFlags = BfCompiler::HotTypeFlag_ActiveFunction;
  5562. doCall = true;
  5563. }
  5564. }
  5565. if (doCall)
  5566. {
  5567. if (HotResolve_AddReachableMethod(hotMethod, typeFlags, true, forceAdd))
  5568. didWork = true;
  5569. }
  5570. }
  5571. if (!didWork)
  5572. break;
  5573. }
  5574. int errorCount = 0;
  5575. for (int typeId = 0; typeId < (int)mHotResolveData->mHotTypeIdFlags.size(); typeId++)
  5576. {
  5577. auto flags = mHotResolveData->mHotTypeIdFlags[typeId];
  5578. if (flags == 0)
  5579. continue;
  5580. auto type = mContext->mTypes[typeId];
  5581. Dictionary<BfHotMethod*, String*> methodNameMap;
  5582. if ((flags > BfCompiler::HotTypeFlag_UserNotUsed) &&
  5583. ((mHotState->mPendingDataChanges.Contains(typeId)) || (mHotState->mPendingFailedSlottings.Contains(typeId))))
  5584. {
  5585. bool isBadTypeUsed = false;
  5586. if ((flags & HotTypeFlag_Heap) != 0)
  5587. isBadTypeUsed = true;
  5588. else if ((flags & (HotTypeFlag_ActiveFunction | HotTypeFlag_Delegate | HotTypeFlag_FuncPtr)) != 0)
  5589. {
  5590. // If we detect an old version being used, it's only an issue if this type can actually be allocated
  5591. if ((flags & HotTypeFlag_CanAllocate) != 0)
  5592. {
  5593. isBadTypeUsed = true;
  5594. }
  5595. }
  5596. if (isBadTypeUsed)
  5597. {
  5598. bool reasonIsActiveMethod = false;
  5599. String methodReason;
  5600. auto reason = mHotResolveData->mReasons[typeId];
  5601. if ((reason != NULL) && (reason->mDataKind == BfHotDepDataKind_Method))
  5602. {
  5603. auto hotMethod = (BfHotMethod*)reason;
  5604. reasonIsActiveMethod = mHotResolveData->mActiveMethods.Contains(hotMethod);
  5605. HotResolve_PopulateMethodNameMap();
  5606. String** strPtr;
  5607. if (mHotData->mMethodNameMap.TryGetValue(hotMethod, &strPtr))
  5608. {
  5609. methodReason += BfDemangler::Demangle((**strPtr), DbgLanguage_Beef, BfDemangler::Flag_BeefFixed);
  5610. }
  5611. }
  5612. errorCount++;
  5613. if (errorCount >= 1000)
  5614. {
  5615. result += "\n (more errors)...";
  5616. break;
  5617. }
  5618. if (!result.IsEmpty())
  5619. result += "\n";
  5620. result += "'";
  5621. result += mContext->TypeIdToString(typeId);
  5622. result += "'";
  5623. if ((flags & BfCompiler::HotTypeFlag_Heap) != 0)
  5624. result += " allocated on the heap";
  5625. else if ((flags & BfCompiler::HotTypeFlag_ActiveFunction) != 0)
  5626. {
  5627. if (reasonIsActiveMethod)
  5628. result += StrFormat(" used by active method '%s'", methodReason.c_str());
  5629. else if (!methodReason.IsEmpty())
  5630. result += StrFormat(" previous data version used by deleted method '%s', reachable by an active method", methodReason.c_str());
  5631. else
  5632. result += " previous data version used by a deleted method reachable by an active method";
  5633. }
  5634. else if ((flags & BfCompiler::HotTypeFlag_Delegate) != 0)
  5635. {
  5636. if (!methodReason.IsEmpty())
  5637. result += StrFormat(" previous data version used by deleted method '%s', reachable by a delegate", methodReason.c_str());
  5638. else
  5639. result += " previous data version used by a deleted method reachable by a delegate";
  5640. }
  5641. else if ((flags & BfCompiler::HotTypeFlag_FuncPtr) != 0)
  5642. {
  5643. if (!methodReason.IsEmpty())
  5644. result += StrFormat(" previous data version used by deleted method '%s', reachable by a function pointer", methodReason.c_str());
  5645. else
  5646. result += " previous data version used by a deleted method reachable by a function pointer";
  5647. }
  5648. else if ((flags & BfCompiler::HotTypeFlag_UserUsed) != 0)
  5649. result += " stated as used by the program";
  5650. }
  5651. }
  5652. String typeName = mContext->TypeIdToString(typeId);
  5653. BfLogSysM(" %d %s %02X\n", typeId, typeName.c_str(), flags);
  5654. }
  5655. if (result.IsEmpty())
  5656. {
  5657. for (auto typeId : mHotState->mPendingDataChanges)
  5658. {
  5659. auto type = mContext->mTypes[typeId];
  5660. auto typeInstance = type->ToTypeInstance();
  5661. BF_ASSERT(typeInstance->mHotTypeData->mPendingDataChange);
  5662. typeInstance->mHotTypeData->mPendingDataChange = false;
  5663. typeInstance->mHotTypeData->mHadDataChange = true;
  5664. typeInstance->mHotTypeData->mVTableOrigLength = -1;
  5665. typeInstance->mHotTypeData->mOrigInterfaceMethodsLength = -1;
  5666. BfLogSysM("Pending data change applied to type %p\n", typeInstance);
  5667. }
  5668. mHotState->mPendingDataChanges.Clear();
  5669. mHotState->mPendingFailedSlottings.Clear();
  5670. }
  5671. }
  5672. ClearOldHotData();
  5673. if ((mHotResolveData->mFlags & HotResolveFlag_HadDataChanges) != 0)
  5674. {
  5675. for (int pass = 0; pass < 2; pass++)
  5676. {
  5677. bool wantsReachable = pass == 0;
  5678. Array<String> methodList;
  5679. for (auto& kv : mHotData->mMethodMap)
  5680. {
  5681. auto hotMethod = kv.mValue;
  5682. bool reachable = mHotResolveData->mReachableMethods.ContainsKey(hotMethod);
  5683. if (reachable != wantsReachable)
  5684. continue;
  5685. String methodName;
  5686. methodName += BfDemangler::Demangle(kv.mKey, DbgLanguage_Beef, BfDemangler::Flag_BeefFixed);
  5687. methodName += " - ";
  5688. methodName += kv.mKey;
  5689. methodList.Add(methodName);
  5690. }
  5691. methodList.Sort([](const String& lhs, const String& rhs) { return lhs < rhs; });
  5692. for (auto& methodName : methodList)
  5693. BfLogSysM("%s: %s\n", wantsReachable ? "Reachable" : "Unreachable", methodName.c_str());
  5694. }
  5695. }
  5696. delete mHotResolveData;
  5697. mHotResolveData = NULL;
  5698. return result;
  5699. }
  5700. void BfCompiler::ClearOldHotData()
  5701. {
  5702. if (mHotData == NULL)
  5703. return;
  5704. // TODO: Get rid of old hot data during hot compiles, too
  5705. // if (IsHotCompile())
  5706. // return;
  5707. BP_ZONE("BfCompiler::ClearOldHotData");
  5708. bool isHotCompile = IsHotCompile();
  5709. auto itr = mHotData->mMethodMap.begin();
  5710. while (itr != mHotData->mMethodMap.end())
  5711. {
  5712. String& methodName = itr->mKey;
  5713. auto hotMethod = itr->mValue;
  5714. bool doDelete = false;
  5715. // If a previous version of a method is not currently active then it should be impossible to ever reach it
  5716. while (hotMethod->mPrevVersion != NULL)
  5717. {
  5718. auto prevMethod = hotMethod->mPrevVersion;
  5719. if (prevMethod->mRefCount > 1)
  5720. {
  5721. BF_ASSERT((mHotResolveData != NULL) && (mHotResolveData->mActiveMethods.Contains(prevMethod)));
  5722. break;
  5723. }
  5724. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  5725. prevMethod->mPrevVersion = NULL;
  5726. prevMethod->Deref();
  5727. }
  5728. BF_ASSERT(hotMethod->mRefCount >= 1);
  5729. if (hotMethod->mPrevVersion == NULL)
  5730. {
  5731. if (hotMethod->mRefCount <= 1)
  5732. {
  5733. doDelete = true;
  5734. }
  5735. else if ((!isHotCompile) && ((hotMethod->mFlags & (BfHotDepDataFlag_IsBound | BfHotDepDataFlag_RetainMethodWithoutBinding)) == 0))
  5736. {
  5737. doDelete = true;
  5738. }
  5739. }
  5740. bool doRemove = doDelete;
  5741. if ((hotMethod->mFlags & BfHotDepDataFlag_HasDup) != 0)
  5742. {
  5743. bool hasDupMethod = false;
  5744. for (int idx = 0; idx < (int)hotMethod->mReferences.size(); idx++)
  5745. {
  5746. auto depData = hotMethod->mReferences[idx];
  5747. if (depData->mDataKind == BfHotDepDataKind_DupMethod)
  5748. {
  5749. auto dupMethod = (BfHotDupMethod*)depData;
  5750. if (doDelete)
  5751. {
  5752. doRemove = false;
  5753. dupMethod->mMethod->mRefCount++;
  5754. itr->mValue = dupMethod->mMethod;
  5755. }
  5756. else
  5757. {
  5758. if ((dupMethod->mMethod->mRefCount == 1) ||
  5759. ((!IsHotCompile()) && (dupMethod->mMethod->mFlags & BfHotDepDataFlag_IsBound) == 0))
  5760. {
  5761. dupMethod->Deref();
  5762. hotMethod->mReferences.RemoveAt(idx);
  5763. idx--;
  5764. }
  5765. }
  5766. }
  5767. }
  5768. }
  5769. if (doDelete)
  5770. {
  5771. BfLogSysM("Deleting hot method %p %s\n", hotMethod, methodName.c_str());
  5772. //BF_ASSERT(hotMethod->mRefCount == 1);
  5773. hotMethod->Clear();
  5774. hotMethod->Deref();
  5775. if (doRemove)
  5776. itr = mHotData->mMethodMap.Remove(itr);
  5777. }
  5778. else
  5779. ++itr;
  5780. }
  5781. mHotData->ClearUnused(IsHotCompile());
  5782. for (auto type : mContext->mResolvedTypes)
  5783. {
  5784. auto typeInst = type->ToTypeInstance();
  5785. if (typeInst == NULL)
  5786. continue;
  5787. if (typeInst->mHotTypeData == NULL)
  5788. continue;
  5789. bool foundCommittedVersion = false;
  5790. auto latestVersionHead = typeInst->mHotTypeData->GetLatestVersionHead();
  5791. for (int typeIdx = (int)typeInst->mHotTypeData->mTypeVersions.size() - 1; typeIdx >= 0; typeIdx--)
  5792. {
  5793. auto hotVersion = typeInst->mHotTypeData->mTypeVersions[typeIdx];
  5794. if (hotVersion == latestVersionHead)
  5795. {
  5796. // We have to keep the latest version head -- otherwise we would lose vdata and interface mapping data
  5797. continue;
  5798. }
  5799. if ((!foundCommittedVersion) && (mHotState != NULL) && (hotVersion->mDeclHotCompileIdx <= mHotState->mCommittedHotCompileIdx))
  5800. {
  5801. // Don't remove the latest committed version
  5802. foundCommittedVersion = true;
  5803. }
  5804. else if (hotVersion->mRefCount == 1)
  5805. {
  5806. typeInst->mHotTypeData->mTypeVersions.RemoveAt(typeIdx);
  5807. hotVersion->Deref();
  5808. BF_ASSERT(typeInst->mHotTypeData->mTypeVersions.size() > 0);
  5809. }
  5810. }
  5811. }
  5812. }
  5813. void BfCompiler::CompileReified()
  5814. {
  5815. BfLogSysM("BfCompiler::CompileReified\n");
  5816. BP_ZONE("Compile_ResolveTypeDefs");
  5817. Array<BfTypeDef*> deferTypeDefs;
  5818. for (auto typeDef : mSystem->mTypeDefs)
  5819. {
  5820. mSystem->CheckLockYield();
  5821. if (mCanceling)
  5822. {
  5823. BfLogSysM("Canceling from Compile typeDef loop\n");
  5824. break;
  5825. }
  5826. if (typeDef->mProject->mDisabled)
  5827. continue;
  5828. if (typeDef->mIsPartial)
  5829. continue;
  5830. auto scratchModule = mContext->mScratchModule;
  5831. bool isAlwaysInclude = (typeDef->mIsAlwaysInclude) || (typeDef->mProject->mAlwaysIncludeAll);
  5832. auto typeOptions = scratchModule->GetTypeOptions(typeDef);
  5833. if (typeOptions != NULL)
  5834. isAlwaysInclude = typeOptions->Apply(isAlwaysInclude, BfOptionFlags_ReflectAlwaysIncludeType);
  5835. if (typeDef->mProject->IsTestProject())
  5836. {
  5837. for (auto methodDef : typeDef->mMethods)
  5838. {
  5839. auto methodDeclaration = methodDef->GetMethodDeclaration();
  5840. if ((methodDeclaration != NULL) && (methodDeclaration->mAttributes != NULL) &&
  5841. (methodDeclaration->mAttributes->Contains("Test")))
  5842. isAlwaysInclude = true;
  5843. }
  5844. }
  5845. //TODO: Just because the type is required doesn't mean we want to reify it. Why did we have that check?
  5846. if ((mOptions.mCompileOnDemandKind != BfCompileOnDemandKind_AlwaysInclude) && (!isAlwaysInclude))
  5847. {
  5848. if (typeDef->mGenericParamDefs.IsEmpty())
  5849. deferTypeDefs.Add(typeDef);
  5850. continue;
  5851. }
  5852. scratchModule->ResolveTypeDef(typeDef, BfPopulateType_Full);
  5853. }
  5854. // Resolve remaining typedefs as unreified so we can check their attributes
  5855. for (auto typeDef : deferTypeDefs)
  5856. {
  5857. auto type = mContext->mUnreifiedModule->ResolveTypeDef(typeDef, BfPopulateType_Identity);
  5858. if (type == NULL)
  5859. continue;
  5860. auto typeInst = type->ToTypeInstance();
  5861. if (typeInst == NULL)
  5862. continue;
  5863. if (typeInst->mIsReified)
  5864. continue;
  5865. mContext->mUnreifiedModule->PopulateType(typeInst, BfPopulateType_Interfaces_Direct);
  5866. if (typeInst->mCustomAttributes == NULL)
  5867. continue;
  5868. bool alwaysInclude = false;
  5869. for (auto& customAttribute : typeInst->mCustomAttributes->mAttributes)
  5870. {
  5871. if (customAttribute.mType->mAttributeData != NULL)
  5872. {
  5873. if (customAttribute.mType->mAttributeData->mAlwaysIncludeUser != 0)
  5874. alwaysInclude = true;
  5875. if ((customAttribute.mType->mAttributeData->mFlags & BfAttributeFlag_AlwaysIncludeTarget) != 0)
  5876. alwaysInclude = true;
  5877. }
  5878. }
  5879. if (alwaysInclude)
  5880. mContext->mScratchModule->PopulateType(typeInst, BfPopulateType_Full);
  5881. }
  5882. PopulateReified();
  5883. }
  5884. bool BfCompiler::DoCompile(const StringImpl& outputDirectory)
  5885. {
  5886. BP_ZONE("BfCompiler::Compile");
  5887. if (mSystem->mTypeDefs.mCount == 0)
  5888. {
  5889. // No-source bailout
  5890. return true;
  5891. }
  5892. if (!mOptions.mErrorString.IsEmpty())
  5893. {
  5894. mPassInstance->Fail(mOptions.mErrorString);
  5895. return false;
  5896. }
  5897. {
  5898. String hotSwapErrors;
  5899. String toolsetErrors;
  5900. for (auto project : mSystem->mProjects)
  5901. {
  5902. if (project->mDisabled)
  5903. continue;
  5904. if (project->mCodeGenOptions.mLTOType != BfLTOType_None)
  5905. {
  5906. if (mOptions.mAllowHotSwapping)
  5907. {
  5908. if (!hotSwapErrors.IsEmpty())
  5909. hotSwapErrors += ", ";
  5910. hotSwapErrors += project->mName;
  5911. }
  5912. if (mOptions.mToolsetType != BfToolsetType_LLVM)
  5913. {
  5914. if (!toolsetErrors.IsEmpty())
  5915. toolsetErrors += ", ";
  5916. toolsetErrors += project->mName;
  5917. }
  5918. }
  5919. }
  5920. if (!hotSwapErrors.IsEmpty())
  5921. mPassInstance->Fail(StrFormat("Hot compilation cannot be used when LTO is enabled in '%s'. Consider setting 'Workspace/Beef/Debug/Enable Hot Compilation' to 'No'.", hotSwapErrors.c_str()));
  5922. if (!toolsetErrors.IsEmpty())
  5923. mPassInstance->Fail(StrFormat("The Workspace Toolset must be set to 'LLVM' in order to use LTO in '%s'. Consider changing 'Workspace/Targeted/Build/Toolset' to 'LLVM'.", toolsetErrors.c_str()));
  5924. }
  5925. //
  5926. {
  5927. String attribName;
  5928. mAttributeTypeOptionMap.Clear();
  5929. for (int typeOptionsIdx = 0; typeOptionsIdx < (int)mSystem->mTypeOptions.size(); typeOptionsIdx++)
  5930. {
  5931. auto& typeOptions = mSystem->mTypeOptions[typeOptionsIdx];
  5932. for (auto& attributeFilter : typeOptions.mAttributeFilters)
  5933. {
  5934. attribName = attributeFilter;
  5935. attribName += "Attribute";
  5936. Array<int>* arrPtr = NULL;
  5937. mAttributeTypeOptionMap.TryAdd(attribName, NULL, &arrPtr);
  5938. arrPtr->Add(typeOptionsIdx);
  5939. }
  5940. }
  5941. }
  5942. mRebuildFileSet.Clear();
  5943. // Inc revision for next run through Compile
  5944. mRevision++;
  5945. mHasComptimeRebuilds = false;
  5946. int revision = mRevision;
  5947. BfLogSysM("Compile Start. Revision: %d. HasParser:%d AutoComplete:%d\n", revision,
  5948. (mResolvePassData != NULL) && (!mResolvePassData->mParsers.IsEmpty()),
  5949. (mResolvePassData != NULL) && (mResolvePassData->mAutoComplete != NULL));
  5950. if (mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  5951. mContext->mUnreifiedModule->mIsReified = true;
  5952. else
  5953. mContext->mUnreifiedModule->mIsReified = false;
  5954. if (mCeMachine != NULL)
  5955. mCeMachine->CompileStarted();
  5956. if (mOptions.mAllowHotSwapping)
  5957. {
  5958. if (mHotData == NULL)
  5959. {
  5960. mHotData = new HotData();
  5961. mHotData->mCompiler = this;
  5962. }
  5963. }
  5964. else
  5965. {
  5966. delete mHotData;
  5967. mHotData = NULL;
  5968. }
  5969. if (IsHotCompile())
  5970. {
  5971. if (!mOptions.mAllowHotSwapping)
  5972. {
  5973. mPassInstance->Fail("Hot Compilation is not enabled");
  5974. return true;
  5975. }
  5976. if (mHotState == NULL)
  5977. {
  5978. mHotState = new HotState();
  5979. mHotState->mHotProject = mOptions.mHotProject;
  5980. }
  5981. else
  5982. {
  5983. // It should be impossible to switch hot projects without a non-hot compile between them
  5984. BF_ASSERT(mHotState->mHotProject == mOptions.mHotProject);
  5985. }
  5986. }
  5987. else
  5988. {
  5989. for (auto& kv : mContext->mSavedTypeDataMap)
  5990. {
  5991. auto savedTypeData = kv.mValue;
  5992. delete savedTypeData->mHotTypeData;
  5993. savedTypeData->mHotTypeData = NULL;
  5994. }
  5995. delete mHotState;
  5996. mHotState = NULL;
  5997. // This will get rid of any old method data so we don't have any more mPrevVersions
  5998. ClearOldHotData();
  5999. }
  6000. int prevUnfinishedModules = mStats.mModulesStarted - mStats.mModulesFinished;
  6001. mCompletionPct = 0;
  6002. memset(&mStats, 0, sizeof(mStats));
  6003. mCodeGen.ClearResults();
  6004. mCodeGen.ResetStats();
  6005. mStats.mModulesStarted = prevUnfinishedModules;
  6006. if ((mLastRevisionAborted) && (!mIsResolveOnly))
  6007. {
  6008. auto _AddCount = [&](BfModule* module)
  6009. {
  6010. if (module->mAddedToCount)
  6011. {
  6012. if (module->mIsReified)
  6013. mStats.mReifiedModuleCount++;
  6014. }
  6015. };
  6016. for (auto mainModule : mContext->mModules)
  6017. {
  6018. _AddCount(mainModule);
  6019. for (auto specKV : mainModule->mSpecializedMethodModules)
  6020. {
  6021. _AddCount(specKV.mValue);
  6022. }
  6023. }
  6024. }
  6025. if (IsHotCompile())
  6026. {
  6027. mContext->EnsureHotMangledVirtualMethodNames();
  6028. }
  6029. mOutputDirectory = outputDirectory;
  6030. mSystem->StartYieldSection();
  6031. mFastFinish = false;
  6032. mHasQueuedTypeRebuilds = false;
  6033. mCanceling = false;
  6034. mSystem->CheckLockYield();
  6035. #ifdef WANT_COMPILE_LOG
  6036. if (!mIsResolveOnly)
  6037. {
  6038. mCompileLogFP = fopen(StrFormat("compile%d.txt", mRevision).c_str(), "wb");
  6039. }
  6040. #endif
  6041. BfTypeDef* typeDef;
  6042. BfLogSysM("UpdateRevisedTypes Revision %d. ResolvePass:%d CursorIdx:%d\n", mRevision, mIsResolveOnly,
  6043. ((mResolvePassData == NULL) || (mResolvePassData->mParsers.IsEmpty())) ? - 1 : mResolvePassData->mParsers[0]->mCursorIdx);
  6044. mCompileState = CompileState_Normal;
  6045. UpdateRevisedTypes();
  6046. // We need to defer processing the graveyard until here, because mLookupResults contain atom references so we need to make sure
  6047. // those aren't deleted until we can properly handle it.
  6048. mSystem->ProcessAtomGraveyard();
  6049. BpEnter("Compile_Start");
  6050. mHasRequiredTypes = true;
  6051. //HashSet<BfTypeDef*> internalTypeDefs;
  6052. auto _GetRequiredType = [&](const StringImpl& typeName, int genericArgCount = 0)
  6053. {
  6054. auto typeDef = mSystem->FindTypeDef(typeName, genericArgCount);
  6055. if (typeDef == NULL)
  6056. {
  6057. mPassInstance->Fail(StrFormat("Unable to find system type: %s", typeName.c_str()));
  6058. mHasRequiredTypes = false;
  6059. }
  6060. return typeDef;
  6061. };
  6062. _GetRequiredType("System.Void");
  6063. _GetRequiredType("System.Boolean");
  6064. _GetRequiredType("System.Int");
  6065. _GetRequiredType("System.Int8");
  6066. _GetRequiredType("System.Int16");
  6067. _GetRequiredType("System.Int32");
  6068. _GetRequiredType("System.Int64");
  6069. _GetRequiredType("System.UInt");
  6070. _GetRequiredType("System.UInt8");
  6071. _GetRequiredType("System.UInt16");
  6072. _GetRequiredType("System.UInt32");
  6073. _GetRequiredType("System.UInt64");
  6074. _GetRequiredType("System.Char8");
  6075. _GetRequiredType("System.Char16");
  6076. mChar32TypeDef = _GetRequiredType("System.Char32");
  6077. mFloatTypeDef = _GetRequiredType("System.Float");
  6078. mDoubleTypeDef = _GetRequiredType("System.Double");
  6079. mMathTypeDef = _GetRequiredType("System.Math");
  6080. mBfObjectTypeDef = _GetRequiredType("System.Object");
  6081. mArray1TypeDef = _GetRequiredType("System.Array1", 1);
  6082. mArray2TypeDef = _GetRequiredType("System.Array2", 1);
  6083. mArray3TypeDef = _GetRequiredType("System.Array3", 1);
  6084. mArray4TypeDef = _GetRequiredType("System.Array4", 1);
  6085. mSpanTypeDef = _GetRequiredType("System.Span", 1);
  6086. mRangeTypeDef = _GetRequiredType("System.Range");
  6087. mClosedRangeTypeDef = _GetRequiredType("System.ClosedRange");
  6088. mIndexTypeDef = _GetRequiredType("System.Index");
  6089. mIndexRangeTypeDef = _GetRequiredType("System.IndexRange");
  6090. mAttributeTypeDef = _GetRequiredType("System.Attribute");
  6091. mAttributeUsageAttributeTypeDef = _GetRequiredType("System.AttributeUsageAttribute");
  6092. mClassVDataTypeDef = _GetRequiredType("System.ClassVData");
  6093. mCLinkAttributeTypeDef = _GetRequiredType("System.CLinkAttribute");
  6094. mImportAttributeTypeDef = _GetRequiredType("System.ImportAttribute");
  6095. mExportAttributeTypeDef = _GetRequiredType("System.ExportAttribute");
  6096. mCReprAttributeTypeDef = _GetRequiredType("System.CReprAttribute");
  6097. mUnderlyingArrayAttributeTypeDef = _GetRequiredType("System.UnderlyingArrayAttribute");
  6098. mAlignAttributeTypeDef = _GetRequiredType("System.AlignAttribute");
  6099. mAllowDuplicatesAttributeTypeDef = _GetRequiredType("System.AllowDuplicatesAttribute");
  6100. mNoDiscardAttributeTypeDef = _GetRequiredType("System.NoDiscardAttribute");
  6101. mDisableChecksAttributeTypeDef = _GetRequiredType("System.DisableChecksAttribute");
  6102. mDisableObjectAccessChecksAttributeTypeDef = _GetRequiredType("System.DisableObjectAccessChecksAttribute");
  6103. mDbgRawAllocDataTypeDef = _GetRequiredType("System.DbgRawAllocData");
  6104. mDeferredCallTypeDef = _GetRequiredType("System.DeferredCall");
  6105. mDelegateTypeDef = _GetRequiredType("System.Delegate");
  6106. mFunctionTypeDef = _GetRequiredType("System.Function");
  6107. mActionTypeDef = _GetRequiredType("System.Action");
  6108. mEnumTypeDef = _GetRequiredType("System.Enum");
  6109. mFriendAttributeTypeDef = _GetRequiredType("System.FriendAttribute");
  6110. mComptimeAttributeTypeDef = _GetRequiredType("System.ComptimeAttribute");
  6111. mConstEvalAttributeTypeDef = _GetRequiredType("System.ConstEvalAttribute");
  6112. mNoExtensionAttributeTypeDef = _GetRequiredType("System.NoExtensionAttribute");
  6113. mCheckedAttributeTypeDef = _GetRequiredType("System.CheckedAttribute");
  6114. mUncheckedAttributeTypeDef = _GetRequiredType("System.UncheckedAttribute");
  6115. mResultTypeDef = _GetRequiredType("System.Result", 1);
  6116. mGCTypeDef = _GetRequiredType("System.GC");
  6117. mGenericIEnumerableTypeDef = _GetRequiredType("System.Collections.IEnumerable", 1);
  6118. mGenericIEnumeratorTypeDef = _GetRequiredType("System.Collections.IEnumerator", 1);
  6119. mGenericIRefEnumeratorTypeDef = _GetRequiredType("System.Collections.IRefEnumerator", 1);
  6120. mInlineAttributeTypeDef = _GetRequiredType("System.InlineAttribute");
  6121. mThreadTypeDef = _GetRequiredType("System.Threading.Thread");
  6122. mInternalTypeDef = _GetRequiredType("System.Internal");
  6123. mPlatformTypeDef = _GetRequiredType("System.Platform");
  6124. mCompilerTypeDef = _GetRequiredType("System.Compiler");
  6125. mCompilerGeneratorTypeDef = _GetRequiredType("System.Compiler.Generator");
  6126. mDiagnosticsDebugTypeDef = _GetRequiredType("System.Diagnostics.Debug");
  6127. mIDisposableTypeDef = _GetRequiredType("System.IDisposable");
  6128. mIIntegerTypeDef = _GetRequiredType("System.IInteger");
  6129. mIPrintableTypeDef = _GetRequiredType("System.IPrintable");
  6130. mIHashableTypeDef = _GetRequiredType("System.IHashable");
  6131. mIComptimeTypeApply = _GetRequiredType("System.IComptimeTypeApply");
  6132. mIComptimeMethodApply = _GetRequiredType("System.IComptimeMethodApply");
  6133. mIOnTypeInitTypeDef = _GetRequiredType("System.IOnTypeInit");
  6134. mIOnTypeDoneTypeDef = _GetRequiredType("System.IOnTypeDone");
  6135. mIOnFieldInitTypeDef = _GetRequiredType("System.IOnFieldInit");
  6136. mIOnMethodInitTypeDef = _GetRequiredType("System.IOnMethodInit");
  6137. mLinkNameAttributeTypeDef = _GetRequiredType("System.LinkNameAttribute");
  6138. mCallingConventionAttributeTypeDef = _GetRequiredType("System.CallingConventionAttribute");
  6139. mMethodRefTypeDef = _GetRequiredType("System.MethodReference", 1);
  6140. mNullableTypeDef = _GetRequiredType("System.Nullable", 1);
  6141. mOrderedAttributeTypeDef = _GetRequiredType("System.OrderedAttribute");
  6142. mPointerTTypeDef = _GetRequiredType("System.Pointer", 1);
  6143. mPointerTypeDef = _GetRequiredType("System.Pointer", 0);
  6144. mReflectTypeIdTypeDef = _GetRequiredType("System.Reflection.TypeId");
  6145. mReflectArrayType = _GetRequiredType("System.Reflection.ArrayType");
  6146. mReflectGenericParamType = _GetRequiredType("System.Reflection.GenericParamType");
  6147. mReflectFieldDataDef = _GetRequiredType("System.Reflection.TypeInstance.FieldData");
  6148. mReflectFieldSplatDataDef = _GetRequiredType("System.Reflection.TypeInstance.FieldSplatData");
  6149. mReflectMethodDataDef = _GetRequiredType("System.Reflection.TypeInstance.MethodData");
  6150. mReflectParamDataDef = _GetRequiredType("System.Reflection.TypeInstance.ParamData");
  6151. mReflectInterfaceDataDef = _GetRequiredType("System.Reflection.TypeInstance.InterfaceData");
  6152. mReflectPointerType = _GetRequiredType("System.Reflection.PointerType");
  6153. mReflectRefType = _GetRequiredType("System.Reflection.RefType");
  6154. mReflectSizedArrayType = _GetRequiredType("System.Reflection.SizedArrayType");
  6155. mReflectConstExprType = _GetRequiredType("System.Reflection.ConstExprType");
  6156. mReflectSpecializedGenericType = _GetRequiredType("System.Reflection.SpecializedGenericType");
  6157. mReflectTypeInstanceTypeDef = _GetRequiredType("System.Reflection.TypeInstance");
  6158. mReflectUnspecializedGenericType = _GetRequiredType("System.Reflection.UnspecializedGenericType");
  6159. mReflectFieldInfoTypeDef = _GetRequiredType("System.Reflection.FieldInfo");
  6160. mReflectMethodInfoTypeDef = _GetRequiredType("System.Reflection.MethodInfo");
  6161. mSizedArrayTypeDef = _GetRequiredType("System.SizedArray", 2);
  6162. mStaticInitAfterAttributeTypeDef = _GetRequiredType("System.StaticInitAfterAttribute");
  6163. mStaticInitPriorityAttributeTypeDef = _GetRequiredType("System.StaticInitPriorityAttribute");
  6164. mStringTypeDef = _GetRequiredType("System.String");
  6165. mStringViewTypeDef = _GetRequiredType("System.StringView");
  6166. mTestAttributeTypeDef = _GetRequiredType("System.TestAttribute");
  6167. mThreadStaticAttributeTypeDef = _GetRequiredType("System.ThreadStaticAttribute");
  6168. mTypeTypeDef = _GetRequiredType("System.Type");
  6169. mUnboundAttributeTypeDef = _GetRequiredType("System.UnboundAttribute");
  6170. mValueTypeTypeDef = _GetRequiredType("System.ValueType");
  6171. mObsoleteAttributeTypeDef = _GetRequiredType("System.ObsoleteAttribute");
  6172. mErrorAttributeTypeDef = _GetRequiredType("System.ErrorAttribute");
  6173. mWarnAttributeTypeDef = _GetRequiredType("System.WarnAttribute");
  6174. mConstSkipAttributeTypeDef = _GetRequiredType("System.ConstSkipAttribute");
  6175. mIgnoreErrorsAttributeTypeDef = _GetRequiredType("System.IgnoreErrorsAttribute");
  6176. mReflectAttributeTypeDef = _GetRequiredType("System.ReflectAttribute");
  6177. mOnCompileAttributeTypeDef = _GetRequiredType("System.OnCompileAttribute");
  6178. for (int i = 0; i < BfTypeCode_Length; i++)
  6179. mContext->mPrimitiveStructTypes[i] = NULL;
  6180. mContext->mBfTypeType = NULL;
  6181. mContext->mBfClassVDataPtrType = NULL;
  6182. if (!mHasRequiredTypes)
  6183. {
  6184. // Force rebuilding
  6185. BfLogSysM("Compile missing required types\n");
  6186. mOptions.mForceRebuildIdx++;
  6187. }
  6188. mSystem->CheckLockYield();
  6189. if (mBfObjectTypeDef != NULL)
  6190. mContext->mScratchModule->ResolveTypeDef(mBfObjectTypeDef);
  6191. VisitSourceExteriorNodes();
  6192. if (!mIsResolveOnly)
  6193. {
  6194. HashSet<BfModule*> foundVDataModuleSet;
  6195. for (auto bfProject : mSystem->mProjects)
  6196. {
  6197. if (bfProject->mDisabled)
  6198. continue;
  6199. if ((mBfObjectTypeDef != NULL) && (!bfProject->ContainsReference(mBfObjectTypeDef->mProject)))
  6200. {
  6201. mPassInstance->Fail(StrFormat("Project '%s' must reference core library '%s'", bfProject->mName.c_str(), mBfObjectTypeDef->mProject->mName.c_str()));
  6202. }
  6203. if ((bfProject->mTargetType != BfTargetType_BeefConsoleApplication) && (bfProject->mTargetType != BfTargetType_BeefWindowsApplication) &&
  6204. (bfProject->mTargetType != BfTargetType_BeefLib_DynamicLib) && (bfProject->mTargetType != BfTargetType_BeefLib_StaticLib) &&
  6205. (bfProject->mTargetType != BfTargetType_C_ConsoleApplication) && (bfProject->mTargetType != BfTargetType_C_WindowsApplication) &&
  6206. (bfProject->mTargetType != BfTargetType_BeefTest) &&
  6207. (bfProject->mTargetType != BfTargetType_BeefApplication_StaticLib) && (bfProject->mTargetType != BfTargetType_BeefApplication_DynamicLib))
  6208. continue;
  6209. if (bfProject->mTargetType == BfTargetType_BeefTest)
  6210. {
  6211. // Force internal test methods
  6212. auto bfModule = mContext->mScratchModule;
  6213. bfModule->GetInternalMethod("Test_Init");
  6214. bfModule->GetInternalMethod("Test_Query");
  6215. bfModule->GetInternalMethod("Test_Finish");
  6216. }
  6217. bool found = false;
  6218. for (auto module : mVDataModules)
  6219. {
  6220. if (module->mProject == bfProject)
  6221. {
  6222. found = true;
  6223. foundVDataModuleSet.Add(module);
  6224. //module->StartNewRevision();
  6225. }
  6226. }
  6227. if (!found)
  6228. {
  6229. auto module = new BfVDataModule(mContext);
  6230. module->mProject = bfProject;
  6231. module->Init();
  6232. module->FinishInit();
  6233. module->mIsSpecialModule = true;
  6234. BF_ASSERT(!mContext->mLockModules);
  6235. mContext->mModules.push_back(module);
  6236. mVDataModules.push_back(module);
  6237. foundVDataModuleSet.Add(module);
  6238. }
  6239. }
  6240. // Remove old vdata
  6241. for (int moduleIdx = 0; moduleIdx < (int) mVDataModules.size(); moduleIdx++)
  6242. {
  6243. auto module = mVDataModules[moduleIdx];
  6244. if (!foundVDataModuleSet.Contains(module))
  6245. {
  6246. delete module;
  6247. mVDataModules.erase(mVDataModules.begin() + moduleIdx);
  6248. moduleIdx--;
  6249. mContext->mModules.Remove(module);
  6250. }
  6251. }
  6252. }
  6253. if (mIsResolveOnly)
  6254. VisitAutocompleteExteriorIdentifiers();
  6255. mStats.mTypesQueued = 0;
  6256. mStats.mMethodsQueued = 0;
  6257. mStats.mTypesQueued += (int)mContext->mPopulateTypeWorkList.size();
  6258. mStats.mMethodsQueued += (int)mContext->mMethodWorkList.size();
  6259. while (true)
  6260. {
  6261. //
  6262. {
  6263. if (mBfObjectTypeDef != NULL)
  6264. mContext->mScratchModule->ResolveTypeDef(mBfObjectTypeDef, BfPopulateType_Full);
  6265. mContext->RemapObject();
  6266. mSystem->CheckLockYield();
  6267. mWantsDeferMethodDecls = mOptions.mCompileOnDemandKind != BfCompileOnDemandKind_AlwaysInclude;
  6268. CompileReified();
  6269. mWantsDeferMethodDecls = false;
  6270. }
  6271. BpLeave();
  6272. BpEnter("Compile_End");
  6273. mContext->mHasReifiedQueuedRebuildTypes = false;
  6274. //
  6275. {
  6276. BP_ZONE("ProcessingLiveness");
  6277. for (auto type : mContext->mResolvedTypes)
  6278. {
  6279. auto depType = type->ToDependedType();
  6280. if (depType != NULL)
  6281. depType->mRebuildFlags = (BfTypeRebuildFlags)(depType->mRebuildFlags | BfTypeRebuildFlag_AwaitingReference);
  6282. }
  6283. bool didWork = false;
  6284. UpdateDependencyMap(mOptions.mCompileOnDemandKind != BfCompileOnDemandKind_ResolveUnused, didWork);
  6285. // If UpdateDependencyMap caused methods to be reified, then we need to run PopulateReified again-
  6286. // because those methods may be virtual and we need to reify overrides (for example).
  6287. // We use the DoWorkLoop result to determine if there were actually any changes from UpdateDependencyMap
  6288. if (didWork)
  6289. {
  6290. PopulateReified();
  6291. }
  6292. }
  6293. if (!mContext->mHasReifiedQueuedRebuildTypes)
  6294. break;
  6295. BfLogSysM("DoCompile looping over CompileReified due to mHasReifiedQueuedRebuildTypes\n");
  6296. }
  6297. // Handle purgatory (ie: old generic types)
  6298. {
  6299. bool didWork = ProcessPurgatory(true);
  6300. if (mOptions.mCompileOnDemandKind != BfCompileOnDemandKind_AlwaysInclude)
  6301. {
  6302. if (DoWorkLoop())
  6303. didWork = true;
  6304. if (didWork)
  6305. PopulateReified();
  6306. }
  6307. }
  6308. // Mark used modules
  6309. if ((mOptions.mCompileOnDemandKind != BfCompileOnDemandKind_AlwaysInclude) && (!mCanceling))
  6310. {
  6311. bool hadActualTarget = false;
  6312. if (!mIsResolveOnly)
  6313. {
  6314. SizedArray<BfModule*, 32> requiredModules;
  6315. for (auto type : mContext->mResolvedTypes)
  6316. {
  6317. auto typeInst = type->ToTypeInstance();
  6318. if (typeInst == NULL)
  6319. continue;
  6320. if (typeInst->mAlwaysIncludeFlags == BfAlwaysIncludeFlag_None)
  6321. continue;
  6322. if (typeInst->IsGenericTypeInstance())
  6323. {
  6324. if ((!typeInst->IsUnspecializedType()) || (typeInst->IsUnspecializedTypeVariation()))
  6325. continue;
  6326. }
  6327. auto requiredModule = typeInst->GetModule();
  6328. if (requiredModule != NULL)
  6329. requiredModules.push_back(requiredModule);
  6330. }
  6331. mContext->mReferencedIFaceSlots.Clear();
  6332. bool hasTests = false;
  6333. for (auto project : mSystem->mProjects)
  6334. {
  6335. if (project->mTargetType == BfTargetType_BeefTest)
  6336. hasTests = true;
  6337. project->mUsedModules.Clear();
  6338. project->mReferencedTypeData.Clear();
  6339. if (project->mDisabled)
  6340. continue;
  6341. if (project->mTargetType == BfTargetType_BeefLib)
  6342. continue;
  6343. hadActualTarget = true;
  6344. for (auto requiredModule : requiredModules)
  6345. {
  6346. mContext->MarkUsedModules(project, requiredModule);
  6347. }
  6348. String entryClassName = project->mStartupObject;
  6349. typeDef = mSystem->FindTypeDef(entryClassName, 0, project, {}, NULL, BfFindTypeDefFlag_AllowGlobal);
  6350. if (typeDef != NULL)
  6351. {
  6352. auto startupType = mContext->mScratchModule->ResolveTypeDef(typeDef);
  6353. if (startupType != NULL)
  6354. {
  6355. auto startupTypeInst = startupType->ToTypeInstance();
  6356. if (startupTypeInst != NULL)
  6357. {
  6358. mContext->MarkUsedModules(project, startupTypeInst->GetModule());
  6359. }
  6360. }
  6361. }
  6362. if (hasTests)
  6363. {
  6364. HashSet<BfProject*> projectSet;
  6365. for (auto type : mContext->mResolvedTypes)
  6366. {
  6367. auto typeInstance = type->ToTypeInstance();
  6368. if (typeInstance != NULL)
  6369. {
  6370. for (auto& methodInstanceGroup : typeInstance->mMethodInstanceGroups)
  6371. {
  6372. if (methodInstanceGroup.mDefault != NULL)
  6373. {
  6374. auto methodInstance = methodInstanceGroup.mDefault;
  6375. auto project = methodInstance->mMethodDef->mDeclaringType->mProject;
  6376. if (project->mTargetType != BfTargetType_BeefTest)
  6377. continue;
  6378. if ((methodInstance->GetCustomAttributes() != NULL) &&
  6379. (methodInstance->GetCustomAttributes()->Contains(mTestAttributeTypeDef)))
  6380. {
  6381. projectSet.Add(project);
  6382. }
  6383. }
  6384. }
  6385. if (!projectSet.IsEmpty())
  6386. {
  6387. for (auto project : projectSet)
  6388. mContext->MarkUsedModules(project, typeInstance->mModule);
  6389. projectSet.Clear();
  6390. }
  6391. }
  6392. }
  6393. }
  6394. }
  6395. // Leave types reified when hot compiling
  6396. if ((!IsHotCompile()) && (hadActualTarget))
  6397. mContext->TryUnreifyModules();
  6398. }
  6399. }
  6400. // Generate slot nums
  6401. if ((!mIsResolveOnly) && (!mCanceling))
  6402. {
  6403. if ((!IsHotCompile()) || (mHotState->mHasNewInterfaceTypes))
  6404. {
  6405. int prevSlotCount = mMaxInterfaceSlots;
  6406. GenerateSlotNums();
  6407. if ((prevSlotCount != -1) && (prevSlotCount != mMaxInterfaceSlots))
  6408. {
  6409. mInterfaceSlotCountChanged = true;
  6410. }
  6411. if (mHotState != NULL)
  6412. mHotState->mHasNewInterfaceTypes = false;
  6413. }
  6414. }
  6415. // Resolve unused types
  6416. if ((mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_ResolveUnused) && (!mCanceling))
  6417. {
  6418. // Finish off any outstanding modules so we can code generate in parallel with handling the unreified stuff
  6419. for (auto module : mContext->mModules)
  6420. {
  6421. if (!module->mIsSpecialModule)
  6422. {
  6423. if ((module->HasCompiledOutput()) && (module->mIsModuleMutable))
  6424. {
  6425. module->Finish();
  6426. }
  6427. }
  6428. }
  6429. DoWorkLoop();
  6430. BfLogSysM("Compile QueueUnused\n");
  6431. mCompileState = BfCompiler::CompileState_Unreified;
  6432. BpLeave();
  6433. BpEnter("Compile_QueueUnused");
  6434. while (true)
  6435. {
  6436. BP_ZONE("Compile_QueueUnused");
  6437. bool queuedMoreMethods = false;
  6438. int startTypeInitCount = mTypeInitCount;
  6439. for (auto typeDef : mSystem->mTypeDefs)
  6440. {
  6441. mSystem->CheckLockYield();
  6442. if (mCanceling)
  6443. {
  6444. BfLogSysM("Canceling from Compile typeDef loop\n");
  6445. break;
  6446. }
  6447. if (typeDef->mProject->mDisabled)
  6448. continue;
  6449. if (typeDef->mIsPartial)
  6450. continue;
  6451. if (typeDef->mTypeCode == BfTypeCode_Extension)
  6452. continue;
  6453. mContext->mUnreifiedModule->ResolveTypeDef(typeDef, BfPopulateType_Full);
  6454. }
  6455. Array<BfTypeInstance*> typeWorkList;
  6456. Array<BfType*> typeList;
  6457. typeList.Reserve(mContext->mResolvedTypes.GetCount());
  6458. for (auto type : mContext->mResolvedTypes)
  6459. typeList.Add(type);
  6460. for (auto type : typeList)
  6461. {
  6462. auto module = type->GetModule();
  6463. if (module == NULL)
  6464. continue;
  6465. if ((type->IsIncomplete()) && (type->IsTypeInstance()) && (!type->IsSpecializedType()))
  6466. {
  6467. mSystem->CheckLockYield();
  6468. module->PopulateType(type, BfPopulateType_Full);
  6469. }
  6470. auto typeInst = type->ToTypeInstance();
  6471. if (typeInst == NULL)
  6472. continue;
  6473. if (typeInst->IsUnspecializedTypeVariation())
  6474. continue;
  6475. if (!typeInst->IsSpecializedType())
  6476. {
  6477. typeWorkList.Add(typeInst);
  6478. }
  6479. }
  6480. for (auto typeInst : typeWorkList)
  6481. {
  6482. // Find any remaining methods for unreified processing
  6483. for (auto&& methodInstGroup : typeInst->mMethodInstanceGroups)
  6484. {
  6485. if ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  6486. (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference))
  6487. {
  6488. if ((methodInstGroup.mDefault != NULL) && (methodInstGroup.mDefault->mIsForeignMethodDef))
  6489. {
  6490. mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodInstGroup.mDefault->mMethodDef, BfTypeVector(),
  6491. (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_ForeignMethodDef | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass));
  6492. queuedMoreMethods = true;
  6493. }
  6494. else
  6495. {
  6496. auto methodDef = typeInst->mTypeDef->mMethods[methodInstGroup.mMethodIdx];
  6497. if (methodDef->mMethodType == BfMethodType_Init)
  6498. continue;
  6499. mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  6500. (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass));
  6501. queuedMoreMethods = true;
  6502. }
  6503. }
  6504. }
  6505. }
  6506. if ((!queuedMoreMethods) && (startTypeInitCount == mTypeInitCount))
  6507. break;
  6508. DoWorkLoop();
  6509. }
  6510. bool didWork = false;
  6511. UpdateDependencyMap(true, didWork);
  6512. // Deleting types can cause reified types to rebuild, so allow that
  6513. mCompileState = BfCompiler::CompileState_Normal;
  6514. DoWorkLoop();
  6515. }
  6516. else
  6517. {
  6518. DoWorkLoop();
  6519. }
  6520. ProcessPurgatory(false);
  6521. // ProcessPurgatory MAY cause type rebuilds which we need to handle
  6522. DoWorkLoop();
  6523. BfLogSysM("Checking mDepsMayHaveDeletedTypes for SanitizeDependencyMap\n");
  6524. if (mDepsMayHaveDeletedTypes)
  6525. SanitizeDependencyMap();
  6526. // Old Mark used modules
  6527. if (!mIsResolveOnly)
  6528. {
  6529. // if ((!mPassInstance->HasFailed()) && (!mCanceling))
  6530. // {
  6531. // if ((!IsHotCompile()) || (mHotState->mHasNewInterfaceTypes))
  6532. // {
  6533. // GenerateSlotNums();
  6534. // if (mHotState != NULL)
  6535. // mHotState->mHasNewInterfaceTypes = false;
  6536. // }
  6537. // }
  6538. if ((!mPassInstance->HasFailed()) && (!mCanceling))
  6539. {
  6540. if (!mOptions.mAllowHotSwapping)
  6541. {
  6542. GenerateDynCastData();
  6543. mContext->ProcessWorkList(false, false);
  6544. }
  6545. mCompileState = BfCompiler::CompileState_VData;
  6546. for (auto vdataModule : mVDataModules)
  6547. CreateVData(vdataModule);
  6548. for (auto vdataModule : mVDataModules)
  6549. FixVDataHash(vdataModule);
  6550. mCompileState = BfCompiler::CompileState_Normal;
  6551. }
  6552. // Don't clear out unused string pool entries while we are hot swapping, because we want string literals
  6553. // to still be the same pointer if it's erased and then put back
  6554. if ((!IsHotCompile()) && (!mCanceling))
  6555. ClearUnusedStringPoolEntries();
  6556. mContext->ValidateDependencies();
  6557. mContext->UpdateAfterDeletingTypes();
  6558. }
  6559. // We need to check the specialized errors before writing out modules --
  6560. // this call is responsible for deleting dead method specializations that contained errors, or for setting
  6561. // the mHadBuildErrors on the module if there was a method specialization error that didn't die
  6562. mContext->CheckSpecializedErrorData();
  6563. mContext->Finish();
  6564. if ((!mIsResolveOnly) && (!IsHotCompile()))
  6565. ClearOldHotData();
  6566. mPassInstance->TryFlushDeferredError();
  6567. BpLeave();
  6568. BpEnter("Compile_Finish");
  6569. //TODO:!!
  6570. //mCanceling = true;
  6571. String moduleListStr;
  6572. int numModulesWritten = 0;
  6573. if (!mCanceling)
  6574. {
  6575. if (!mIsResolveOnly)
  6576. {
  6577. int idx = 0;
  6578. BF_ASSERT(mContext->mMethodWorkList.IsEmpty());
  6579. //bfContext->mLockModules = true;
  6580. for (int moduleIdx = 0; moduleIdx < (int)mContext->mModules.size(); moduleIdx++)
  6581. {
  6582. //bool clearModule = false;
  6583. auto mainModule = mContext->mModules[moduleIdx];
  6584. BfModule* bfModule = mainModule;
  6585. if (bfModule->mIsReified)
  6586. {
  6587. auto itr = mainModule->mSpecializedMethodModules.begin();
  6588. while (true)
  6589. {
  6590. if (bfModule->mIsModuleMutable)
  6591. {
  6592. //clearModule = true;
  6593. // Note that Finish will just return immediately if we have errors, we don't write out modules with errors
  6594. // The 'mLastModuleWrittenRevision' will not be updated in the case.
  6595. bfModule->Finish();
  6596. mainModule->mRevision = std::max(mainModule->mRevision, bfModule->mRevision);
  6597. }
  6598. if (bfModule->mLastModuleWrittenRevision == mRevision)
  6599. {
  6600. if (!moduleListStr.empty())
  6601. moduleListStr += ", ";
  6602. moduleListStr += bfModule->mModuleName;
  6603. numModulesWritten++;
  6604. }
  6605. if (bfModule->mParentModule != NULL)
  6606. {
  6607. for (auto& fileName : bfModule->mOutFileNames)
  6608. {
  6609. if (!mainModule->mOutFileNames.Contains(fileName))
  6610. mainModule->mOutFileNames.push_back(fileName);
  6611. }
  6612. }
  6613. if (bfModule->mNextAltModule != NULL)
  6614. {
  6615. bfModule = bfModule->mNextAltModule;
  6616. }
  6617. else
  6618. {
  6619. if (itr == mainModule->mSpecializedMethodModules.end())
  6620. break;
  6621. bfModule = itr->mValue;
  6622. ++itr;
  6623. }
  6624. }
  6625. }
  6626. mainModule->ClearModule();
  6627. }
  6628. //bfContext->mLockModules = false;
  6629. }
  6630. else
  6631. {
  6632. bool isTargeted = (mResolvePassData != NULL) && (!mResolvePassData->mParsers.IsEmpty());
  6633. if (!isTargeted)
  6634. {
  6635. for (auto bfModule : mContext->mModules)
  6636. {
  6637. if (bfModule->mIsModuleMutable)
  6638. {
  6639. bfModule->Finish();
  6640. bfModule->mRevision = std::max(bfModule->mRevision, bfModule->mRevision);
  6641. bfModule->ClearModuleData();
  6642. }
  6643. }
  6644. }
  6645. }
  6646. }
  6647. /*if (!moduleListStr.empty())
  6648. mPassInstance->OutputLine(StrFormat("%d modules generated: %s", numModulesWritten, moduleListStr.c_str()));*/
  6649. //CompileLog("%d object files written: %s\n", numModulesWritten, moduleListStr.c_str());
  6650. //printf("Compile done, waiting for finish\n");
  6651. while (true)
  6652. {
  6653. if (mCanceling)
  6654. mCodeGen.Cancel();
  6655. bool isDone = mCodeGen.Finish();
  6656. UpdateCompletion();
  6657. if (isDone)
  6658. break;
  6659. }
  6660. mCodeGen.ProcessErrors(mPassInstance, mCanceling);
  6661. mCeMachine->CompileDone();
  6662. // This has to happen after codegen because we may delete modules that are referenced in codegen
  6663. mContext->Cleanup();
  6664. if ((!IsHotCompile()) && (!mIsResolveOnly) && (!mCanceling))
  6665. {
  6666. // Only save 'saved type data' for temporarily-deleted types like on-demand types.
  6667. // If we don't reuse it within a compilation pass then we put those IDs up to be
  6668. // reused later. We don't do this for hot reloading because there are cases like
  6669. // a user renaming a type that we want to allow him to be able to undo and then
  6670. // hot-recompile successfully.
  6671. for (auto& kv : mContext->mSavedTypeDataMap)
  6672. {
  6673. auto savedTypeData = kv.mValue;
  6674. mTypeIdFreeList.Add(savedTypeData->mTypeId);
  6675. delete savedTypeData;
  6676. }
  6677. mContext->mSavedTypeDataMap.Clear();
  6678. mContext->mSavedTypeData.Clear();
  6679. }
  6680. #ifdef BF_PLATFORM_WINDOWS
  6681. if (!mIsResolveOnly)
  6682. {
  6683. if (!IsHotCompile())
  6684. {
  6685. // Remove individually-written object files from any libs that previously had them,
  6686. // in the case that lib settings changed (ie: switching a module from Og+ to O0)
  6687. for (auto mainModule : mContext->mModules)
  6688. {
  6689. BfModule* bfModule = mainModule;
  6690. if (bfModule->mIsReified)
  6691. {
  6692. for (auto& outFileName : bfModule->mOutFileNames)
  6693. {
  6694. if (outFileName.mModuleWritten)
  6695. BeLibManager::Get()->AddUsedFileName(outFileName.mFileName);
  6696. }
  6697. }
  6698. }
  6699. }
  6700. auto libManager = BeLibManager::Get();
  6701. libManager->Finish();
  6702. if (!libManager->mErrors.IsEmpty())
  6703. {
  6704. for (auto& error : libManager->mErrors)
  6705. mPassInstance->Fail(error);
  6706. // We need to rebuild everything just to force that lib to get repopulated
  6707. mOptions.mForceRebuildIdx++;
  6708. }
  6709. libManager->mErrors.Clear();
  6710. }
  6711. #endif
  6712. int numObjFilesWritten = 0;
  6713. for (auto& fileEntry : mCodeGen.mCodeGenFiles)
  6714. {
  6715. if (!fileEntry.mWasCached)
  6716. numObjFilesWritten++;
  6717. }
  6718. mPassInstance->OutputLine(StrFormat(":low %d module%s built, %d object file%s generated",
  6719. numModulesWritten, (numModulesWritten != 1) ? "s" : "",
  6720. numObjFilesWritten, (numObjFilesWritten != 1) ? "s" : ""));
  6721. if ((mCeMachine != NULL) && (!mIsResolveOnly) && (mCeMachine->mRevisionExecuteTime > 0))
  6722. {
  6723. mPassInstance->OutputLine(StrFormat(":med Comptime execution time: %0.2fs", mCeMachine->mRevisionExecuteTime / 1000.0f));
  6724. }
  6725. BpLeave();
  6726. mPassInstance->WriteErrorSummary();
  6727. if ((mCanceling) && (!mIsResolveOnly))
  6728. {
  6729. mPassInstance->Fail("Build canceled");
  6730. mContext->CancelWorkItems();
  6731. CompileLog("Compile canceled\n");
  6732. }
  6733. BfLogSysM("Compile Done. Revision:%d TypesPopulated:%d MethodsDeclared:%d MethodsProcessed:%d Canceled? %d\n", revision, mStats.mTypesPopulated, mStats.mMethodDeclarations, mStats.mMethodsProcessed, mCanceling);
  6734. UpdateCompletion();
  6735. if ((!mIsResolveOnly) && (!mPassInstance->HasFailed()) && (!mCanceling))
  6736. {
  6737. //BF_ASSERT(mCompletionPct >= 0.99999f);
  6738. }
  6739. if (mCompileLogFP != NULL)
  6740. {
  6741. fclose(mCompileLogFP);
  6742. mCompileLogFP = NULL;
  6743. }
  6744. UpdateCompletion();
  6745. mStats.mTotalTypes = mContext->mResolvedTypes.GetCount();
  6746. String compileInfo;
  6747. if (mIsResolveOnly)
  6748. compileInfo += StrFormat("ResolveOnly ResolveType:%d Parser:%d\n", mResolvePassData->mResolveType, !mResolvePassData->mParsers.IsEmpty());
  6749. compileInfo += StrFormat("TotalTypes:%d\nTypesPopulated:%d\nMethodsDeclared:%d\nMethodsProcessed:%d\nCanceled? %d\n", mStats.mTotalTypes, mStats.mTypesPopulated, mStats.mMethodDeclarations, mStats.mMethodsProcessed, mCanceling);
  6750. compileInfo += StrFormat("TypesPopulated:%d\n", mStats.mTypesPopulated);
  6751. compileInfo += StrFormat("MethodDecls:%d\nMethodsProcessed:%d\nModulesStarted:%d\nModulesFinished:%d\n", mStats.mMethodDeclarations, mStats.mMethodsProcessed, mStats.mModulesFinished);
  6752. BpEvent("CompileDone", compileInfo.c_str());
  6753. if (mHotState != NULL)
  6754. {
  6755. for (auto& fileEntry : mCodeGen.mCodeGenFiles)
  6756. {
  6757. if (fileEntry.mWasCached)
  6758. continue;
  6759. mHotState->mQueuedOutFiles.Add(fileEntry);
  6760. }
  6761. if (!mPassInstance->HasFailed())
  6762. {
  6763. // Clear these out when we know we've compiled without error
  6764. mHotState->mNewlySlottedTypeIds.Clear();
  6765. mHotState->mSlotDefineTypeIds.Clear();
  6766. }
  6767. }
  6768. mCompileState = BfCompiler::CompileState_None;
  6769. // extern MemReporter gBEMemReporter;
  6770. // extern int gBEMemReporterSize;
  6771. // gBEMemReporter.Report();
  6772. // int memReporterSize = gBEMemReporterSize;
  6773. mLastRevisionAborted = mCanceling;
  6774. bool didCancel = mCanceling;
  6775. mCanceling = false;
  6776. mContext->ValidateDependencies();
  6777. if (mNeedsFullRefresh)
  6778. {
  6779. mNeedsFullRefresh = false;
  6780. return false;
  6781. }
  6782. if (didCancel)
  6783. mLastHadComptimeRebuilds = mHasComptimeRebuilds || mLastHadComptimeRebuilds;
  6784. else
  6785. mLastHadComptimeRebuilds = mHasComptimeRebuilds;
  6786. return !didCancel && !mHasQueuedTypeRebuilds;
  6787. }
  6788. bool BfCompiler::Compile(const StringImpl& outputDirectory)
  6789. {
  6790. bool success = DoCompile(outputDirectory);
  6791. if (!success)
  6792. return false;
  6793. if (mPassInstance->HasFailed())
  6794. return true;
  6795. if (!mInterfaceSlotCountChanged)
  6796. return true;
  6797. BfLogSysM("Interface slot count increased. Rebuilding relevant modules.\n");
  6798. mPassInstance->OutputLine("Interface slot count increased. Rebuilding relevant modules.");
  6799. // Recompile with the increased slot count
  6800. success = DoCompile(outputDirectory);
  6801. BF_ASSERT(!mInterfaceSlotCountChanged);
  6802. return success;
  6803. }
  6804. void BfCompiler::ClearResults()
  6805. {
  6806. BP_ZONE("BfCompiler::ClearResults");
  6807. mCodeGen.ClearResults();
  6808. }
  6809. // Can should still leave the system in a state such that we when we save as much progress as possible while
  6810. // still leaving the system in a state that the next attempt at compile will resume with a valid state
  6811. // Canceling will still process the pending PopulateType calls but may leave items in the method worklist.
  6812. // Note that Cancel is an async request to cancel
  6813. void BfCompiler::Cancel()
  6814. {
  6815. mCanceling = true;
  6816. mFastFinish = true;
  6817. mHadCancel = true;
  6818. if (mCeMachine != NULL)
  6819. {
  6820. AutoCrit autoCrit(mCeMachine->mCritSect);
  6821. mCeMachine->mSpecialCheck = true;
  6822. mFastFinish = true;
  6823. }
  6824. BfLogSysM("BfCompiler::Cancel\n");
  6825. BpEvent("BfCompiler::Cancel", "");
  6826. }
  6827. void BfCompiler::RequestFastFinish()
  6828. {
  6829. mFastFinish = true;
  6830. if (mCeMachine != NULL)
  6831. mCeMachine->mSpecialCheck = true;
  6832. BfLogSysM("BfCompiler::RequestFastFinish\n");
  6833. BpEvent("BfCompiler::RequestFastFinish", "");
  6834. }
  6835. //#define WANT_COMPILE_LOG
  6836. void BfCompiler::CompileLog(const char* fmt ...)
  6837. {
  6838. #ifdef WANT_COMPILE_LOG
  6839. if (mCompileLogFP == NULL)
  6840. return;
  6841. //static int lineNum = 0;
  6842. //lineNum++;
  6843. va_list argList;
  6844. va_start(argList, fmt);
  6845. String aResult = vformat(fmt, argList);
  6846. va_end(argList);
  6847. //aResult = StrFormat("%d ", lineNum) + aResult;
  6848. fwrite(aResult.c_str(), 1, aResult.length(), mCompileLogFP);
  6849. #endif
  6850. }
  6851. void BfCompiler::ReportMemory(MemReporter* memReporter)
  6852. {
  6853. AutoCrit crit(mSystem->mDataLock);
  6854. {
  6855. AutoMemReporter autoMemReporter(memReporter, "Context");
  6856. mContext->ReportMemory(memReporter);
  6857. }
  6858. for (auto type : mContext->mResolvedTypes)
  6859. {
  6860. AutoMemReporter autoMemReporter(memReporter, "Types");
  6861. type->ReportMemory(memReporter);
  6862. }
  6863. for (auto module : mContext->mModules)
  6864. {
  6865. AutoMemReporter autoMemReporter(memReporter, "Modules");
  6866. module->ReportMemory(memReporter);
  6867. }
  6868. {
  6869. AutoMemReporter autoMemReporter(memReporter, "ScratchModule");
  6870. mContext->mScratchModule->ReportMemory(memReporter);
  6871. }
  6872. for (auto vdataModule : mVDataModules)
  6873. {
  6874. AutoMemReporter autoMemReporter(memReporter, "VDataModules");
  6875. vdataModule->ReportMemory(memReporter);
  6876. }
  6877. if (mHotData != NULL)
  6878. {
  6879. AutoMemReporter autoMemReporter(memReporter, "HotData");
  6880. memReporter->Add(sizeof(HotData));
  6881. memReporter->AddMap(mHotData->mMethodMap);
  6882. for (auto& kv : mHotData->mMethodMap)
  6883. {
  6884. memReporter->AddStr(kv.mKey);
  6885. memReporter->Add(sizeof(BfHotMethod));
  6886. memReporter->AddVec(kv.mValue->mReferences);
  6887. }
  6888. }
  6889. if (mHotState != NULL)
  6890. {
  6891. AutoMemReporter autoMemReporter(memReporter, "HotState");
  6892. memReporter->Add(sizeof(HotState));
  6893. memReporter->AddVec(mHotState->mQueuedOutFiles, false);
  6894. memReporter->AddHashSet(mHotState->mSlotDefineTypeIds, false);
  6895. memReporter->AddHashSet(mHotState->mPendingDataChanges, false);
  6896. memReporter->AddMap(mHotState->mDeletedTypeNameMap, false);
  6897. for (auto& kv : mHotState->mDeletedTypeNameMap)
  6898. {
  6899. memReporter->AddStr(kv.mKey, false);
  6900. }
  6901. }
  6902. }
  6903. //////////////////////////////////////////////////////////////////////////
  6904. void BfCompiler::GenerateAutocompleteInfo()
  6905. {
  6906. BP_ZONE("BfCompiler::GetAutocompleteInfo");
  6907. String& autoCompleteResultString = *gTLStrReturn.Get();
  6908. autoCompleteResultString.Clear();
  6909. auto bfModule = mResolvePassData->mAutoComplete->mModule;
  6910. if (bfModule != NULL)
  6911. {
  6912. auto autoComplete = mResolvePassData->mAutoComplete;
  6913. if (autoComplete->mResolveType == BfResolveType_GetNavigationData)
  6914. return; // Already handled
  6915. if (autoComplete->mResolveType == BfResolveType_GetResultString)
  6916. {
  6917. autoCompleteResultString = autoComplete->mResultString;
  6918. return;
  6919. }
  6920. if (autoComplete->mUncertain)
  6921. autoCompleteResultString += "uncertain\n";
  6922. if (autoComplete->mDefaultSelection.length() != 0)
  6923. autoCompleteResultString += StrFormat("select\t%s\n", autoComplete->mDefaultSelection.c_str());
  6924. auto _EncodeTypeDef = [] (BfTypeDef* typeDef)
  6925. {
  6926. StringT<128> typeName = typeDef->mProject->mName;
  6927. typeName += ":";
  6928. typeName += typeDef->mFullName.ToString();
  6929. if (!typeDef->mGenericParamDefs.IsEmpty())
  6930. typeName += StrFormat("`%d", (int)typeDef->mGenericParamDefs.size());
  6931. return typeName;
  6932. };
  6933. if (autoComplete->mResolveType == BfResolveType_GetSymbolInfo)
  6934. {
  6935. if (autoComplete->mDefTypeGenericParamIdx != -1)
  6936. {
  6937. autoCompleteResultString += StrFormat("typeGenericParam\t%d\n", autoComplete->mDefTypeGenericParamIdx);
  6938. autoCompleteResultString += StrFormat("typeRef\t%s\n", _EncodeTypeDef(autoComplete->mDefType).c_str());
  6939. }
  6940. else if (autoComplete->mDefMethodGenericParamIdx != -1)
  6941. {
  6942. autoCompleteResultString += StrFormat("methodGenericParam\t%d\n", autoComplete->mDefMethodGenericParamIdx);
  6943. autoCompleteResultString += StrFormat("methodRef\t%s\t%d\n", _EncodeTypeDef(autoComplete->mDefType).c_str(), autoComplete->mDefMethod->mIdx);
  6944. }
  6945. else if ((autoComplete->mReplaceLocalId != -1) && (autoComplete->mDefMethod != NULL))
  6946. {
  6947. autoCompleteResultString += StrFormat("localId\t%d\n", autoComplete->mReplaceLocalId);
  6948. autoCompleteResultString += StrFormat("methodRef\t%s\t%d\n", _EncodeTypeDef(autoComplete->mDefType).c_str(), autoComplete->mDefMethod->mIdx);
  6949. }
  6950. else if (autoComplete->mDefField != NULL)
  6951. {
  6952. autoCompleteResultString += StrFormat("fieldRef\t%s\t%d\n", _EncodeTypeDef(autoComplete->mDefType).c_str(), autoComplete->mDefField->mIdx);
  6953. }
  6954. else if (autoComplete->mDefProp != NULL)
  6955. {
  6956. autoCompleteResultString += StrFormat("propertyRef\t%s\t%d\n", _EncodeTypeDef(autoComplete->mDefType).c_str(), autoComplete->mDefProp->mIdx);
  6957. }
  6958. else if (autoComplete->mDefMethod != NULL)
  6959. {
  6960. if (autoComplete->mDefMethod->mMethodType == BfMethodType_Ctor)
  6961. autoCompleteResultString += StrFormat("ctorRef\t%s\t%d\n", _EncodeTypeDef(autoComplete->mDefType).c_str(), autoComplete->mDefMethod->mIdx);
  6962. else
  6963. autoCompleteResultString += StrFormat("methodRef\t%s\t%d\n", _EncodeTypeDef(autoComplete->mDefType).c_str(), autoComplete->mDefMethod->mIdx);
  6964. }
  6965. else if (autoComplete->mDefType != NULL)
  6966. {
  6967. autoCompleteResultString += StrFormat("typeRef\t%s\n", _EncodeTypeDef(autoComplete->mDefType).c_str());
  6968. }
  6969. else if (!autoComplete->mDefNamespace.IsEmpty())
  6970. {
  6971. autoCompleteResultString += StrFormat("namespaceRef\t%s\n", autoComplete->mDefNamespace.ToString().c_str());
  6972. }
  6973. if (autoComplete->mInsertEndIdx > 0)
  6974. {
  6975. if (!mResolvePassData->mParsers.IsEmpty())
  6976. {
  6977. if (mResolvePassData->mParsers[0]->mSrc[autoComplete->mInsertEndIdx - 1] == '!')
  6978. autoComplete->mInsertEndIdx--;
  6979. }
  6980. }
  6981. }
  6982. const char* wantsDocEntry = NULL;
  6983. if (!autoComplete->mDocumentationEntryName.IsEmpty())
  6984. wantsDocEntry = autoComplete->mDocumentationEntryName.c_str();
  6985. if (autoComplete->mInsertStartIdx != -1)
  6986. {
  6987. autoCompleteResultString += StrFormat("insertRange\t%d %d\n", autoComplete->mInsertStartIdx, autoComplete->mInsertEndIdx);
  6988. }
  6989. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mGetDefinitionNode == NULL) && (autoComplete->mIsGetDefinition) && (autoComplete->mMethodMatchInfo != NULL))
  6990. {
  6991. // Take loc from methodMatchInfo
  6992. if (autoComplete->mMethodMatchInfo->mInstanceList.size() > 0)
  6993. {
  6994. int bestIdx = autoComplete->mMethodMatchInfo->mBestIdx;
  6995. auto typeInst = autoComplete->mMethodMatchInfo->mInstanceList[bestIdx].mTypeInstance;
  6996. auto methodDef = autoComplete->mMethodMatchInfo->mInstanceList[bestIdx].mMethodDef;
  6997. if (methodDef->mMethodDeclaration != NULL)
  6998. {
  6999. auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(methodDef->mMethodDeclaration);
  7000. if (ctorDecl != NULL)
  7001. autoComplete->SetDefinitionLocation(ctorDecl->mThisToken);
  7002. else
  7003. autoComplete->SetDefinitionLocation(methodDef->GetMethodDeclaration()->mNameNode);
  7004. }
  7005. else // Just select type then
  7006. autoComplete->SetDefinitionLocation(typeInst->mTypeDef->mTypeDeclaration->mNameNode);
  7007. }
  7008. }
  7009. if (autoComplete->mGetDefinitionNode != NULL)
  7010. {
  7011. auto astNode = autoComplete->mGetDefinitionNode;
  7012. auto bfSource = autoComplete->mGetDefinitionNode->GetSourceData()->ToParserData();
  7013. if (bfSource != NULL)
  7014. {
  7015. int line = 0;
  7016. int lineChar = 0;
  7017. bfSource->GetLineCharAtIdx(astNode->GetSrcStart(), line, lineChar);
  7018. autoCompleteResultString += StrFormat("defLoc\t%s\t%d\t%d\n", bfSource->mFileName.c_str(), line, lineChar);
  7019. }
  7020. }
  7021. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  7022. if ((methodMatchInfo != NULL) && (wantsDocEntry == NULL))
  7023. {
  7024. if (methodMatchInfo->mInstanceList.size() > 0)
  7025. {
  7026. if (autoComplete->mIdentifierUsed != NULL)
  7027. {
  7028. String filter;
  7029. if (autoComplete->mIdentifierUsed != NULL)
  7030. autoComplete->mIdentifierUsed->ToString(filter);
  7031. auto& bestInstance = methodMatchInfo->mInstanceList[methodMatchInfo->mBestIdx];
  7032. auto bestMethodDef = bestInstance.mMethodDef;
  7033. if (bestMethodDef != NULL)
  7034. {
  7035. for (int paramIdx = 0; paramIdx < bestMethodDef->mParams.mSize; paramIdx++)
  7036. {
  7037. if ((paramIdx == 0) && (bestMethodDef->mMethodType == BfMethodType_Extension))
  7038. continue;
  7039. autoComplete->AddEntry(AutoCompleteEntry("param", bestMethodDef->mParams[paramIdx]->mName + ":"), filter);
  7040. }
  7041. }
  7042. }
  7043. String invokeInfoText;
  7044. invokeInfoText += StrFormat("%d", methodMatchInfo->mBestIdx);
  7045. for (int srcPosIdx = 0; srcPosIdx < (int)methodMatchInfo->mSrcPositions.size(); srcPosIdx++)
  7046. invokeInfoText += StrFormat(" %d", methodMatchInfo->mSrcPositions[srcPosIdx]);
  7047. autoCompleteResultString += "invokeInfo\t";
  7048. autoCompleteResultString += invokeInfoText;
  7049. autoCompleteResultString += "\n";
  7050. }
  7051. int idx = 0;
  7052. for (auto& methodEntry : methodMatchInfo->mInstanceList)
  7053. {
  7054. String methodText;
  7055. if (methodEntry.mPayloadEnumField != NULL)
  7056. {
  7057. auto payloadFieldDef = methodEntry.mPayloadEnumField->GetFieldDef();
  7058. methodText += payloadFieldDef->mName;
  7059. methodText += "(\x1";
  7060. auto payloadType = methodEntry.mPayloadEnumField->mResolvedType;
  7061. BF_ASSERT(payloadType->IsTuple());
  7062. if (payloadType->IsTuple())
  7063. {
  7064. auto tupleType = (BfTypeInstance*)payloadType;
  7065. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  7066. {
  7067. auto fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  7068. auto fieldDef = fieldInstance->GetFieldDef();
  7069. if (fieldIdx > 0)
  7070. methodText += ",\x1 ";
  7071. methodText += bfModule->TypeToString(fieldInstance->mResolvedType, BfTypeNameFlag_ResolveGenericParamNames);
  7072. if (!fieldDef->IsUnnamedTupleField())
  7073. {
  7074. methodText += " ";
  7075. if (fieldDef->mName.StartsWith("_"))
  7076. methodText += fieldDef->mName.Substring(1);
  7077. else
  7078. methodText += fieldDef->mName;
  7079. }
  7080. }
  7081. }
  7082. methodText += "\x1)";
  7083. }
  7084. else
  7085. {
  7086. BfMethodInstance* methodInstance = NULL;
  7087. if (methodEntry.mMethodDef->mIdx < 0)
  7088. {
  7089. for (auto localMethod : mContext->mLocalMethodGraveyard)
  7090. {
  7091. if (localMethod->mMethodDef == methodEntry.mMethodDef)
  7092. {
  7093. methodInstance = localMethod->mMethodInstanceGroup->mDefault;
  7094. break;
  7095. }
  7096. }
  7097. }
  7098. else
  7099. methodInstance = bfModule->GetRawMethodInstanceAtIdx(methodEntry.mTypeInstance, methodEntry.mMethodDef->mIdx);
  7100. auto curMethodInstance = methodInstance;
  7101. curMethodInstance = methodMatchInfo->mCurMethodInstance;
  7102. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(bfModule->mCurTypeInstance, methodMatchInfo->mCurTypeInstance);
  7103. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(bfModule->mCurMethodInstance, curMethodInstance);
  7104. Array<String> genericMethodNameOverrides;
  7105. Array<String>* genericMethodNameOverridesPtr = NULL;
  7106. if (methodInstance->GetNumGenericArguments() != 0)
  7107. {
  7108. genericMethodNameOverridesPtr = &genericMethodNameOverrides;
  7109. for (int methodGenericArgIdx = 0; methodGenericArgIdx < (int)methodInstance->GetNumGenericArguments(); methodGenericArgIdx++)
  7110. {
  7111. BfType* methodGenericArg = NULL;
  7112. if (methodEntry.mGenericArguments.size() > 0)
  7113. methodGenericArg = methodEntry.mGenericArguments[methodGenericArgIdx];
  7114. String argName;
  7115. if (methodGenericArg == NULL)
  7116. argName = methodInstance->mMethodDef->mGenericParams[methodGenericArgIdx]->mName;
  7117. else
  7118. argName = bfModule->TypeToString(methodGenericArg, BfTypeNameFlag_ResolveGenericParamNames, NULL);
  7119. genericMethodNameOverrides.push_back(argName);
  7120. }
  7121. }
  7122. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Extension)
  7123. methodText += "(extension) ";
  7124. if (methodInstance->mMethodDef->mMethodType != BfMethodType_Ctor)
  7125. {
  7126. if (methodInstance->mReturnType != NULL)
  7127. methodText += bfModule->TypeToString(methodInstance->mReturnType, BfTypeNameFlag_ResolveGenericParamNames, genericMethodNameOverridesPtr);
  7128. else
  7129. methodText += BfTypeUtils::TypeToString(methodInstance->mMethodDef->mReturnTypeRef);
  7130. methodText += " ";
  7131. }
  7132. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  7133. methodText += "this";
  7134. else
  7135. {
  7136. auto methodName = methodInstance->mMethodDef->mName;
  7137. int splitIdx = (int)methodName.IndexOf('@');
  7138. if (splitIdx != -1)
  7139. methodText += methodName.Substring(0, splitIdx);
  7140. else
  7141. methodText += methodName;
  7142. }
  7143. if (methodInstance->GetNumGenericArguments() != 0)
  7144. {
  7145. methodText += "<";
  7146. for (int methodGenericArgIdx = 0; methodGenericArgIdx < (int)methodInstance->GetNumGenericArguments(); methodGenericArgIdx++)
  7147. {
  7148. if (methodGenericArgIdx > 0)
  7149. methodText += ", ";
  7150. methodText += genericMethodNameOverrides[methodGenericArgIdx];
  7151. }
  7152. methodText += ">";
  7153. }
  7154. //TODO: Show default param values also
  7155. methodText += "(\x1";
  7156. if (methodInstance->GetParamCount() == 0)
  7157. {
  7158. // Hm - is this ever useful? Messes up some cases actually
  7159. // If param resolution failed then we need to print the original param def
  7160. /*for (int paramIdx = 0; paramIdx < (int) methodInstance->mMethodDef->mParams.size(); paramIdx++)
  7161. {
  7162. if (paramIdx > 0)
  7163. methodText += ",\x1 ";
  7164. auto paramDef = methodInstance->mMethodDef->mParams[paramIdx];
  7165. methodText += BfTypeUtils::TypeToString(paramDef->mTypeRef);
  7166. methodText += " ";
  7167. methodText += paramDef->mName;
  7168. }*/
  7169. }
  7170. int dispParamIdx = 0;
  7171. StringT<64> paramName;
  7172. for (int paramIdx = 0; paramIdx < (int)methodInstance->GetParamCount(); paramIdx++)
  7173. {
  7174. auto paramKind = methodInstance->GetParamKind(paramIdx);
  7175. if ((paramKind == BfParamKind_ImplicitCapture) || (paramKind == BfParamKind_AppendIdx))
  7176. continue;
  7177. if (dispParamIdx > 0)
  7178. methodText += ",\x1 ";
  7179. if ((paramIdx == 0) && (methodInstance->mMethodDef->mMethodType == BfMethodType_Extension))
  7180. continue;
  7181. auto type = methodInstance->GetParamType(paramIdx);
  7182. BfExpression* paramInitializer = methodInstance->GetParamInitializer(paramIdx);
  7183. if (paramInitializer != NULL)
  7184. methodText += "[";
  7185. if (paramKind == BfParamKind_Params)
  7186. methodText += "params ";
  7187. if (type->IsGenericParam())
  7188. {
  7189. auto genericParamType = (BfGenericParamType*)type;
  7190. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  7191. {
  7192. BfMethodInstance* checkMethodInstance = methodInstance;
  7193. if (checkMethodInstance->GetNumGenericParams() == 0)
  7194. checkMethodInstance = methodEntry.mCurMethodInstance;
  7195. if (genericParamType->mGenericParamIdx < checkMethodInstance->GetNumGenericParams())
  7196. {
  7197. auto genericParamInstance = checkMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  7198. methodText += genericParamInstance->GetGenericParamDef()->mName;
  7199. }
  7200. else
  7201. {
  7202. methodText += StrFormat("@M%d", genericParamType->mGenericParamIdx);
  7203. }
  7204. }
  7205. else
  7206. {
  7207. BfTypeInstance* genericType = methodEntry.mTypeInstance->ToGenericTypeInstance();
  7208. if (genericType == NULL)
  7209. {
  7210. if (methodEntry.mCurMethodInstance != NULL)
  7211. genericType = methodEntry.mCurMethodInstance->GetOwner()->ToGenericTypeInstance();
  7212. }
  7213. if ((genericType != NULL) && (genericParamType->mGenericParamIdx < (int)genericType->mGenericTypeInfo->mGenericParams.size()))
  7214. {
  7215. auto genericParamInstance = genericType->mGenericTypeInfo->mGenericParams[genericParamType->mGenericParamIdx];
  7216. methodText += genericParamInstance->GetGenericParamDef()->mName;
  7217. }
  7218. else
  7219. {
  7220. methodText += StrFormat("@T%d", genericParamType->mGenericParamIdx);
  7221. }
  7222. }
  7223. }
  7224. else
  7225. methodText += bfModule->TypeToString(type, BfTypeNameFlag_ResolveGenericParamNames, genericMethodNameOverridesPtr);
  7226. int namePrefixCount = 0;
  7227. methodInstance->GetParamName(paramIdx, paramName, namePrefixCount);
  7228. if (!paramName.IsEmpty())
  7229. {
  7230. methodText += " ";
  7231. for (int i = 0; i < namePrefixCount; i++)
  7232. methodText += "@";
  7233. methodText += paramName;
  7234. }
  7235. if (paramInitializer != NULL)
  7236. {
  7237. methodText += " = ";
  7238. methodText += paramInitializer->ToString();
  7239. methodText += "]";
  7240. }
  7241. dispParamIdx++;
  7242. }
  7243. methodText += "\x1)";
  7244. }
  7245. if (methodEntry.mMethodDef != NULL)
  7246. {
  7247. auto methodDeclaration = methodEntry.mMethodDef->GetMethodDeclaration();
  7248. if ((methodDeclaration != NULL) && (methodDeclaration->mDocumentation != NULL))
  7249. {
  7250. String docString;
  7251. methodDeclaration->mDocumentation->GetDocString(docString);
  7252. methodText += "\x03";
  7253. methodText += docString;
  7254. }
  7255. }
  7256. autoCompleteResultString += "invoke\t" + methodText + "\n";
  7257. idx++;
  7258. }
  7259. }
  7260. Array<AutoCompleteEntry*> entries;
  7261. for (auto& entry : autoComplete->mEntriesSet)
  7262. {
  7263. entries.Add(&entry);
  7264. }
  7265. std::sort(entries.begin(), entries.end(), [](AutoCompleteEntry* lhs, AutoCompleteEntry* rhs)
  7266. {
  7267. if (lhs->mScore == rhs->mScore)
  7268. return stricmp(lhs->mDisplay, rhs->mDisplay) < 0;
  7269. return lhs->mScore > rhs->mScore;
  7270. });
  7271. String docString;
  7272. for (auto entry : entries)
  7273. {
  7274. if ((wantsDocEntry != NULL) && (entry->mDocumentation == NULL))
  7275. continue;
  7276. autoCompleteResultString += String(entry->mEntryType);
  7277. autoCompleteResultString += '\t';
  7278. for (int i = 0; i < entry->mNamePrefixCount; i++)
  7279. autoCompleteResultString += '@';
  7280. autoCompleteResultString += String(entry->mDisplay);
  7281. if (entry->mMatchesLength > 0)
  7282. {
  7283. autoCompleteResultString += "\x02";
  7284. for (int i = 0; i < entry->mMatchesLength; i++)
  7285. {
  7286. int match = entry->mMatches[i];
  7287. char buffer[16];
  7288. itoa(match, buffer, 16);
  7289. autoCompleteResultString += String(buffer);
  7290. autoCompleteResultString += ",";
  7291. }
  7292. autoCompleteResultString += "X";
  7293. }
  7294. if (entry->mDocumentation != NULL)
  7295. {
  7296. autoCompleteResultString += '\x03';
  7297. autoCompleteResultString += entry->mDocumentation;
  7298. }
  7299. autoCompleteResultString += '\n';
  7300. }
  7301. }
  7302. }
  7303. struct TypeDefMatchHelper
  7304. {
  7305. public:
  7306. struct SearchEntry
  7307. {
  7308. String mStr;
  7309. int mGenericCount;
  7310. SearchEntry()
  7311. {
  7312. mGenericCount = 0;
  7313. }
  7314. };
  7315. public:
  7316. StringImpl& mResult;
  7317. Array<SearchEntry> mSearch;
  7318. uint32 mFoundFlags;
  7319. int32 mFoundCount;
  7320. bool mHasDotSearch;
  7321. String mCurTypeName;
  7322. String mTempStr;
  7323. public:
  7324. TypeDefMatchHelper(StringImpl& str) : mResult(str)
  7325. {
  7326. mFoundFlags = 0;
  7327. mFoundCount = 0;
  7328. mHasDotSearch = false;
  7329. }
  7330. void Sanitize(StringImpl& str)
  7331. {
  7332. for (int i = 0; i < (int)str.length(); i++)
  7333. {
  7334. char c = str[i];
  7335. if (c < (char)32)
  7336. {
  7337. str[i] = ' ';
  7338. }
  7339. }
  7340. }
  7341. void AddParams(BfMethodDef* methodDef, StringImpl& result)
  7342. {
  7343. int visParamIdx = 0;
  7344. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size(); paramIdx++)
  7345. {
  7346. auto paramDef = methodDef->mParams[paramIdx];
  7347. if ((paramDef->mParamKind == BfParamKind_AppendIdx) || (paramDef->mParamKind == BfParamKind_ImplicitCapture))
  7348. continue;
  7349. if (visParamIdx > 0)
  7350. result += ", ";
  7351. StringT<64> refName;
  7352. paramDef->mTypeRef->ToString(refName);
  7353. Sanitize(refName);
  7354. result += refName;
  7355. result += " ";
  7356. result += paramDef->mName;
  7357. visParamIdx++;
  7358. }
  7359. }
  7360. void AddLocation(BfAstNode* node)
  7361. {
  7362. if (node == NULL)
  7363. return;
  7364. auto parserData = node->GetSourceData()->ToParserData();
  7365. if (parserData != NULL)
  7366. {
  7367. mResult += parserData->mFileName;
  7368. int lineNum = 0;
  7369. int column = 0;
  7370. parserData->GetLineCharAtIdx(node->GetSrcStart(), lineNum, column);
  7371. mResult += StrFormat("\t%d\t%d", lineNum, column);
  7372. }
  7373. };
  7374. void AddFieldDef(BfFieldDef* fieldDef)
  7375. {
  7376. mResult += "\t";
  7377. AddLocation(fieldDef->GetRefNode());
  7378. mResult += "\n";
  7379. }
  7380. void AddPropertyDef(BfTypeDef* typeDef, BfPropertyDef* propDef)
  7381. {
  7382. if (propDef->mName == "[]")
  7383. {
  7384. mResult += "[";
  7385. for (auto methodDef : propDef->mMethods)
  7386. {
  7387. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  7388. {
  7389. AddParams(methodDef, mResult);
  7390. break;
  7391. }
  7392. }
  7393. mResult += "]";
  7394. }
  7395. else
  7396. mResult += propDef->mName;
  7397. mResult += "\t";
  7398. auto refNode = propDef->GetRefNode();
  7399. if (refNode == NULL)
  7400. refNode = typeDef->GetRefNode();
  7401. AddLocation(refNode);
  7402. mResult += "\n";
  7403. }
  7404. void GetGenericStr(BfMethodDef* methodDef, StringImpl& result)
  7405. {
  7406. if (methodDef->mGenericParams.IsEmpty())
  7407. return;
  7408. result += "<";
  7409. for (int i = 0; i < methodDef->mGenericParams.mSize; i++)
  7410. {
  7411. if (i > 0)
  7412. result += ", ";
  7413. result += methodDef->mGenericParams[i]->mName;
  7414. }
  7415. result += ">";
  7416. }
  7417. void GetMethodDefString(BfMethodDef* methodDef, StringImpl& result, int* genericStrIdx = NULL)
  7418. {
  7419. if (methodDef->mMethodType == BfMethodType_Ctor)
  7420. {
  7421. if (methodDef->mIsStatic)
  7422. result += "static ";
  7423. result += "this";
  7424. }
  7425. else if (methodDef->mMethodType == BfMethodType_Dtor)
  7426. {
  7427. if (methodDef->mIsStatic)
  7428. result += "static ";
  7429. result += "~this";
  7430. }
  7431. else
  7432. result += methodDef->mName;
  7433. if (methodDef->mMethodType == BfMethodType_Mixin)
  7434. result += "!";
  7435. if (!methodDef->mGenericParams.IsEmpty())
  7436. {
  7437. if (genericStrIdx != NULL)
  7438. {
  7439. *genericStrIdx = result.mLength;
  7440. }
  7441. else
  7442. {
  7443. GetGenericStr(methodDef, result);
  7444. }
  7445. }
  7446. result += "(";
  7447. AddParams(methodDef, result);
  7448. result += ")";
  7449. }
  7450. void AddMethodDef(BfMethodDef* methodDef, StringImpl* methodDefString = NULL)
  7451. {
  7452. if (methodDefString != NULL)
  7453. mResult += *methodDefString;
  7454. else
  7455. GetMethodDefString(methodDef, mResult);
  7456. mResult += "\t";
  7457. AddLocation(methodDef->GetRefNode());
  7458. mResult += "\n";
  7459. }
  7460. void ClearResults()
  7461. {
  7462. mFoundFlags = 0;
  7463. mFoundCount = 0;
  7464. }
  7465. bool MergeFlags(uint32 flags)
  7466. {
  7467. int flagIdx = 0;
  7468. while (flags > 0)
  7469. {
  7470. if (((flags & 1) != 0) && ((mFoundFlags & (1 << flagIdx)) == 0))
  7471. {
  7472. mFoundFlags |= (1 << flagIdx);
  7473. mFoundCount++;
  7474. }
  7475. flags >>= 1;
  7476. flagIdx++;
  7477. }
  7478. return mFoundCount == mSearch.mSize;
  7479. }
  7480. uint32 CheckMatch(const StringView& str, int startIdx = 0)
  7481. {
  7482. uint32 matchFlags = 0;
  7483. for (int i = startIdx; i < mSearch.mSize; i++)
  7484. {
  7485. auto& search = mSearch[i];
  7486. if (((mFoundFlags & (1 << i)) == 0) && (str.IndexOf(search.mStr, true) != -1))
  7487. {
  7488. bool genericMatches = true;
  7489. if (search.mGenericCount > 0)
  7490. {
  7491. genericMatches = false;
  7492. int countIdx = (int)str.LastIndexOf('`');
  7493. if (countIdx > 0)
  7494. {
  7495. int genericCount = atoi(str.mPtr + countIdx + 1);
  7496. genericMatches = ((genericCount == search.mGenericCount) || (search.mGenericCount == 1)) &&
  7497. (countIdx == (int)search.mStr.length());
  7498. }
  7499. }
  7500. if (genericMatches)
  7501. {
  7502. mFoundCount++;
  7503. matchFlags |= (1 << i);
  7504. mFoundFlags |= (1 << i);
  7505. }
  7506. }
  7507. }
  7508. return matchFlags;
  7509. }
  7510. bool CheckCompletesMatch(BfAtomComposite& name)
  7511. {
  7512. for (int i = 0; i < name.mSize; i++)
  7513. {
  7514. CheckMatch(name.mParts[i]->mString);
  7515. if (mFoundCount == mSearch.mSize)
  7516. return true;
  7517. }
  7518. return false;
  7519. }
  7520. bool IsFullMatch()
  7521. {
  7522. return mFoundCount == mSearch.mSize;
  7523. }
  7524. bool CheckMemberMatch(BfTypeDef* typeDef, const StringView& str)
  7525. {
  7526. if (CheckMatch(str) == 0)
  7527. {
  7528. if (mHasDotSearch)
  7529. {
  7530. mTempStr.Clear();
  7531. mTempStr += mCurTypeName;
  7532. mTempStr += ".";
  7533. mTempStr += str;
  7534. if (CheckMatch(mTempStr) == 0)
  7535. return false;
  7536. }
  7537. else
  7538. return false;
  7539. }
  7540. if ((IsFullMatch()) || (CheckCompletesMatch(typeDef->mFullName)))
  7541. return true;
  7542. return false;
  7543. }
  7544. };
  7545. String BfCompiler::GetTypeDefList(bool includeLocation)
  7546. {
  7547. String result;
  7548. TypeDefMatchHelper matchHelper(result);
  7549. BfProject* curProject = NULL;
  7550. Dictionary<BfProject*, int> projectIds;
  7551. for (auto typeDef : mSystem->mTypeDefs)
  7552. {
  7553. if (typeDef->mProject != curProject)
  7554. {
  7555. curProject = typeDef->mProject;
  7556. int* projectIdPtr;
  7557. if (projectIds.TryAdd(curProject, NULL, &projectIdPtr))
  7558. {
  7559. *projectIdPtr = (int)projectIds.size() - 1;
  7560. result += '+';
  7561. result += curProject->mName;
  7562. result += '\n';
  7563. }
  7564. else
  7565. {
  7566. char str[32];
  7567. sprintf(str, "=%d\n", *projectIdPtr);
  7568. result += str;
  7569. }
  7570. }
  7571. if (((!typeDef->mIsPartial) || (typeDef->mIsCombinedPartial)))
  7572. {
  7573. if (typeDef->IsGlobalsContainer())
  7574. {
  7575. result += 'g';
  7576. if (!typeDef->mNamespace.IsEmpty())
  7577. {
  7578. typeDef->mNamespace.ToString(result);
  7579. result += '.';
  7580. }
  7581. result += ":static\n";
  7582. continue;
  7583. }
  7584. else if (typeDef->mTypeCode == BfTypeCode_Interface)
  7585. result += 'i';
  7586. else if (typeDef->mTypeCode == BfTypeCode_Object)
  7587. result += 'c';
  7588. else
  7589. result += 'v';
  7590. String typeName = BfTypeUtils::TypeToString(typeDef, BfTypeNameFlag_InternalName);
  7591. if (includeLocation)
  7592. {
  7593. result += typeName + "\t";
  7594. matchHelper.AddLocation(typeDef->GetRefNode());
  7595. result += "\n";
  7596. }
  7597. else
  7598. {
  7599. result += typeName + "\n";
  7600. }
  7601. }
  7602. }
  7603. return result;
  7604. }
  7605. String BfCompiler::GetGeneratorString(BfTypeDef* typeDef, BfTypeInstance* typeInst, const StringImpl& generatorMethodName, const StringImpl* args)
  7606. {
  7607. if (typeInst == NULL)
  7608. {
  7609. auto type = mContext->mUnreifiedModule->ResolveTypeDef(typeDef, BfPopulateType_BaseType);
  7610. if (type != NULL)
  7611. typeInst = type->ToTypeInstance();
  7612. if (typeInst == NULL)
  7613. return "";
  7614. }
  7615. BfTypeVector typeVector;
  7616. typeVector.Add(typeInst);
  7617. auto generatorTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompilerGeneratorTypeDef)->ToTypeInstance();
  7618. auto methodDef = generatorTypeInst->mTypeDef->GetMethodByName(generatorMethodName);
  7619. auto moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(generatorTypeInst, methodDef, typeVector);
  7620. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mContext->mUnreifiedModule->mCurMethodInstance, moduleMethodInstance.mMethodInstance);
  7621. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mContext->mUnreifiedModule->mCurTypeInstance, typeInst);
  7622. BfExprEvaluator exprEvaluator(mContext->mUnreifiedModule);
  7623. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(BfEvalExprFlags_Comptime | BfEvalExprFlags_NoCeRebuildFlags);
  7624. SizedArray<BfIRValue, 1> irArgs;
  7625. if (args != NULL)
  7626. irArgs.Add(mContext->mUnreifiedModule->GetStringObjectValue(*args));
  7627. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs, NULL, BfCreateCallFlags_None);
  7628. if (callResult.mValue.IsConst())
  7629. {
  7630. auto stringPtr = mContext->mUnreifiedModule->GetStringPoolString(callResult.mValue, mContext->mUnreifiedModule->mBfIRBuilder);
  7631. if (stringPtr != NULL)
  7632. return *stringPtr;
  7633. }
  7634. return "";
  7635. }
  7636. void BfCompiler::HandleGeneratorErrors(StringImpl& result)
  7637. {
  7638. if ((mPassInstance->mErrors.IsEmpty()) && (mPassInstance->mOutStream.IsEmpty()))
  7639. return;
  7640. result.Clear();
  7641. for (auto& msg : mPassInstance->mOutStream)
  7642. {
  7643. String error = msg;
  7644. error.Replace('\n', '\r');
  7645. result += "!error\t";
  7646. result += error;
  7647. result += "\n";
  7648. }
  7649. }
  7650. String BfCompiler::GetGeneratorTypeDefList()
  7651. {
  7652. String result;
  7653. BfProject* curProject = NULL;
  7654. Dictionary<BfProject*, int> projectIds;
  7655. BfResolvePassData resolvePassData;
  7656. SetAndRestoreValue<BfResolvePassData*> prevResolvePassData(mResolvePassData, &resolvePassData);
  7657. BfPassInstance passInstance(mSystem);
  7658. SetAndRestoreValue<BfPassInstance*> prevPassInstance(mPassInstance, &passInstance);
  7659. for (auto typeDef : mSystem->mTypeDefs)
  7660. {
  7661. if (typeDef->mProject->mDisabled)
  7662. continue;
  7663. if (typeDef->mIsPartial)
  7664. continue;
  7665. auto type = mContext->mUnreifiedModule->ResolveTypeDef(typeDef, BfPopulateType_BaseType);
  7666. if ((type != NULL) && (type->IsTypeInstance()))
  7667. {
  7668. auto typeInst = type->ToTypeInstance();
  7669. if ((typeInst->mBaseType != NULL) && (typeInst->mBaseType->IsInstanceOf(mCompilerGeneratorTypeDef)))
  7670. {
  7671. result += typeDef->mProject->mName;
  7672. result += ":";
  7673. result += BfTypeUtils::TypeToString(typeDef, BfTypeNameFlag_InternalName);
  7674. String nameString = GetGeneratorString(typeDef, typeInst, "GetName", NULL);
  7675. if (!nameString.IsEmpty())
  7676. result += "\t" + nameString;
  7677. result += "\n";
  7678. }
  7679. }
  7680. }
  7681. HandleGeneratorErrors(result);
  7682. return result;
  7683. }
  7684. String BfCompiler::GetGeneratorInitData(const StringImpl& typeName, const StringImpl& args)
  7685. {
  7686. BfResolvePassData resolvePassData;
  7687. SetAndRestoreValue<BfResolvePassData*> prevResolvePassData(mResolvePassData, &resolvePassData);
  7688. BfPassInstance passInstance(mSystem);
  7689. SetAndRestoreValue<BfPassInstance*> prevPassInstance(mPassInstance, &passInstance);
  7690. Array<BfTypeDef*> typeDefs;
  7691. GetTypeDefs(typeName, typeDefs);
  7692. String result;
  7693. for (auto typeDef : typeDefs)
  7694. {
  7695. result += GetGeneratorString(typeDef, NULL, "InitUI", &args);
  7696. if (!result.IsEmpty())
  7697. break;
  7698. }
  7699. HandleGeneratorErrors(result);
  7700. return result;
  7701. }
  7702. String BfCompiler::GetGeneratorGenData(const StringImpl& typeName, const StringImpl& args)
  7703. {
  7704. BfResolvePassData resolvePassData;
  7705. SetAndRestoreValue<BfResolvePassData*> prevResolvePassData(mResolvePassData, &resolvePassData);
  7706. BfPassInstance passInstance(mSystem);
  7707. SetAndRestoreValue<BfPassInstance*> prevPassInstance(mPassInstance, &passInstance);
  7708. Array<BfTypeDef*> typeDefs;
  7709. GetTypeDefs(typeName, typeDefs);
  7710. String result;
  7711. for (auto typeDef : typeDefs)
  7712. {
  7713. result += GetGeneratorString(typeDef, NULL, "Generate", &args);
  7714. if (!result.IsEmpty())
  7715. break;
  7716. }
  7717. HandleGeneratorErrors(result);
  7718. return result;
  7719. }
  7720. String BfCompiler::GetTypeDefMatches(const StringImpl& searchStr, bool includeLocation)
  7721. {
  7722. String result;
  7723. TypeDefMatchHelper matchHelper(result);
  7724. int openParenIdx = -1;
  7725. bool parenHasDot = false;
  7726. //
  7727. {
  7728. int searchIdx = 0;
  7729. while (searchIdx < (int)searchStr.length())
  7730. {
  7731. int spacePos = (int)searchStr.IndexOf(' ', searchIdx);
  7732. String str;
  7733. if (spacePos == -1)
  7734. str = searchStr.Substring(searchIdx);
  7735. else
  7736. str = searchStr.Substring(searchIdx, (int)(spacePos - searchIdx));
  7737. str.Trim();
  7738. TypeDefMatchHelper::SearchEntry searchEntry;
  7739. for (int i = 0; i < (int)str.length(); i++)
  7740. {
  7741. char c = str[i];
  7742. if (c == '<')
  7743. {
  7744. searchEntry.mGenericCount = 1;
  7745. searchEntry.mStr = str.Substring(0, i);
  7746. }
  7747. else if (searchEntry.mGenericCount > 0)
  7748. {
  7749. if (c == ',')
  7750. searchEntry.mGenericCount++;
  7751. }
  7752. }
  7753. if (searchEntry.mStr.IsEmpty())
  7754. searchEntry.mStr = str;
  7755. if (str.Contains('('))
  7756. {
  7757. if (str.Contains('.'))
  7758. parenHasDot = true;
  7759. if (openParenIdx == -1)
  7760. openParenIdx = matchHelper.mSearch.mSize;
  7761. }
  7762. if (!searchEntry.mStr.IsEmpty())
  7763. matchHelper.mSearch.Add(searchEntry);
  7764. if (str.Contains('.'))
  7765. matchHelper.mHasDotSearch = true;
  7766. if (spacePos == -1)
  7767. break;
  7768. searchIdx = spacePos + 1;
  7769. }
  7770. //// We sort from longest to shortest to make sure longer strings match before shorter, which
  7771. //// matters when the shorter string is a subset of the longer string
  7772. //matchHelper.mSearch.Sort([](const String& lhs, const String& rhs)
  7773. // {
  7774. // int lenCmp = (int)(rhs.length() - lhs.length());
  7775. // if (lenCmp != 0)
  7776. // return lenCmp < 0;
  7777. // return lhs < rhs;
  7778. // });
  7779. }
  7780. BfProject* curProject = NULL;
  7781. Dictionary<BfProject*, int> projectIds;
  7782. Dictionary<BfAtom*, int> atomMatchMap;
  7783. struct ProjectInfo
  7784. {
  7785. Dictionary<String, int> matchedNames;
  7786. };
  7787. Array<ProjectInfo> projectInfos;
  7788. projectInfos.Resize(mSystem->mProjects.size());
  7789. String typeName;
  7790. String foundName;
  7791. int partialIdx = 0;
  7792. for (auto typeDef : mSystem->mTypeDefs)
  7793. {
  7794. if (typeDef->mIsPartial)
  7795. continue;
  7796. bool fullyMatchesName = false;
  7797. if (matchHelper.mHasDotSearch)
  7798. {
  7799. matchHelper.mCurTypeName.Clear();
  7800. typeDef->mFullNameEx.ToString(matchHelper.mCurTypeName);
  7801. matchHelper.ClearResults();
  7802. matchHelper.CheckMatch(matchHelper.mCurTypeName);
  7803. fullyMatchesName = matchHelper.IsFullMatch();
  7804. }
  7805. int matchIdx = -1;
  7806. String tempStr;
  7807. if (!fullyMatchesName)
  7808. {
  7809. for (auto fieldDef : typeDef->mFields)
  7810. {
  7811. if (BfNodeIsA<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  7812. continue;
  7813. matchHelper.ClearResults();
  7814. bool hasMatch = false;
  7815. if (matchHelper.CheckMemberMatch(typeDef, fieldDef->mName))
  7816. {
  7817. result += "F";
  7818. if (BfTypeUtils::TypeToString(result, typeDef, (BfTypeNameFlags)(BfTypeNameFlag_HideGlobalName | BfTypeNameFlag_InternalName)))
  7819. result += ".";
  7820. result += fieldDef->mName;
  7821. matchHelper.AddFieldDef(fieldDef);
  7822. }
  7823. }
  7824. for (auto propDef : typeDef->mProperties)
  7825. {
  7826. if (propDef->GetRefNode() == NULL)
  7827. continue;
  7828. matchHelper.ClearResults();
  7829. if (matchHelper.CheckMemberMatch(typeDef, propDef->mName))
  7830. {
  7831. result += "P";
  7832. if (BfTypeUtils::TypeToString(result, typeDef, (BfTypeNameFlags)(BfTypeNameFlag_HideGlobalName | BfTypeNameFlag_InternalName)))
  7833. result += ".";
  7834. matchHelper.AddPropertyDef(typeDef, propDef);
  7835. }
  7836. }
  7837. for (auto methodDef : typeDef->mMethods)
  7838. {
  7839. if ((methodDef->mMethodType != BfMethodType_Normal) &&
  7840. (methodDef->mMethodType != BfMethodType_Mixin) &&
  7841. (methodDef->mMethodType != BfMethodType_Ctor) &&
  7842. (methodDef->mMethodType != BfMethodType_Dtor))
  7843. continue;
  7844. if (methodDef->mMethodDeclaration == NULL)
  7845. continue;
  7846. matchHelper.ClearResults();
  7847. bool matches = matchHelper.CheckMemberMatch(typeDef, methodDef->mName);
  7848. bool hasTypeString = false;
  7849. bool hasMethodString = false;
  7850. int genericMethodParamIdx = -1;
  7851. if ((!matches) && (openParenIdx != -1))
  7852. {
  7853. hasMethodString = true;
  7854. tempStr.Clear();
  7855. if (parenHasDot)
  7856. {
  7857. hasTypeString = true;
  7858. if (BfTypeUtils::TypeToString(tempStr, typeDef, (BfTypeNameFlags)(BfTypeNameFlag_HideGlobalName | BfTypeNameFlag_InternalName)))
  7859. tempStr += ".";
  7860. }
  7861. matchHelper.GetMethodDefString(methodDef, tempStr, &genericMethodParamIdx);
  7862. matchHelper.CheckMatch(tempStr, openParenIdx);
  7863. matches = matchHelper.IsFullMatch();
  7864. }
  7865. if (matches)
  7866. {
  7867. if (methodDef->mIsOverride)
  7868. result += "o";
  7869. else
  7870. result += "M";
  7871. if (!hasTypeString)
  7872. {
  7873. if (BfTypeUtils::TypeToString(result, typeDef, (BfTypeNameFlags)(BfTypeNameFlag_HideGlobalName | BfTypeNameFlag_InternalName)))
  7874. result += ".";
  7875. }
  7876. if (hasMethodString)
  7877. {
  7878. if (genericMethodParamIdx != -1)
  7879. {
  7880. result += StringView(tempStr, 0, genericMethodParamIdx);
  7881. matchHelper.GetGenericStr(methodDef, result);
  7882. result += StringView(tempStr, genericMethodParamIdx);
  7883. tempStr.Clear();
  7884. matchHelper.AddMethodDef(methodDef, &tempStr);
  7885. }
  7886. else
  7887. matchHelper.AddMethodDef(methodDef, &tempStr);
  7888. }
  7889. else
  7890. matchHelper.AddMethodDef(methodDef);
  7891. }
  7892. }
  7893. uint32 matchFlags = 0;
  7894. for (int atomIdx = typeDef->mFullNameEx.mSize - 1; atomIdx >= 0; atomIdx--)
  7895. {
  7896. auto atom = typeDef->mFullNameEx.mParts[atomIdx];
  7897. int* matchesPtr = NULL;
  7898. if (atomMatchMap.TryAdd(atom, NULL, &matchesPtr))
  7899. {
  7900. matchHelper.ClearResults();
  7901. *matchesPtr = matchHelper.CheckMatch(atom->mString);
  7902. }
  7903. if (*matchesPtr != 0)
  7904. {
  7905. if (matchIdx == -1)
  7906. matchIdx = atomIdx;
  7907. matchFlags |= *matchesPtr;
  7908. }
  7909. }
  7910. matchHelper.ClearResults();
  7911. if (!matchHelper.MergeFlags(matchFlags))
  7912. {
  7913. continue;
  7914. }
  7915. }
  7916. if (typeDef->mProject != curProject)
  7917. {
  7918. curProject = typeDef->mProject;
  7919. int* projectIdPtr;
  7920. if (projectIds.TryAdd(curProject, NULL, &projectIdPtr))
  7921. {
  7922. *projectIdPtr = (int)projectIds.size() - 1;
  7923. result += "+";
  7924. result += curProject->mName;
  7925. result += "\n";
  7926. }
  7927. else
  7928. {
  7929. char str[32];
  7930. sprintf(str, "=%d\n", *projectIdPtr);
  7931. result += str;
  7932. }
  7933. }
  7934. typeName = BfTypeUtils::TypeToString(typeDef, BfTypeNameFlag_InternalName);
  7935. if (matchIdx != -1)
  7936. {
  7937. int* matchIdxPtr = 0;
  7938. auto projectInfo = &projectInfos[typeDef->mProject->mIdx];
  7939. int dotCount = 0;
  7940. foundName = typeName;
  7941. for (int i = 0; i < (int)typeName.length(); i++)
  7942. {
  7943. if (typeName[i] == '.')
  7944. {
  7945. if (dotCount == matchIdx)
  7946. {
  7947. foundName.Clear();
  7948. foundName.Append(typeName.c_str(), i);
  7949. break;
  7950. }
  7951. dotCount++;
  7952. }
  7953. }
  7954. if (projectInfo->matchedNames.TryAdd(foundName, NULL, &matchIdxPtr))
  7955. {
  7956. *matchIdxPtr = partialIdx++;
  7957. result += StrFormat(">%d@", matchIdx);
  7958. }
  7959. else
  7960. {
  7961. result += StrFormat("<%d@", *matchIdxPtr);
  7962. }
  7963. }
  7964. else
  7965. {
  7966. result += ":";
  7967. }
  7968. if (typeDef->IsGlobalsContainer())
  7969. {
  7970. result += "g";
  7971. if (!typeDef->mNamespace.IsEmpty())
  7972. {
  7973. typeDef->mNamespace.ToString(result);
  7974. result += ".";
  7975. }
  7976. result += ":static\n";
  7977. continue;
  7978. }
  7979. else if (typeDef->mTypeCode == BfTypeCode_Interface)
  7980. result += "i";
  7981. else if (typeDef->mTypeCode == BfTypeCode_Object)
  7982. result += "c";
  7983. else
  7984. result += "v";
  7985. if (includeLocation)
  7986. {
  7987. result += typeName + "\t";
  7988. matchHelper.AddLocation(typeDef->GetRefNode());
  7989. result += "\n";
  7990. }
  7991. else
  7992. {
  7993. result += typeName + "\n";
  7994. }
  7995. }
  7996. return result;
  7997. }
  7998. void BfCompiler::GetTypeDefs(const StringImpl& inTypeName, Array<BfTypeDef*>& typeDefs)
  7999. {
  8000. BfProject* project = NULL;
  8001. int idx = 0;
  8002. int sep = (int)inTypeName.LastIndexOf(':');
  8003. if (sep != -1)
  8004. {
  8005. int startProjName = (int)inTypeName.LastIndexOf(':', sep - 1) + 1;
  8006. idx = sep + 1;
  8007. project = mSystem->GetProject(inTypeName.Substring(startProjName, sep - startProjName));
  8008. }
  8009. String typeName;
  8010. int genericCount = 0;
  8011. int pendingGenericCount = 0;
  8012. for (; idx < (int)inTypeName.length(); idx++)
  8013. {
  8014. char c = inTypeName[idx];
  8015. if (c == '<')
  8016. genericCount = 1;
  8017. else if (genericCount > 0)
  8018. {
  8019. if (c == ',')
  8020. genericCount++;
  8021. else if (c == '>')
  8022. {
  8023. pendingGenericCount = genericCount;
  8024. genericCount = 0;
  8025. }
  8026. }
  8027. else
  8028. {
  8029. if (pendingGenericCount != 0)
  8030. {
  8031. typeName += StrFormat("`%d", pendingGenericCount);
  8032. pendingGenericCount = 0;
  8033. }
  8034. typeName += c;
  8035. }
  8036. }
  8037. bool isGlobals = false;
  8038. if (typeName == ":static")
  8039. {
  8040. typeName.clear();
  8041. isGlobals = true;
  8042. }
  8043. if (typeName.EndsWith(".:static"))
  8044. {
  8045. typeName.RemoveToEnd(typeName.length() - 8);
  8046. isGlobals = true;
  8047. }
  8048. for (int i = 0; i < (int)typeName.length(); i++)
  8049. if (typeName[i] == '+')
  8050. typeName[i] = '.';
  8051. BfAtomComposite nameComposite;
  8052. if ((typeName.IsEmpty()) || (mSystem->ParseAtomComposite(typeName, nameComposite)))
  8053. {
  8054. auto itr = mSystem->mTypeDefs.TryGet(nameComposite);
  8055. while (itr)
  8056. {
  8057. auto typeDef = *itr;
  8058. if ((!typeDef->mIsPartial) &&
  8059. (typeDef->mProject == project) &&
  8060. (typeDef->mFullName == nameComposite) &&
  8061. (typeDef->IsGlobalsContainer() == isGlobals) &&
  8062. (typeDef->GetSelfGenericParamCount() == pendingGenericCount))
  8063. {
  8064. typeDefs.Add(typeDef);
  8065. }
  8066. itr.MoveToNextHashMatch();
  8067. }
  8068. }
  8069. }
  8070. String BfCompiler::GetTypeDefInfo(const StringImpl& inTypeName)
  8071. {
  8072. Array<BfTypeDef*> typeDefs;
  8073. GetTypeDefs(inTypeName, typeDefs);
  8074. String result;
  8075. TypeDefMatchHelper matchHelper(result);
  8076. for (auto typeDef : typeDefs)
  8077. {
  8078. auto refNode = typeDef->GetRefNode();
  8079. result += "S";
  8080. matchHelper.AddLocation(refNode);
  8081. result += "\n";
  8082. for (auto fieldDef : typeDef->mFields)
  8083. {
  8084. result += "F";
  8085. result += fieldDef->mName;
  8086. matchHelper.AddFieldDef(fieldDef);
  8087. }
  8088. for (auto propDef : typeDef->mProperties)
  8089. {
  8090. if (propDef->GetRefNode() == NULL)
  8091. continue;
  8092. result += "P";
  8093. matchHelper.AddPropertyDef(typeDef, propDef);
  8094. }
  8095. for (auto methodDef : typeDef->mMethods)
  8096. {
  8097. if ((methodDef->mMethodType != BfMethodType_Normal) &&
  8098. (methodDef->mMethodType != BfMethodType_Mixin) &&
  8099. (methodDef->mMethodType != BfMethodType_Ctor) &&
  8100. (methodDef->mMethodType != BfMethodType_Dtor))
  8101. continue;
  8102. if (methodDef->mMethodDeclaration == NULL)
  8103. continue;
  8104. result += "M";
  8105. matchHelper.AddMethodDef(methodDef);
  8106. }
  8107. }
  8108. return result;
  8109. }
  8110. int BfCompiler::GetTypeId(const StringImpl& typeName)
  8111. {
  8112. auto type = GetType(typeName);
  8113. if (type != NULL)
  8114. return type->mTypeId;
  8115. return -1;
  8116. }
  8117. BfType* BfCompiler::GetType(const StringImpl& fullTypeName)
  8118. {
  8119. AutoCrit autoCrit(mSystem->mSystemLock);
  8120. BfPassInstance passInstance(mSystem);
  8121. BfProject* activeProject = NULL;
  8122. String typeName = fullTypeName;
  8123. int colonPos = (int)typeName.LastIndexOf(':');
  8124. if (colonPos != -1)
  8125. {
  8126. int startProjName = (int)typeName.LastIndexOf(':', colonPos - 1) + 1;
  8127. activeProject = mSystem->GetProject(typeName.Substring(startProjName, colonPos - startProjName));
  8128. typeName.Remove(0, colonPos + 1);
  8129. }
  8130. BfTypeState typeState;
  8131. typeState.mPrevState = mContext->mCurTypeState;
  8132. typeState.mActiveProject = activeProject;
  8133. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  8134. BfParser parser(mSystem);
  8135. parser.SetSource(typeName.c_str(), (int)typeName.length());
  8136. parser.Parse(&passInstance);
  8137. BfReducer reducer;
  8138. reducer.mAlloc = parser.mAlloc;
  8139. reducer.mPassInstance = &passInstance;
  8140. if (parser.mRootNode->mChildArr.mSize == 0)
  8141. return NULL;
  8142. auto firstNode = parser.mRootNode->mChildArr[0];
  8143. auto endIdx = parser.mRootNode->mSrcEnd;
  8144. reducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8145. reducer.mVisitorPos.MoveNext();
  8146. auto typeRef = reducer.CreateTypeRef(firstNode);
  8147. if (typeRef == NULL)
  8148. return NULL;
  8149. BfResolvePassData resolvePass;
  8150. SetAndRestoreValue<bool> prevIgnoreError(mContext->mScratchModule->mIgnoreErrors, true);
  8151. SetAndRestoreValue<bool> prevIgnoreWarnings(mContext->mScratchModule->mIgnoreWarnings, true);
  8152. SetAndRestoreValue<BfResolvePassData*> prevResolvePass(mResolvePassData, &resolvePass);
  8153. auto type = mContext->mScratchModule->ResolveTypeRef(typeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(
  8154. BfResolveTypeRefFlag_NoCreate | BfResolveTypeRefFlag_AllowUnboundGeneric | BfResolveTypeRefFlag_AllowGlobalContainer));
  8155. if (type != NULL)
  8156. return type;
  8157. return NULL;
  8158. }
  8159. int BfCompiler::GetEmitSource(const StringImpl& fileName, StringImpl* outBuffer)
  8160. {
  8161. int lastDollarPos = (int)fileName.LastIndexOf('$');
  8162. if (lastDollarPos == -1)
  8163. return -1;
  8164. String typeName = fileName.Substring(lastDollarPos + 1);
  8165. int typeId = GetTypeId(typeName);
  8166. if ((typeId <= 0) || (typeId >= mContext->mTypes.mSize))
  8167. return -1;
  8168. auto type = mContext->mTypes[typeId];
  8169. if (type == NULL)
  8170. return -1;
  8171. auto typeInst = type->ToTypeInstance();
  8172. if (typeInst == NULL)
  8173. return -1;
  8174. auto typeDef = typeInst->mTypeDef;
  8175. if (typeDef->mEmitParent == NULL)
  8176. return -1;
  8177. auto emitParser = typeDef->mSource->ToParser();
  8178. if (emitParser == NULL)
  8179. return -1;
  8180. if (outBuffer != NULL)
  8181. outBuffer->Append(emitParser->mSrc, emitParser->mSrcLength);
  8182. return typeInst->mRevision;
  8183. }
  8184. String BfCompiler::GetEmitLocation(const StringImpl& typeName, int emitLine, int& outEmbedLine, int& outEmbedLineChar, uint64& outHash)
  8185. {
  8186. outEmbedLine = 0;
  8187. int typeId = GetTypeId(typeName);
  8188. if (typeId <= 0)
  8189. return "";
  8190. auto bfType = mContext->FindTypeById(typeId);
  8191. if (bfType == NULL)
  8192. return "";
  8193. auto typeInst = bfType->ToTypeInstance();
  8194. if (typeInst == NULL)
  8195. return "";
  8196. if (typeInst->mCeTypeInfo == NULL)
  8197. return "";
  8198. for (auto& kv : typeInst->mCeTypeInfo->mEmitSourceMap)
  8199. {
  8200. int partialIdx = (int)(kv.mKey >> 32);
  8201. int charIdx = (int)(kv.mKey & 0xFFFFFFFF);
  8202. auto typeDef = typeInst->mTypeDef;
  8203. if (partialIdx > 0)
  8204. typeDef = typeDef->mPartials[partialIdx];
  8205. auto origParser = typeDef->GetDefinition()->GetLastSource()->ToParser();
  8206. if (origParser == NULL)
  8207. continue;
  8208. auto emitParser = typeInst->mTypeDef->GetLastSource()->ToParser();
  8209. if (emitParser == NULL)
  8210. continue;
  8211. int startLine = 0;
  8212. int startLineChar = 0;
  8213. emitParser->GetLineCharAtIdx(kv.mValue.mSrcStart, startLine, startLineChar);
  8214. int endLine = 0;
  8215. int endLineChar = 0;
  8216. emitParser->GetLineCharAtIdx(kv.mValue.mSrcEnd - 1, endLine, endLineChar);
  8217. outHash = Hash64(emitParser->mSrc + kv.mValue.mSrcStart, kv.mValue.mSrcEnd - kv.mValue.mSrcStart);
  8218. if ((emitLine >= startLine) && (emitLine <= endLine))
  8219. {
  8220. origParser->GetLineCharAtIdx(charIdx, outEmbedLine, outEmbedLineChar);
  8221. return origParser->mFileName;
  8222. }
  8223. }
  8224. return "";
  8225. }
  8226. bool BfCompiler::WriteEmitData(const StringImpl& filePath, BfProject* project)
  8227. {
  8228. ZipFile zipFile;
  8229. for (auto type : mContext->mResolvedTypes)
  8230. {
  8231. auto typeInst = type->ToTypeInstance();
  8232. if (typeInst == NULL)
  8233. continue;
  8234. if (typeInst->mTypeDef->mEmitParent == NULL)
  8235. continue;
  8236. if (!project->ContainsReference(typeInst->mTypeDef->mProject))
  8237. continue;
  8238. auto bfParser = typeInst->mTypeDef->GetLastSource()->ToParser();
  8239. String name = bfParser->mFileName;
  8240. if (name.StartsWith("$Emit$"))
  8241. name.Remove(0, 6);
  8242. String path = EncodeFileName(name);
  8243. path.Append(".bf");
  8244. if (!zipFile.IsOpen())
  8245. {
  8246. if (!zipFile.Create(filePath))
  8247. return false;
  8248. }
  8249. zipFile.Add(path, Span<uint8>((uint8*)bfParser->mSrc, bfParser->mSrcLength));
  8250. }
  8251. if (zipFile.IsOpen())
  8252. return zipFile.Close();
  8253. return true;
  8254. }
  8255. //////////////////////////////////////////////////////////////////////////
  8256. PerfManager* BfGetPerfManager(BfParser* bfParser);
  8257. /*BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetDefaultTargetTriple(BfCompiler* bfCompiler)
  8258. {
  8259. String& autoCompleteResultString = *gTLStrReturn.Get();
  8260. return autoCompleteResultString.c_str();
  8261. }*/
  8262. BF_EXPORT bool BF_CALLTYPE BfCompiler_Compile(BfCompiler* bfCompiler, BfPassInstance* bfPassInstance, const char* outputPath)
  8263. {
  8264. BP_ZONE("BfCompiler_Compile");
  8265. SetAndRestoreValue<BfPassInstance*> prevPassInstance(bfCompiler->mPassInstance, bfPassInstance);
  8266. bfCompiler->mPassInstance = bfPassInstance;
  8267. bfCompiler->Compile(outputPath);
  8268. return !bfCompiler->mPassInstance->HasFailed();
  8269. }
  8270. BF_EXPORT void BF_CALLTYPE BfCompiler_ClearResults(BfCompiler* bfCompiler)
  8271. {
  8272. bfCompiler->ClearResults();
  8273. }
  8274. BF_EXPORT bool BF_CALLTYPE BfCompiler_ClassifySource(BfCompiler* bfCompiler, BfPassInstance* bfPassInstance, BfResolvePassData* resolvePassData)
  8275. {
  8276. BP_ZONE("BfCompiler_ClassifySource");
  8277. bfCompiler->mSystem->AssertWeHaveLock();
  8278. String& autoCompleteResultString = *gTLStrReturn.Get();
  8279. autoCompleteResultString.clear();
  8280. bfPassInstance->mCompiler = bfCompiler;
  8281. for (auto parser : resolvePassData->mParsers)
  8282. bfPassInstance->mFilterErrorsTo.Add(parser->mSourceData);
  8283. bfPassInstance->mTrimMessagesToCursor = true;
  8284. SetAndRestoreValue<BfResolvePassData*> prevCompilerResolvePassData(bfCompiler->mResolvePassData, resolvePassData);
  8285. SetAndRestoreValue<BfPassInstance*> prevPassInstance(bfCompiler->mPassInstance, bfPassInstance);
  8286. bool canceled = false;
  8287. if ((resolvePassData->mAutoComplete != NULL) && (!resolvePassData->mParsers.IsEmpty()))
  8288. {
  8289. bfCompiler->ProcessAutocompleteTempType();
  8290. }
  8291. else
  8292. canceled = !bfCompiler->Compile("");
  8293. return !canceled;
  8294. }
  8295. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetCollapseRegions(BfCompiler* bfCompiler, BfParser* bfParser, BfResolvePassData* resolvePassData, char* explicitEmitTypeNames)
  8296. {
  8297. bfCompiler->mSystem->AssertWeHaveLock();
  8298. String& outString = *gTLStrReturn.Get();
  8299. outString.Clear();
  8300. class CollapseVisitor : public BfElementVisitor
  8301. {
  8302. public:
  8303. BfAstNode* mParentNode;
  8304. BfParser* mParser;
  8305. String& mOutString;
  8306. HashSet<int> mEndsFound;
  8307. char mSeriesKind;
  8308. int mStartSeriesIdx;
  8309. int mEndSeriesIdx;
  8310. public:
  8311. CollapseVisitor(BfParser* parser, String& string) : mOutString(string)
  8312. {
  8313. mParser = parser;
  8314. mParentNode = NULL;
  8315. mSeriesKind = 0;
  8316. mStartSeriesIdx = -1;
  8317. mEndSeriesIdx = -1;
  8318. }
  8319. void UpdateSeries(BfAstNode* node, char kind)
  8320. {
  8321. if (mStartSeriesIdx != -1)
  8322. {
  8323. if ((node->mTriviaStart != mEndSeriesIdx) || (kind != mSeriesKind))
  8324. {
  8325. FlushSeries();
  8326. mStartSeriesIdx = node->mSrcStart;
  8327. }
  8328. }
  8329. else
  8330. mStartSeriesIdx = node->mSrcStart;
  8331. mSeriesKind = kind;
  8332. mEndSeriesIdx = BF_MIN(node->mSrcEnd, mParser->mSrcLength -1);
  8333. }
  8334. void FlushSeries()
  8335. {
  8336. if (mStartSeriesIdx != -1)
  8337. {
  8338. bool ownsLine = true;
  8339. for (int checkIdx = mStartSeriesIdx - 1; checkIdx >= 0; checkIdx--)
  8340. {
  8341. char c = mParser->mSrc[checkIdx];
  8342. if (c == '\n')
  8343. break;
  8344. if (!isspace((uint8)c))
  8345. {
  8346. ownsLine = false;
  8347. break;
  8348. }
  8349. }
  8350. int anchor = mStartSeriesIdx;
  8351. if (!ownsLine)
  8352. {
  8353. int checkLine = GetLineStartAfter(anchor);
  8354. if (checkLine != -1)
  8355. {
  8356. anchor = checkLine;
  8357. for (; anchor < mEndSeriesIdx; anchor++)
  8358. {
  8359. if (!::isspace((uint8)mParser->mSrc[anchor]))
  8360. break;
  8361. }
  8362. }
  8363. }
  8364. Add(anchor, mEndSeriesIdx, mSeriesKind);
  8365. }
  8366. mStartSeriesIdx = -1;
  8367. }
  8368. int GetLineStartAfter(int startIdx)
  8369. {
  8370. for (int i = startIdx; i < mParser->mSrcLength - 1; i++)
  8371. {
  8372. if (mParser->mSrc[i] == '\n')
  8373. return i + 1;
  8374. }
  8375. return -1;
  8376. }
  8377. int GetLineEndBefore(int startIdx)
  8378. {
  8379. for (int i = startIdx; i >= 1; i--)
  8380. {
  8381. if (mParser->mSrc[i] == '\n')
  8382. return i;
  8383. }
  8384. return -1;
  8385. }
  8386. void Add(int anchor, int end, char kind = '?', int minLines = 2)
  8387. {
  8388. if ((anchor == -1) || (end == -1))
  8389. return;
  8390. if (!mEndsFound.Add(end))
  8391. return;
  8392. int lineCount = 1;
  8393. for (int i = anchor; i < end; i++)
  8394. {
  8395. if (mParser->mSrc[i] == '\n')
  8396. {
  8397. lineCount++;
  8398. if (lineCount >= minLines)
  8399. break;
  8400. }
  8401. }
  8402. if (lineCount < minLines)
  8403. return;
  8404. char str[1024];
  8405. sprintf(str, "%c%d,%d\n", kind, anchor, end);
  8406. mOutString.Append(str);
  8407. }
  8408. void Add(BfAstNode* anchor, BfAstNode* end, char kind = '?', int minLines = 2)
  8409. {
  8410. if ((anchor == NULL) || (end == NULL))
  8411. return;
  8412. Add(anchor->mSrcStart, end->mSrcEnd - 1, kind, minLines);
  8413. }
  8414. virtual void Visit(BfMethodDeclaration* methodDeclaration) override
  8415. {
  8416. int anchorIdx = methodDeclaration->mSrcStart;
  8417. if (methodDeclaration->mNameNode != NULL)
  8418. anchorIdx = methodDeclaration->mNameNode->mSrcEnd - 1;
  8419. if (methodDeclaration->mCloseParen != NULL)
  8420. anchorIdx = methodDeclaration->mCloseParen->mSrcEnd - 1;
  8421. if (methodDeclaration->mBody != NULL)
  8422. Add(anchorIdx, methodDeclaration->mBody->mSrcEnd - 1, 'M');
  8423. BfElementVisitor::Visit(methodDeclaration);
  8424. }
  8425. virtual void Visit(BfNamespaceDeclaration* namespaceDeclaration) override
  8426. {
  8427. Add(namespaceDeclaration->mNamespaceNode, namespaceDeclaration->mBody, 'N');
  8428. BfElementVisitor::Visit(namespaceDeclaration);
  8429. }
  8430. virtual void Visit(BfUsingDirective* usingDirective) override
  8431. {
  8432. UpdateSeries(usingDirective, 'U');
  8433. BfElementVisitor::Visit(usingDirective);
  8434. }
  8435. virtual void Visit(BfTypeDeclaration* typeDeclaration) override
  8436. {
  8437. BfAstNode* anchor = typeDeclaration->mNameNode;
  8438. if (anchor == NULL)
  8439. anchor = typeDeclaration->mStaticSpecifier;
  8440. Add(anchor, typeDeclaration->mDefineNode, 'T');
  8441. BfElementVisitor::Visit(typeDeclaration);
  8442. }
  8443. virtual void Visit(BfPropertyDeclaration* properyDeclaration) override
  8444. {
  8445. Add(properyDeclaration->mNameNode, properyDeclaration->mDefinitionBlock, 'P');
  8446. BfElementVisitor::Visit(properyDeclaration);
  8447. }
  8448. virtual void Visit(BfIndexerDeclaration* indexerDeclaration) override
  8449. {
  8450. Add(indexerDeclaration->mThisToken, indexerDeclaration->mDefinitionBlock, 'P');
  8451. BfElementVisitor::Visit(indexerDeclaration);
  8452. }
  8453. virtual void Visit(BfPropertyMethodDeclaration* methodDeclaration) override
  8454. {
  8455. Add(methodDeclaration->mNameNode, methodDeclaration->mBody);
  8456. BfElementVisitor::Visit(methodDeclaration);
  8457. }
  8458. virtual void Visit(BfIfStatement* ifStatement) override
  8459. {
  8460. Add(ifStatement->mCloseParen, ifStatement->mTrueStatement);
  8461. if (auto elseBlock = BfNodeDynCast<BfBlock>(ifStatement->mFalseStatement))
  8462. Add(ifStatement->mElseToken, elseBlock);
  8463. BfElementVisitor::Visit(ifStatement);
  8464. }
  8465. virtual void Visit(BfRepeatStatement* repeatStatement) override
  8466. {
  8467. Add(repeatStatement->mRepeatToken, repeatStatement);
  8468. if (repeatStatement->mEmbeddedStatement != NULL)
  8469. mEndsFound.Add(repeatStatement->mEmbeddedStatement->mSrcEnd - 1);
  8470. BfElementVisitor::Visit(repeatStatement);
  8471. }
  8472. virtual void Visit(BfWhileStatement* whileStatement) override
  8473. {
  8474. Add(whileStatement->mCloseParen, whileStatement->mEmbeddedStatement);
  8475. BfElementVisitor::Visit(whileStatement);
  8476. }
  8477. virtual void Visit(BfDoStatement* doStatement) override
  8478. {
  8479. Add(doStatement->mDoToken, doStatement->mEmbeddedStatement);
  8480. BfElementVisitor::Visit(doStatement);
  8481. }
  8482. virtual void Visit(BfForStatement* forStatement) override
  8483. {
  8484. Add(forStatement->mCloseParen, forStatement->mEmbeddedStatement);
  8485. BfElementVisitor::Visit(forStatement);
  8486. }
  8487. virtual void Visit(BfForEachStatement* forStatement) override
  8488. {
  8489. Add(forStatement->mCloseParen, forStatement->mEmbeddedStatement);
  8490. BfElementVisitor::Visit(forStatement);
  8491. }
  8492. virtual void Visit(BfUsingStatement* usingStatement) override
  8493. {
  8494. Add(usingStatement->mUsingToken, usingStatement->mEmbeddedStatement);
  8495. BfElementVisitor::Visit(usingStatement);
  8496. }
  8497. virtual void Visit(BfSwitchStatement* switchStatement) override
  8498. {
  8499. Add(switchStatement->mOpenParen, switchStatement->mCloseBrace);
  8500. BfElementVisitor::Visit(switchStatement);
  8501. }
  8502. virtual void Visit(BfLambdaBindExpression* lambdaExpression) override
  8503. {
  8504. Add(lambdaExpression->mFatArrowToken, lambdaExpression->mBody);
  8505. BfElementVisitor::Visit(lambdaExpression);
  8506. }
  8507. virtual void Visit(BfBlock* block) override
  8508. {
  8509. Add(block->mOpenBrace, block->mCloseBrace);
  8510. BfElementVisitor::Visit(block);
  8511. }
  8512. virtual void Visit(BfInitializerExpression* initExpr) override
  8513. {
  8514. Add(initExpr->mOpenBrace, initExpr->mCloseBrace);
  8515. BfElementVisitor::Visit(initExpr);
  8516. }
  8517. virtual void Visit(BfInvocationExpression* invocationExpr) override
  8518. {
  8519. Add(invocationExpr->mOpenParen, invocationExpr->mCloseParen, '?', 3);
  8520. BfElementVisitor::Visit(invocationExpr);
  8521. }
  8522. };
  8523. CollapseVisitor collapseVisitor(bfParser, outString);
  8524. collapseVisitor.VisitChild(bfParser->mRootNode);
  8525. BfAstNode* condStart = NULL;
  8526. BfAstNode* regionStart = NULL;
  8527. BfPreprocessorNode* prevPreprocessorNode = NULL;
  8528. int ignoredSectionStart = -1;
  8529. if (bfParser->mSidechannelRootNode != NULL)
  8530. {
  8531. for (auto element : bfParser->mSidechannelRootNode->mChildArr)
  8532. {
  8533. if (auto preprocessorNode = BfNodeDynCast<BfPreprocessorNode>(element))
  8534. {
  8535. if ((ignoredSectionStart != -1) && (prevPreprocessorNode != NULL) && (prevPreprocessorNode->mCommand != NULL))
  8536. {
  8537. collapseVisitor.Add(prevPreprocessorNode->mCommand->mSrcStart, preprocessorNode->mSrcEnd - 1);
  8538. ignoredSectionStart = -1;
  8539. }
  8540. StringView sv = preprocessorNode->mCommand->ToStringView();
  8541. if (sv == "region")
  8542. regionStart = preprocessorNode->mCommand;
  8543. else if (sv == "endregion")
  8544. {
  8545. if (regionStart != NULL)
  8546. collapseVisitor.Add(regionStart->mSrcStart, preprocessorNode->mCommand->mSrcStart, 'R');
  8547. regionStart = NULL;
  8548. }
  8549. else if (sv == "if")
  8550. {
  8551. condStart = preprocessorNode->mCommand;
  8552. }
  8553. else if (sv == "endif")
  8554. {
  8555. if (condStart != NULL)
  8556. collapseVisitor.Add(condStart->mSrcStart, preprocessorNode->mCommand->mSrcStart);
  8557. condStart = NULL;
  8558. }
  8559. else if ((sv == "else") || (sv == "elif"))
  8560. {
  8561. if (condStart != NULL)
  8562. collapseVisitor.Add(condStart->mSrcStart, collapseVisitor.GetLineEndBefore(preprocessorNode->mSrcStart));
  8563. condStart = preprocessorNode->mCommand;
  8564. }
  8565. prevPreprocessorNode = preprocessorNode;
  8566. }
  8567. if (auto preprocessorNode = BfNodeDynCast<BfPreprocesorIgnoredSectionNode>(element))
  8568. {
  8569. if (ignoredSectionStart == -1)
  8570. {
  8571. for (int i = preprocessorNode->mSrcStart; i < preprocessorNode->mSrcEnd - 1; i++)
  8572. {
  8573. if (bfParser->mSrc[i] == '\n')
  8574. {
  8575. ignoredSectionStart = i + 1;
  8576. break;
  8577. }
  8578. }
  8579. }
  8580. }
  8581. char kind = 0;
  8582. if (auto commentNode = BfNodeDynCast<BfCommentNode>(element))
  8583. {
  8584. collapseVisitor.UpdateSeries(commentNode, 'C');
  8585. }
  8586. }
  8587. }
  8588. collapseVisitor.FlushSeries();
  8589. Array<BfTypeInstance*> explicitEmitTypes;
  8590. String checkStr = explicitEmitTypeNames;
  8591. for (auto typeName : checkStr.Split('\n'))
  8592. {
  8593. if (typeName.IsEmpty())
  8594. continue;
  8595. auto bfType = bfCompiler->GetType(typeName);
  8596. if ((bfType != NULL) && (bfType->IsTypeInstance()))
  8597. explicitEmitTypes.Add(bfType->ToTypeInstance());
  8598. }
  8599. // Embed emit info
  8600. BfPassInstance bfPassInstance(bfCompiler->mSystem);
  8601. SetAndRestoreValue<BfResolvePassData*> prevCompilerResolvePassData(bfCompiler->mResolvePassData, resolvePassData);
  8602. SetAndRestoreValue<BfPassInstance*> prevPassInstance(bfCompiler->mPassInstance, &bfPassInstance);
  8603. HashSet<BfTypeDef*> typeHashSet;
  8604. for (auto typeDef : bfParser->mTypeDefs)
  8605. typeHashSet.Add(typeDef);
  8606. Dictionary<int, int> foundTypeIds;
  8607. struct _EmitSource
  8608. {
  8609. BfParser* mEmitParser;
  8610. bool mIsPrimary;
  8611. };
  8612. Dictionary<BfTypeDef*, Dictionary<int, _EmitSource>> emitLocMap;
  8613. bool mayHaveMissedEmits = false;
  8614. for (auto type : bfCompiler->mContext->mResolvedTypes)
  8615. {
  8616. auto typeInst = type->ToTypeInstance();
  8617. if (typeInst == NULL)
  8618. continue;
  8619. if (typeHashSet.Contains(typeInst->mTypeDef->GetDefinition()->GetLatest()))
  8620. {
  8621. if (typeInst->mCeTypeInfo == NULL)
  8622. continue;
  8623. if ((typeInst->mCeTypeInfo->mMayHaveUniqueEmitLocations) && (!mayHaveMissedEmits))
  8624. {
  8625. outString += "~\n";
  8626. mayHaveMissedEmits = true;
  8627. }
  8628. for (auto& kv : typeInst->mCeTypeInfo->mEmitSourceMap)
  8629. {
  8630. int partialIdx = (int)(kv.mKey >> 32);
  8631. int charIdx = (int)(kv.mKey & 0xFFFFFFFF);
  8632. auto typeDef = typeInst->mTypeDef;
  8633. if (partialIdx > 0)
  8634. typeDef = typeDef->mPartials[partialIdx];
  8635. auto emitParser = typeInst->mTypeDef->GetLastSource()->ToParser();
  8636. Dictionary<int, _EmitSource>* map = NULL;
  8637. emitLocMap.TryAdd(typeDef->GetDefinition()->GetLatest(), NULL, &map);
  8638. _EmitSource emitSource;
  8639. emitSource.mEmitParser = emitParser;
  8640. emitSource.mIsPrimary = false;
  8641. (*map)[charIdx] = emitSource;
  8642. }
  8643. }
  8644. }
  8645. for (auto typeDef : bfParser->mTypeDefs)
  8646. {
  8647. auto useTypeDef = typeDef;
  8648. if (useTypeDef->mIsPartial)
  8649. {
  8650. useTypeDef = bfCompiler->mSystem->GetCombinedPartial(useTypeDef);
  8651. if (useTypeDef == NULL)
  8652. continue;
  8653. }
  8654. auto _GetTypeEmbedId = [&](BfTypeInstance* typeInst, BfParser* emitParser)
  8655. {
  8656. int* keyPtr = NULL;
  8657. int* valuePtr = NULL;
  8658. if (foundTypeIds.TryAdd(typeInst->mTypeId, &keyPtr, &valuePtr))
  8659. {
  8660. *valuePtr = foundTypeIds.mCount - 1;
  8661. outString += "+";
  8662. if ((emitParser == NULL) || (!emitParser->mIsEmitted))
  8663. {
  8664. outString += bfCompiler->mContext->mScratchModule->TypeToString(typeInst, BfTypeNameFlag_AddProjectName);
  8665. }
  8666. else
  8667. {
  8668. int dollarPos = (int)emitParser->mFileName.LastIndexOf('$');
  8669. if (dollarPos != -1)
  8670. outString += emitParser->mFileName.Substring(dollarPos + 1);
  8671. }
  8672. outString += "\n";
  8673. }
  8674. return *valuePtr;
  8675. };
  8676. auto type = bfCompiler->mContext->mScratchModule->ResolveTypeDef(useTypeDef);
  8677. if (type == NULL)
  8678. continue;
  8679. if (auto typeInst = type->ToTypeInstance())
  8680. {
  8681. auto origTypeInst = typeInst;
  8682. for (auto checkIdx = explicitEmitTypes.mSize - 1; checkIdx >= 0; checkIdx--)
  8683. {
  8684. auto checkType = explicitEmitTypes[checkIdx];
  8685. if (checkType->mTypeDef->GetDefinition()->GetLatest() == typeInst->mTypeDef->GetDefinition()->GetLatest())
  8686. {
  8687. typeInst = checkType;
  8688. bfCompiler->mContext->mScratchModule->PopulateType(typeInst);
  8689. break;
  8690. }
  8691. }
  8692. if (typeInst->mCeTypeInfo != NULL)
  8693. {
  8694. for (auto& kv : typeInst->mCeTypeInfo->mEmitSourceMap)
  8695. {
  8696. int partialIdx = (int)(kv.mKey >> 32);
  8697. int charIdx = (int)(kv.mKey & 0xFFFFFFFF);
  8698. auto typeDef = typeInst->mTypeDef;
  8699. if (partialIdx > 0)
  8700. typeDef = typeDef->mPartials[partialIdx];
  8701. auto parser = typeDef->GetDefinition()->GetLastSource()->ToParser();
  8702. if (parser == NULL)
  8703. continue;
  8704. if (!FileNameEquals(parser->mFileName, bfParser->mFileName))
  8705. continue;
  8706. auto bfParser = typeDef->GetLastSource()->ToParser();
  8707. auto emitParser = typeInst->mTypeDef->GetLastSource()->ToParser();
  8708. if (emitParser == NULL)
  8709. continue;
  8710. Dictionary<int, _EmitSource>* map = NULL;
  8711. if (emitLocMap.TryGetValue(typeDef->GetDefinition(), &map))
  8712. {
  8713. _EmitSource emitSource;
  8714. emitSource.mEmitParser = emitParser;
  8715. emitSource.mIsPrimary = true;
  8716. (*map)[charIdx] = emitSource;
  8717. }
  8718. int startLine = 0;
  8719. int startLineChar = 0;
  8720. if (kv.mValue.mSrcStart >= 0)
  8721. emitParser->GetLineCharAtIdx(kv.mValue.mSrcStart, startLine, startLineChar);
  8722. int srcEnd = kv.mValue.mSrcEnd - 1;
  8723. while (srcEnd >= kv.mValue.mSrcStart)
  8724. {
  8725. char c = emitParser->mSrc[srcEnd];
  8726. if (!::isspace((uint8)c))
  8727. break;
  8728. srcEnd--;
  8729. }
  8730. int embedId = _GetTypeEmbedId(typeInst, emitParser);
  8731. if (embedId == -1)
  8732. continue;
  8733. int endLine = 0;
  8734. int endLineChar = 0;
  8735. if (srcEnd >= 0)
  8736. emitParser->GetLineCharAtIdx(srcEnd, endLine, endLineChar);
  8737. int textVersion = -1;
  8738. auto declParser = typeInst->mTypeDef->mTypeDeclaration->GetParser();
  8739. if (declParser != NULL)
  8740. textVersion = declParser->mTextVersion;
  8741. char emitChar = (kv.mValue.mKind == BfCeTypeEmitSourceKind_Type) ? 't' : 'm';
  8742. outString += StrFormat("%c%d,%d,%d,%d,%d\n", emitChar, embedId, charIdx, startLine, endLine + 1, textVersion);
  8743. }
  8744. }
  8745. if (typeInst->IsGenericTypeInstance())
  8746. {
  8747. String emitName;
  8748. auto _CheckTypeDef = [&](BfTypeDef* typeDef)
  8749. {
  8750. auto parser = typeDef->GetDefinition()->GetLastSource()->ToParser();
  8751. if (parser == NULL)
  8752. return;
  8753. if (!FileNameEquals(parser->mFileName, bfParser->mFileName))
  8754. return;
  8755. Dictionary<int, _EmitSource>* map = NULL;
  8756. if (emitLocMap.TryGetValue(typeDef, &map))
  8757. {
  8758. for (auto& kv : *map)
  8759. {
  8760. if (kv.mValue.mIsPrimary)
  8761. continue;
  8762. int embedId = _GetTypeEmbedId(typeInst, NULL);
  8763. if (embedId == -1)
  8764. continue;
  8765. char emitChar = 't';
  8766. outString += StrFormat("%c%d,%d,%d,%d,%d\n", emitChar, embedId, kv.mKey, 0, 0, -1);
  8767. }
  8768. }
  8769. };
  8770. _CheckTypeDef(typeInst->mTypeDef->GetDefinition());
  8771. for (auto partialTypeDef : typeInst->mTypeDef->mPartials)
  8772. _CheckTypeDef(partialTypeDef);
  8773. }
  8774. }
  8775. }
  8776. return outString.c_str();
  8777. }
  8778. BF_EXPORT bool BF_CALLTYPE BfCompiler_VerifyTypeName(BfCompiler* bfCompiler, char* name, int cursorPos)
  8779. {
  8780. bfCompiler->mSystem->AssertWeHaveLock();
  8781. String typeName = name;
  8782. auto system = bfCompiler->mSystem;
  8783. AutoCrit autoCrit(system->mSystemLock);
  8784. String& autoCompleteResultString = *gTLStrReturn.Get();
  8785. autoCompleteResultString.Clear();
  8786. BfPassInstance passInstance(bfCompiler->mSystem);
  8787. BfParser parser(bfCompiler->mSystem);
  8788. parser.SetSource(typeName.c_str(), (int)typeName.length());
  8789. parser.Parse(&passInstance);
  8790. parser.mCursorIdx = cursorPos;
  8791. parser.mCursorCheckIdx = cursorPos;
  8792. BfReducer reducer;
  8793. reducer.mAlloc = parser.mAlloc;
  8794. reducer.mPassInstance = &passInstance;
  8795. reducer.mAllowTypeWildcard = true;
  8796. if (parser.mRootNode->mChildArr.mSize == 0)
  8797. return false;
  8798. bool attribWasClosed = false;
  8799. bool isAttributeRef = false;
  8800. auto firstNode = parser.mRootNode->mChildArr[0];
  8801. auto endIdx = parser.mRootNode->mSrcEnd;
  8802. reducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8803. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(firstNode))
  8804. {
  8805. if (tokenNode->mToken == BfToken_LBracket)
  8806. {
  8807. if (auto lastToken = BfNodeDynCast<BfTokenNode>(parser.mRootNode->mChildArr.back()))
  8808. {
  8809. if (lastToken->mToken == BfToken_RBracket)
  8810. {
  8811. attribWasClosed = true;
  8812. endIdx = lastToken->mSrcStart;
  8813. }
  8814. }
  8815. isAttributeRef = true;
  8816. if (parser.mRootNode->mChildArr.mSize < 2)
  8817. return false;
  8818. firstNode = parser.mRootNode->mChildArr[1];
  8819. reducer.mVisitorPos.MoveNext();
  8820. }
  8821. }
  8822. reducer.mVisitorPos.MoveNext();
  8823. auto typeRef = reducer.CreateTypeRef(firstNode);
  8824. if (typeRef == NULL)
  8825. return false;
  8826. BfResolvePassData resolvePassData;
  8827. if (cursorPos != -1)
  8828. {
  8829. resolvePassData.mResolveType = BfResolveType_Autocomplete;
  8830. parser.mParserFlags = (BfParserFlag)(parser.mParserFlags | ParserFlag_Autocomplete);
  8831. resolvePassData.mAutoComplete = new BfAutoComplete();
  8832. resolvePassData.mAutoComplete->mResolveType = BfResolveType_VerifyTypeName;
  8833. resolvePassData.mAutoComplete->mSystem = bfCompiler->mSystem;
  8834. resolvePassData.mAutoComplete->mCompiler = bfCompiler;
  8835. resolvePassData.mAutoComplete->mModule = bfCompiler->mContext->mScratchModule;
  8836. }
  8837. resolvePassData.mParsers.Add(&parser);
  8838. SetAndRestoreValue<BfResolvePassData*> prevCompilerResolvePassData(bfCompiler->mResolvePassData, &resolvePassData);
  8839. SetAndRestoreValue<BfPassInstance*> prevPassInstance(bfCompiler->mPassInstance, &passInstance);
  8840. if (resolvePassData.mAutoComplete != NULL)
  8841. {
  8842. if (isAttributeRef)
  8843. resolvePassData.mAutoComplete->CheckAttributeTypeRef(typeRef);
  8844. else
  8845. resolvePassData.mAutoComplete->CheckTypeRef(typeRef, false);
  8846. bfCompiler->GenerateAutocompleteInfo();
  8847. }
  8848. if (passInstance.HasFailed())
  8849. return false;
  8850. if (typeRef->mSrcEnd != endIdx)
  8851. return false;
  8852. if (!bfCompiler->mContext->mScratchModule->ValidateTypeWildcard(typeRef, isAttributeRef))
  8853. return false;
  8854. if ((isAttributeRef) && (!attribWasClosed))
  8855. return false;
  8856. return true;
  8857. }
  8858. BF_EXPORT void BF_CALLTYPE BfCompiler_ClearCompletionPercentage(BfCompiler* bfCompiler)
  8859. {
  8860. bfCompiler->mCompletionPct = 0;
  8861. }
  8862. BF_EXPORT float BF_CALLTYPE BfCompiler_GetCompletionPercentage(BfCompiler* bfCompiler)
  8863. {
  8864. return bfCompiler->mCompletionPct;
  8865. }
  8866. BF_EXPORT int BF_CALLTYPE BfCompiler_GetCompileRevision(BfCompiler* bfCompiler)
  8867. {
  8868. return bfCompiler->mRevision;
  8869. }
  8870. BF_EXPORT int BF_CALLTYPE BfCompiler_GetCurConstEvalExecuteId(BfCompiler* bfCompiler)
  8871. {
  8872. return bfCompiler->mCurCEExecuteId;
  8873. }
  8874. BF_EXPORT float BF_CALLTYPE BfCompiler_GetLastHadComptimeRebuilds(BfCompiler* bfCompiler)
  8875. {
  8876. return bfCompiler->mLastHadComptimeRebuilds;
  8877. }
  8878. BF_EXPORT void BF_CALLTYPE BfCompiler_Cancel(BfCompiler* bfCompiler)
  8879. {
  8880. bfCompiler->Cancel();
  8881. }
  8882. BF_EXPORT void BF_CALLTYPE BfCompiler_RequestFastFinish(BfCompiler* bfCompiler)
  8883. {
  8884. bfCompiler->RequestFastFinish();
  8885. }
  8886. BF_EXPORT void BF_CALLTYPE BfCompiler_ClearBuildCache(BfCompiler* bfCompiler)
  8887. {
  8888. bfCompiler->ClearBuildCache();
  8889. }
  8890. BF_EXPORT void BF_CALLTYPE BfCompiler_SetBuildValue(BfCompiler* bfCompiler, char* cacheDir, char* key, char* value)
  8891. {
  8892. bfCompiler->mCodeGen.SetBuildValue(cacheDir, key, value);
  8893. }
  8894. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetBuildValue(BfCompiler* bfCompiler, char* cacheDir, char* key)
  8895. {
  8896. String& outString = *gTLStrReturn.Get();
  8897. outString = bfCompiler->mCodeGen.GetBuildValue(cacheDir, key);
  8898. return outString.c_str();
  8899. }
  8900. BF_EXPORT void BF_CALLTYPE BfCompiler_WriteBuildCache(BfCompiler* bfCompiler, char* cacheDir)
  8901. {
  8902. bfCompiler->mCodeGen.WriteBuildCache(cacheDir);
  8903. }
  8904. BF_EXPORT void BF_CALLTYPE BfCompiler_Delete(BfCompiler* bfCompiler)
  8905. {
  8906. delete bfCompiler;
  8907. }
  8908. BF_EXPORT void BF_CALLTYPE BfCompiler_ProgramDone()
  8909. {
  8910. #ifdef BF_PLATFORM_WINDOWS
  8911. BeLibManager::Get()->Clear();
  8912. #endif
  8913. }
  8914. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetGeneratorTypeDefList(BfCompiler* bfCompiler)
  8915. {
  8916. String& outString = *gTLStrReturn.Get();
  8917. outString.clear();
  8918. outString = bfCompiler->GetGeneratorTypeDefList();
  8919. return outString.c_str();
  8920. }
  8921. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetGeneratorInitData(BfCompiler* bfCompiler, char* typeDefName, char* args)
  8922. {
  8923. String& outString = *gTLStrReturn.Get();
  8924. outString.clear();
  8925. outString = bfCompiler->GetGeneratorInitData(typeDefName, args);
  8926. return outString.c_str();
  8927. }
  8928. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetGeneratorGenData(BfCompiler* bfCompiler, char* typeDefName, char* args)
  8929. {
  8930. String& outString = *gTLStrReturn.Get();
  8931. outString.clear();
  8932. outString = bfCompiler->GetGeneratorGenData(typeDefName, args);
  8933. return outString.c_str();
  8934. }
  8935. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetTypeDefList(BfCompiler* bfCompiler, bool includeLocation)
  8936. {
  8937. String& outString = *gTLStrReturn.Get();
  8938. outString.clear();
  8939. outString = bfCompiler->GetTypeDefList(includeLocation);
  8940. return outString.c_str();
  8941. }
  8942. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetTypeDefMatches(BfCompiler* bfCompiler, const char* searchStr, bool includeLocation)
  8943. {
  8944. String& outString = *gTLStrReturn.Get();
  8945. outString.clear();
  8946. outString = bfCompiler->GetTypeDefMatches(searchStr, includeLocation);
  8947. return outString.c_str();
  8948. }
  8949. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetTypeDefInfo(BfCompiler* bfCompiler, const char* typeDefName)
  8950. {
  8951. String& outString = *gTLStrReturn.Get();
  8952. outString.clear();
  8953. outString = bfCompiler->GetTypeDefInfo(typeDefName);
  8954. return outString.c_str();
  8955. }
  8956. BF_EXPORT int BF_CALLTYPE BfCompiler_GetTypeId(BfCompiler* bfCompiler, const char* name)
  8957. {
  8958. return bfCompiler->GetTypeId(name);
  8959. }
  8960. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetTypeInfo(BfCompiler* bfCompiler, const char* name)
  8961. {
  8962. bfCompiler->mSystem->AssertWeHaveLock();
  8963. String& outString = *gTLStrReturn.Get();
  8964. outString = "";
  8965. String typeName = name;
  8966. auto system = bfCompiler->mSystem;
  8967. AutoCrit autoCrit(system->mSystemLock);
  8968. String& autoCompleteResultString = *gTLStrReturn.Get();
  8969. autoCompleteResultString.Clear();
  8970. BfPassInstance passInstance(bfCompiler->mSystem);
  8971. BfParser parser(bfCompiler->mSystem);
  8972. parser.SetSource(typeName.c_str(), (int)typeName.length());
  8973. parser.Parse(&passInstance);
  8974. BfReducer reducer;
  8975. reducer.mAlloc = parser.mAlloc;
  8976. reducer.mPassInstance = &passInstance;
  8977. reducer.mAllowTypeWildcard = true;
  8978. if (parser.mRootNode->mChildArr.mSize == 0)
  8979. return "";
  8980. bool attribWasClosed = false;
  8981. bool isAttributeRef = false;
  8982. auto firstNode = parser.mRootNode->mChildArr[0];
  8983. auto endIdx = parser.mRootNode->mSrcEnd;
  8984. reducer.mVisitorPos = BfReducer::BfVisitorPos(parser.mRootNode);
  8985. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(firstNode))
  8986. {
  8987. if (tokenNode->mToken == BfToken_LBracket)
  8988. {
  8989. if (auto lastToken = BfNodeDynCast<BfTokenNode>(parser.mRootNode->mChildArr.back()))
  8990. {
  8991. if (lastToken->mToken == BfToken_RBracket)
  8992. {
  8993. attribWasClosed = true;
  8994. endIdx = lastToken->mSrcStart;
  8995. }
  8996. }
  8997. isAttributeRef = true;
  8998. if (parser.mRootNode->mChildArr.mSize < 2)
  8999. return "";
  9000. firstNode = parser.mRootNode->mChildArr[1];
  9001. reducer.mVisitorPos.MoveNext();
  9002. }
  9003. }
  9004. reducer.mVisitorPos.MoveNext();
  9005. auto typeRef = reducer.CreateTypeRef(firstNode);
  9006. if (typeRef == NULL)
  9007. return "";
  9008. BfResolvePassData resolvePass;
  9009. SetAndRestoreValue<bool> prevIgnoreError(bfCompiler->mContext->mScratchModule->mIgnoreErrors, true);
  9010. SetAndRestoreValue<bool> prevIgnoreWarnings(bfCompiler->mContext->mScratchModule->mIgnoreWarnings, true);
  9011. SetAndRestoreValue<BfResolvePassData*> prevResolvePass(bfCompiler->mResolvePassData, &resolvePass);
  9012. auto type = bfCompiler->mContext->mScratchModule->ResolveTypeRef(typeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_NoCreate);
  9013. if (type != NULL)
  9014. {
  9015. bfCompiler->mContext->mScratchModule->PopulateType(type);
  9016. outString += "Found";
  9017. if (auto typeInst = type->ToTypeInstance())
  9018. {
  9019. if (typeInst->mIsReified)
  9020. outString += " Reified";
  9021. if (typeInst->HasBeenInstantiated())
  9022. outString += " Instantiated";
  9023. if (typeInst->mTypeFailed)
  9024. outString += " TypeFailed";
  9025. if (auto genericTypeInst = typeInst->ToGenericTypeInstance())
  9026. {
  9027. if (genericTypeInst->mGenericTypeInfo->mHadValidateErrors)
  9028. outString += " ValidateErrors";
  9029. }
  9030. }
  9031. }
  9032. return outString.c_str();
  9033. }
  9034. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetGenericTypeInstances(BfCompiler* bfCompiler, const char* typeName)
  9035. {
  9036. String& outString = *gTLStrReturn.Get();
  9037. outString = "";
  9038. String checkTypeName = typeName;
  9039. auto lookupType = bfCompiler->GetType(checkTypeName);
  9040. if (lookupType == NULL)
  9041. {
  9042. // Convert potentially-specialized type name into an unspecialized type name
  9043. int chevronDepth = 0;
  9044. int chevronStart = -1;
  9045. for (int i = 0; i < (int)checkTypeName.mLength; i++)
  9046. {
  9047. char c = checkTypeName[i];
  9048. if (c == '<')
  9049. {
  9050. if (chevronDepth == 0)
  9051. chevronStart = i;
  9052. chevronDepth++;
  9053. }
  9054. else if (c == '>')
  9055. {
  9056. chevronDepth--;
  9057. if (chevronDepth == 0)
  9058. {
  9059. checkTypeName.Remove(chevronStart + 1, i - chevronStart - 1);
  9060. i = chevronStart + 1;
  9061. }
  9062. }
  9063. }
  9064. lookupType = bfCompiler->GetType(checkTypeName);
  9065. if (lookupType == NULL)
  9066. return "";
  9067. }
  9068. auto lookupTypeInst = lookupType->ToTypeInstance();
  9069. if (lookupTypeInst == NULL)
  9070. return "";
  9071. for (auto type : bfCompiler->mContext->mResolvedTypes)
  9072. {
  9073. auto typeInst = type->ToTypeInstance();
  9074. if (typeInst == NULL)
  9075. continue;
  9076. if (typeInst->IsUnspecializedTypeVariation())
  9077. continue;
  9078. if (typeInst->mTypeDef->GetDefinition()->GetLatest() == lookupTypeInst->mTypeDef->GetDefinition()->GetLatest())
  9079. {
  9080. outString += bfCompiler->mContext->mScratchModule->TypeToString(typeInst, BfTypeNameFlag_AddProjectName);
  9081. outString += "\n";
  9082. }
  9083. }
  9084. return outString.c_str();
  9085. }
  9086. enum BfUsedOutputFlags
  9087. {
  9088. BfUsedOutputFlags_None = 0,
  9089. BfUsedOutputFlags_FlushQueuedHotFiles = 1,
  9090. BfUsedOutputFlags_SkipImports = 2,
  9091. };
  9092. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetUsedOutputFileNames(BfCompiler* bfCompiler, BfProject* bfProject, BfUsedOutputFlags flags, bool* hadOutputChanges)
  9093. {
  9094. bfCompiler->mSystem->AssertWeHaveLock();
  9095. BP_ZONE("BfCompiler_GetUsedOutputFileNames");
  9096. *hadOutputChanges = false;
  9097. String& outString = *gTLStrReturn.Get();
  9098. outString.clear();
  9099. Array<BfModule*> moduleList;
  9100. moduleList.Reserve(bfProject->mUsedModules.size());
  9101. if (bfCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  9102. {
  9103. for (auto mainModule : bfCompiler->mContext->mModules)
  9104. {
  9105. if ((!mainModule->mIsReified) || (mainModule->mIsScratchModule))
  9106. continue;
  9107. if (bfCompiler->mOptions.mHotProject != NULL)
  9108. continue; // Only add new objs from mCodeGen.mCodeGenFiles during hot reload
  9109. if (!bfCompiler->IsModuleAccessible(mainModule, bfProject))
  9110. continue;
  9111. moduleList.push_back(mainModule);
  9112. }
  9113. }
  9114. else
  9115. {
  9116. for (auto mainModule : bfProject->mUsedModules)
  9117. {
  9118. if ((!mainModule->mIsReified) || (mainModule->mIsScratchModule))
  9119. continue;
  9120. if (bfCompiler->mOptions.mHotProject != NULL)
  9121. continue; // Only add new objs from mCodeGen.mCodeGenFiles during hot reload
  9122. moduleList.push_back(mainModule);
  9123. }
  9124. }
  9125. std::sort(moduleList.begin(), moduleList.end(), [&](BfModule* moduleA, BfModule* moduleB) { return moduleA->mModuleName < moduleB->mModuleName; } );
  9126. HashSet<String> usedFileNames;
  9127. usedFileNames.Reserve(moduleList.size());
  9128. //for (auto mainModule : moduleList)
  9129. for (int i = 0; i < moduleList.mSize; i++)
  9130. {
  9131. auto mainModule = moduleList[i];
  9132. BF_ASSERT_REL(!mainModule->mIsDeleting);
  9133. BF_ASSERT_REL((mainModule->mRevision > -2) && (mainModule->mRevision < 1000000));
  9134. if ((flags & BfUsedOutputFlags_SkipImports) == 0)
  9135. {
  9136. for (auto fileNameIdx : mainModule->mImportFileNames)
  9137. {
  9138. auto fileName = bfCompiler->mContext->mStringObjectIdMap[fileNameIdx].mString;
  9139. if (!usedFileNames.TryAdd(fileName, NULL))
  9140. continue;
  9141. if (!outString.empty())
  9142. outString += "\n";
  9143. outString += fileName;
  9144. }
  9145. }
  9146. for (auto& moduleFileName : mainModule->mOutFileNames)
  9147. {
  9148. if (!moduleFileName.mModuleWritten)
  9149. continue;
  9150. bool canReference = true;
  9151. for (auto project : moduleFileName.mProjects)
  9152. {
  9153. if (!bfProject->ContainsReference(project))
  9154. canReference = false;
  9155. if (bfProject != project)
  9156. {
  9157. //TODO: What was this for?
  9158. // if (project->mTargetType == BfTargetType_BeefDynLib)
  9159. // canReference = false;
  9160. }
  9161. }
  9162. if (!canReference)
  9163. continue;
  9164. String fileName = moduleFileName.mFileName;
  9165. #ifdef BF_PLATFORM_WINDOWS
  9166. if (moduleFileName.mWroteToLib)
  9167. fileName = BeLibManager::GetLibFilePath(fileName);
  9168. #endif
  9169. if (!usedFileNames.TryAdd(fileName, NULL))
  9170. continue;
  9171. if (!outString.empty())
  9172. outString += "\n";
  9173. outString += fileName;
  9174. }
  9175. }
  9176. if (bfCompiler->mHotState != NULL)
  9177. {
  9178. Array<String> outPaths;
  9179. for (int i = 0; i < (int)bfCompiler->mHotState->mQueuedOutFiles.size(); i++)
  9180. {
  9181. auto& fileEntry = bfCompiler->mHotState->mQueuedOutFiles[i];
  9182. if (fileEntry.mProject != bfProject)
  9183. continue;
  9184. if (!bfCompiler->mHotState->mHotProject->mUsedModules.Contains(fileEntry.mModule))
  9185. continue;
  9186. outPaths.Add(fileEntry.mFileName);
  9187. if ((flags & BfUsedOutputFlags_FlushQueuedHotFiles) != 0)
  9188. {
  9189. bfCompiler->mHotState->mQueuedOutFiles.RemoveAtFast(i);
  9190. i--;
  9191. }
  9192. }
  9193. std::sort(outPaths.begin(), outPaths.end(), [](const String& lhs, const String& rhs) { return lhs < rhs; });
  9194. for (auto& path : outPaths)
  9195. {
  9196. if (!outString.empty())
  9197. outString += "\n";
  9198. outString += path;
  9199. outString += BF_OBJ_EXT;
  9200. }
  9201. }
  9202. for (auto& fileEntry : bfCompiler->mCodeGen.mCodeGenFiles)
  9203. {
  9204. if (fileEntry.mWasCached)
  9205. continue;
  9206. if (!bfProject->ContainsReference(fileEntry.mProject))
  9207. continue;
  9208. *hadOutputChanges = true;
  9209. }
  9210. return outString.c_str();
  9211. }
  9212. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetAutocompleteInfo(BfCompiler* bfCompiler)
  9213. {
  9214. String& autoCompleteResultString = *gTLStrReturn.Get();
  9215. return autoCompleteResultString.c_str();
  9216. }
  9217. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetRebuildFileSet(BfCompiler* bfCompiler)
  9218. {
  9219. String& autoCompleteResultString = *gTLStrReturn.Get();
  9220. for (auto& val : bfCompiler->mRebuildFileSet)
  9221. {
  9222. autoCompleteResultString += val;
  9223. autoCompleteResultString += "\n";
  9224. }
  9225. return autoCompleteResultString.c_str();
  9226. }
  9227. BF_EXPORT void BF_CALLTYPE BfCompiler_FileChanged(BfCompiler* bfCompiler, const char* dirPath)
  9228. {
  9229. bfCompiler->mRebuildChangedFileSet.Add(dirPath);
  9230. }
  9231. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetSymbolReferences(BfCompiler* bfCompiler, BfPassInstance* bfPassInstance, BfResolvePassData* resolvePassData)
  9232. {
  9233. bfCompiler->mSystem->AssertWeHaveLock();
  9234. BP_ZONE("BfCompiler_GetSymbolReferences");
  9235. String& outString = *gTLStrReturn.Get();
  9236. outString.clear();
  9237. SetAndRestoreValue<BfResolvePassData*> prevCompilerResolvePassData(bfCompiler->mResolvePassData, resolvePassData);
  9238. SetAndRestoreValue<BfPassInstance*> prevPassInstance(bfCompiler->mPassInstance, bfPassInstance);
  9239. bfCompiler->GetSymbolReferences();
  9240. std::map<String, String*> sortedParserMap;
  9241. for (auto& parserDataPair : resolvePassData->mFoundSymbolReferencesParserData)
  9242. {
  9243. if (!parserDataPair.mKey->mFileName.Contains('|'))
  9244. sortedParserMap.insert(std::make_pair(parserDataPair.mKey->mFileName, &parserDataPair.mValue));
  9245. }
  9246. for (auto& parserData : sortedParserMap)
  9247. {
  9248. if (!outString.empty())
  9249. outString += "\n";
  9250. outString += parserData.first + "\t" + *(parserData.second);
  9251. }
  9252. return outString.c_str();
  9253. }
  9254. BF_EXPORT bool BF_CALLTYPE BfCompiler_GetHasHotPendingDataChanges(BfCompiler* bfCompiler)
  9255. {
  9256. return (bfCompiler->mHotState != NULL) &&
  9257. ((!bfCompiler->mHotState->mPendingDataChanges.IsEmpty()) || (!bfCompiler->mHotState->mPendingFailedSlottings.IsEmpty()));
  9258. }
  9259. BF_EXPORT void BF_CALLTYPE BfCompiler_HotCommit(BfCompiler* bfCompiler)
  9260. {
  9261. bfCompiler->HotCommit();
  9262. }
  9263. BF_EXPORT void BF_CALLTYPE BfCompiler_HotResolve_Start(BfCompiler* bfCompiler, int flags)
  9264. {
  9265. bfCompiler->HotResolve_Start((BfCompiler::HotResolveFlags)flags);
  9266. }
  9267. BF_EXPORT void BF_CALLTYPE BfCompiler_HotResolve_AddActiveMethod(BfCompiler* bfCompiler, const char* methodName)
  9268. {
  9269. bfCompiler->HotResolve_AddActiveMethod(methodName);
  9270. }
  9271. BF_EXPORT void BF_CALLTYPE BfCompiler_HotResolve_AddDelegateMethod(BfCompiler* bfCompiler, const char* methodName)
  9272. {
  9273. bfCompiler->HotResolve_AddDelegateMethod(methodName);
  9274. }
  9275. // 0: heap, 1: user stated 'not used', 2: user stated 'used'
  9276. BF_EXPORT void BF_CALLTYPE BfCompiler_HotResolve_ReportType(BfCompiler* bfCompiler, int typeId, int usageKind)
  9277. {
  9278. bfCompiler->HotResolve_ReportType(typeId, (BfCompiler::HotTypeFlags)usageKind);
  9279. }
  9280. // 0: heap, 1: user stated 'used', 2: user stated 'not used'
  9281. BF_EXPORT void BF_CALLTYPE BfCompiler_HotResolve_ReportTypeRange(BfCompiler* bfCompiler, const char* typeName, int usageKind)
  9282. {
  9283. //TODO: Implement
  9284. }
  9285. BF_EXPORT const char* BF_CALLTYPE BfCompiler_HotResolve_Finish(BfCompiler* bfCompiler)
  9286. {
  9287. String& outString = *gTLStrReturn.Get();
  9288. outString = bfCompiler->HotResolve_Finish();
  9289. return outString.c_str();
  9290. }
  9291. static BfPlatformType GetPlatform(StringView str)
  9292. {
  9293. while (!str.IsEmpty())
  9294. {
  9295. char c = str[str.mLength - 1];
  9296. if (((c >= '0') && (c <= '9')) || (c == '.'))
  9297. str.RemoveFromEnd(1);
  9298. else
  9299. break;
  9300. }
  9301. bool hasLinux = false;
  9302. for (auto elem : str.Split('-'))
  9303. {
  9304. if (elem == "linux")
  9305. hasLinux = true;
  9306. else if (elem == "windows")
  9307. return BfPlatformType_Windows;
  9308. else if (elem == "macosx")
  9309. return BfPlatformType_macOS;
  9310. else if (elem == "ios")
  9311. return BfPlatformType_iOS;
  9312. else if ((elem == "android") || (elem == "androideabi"))
  9313. return BfPlatformType_Android;
  9314. else if ((elem == "wasm32") || (elem == "wasm64"))
  9315. return BfPlatformType_Wasm;
  9316. }
  9317. if (hasLinux)
  9318. return BfPlatformType_Linux;
  9319. return BfPlatformType_Unknown;
  9320. }
  9321. BF_EXPORT void BF_CALLTYPE BfCompiler_SetOptions(BfCompiler* bfCompiler, BfProject* hotProject, int hotIdx,
  9322. const char* targetTriple, const char* targetCPU, int toolsetType, int simdSetting, int allocStackCount, int maxWorkerThreads,
  9323. BfCompilerOptionFlags optionFlags, char* mallocLinkName, char* freeLinkName)
  9324. {
  9325. BfLogSys(bfCompiler->mSystem, "BfCompiler_SetOptions\n");
  9326. //printf("BfCompiler_SetOptions Threads:%d\n", maxWorkerThreads);
  9327. auto options = &bfCompiler->mOptions;
  9328. options->mErrorString.Clear();
  9329. options->mHotProject = hotProject;
  9330. options->mHotCompileIdx = hotIdx;
  9331. options->mTargetTriple = targetTriple;
  9332. options->mTargetCPU = targetCPU;
  9333. if (options->mTargetTriple.StartsWith("x86_64-"))
  9334. options->mMachineType = BfMachineType_x64;
  9335. else if (options->mTargetTriple.StartsWith("i686-"))
  9336. options->mMachineType = BfMachineType_x86;
  9337. else if ((options->mTargetTriple.StartsWith("arm64")) || (options->mTargetTriple.StartsWith("aarch64")))
  9338. options->mMachineType = BfMachineType_AArch64;
  9339. else if (options->mTargetTriple.StartsWith("armv"))
  9340. options->mMachineType = BfMachineType_ARM;
  9341. else if (options->mTargetTriple.StartsWith("wasm32"))
  9342. options->mMachineType = BfMachineType_Wasm32;
  9343. else if (options->mTargetTriple.StartsWith("wasm64"))
  9344. options->mMachineType = BfMachineType_Wasm64;
  9345. else
  9346. options->mMachineType = BfMachineType_x64; // Default
  9347. options->mPlatformType = GetPlatform(options->mTargetTriple);
  9348. options->mCLongSize = 4;
  9349. if ((options->mMachineType == BfMachineType_AArch64) || (options->mMachineType == BfMachineType_x64))
  9350. {
  9351. if (options->mPlatformType != BfPlatformType_Windows)
  9352. options->mCLongSize = 8;
  9353. }
  9354. bfCompiler->mCodeGen.SetMaxThreads(maxWorkerThreads);
  9355. if (!bfCompiler->mIsResolveOnly)
  9356. {
  9357. bool allowHotSwapping = (optionFlags & BfCompilerOptionFlag_EnableHotSwapping) != 0;
  9358. bool emitDebugInfo = (optionFlags & BfCompilerOptionFlag_EmitDebugInfo) != 0;
  9359. // These settings only matter for code generation, they are not applicable for resolveOnly
  9360. options->mCompileOnDemandKind = BfCompileOnDemandKind_ResolveUnused;
  9361. //options->mCompileOnDemandKind = BfCompileOnDemandKind_AlwaysInclude;
  9362. options->mToolsetType = (BfToolsetType)toolsetType;
  9363. options->mSIMDSetting = (BfSIMDSetting)simdSetting;
  9364. options->mIncrementalBuild = (optionFlags & BfCompilerOptionFlag_IncrementalBuild) != 0;
  9365. options->mWriteIR = (optionFlags & BfCompilerOptionFlag_WriteIR) != 0;
  9366. options->mGenerateObj = (optionFlags & BfCompilerOptionFlag_GenerateOBJ) != 0;
  9367. options->mGenerateBitcode = (optionFlags & BfCompilerOptionFlag_GenerateBitcode) != 0;
  9368. options->mNoFramePointerElim = (optionFlags & BfCompilerOptionFlag_NoFramePointerElim) != 0;
  9369. options->mInitLocalVariables = (optionFlags & BfCompilerOptionFlag_ClearLocalVars) != 0;
  9370. options->mRuntimeChecks = (optionFlags & BfCompilerOptionFlag_RuntimeChecks) != 0;
  9371. options->mEmitDynamicCastCheck = (optionFlags & BfCompilerOptionFlag_EmitDynamicCastCheck) != 0;
  9372. options->mObjectHasDebugFlags = (optionFlags & BfCompilerOptionFlag_EnableObjectDebugFlags) != 0;
  9373. options->mEnableRealtimeLeakCheck = ((optionFlags & BfCompilerOptionFlag_EnableRealtimeLeakCheck) != 0) && options->mObjectHasDebugFlags;
  9374. options->mDebugAlloc = ((optionFlags & BfCompilerOptionFlag_DebugAlloc) != 0) || options->mEnableRealtimeLeakCheck;
  9375. options->mOmitDebugHelpers = (optionFlags & BfCompilerOptionFlag_OmitDebugHelpers) != 0;
  9376. #ifdef _WINDOWS
  9377. // if (options->mToolsetType == BfToolsetType_GNU)
  9378. // {
  9379. // options->mErrorString = "Toolset 'GNU' is not available on this platform. Consider changing 'Workspace/General/Toolset'.";
  9380. // }
  9381. #else
  9382. // if (options->mToolsetType == BfToolsetType_Microsoft)
  9383. // {
  9384. // options->mErrorString = "Toolset 'Microsoft' is not available on this platform. Consider changing 'Workspace/General/Toolset'.";
  9385. // }
  9386. BF_ASSERT(!options->mEnableRealtimeLeakCheck);
  9387. #endif
  9388. options->mEmitObjectAccessCheck = (optionFlags & BfCompilerOptionFlag_EmitObjectAccessCheck) != 0;
  9389. options->mArithmeticChecks = (optionFlags & BfCompilerOptionFlag_ArithmeticChecks) != 0;
  9390. options->mAllocStackCount = allocStackCount;
  9391. if (hotProject != NULL)
  9392. {
  9393. String errorName;
  9394. if (options->mAllowHotSwapping != allowHotSwapping)
  9395. errorName = "Hot Compilation Enabled";
  9396. else if (options->mMallocLinkName != mallocLinkName)
  9397. errorName = "Malloc";
  9398. else if (options->mFreeLinkName != freeLinkName)
  9399. errorName = "Free";
  9400. if (!options->mEmitDebugInfo)
  9401. {
  9402. options->mErrorString = "Hot compilation cannot be used when the target is not built with debug information. Consider setting 'Workspace/Beef/Debug/Debug Information' to 'Yes'.";
  9403. }
  9404. else if (!errorName.IsEmpty())
  9405. {
  9406. options->mErrorString = StrFormat("Unable to change option '%s' during hot compilation", errorName.c_str());
  9407. }
  9408. }
  9409. else
  9410. {
  9411. options->mAllowHotSwapping = allowHotSwapping;
  9412. options->mHasVDataExtender = options->mAllowHotSwapping;
  9413. options->mMallocLinkName = mallocLinkName;
  9414. options->mFreeLinkName = freeLinkName;
  9415. options->mEmitDebugInfo = emitDebugInfo;
  9416. options->mEmitLineInfo = (optionFlags & BfCompilerOptionFlag_EmitLineInfo) != 0;;
  9417. options->mEnableCustodian = (optionFlags & BfCompilerOptionFlag_EnableCustodian) != 0;
  9418. options->mEnableSideStack = (optionFlags & BfCompilerOptionFlag_EnableSideStack) != 0;
  9419. }
  9420. }
  9421. else
  9422. {
  9423. options->mCompileOnDemandKind = BfCompileOnDemandKind_AlwaysInclude;
  9424. options->mAllowHotSwapping = false;
  9425. options->mObjectHasDebugFlags = false;
  9426. options->mEnableRealtimeLeakCheck = false;
  9427. options->mEmitObjectAccessCheck = false;
  9428. options->mArithmeticChecks = false;
  9429. options->mEmitDynamicCastCheck = false;
  9430. options->mRuntimeChecks = (optionFlags & BfCompilerOptionFlag_RuntimeChecks) != 0;
  9431. }
  9432. }
  9433. BF_EXPORT void BF_CALLTYPE BfCompiler_ForceRebuild(BfCompiler* bfCompiler)
  9434. {
  9435. bfCompiler->mOptions.mForceRebuildIdx++;
  9436. }
  9437. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetEmitSource(BfCompiler* bfCompiler, char* fileName)
  9438. {
  9439. String& outString = *gTLStrReturn.Get();
  9440. outString.clear();
  9441. bfCompiler->GetEmitSource(fileName, &outString);
  9442. if (outString.IsEmpty())
  9443. return NULL;
  9444. return outString.c_str();
  9445. }
  9446. BF_EXPORT int32 BF_CALLTYPE BfCompiler_GetEmitSourceVersion(BfCompiler* bfCompiler, char* fileName)
  9447. {
  9448. return bfCompiler->GetEmitSource(fileName, NULL);
  9449. }
  9450. BF_EXPORT const char* BF_CALLTYPE BfCompiler_GetEmitLocation(BfCompiler* bfCompiler, char* typeName, int line, int& outEmbedLine, int& outEmbedLineChar, uint64& outHash)
  9451. {
  9452. String& outString = *gTLStrReturn.Get();
  9453. outString.clear();
  9454. outString = bfCompiler->GetEmitLocation(typeName, line, outEmbedLine, outEmbedLineChar, outHash);
  9455. return outString.c_str();
  9456. }
  9457. BF_EXPORT bool BF_CALLTYPE BfCompiler_WriteEmitData(BfCompiler* bfCompiler, char* filePath, BfProject* project)
  9458. {
  9459. return bfCompiler->WriteEmitData(filePath, project);
  9460. }