checker.cpp 194 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620
  1. #define DEBUG_CHECK_ALL_PROCEDURES 1
  2. #include "entity.cpp"
  3. #include "types.cpp"
  4. String get_final_microarchitecture();
  5. gb_internal void check_expr(CheckerContext *c, Operand *operand, Ast *expression);
  6. gb_internal void check_expr_or_type(CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint=nullptr);
  7. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t);
  8. gb_internal Type *check_type(CheckerContext *ctx, Ast *e);
  9. gb_internal bool is_operand_value(Operand o) {
  10. switch (o.mode) {
  11. case Addressing_Value:
  12. case Addressing_Context:
  13. case Addressing_Variable:
  14. case Addressing_Constant:
  15. case Addressing_MapIndex:
  16. case Addressing_OptionalOk:
  17. case Addressing_OptionalOkPtr:
  18. case Addressing_SoaVariable:
  19. case Addressing_SwizzleValue:
  20. case Addressing_SwizzleVariable:
  21. return true;
  22. }
  23. return false;
  24. }
  25. gb_internal bool is_operand_nil(Operand o) {
  26. return o.mode == Addressing_Value && o.type == t_untyped_nil;
  27. }
  28. gb_internal bool is_operand_uninit(Operand o) {
  29. return o.mode == Addressing_Value && o.type == t_untyped_uninit;
  30. }
  31. gb_internal bool check_rtti_type_disallowed(Token const &token, Type *type, char const *format) {
  32. if (build_context.no_rtti && type) {
  33. if (is_type_any(type)) {
  34. gbString t = type_to_string(type);
  35. error(token, format, t);
  36. gb_string_free(t);
  37. return true;
  38. }
  39. }
  40. return false;
  41. }
  42. gb_internal bool check_rtti_type_disallowed(Ast *expr, Type *type, char const *format) {
  43. GB_ASSERT(expr != nullptr);
  44. return check_rtti_type_disallowed(ast_token(expr), type, format);
  45. }
  46. gb_internal void scope_reserve(Scope *scope, isize count) {
  47. string_map_reserve(&scope->elements, 2*count);
  48. }
  49. gb_internal void entity_graph_node_set_destroy(EntityGraphNodeSet *s) {
  50. ptr_set_destroy(s);
  51. }
  52. gb_internal void entity_graph_node_set_add(EntityGraphNodeSet *s, EntityGraphNode *n) {
  53. ptr_set_add(s, n);
  54. }
  55. // gb_internal bool entity_graph_node_set_exists(EntityGraphNodeSet *s, EntityGraphNode *n) {
  56. // return ptr_set_exists(s, n);
  57. // }
  58. gb_internal void entity_graph_node_set_remove(EntityGraphNodeSet *s, EntityGraphNode *n) {
  59. ptr_set_remove(s, n);
  60. }
  61. gb_internal void entity_graph_node_destroy(EntityGraphNode *n, gbAllocator a) {
  62. entity_graph_node_set_destroy(&n->pred);
  63. entity_graph_node_set_destroy(&n->succ);
  64. gb_free(a, n);
  65. }
  66. gb_internal int entity_graph_node_cmp(EntityGraphNode **data, isize i, isize j) {
  67. EntityGraphNode *x = data[i];
  68. EntityGraphNode *y = data[j];
  69. u64 a = x->entity->order_in_src;
  70. u64 b = y->entity->order_in_src;
  71. if (x->dep_count < y->dep_count) {
  72. return -1;
  73. }
  74. if (x->dep_count == y->dep_count) {
  75. return a < b ? -1 : b > a;
  76. }
  77. return +1;
  78. }
  79. gb_internal void entity_graph_node_swap(EntityGraphNode **data, isize i, isize j) {
  80. EntityGraphNode *x = data[i];
  81. EntityGraphNode *y = data[j];
  82. data[i] = y;
  83. data[j] = x;
  84. x->index = j;
  85. y->index = i;
  86. }
  87. gb_internal void import_graph_node_set_destroy(ImportGraphNodeSet *s) {
  88. ptr_set_destroy(s);
  89. }
  90. gb_internal void import_graph_node_set_add(ImportGraphNodeSet *s, ImportGraphNode *n) {
  91. ptr_set_add(s, n);
  92. }
  93. // gb_internal bool import_graph_node_set_exists(ImportGraphNodeSet *s, ImportGraphNode *n) {
  94. // return ptr_set_exists(s, n);
  95. // }
  96. // gb_internal void import_graph_node_set_remove(ImportGraphNodeSet *s, ImportGraphNode *n) {
  97. // ptr_set_remove(s, n);
  98. // }
  99. gb_internal ImportGraphNode *import_graph_node_create(gbAllocator a, AstPackage *pkg) {
  100. ImportGraphNode *n = gb_alloc_item(a, ImportGraphNode);
  101. n->pkg = pkg;
  102. n->scope = pkg->scope;
  103. return n;
  104. }
  105. gb_internal void import_graph_node_destroy(ImportGraphNode *n, gbAllocator a) {
  106. import_graph_node_set_destroy(&n->pred);
  107. import_graph_node_set_destroy(&n->succ);
  108. gb_free(a, n);
  109. }
  110. gb_internal int import_graph_node_cmp(ImportGraphNode **data, isize i, isize j) {
  111. ImportGraphNode *x = data[i];
  112. ImportGraphNode *y = data[j];
  113. GB_ASSERT(x != y);
  114. GB_ASSERT(x->scope != y->scope);
  115. bool xg = (x->scope->flags&ScopeFlag_Global) != 0;
  116. bool yg = (y->scope->flags&ScopeFlag_Global) != 0;
  117. if (xg != yg) return xg ? -1 : +1;
  118. if (xg && yg) return x->pkg->id < y->pkg->id ? +1 : -1;
  119. if (x->dep_count < y->dep_count) return -1;
  120. if (x->dep_count > y->dep_count) return +1;
  121. return 0;
  122. }
  123. gb_internal void import_graph_node_swap(ImportGraphNode **data, isize i, isize j) {
  124. ImportGraphNode *x = data[i];
  125. ImportGraphNode *y = data[j];
  126. data[i] = y;
  127. data[j] = x;
  128. x->index = j;
  129. y->index = i;
  130. }
  131. gb_internal void init_decl_info(DeclInfo *d, Scope *scope, DeclInfo *parent) {
  132. gb_zero_item(d);
  133. if (parent) {
  134. mutex_lock(&parent->next_mutex);
  135. d->next_sibling = parent->next_child;
  136. parent->next_child = d;
  137. mutex_unlock(&parent->next_mutex);
  138. }
  139. d->parent = parent;
  140. d->scope = scope;
  141. ptr_set_init(&d->deps, 0);
  142. ptr_set_init(&d->type_info_deps, 0);
  143. d->labels.allocator = heap_allocator();
  144. d->variadic_reuses.allocator = heap_allocator();
  145. d->variadic_reuse_max_bytes = 0;
  146. d->variadic_reuse_max_align = 1;
  147. }
  148. gb_internal DeclInfo *make_decl_info(Scope *scope, DeclInfo *parent) {
  149. DeclInfo *d = gb_alloc_item(permanent_allocator(), DeclInfo);
  150. init_decl_info(d, scope, parent);
  151. return d;
  152. }
  153. // gb_internal void destroy_declaration_info(DeclInfo *d) {
  154. // mutex_destroy(&d->proc_checked_mutex);
  155. // ptr_set_destroy(&d->deps);
  156. // array_free(&d->labels);
  157. // }
  158. // gb_internal bool decl_info_has_init(DeclInfo *d) {
  159. // if (d->init_expr != nullptr) {
  160. // return true;
  161. // }
  162. // if (d->proc_lit != nullptr) {
  163. // switch (d->proc_lit->kind) {
  164. // case_ast_node(pl, ProcLit, d->proc_lit);
  165. // if (pl->body != nullptr) {
  166. // return true;
  167. // }
  168. // case_end;
  169. // }
  170. // }
  171. // return false;
  172. // }
  173. gb_internal Scope *create_scope(CheckerInfo *info, Scope *parent) {
  174. Scope *s = gb_alloc_item(permanent_allocator(), Scope);
  175. s->parent = parent;
  176. if (parent != nullptr && parent != builtin_pkg->scope) {
  177. Scope *prev_head_child = parent->head_child.exchange(s, std::memory_order_acq_rel);
  178. if (prev_head_child) {
  179. s->next.store(prev_head_child, std::memory_order_release);
  180. }
  181. }
  182. if (parent != nullptr && parent->flags & ScopeFlag_ContextDefined) {
  183. s->flags |= ScopeFlag_ContextDefined;
  184. }
  185. return s;
  186. }
  187. gb_internal Scope *create_scope_from_file(CheckerInfo *info, AstFile *f) {
  188. GB_ASSERT(f != nullptr);
  189. GB_ASSERT(f->pkg != nullptr);
  190. GB_ASSERT(f->pkg->scope != nullptr);
  191. isize init_elements_capacity = gb_max(DEFAULT_SCOPE_CAPACITY, 2*f->total_file_decl_count);
  192. Scope *s = create_scope(info, f->pkg->scope);
  193. string_map_init(&s->elements, init_elements_capacity);
  194. s->flags |= ScopeFlag_File;
  195. s->file = f;
  196. f->scope = s;
  197. return s;
  198. }
  199. gb_internal Scope *create_scope_from_package(CheckerContext *c, AstPackage *pkg) {
  200. GB_ASSERT(pkg != nullptr);
  201. isize total_pkg_decl_count = 0;
  202. for (AstFile *file : pkg->files) {
  203. total_pkg_decl_count += file->total_file_decl_count;
  204. }
  205. isize init_elements_capacity = gb_max(DEFAULT_SCOPE_CAPACITY, 2*total_pkg_decl_count);
  206. Scope *s = create_scope(c->info, builtin_pkg->scope);
  207. string_map_init(&s->elements, init_elements_capacity);
  208. s->flags |= ScopeFlag_Pkg;
  209. s->pkg = pkg;
  210. pkg->scope = s;
  211. if (pkg->fullpath == c->checker->parser->init_fullpath || pkg->kind == Package_Init) {
  212. s->flags |= ScopeFlag_Init;
  213. }
  214. if (pkg->kind == Package_Runtime) {
  215. s->flags |= ScopeFlag_Global;
  216. }
  217. if (s->flags & (ScopeFlag_Init|ScopeFlag_Global)) {
  218. s->flags |= ScopeFlag_HasBeenImported;
  219. }
  220. s->flags |= ScopeFlag_ContextDefined;
  221. return s;
  222. }
  223. gb_internal void destroy_scope(Scope *scope) {
  224. for (Scope *child = scope->head_child; child != nullptr; child = child->next) {
  225. destroy_scope(child);
  226. }
  227. string_map_destroy(&scope->elements);
  228. ptr_set_destroy(&scope->imported);
  229. // NOTE(bill): No need to free scope as it "should" be allocated in an arena (except for the global scope)
  230. }
  231. gb_internal void add_scope(CheckerContext *c, Ast *node, Scope *scope) {
  232. GB_ASSERT(node != nullptr);
  233. GB_ASSERT(scope != nullptr);
  234. scope->node = node;
  235. switch (node->kind) {
  236. case Ast_BlockStmt: node->BlockStmt.scope = scope; break;
  237. case Ast_IfStmt: node->IfStmt.scope = scope; break;
  238. case Ast_ForStmt: node->ForStmt.scope = scope; break;
  239. case Ast_RangeStmt: node->RangeStmt.scope = scope; break;
  240. case Ast_UnrollRangeStmt: node->UnrollRangeStmt.scope = scope; break;
  241. case Ast_CaseClause: node->CaseClause.scope = scope; break;
  242. case Ast_SwitchStmt: node->SwitchStmt.scope = scope; break;
  243. case Ast_TypeSwitchStmt: node->TypeSwitchStmt.scope = scope; break;
  244. case Ast_ProcType: node->ProcType.scope = scope; break;
  245. case Ast_StructType: node->StructType.scope = scope; break;
  246. case Ast_UnionType: node->UnionType.scope = scope; break;
  247. case Ast_EnumType: node->EnumType.scope = scope; break;
  248. case Ast_BitFieldType: node->BitFieldType.scope = scope; break;
  249. default: GB_PANIC("Invalid node for add_scope: %.*s", LIT(ast_strings[node->kind]));
  250. }
  251. }
  252. gb_internal Scope *scope_of_node(Ast *node) {
  253. if (node == nullptr) {
  254. return nullptr;
  255. }
  256. switch (node->kind) {
  257. case Ast_BlockStmt: return node->BlockStmt.scope;
  258. case Ast_IfStmt: return node->IfStmt.scope;
  259. case Ast_ForStmt: return node->ForStmt.scope;
  260. case Ast_RangeStmt: return node->RangeStmt.scope;
  261. case Ast_UnrollRangeStmt: return node->UnrollRangeStmt.scope;
  262. case Ast_CaseClause: return node->CaseClause.scope;
  263. case Ast_SwitchStmt: return node->SwitchStmt.scope;
  264. case Ast_TypeSwitchStmt: return node->TypeSwitchStmt.scope;
  265. case Ast_ProcType: return node->ProcType.scope;
  266. case Ast_StructType: return node->StructType.scope;
  267. case Ast_UnionType: return node->UnionType.scope;
  268. case Ast_EnumType: return node->EnumType.scope;
  269. case Ast_BitFieldType: return node->BitFieldType.scope;
  270. }
  271. GB_PANIC("Invalid node for add_scope: %.*s", LIT(ast_strings[node->kind]));
  272. return nullptr;
  273. }
  274. gb_internal void check_open_scope(CheckerContext *c, Ast *node) {
  275. node = unparen_expr(node);
  276. GB_ASSERT(node != nullptr);
  277. GB_ASSERT(node->kind == Ast_Invalid ||
  278. is_ast_stmt(node) ||
  279. is_ast_type(node));
  280. Scope *scope = create_scope(c->info, c->scope);
  281. add_scope(c, node, scope);
  282. switch (node->kind) {
  283. case Ast_ProcType:
  284. scope->flags |= ScopeFlag_Proc;
  285. break;
  286. case Ast_StructType:
  287. case Ast_EnumType:
  288. case Ast_UnionType:
  289. case Ast_BitSetType:
  290. case Ast_BitFieldType:
  291. scope->flags |= ScopeFlag_Type;
  292. break;
  293. }
  294. c->scope = scope;
  295. c->state_flags |= StateFlag_bounds_check;
  296. }
  297. gb_internal void check_close_scope(CheckerContext *c) {
  298. c->scope = c->scope->parent;
  299. }
  300. gb_internal Entity *scope_lookup_current(Scope *s, String const &name) {
  301. Entity **found = string_map_get(&s->elements, name);
  302. if (found) {
  303. return *found;
  304. }
  305. return nullptr;
  306. }
  307. gb_internal void scope_lookup_parent(Scope *scope, String const &name, Scope **scope_, Entity **entity_) {
  308. if (scope != nullptr) {
  309. bool gone_thru_proc = false;
  310. bool gone_thru_package = false;
  311. StringHashKey key = string_hash_string(name);
  312. for (Scope *s = scope; s != nullptr; s = s->parent) {
  313. Entity **found = nullptr;
  314. rw_mutex_shared_lock(&s->mutex);
  315. found = string_map_get(&s->elements, key);
  316. rw_mutex_shared_unlock(&s->mutex);
  317. if (found) {
  318. Entity *e = *found;
  319. if (gone_thru_proc) {
  320. if (e->kind == Entity_Label) {
  321. continue;
  322. }
  323. if (e->kind == Entity_Variable) {
  324. if (e->scope->flags&ScopeFlag_File) {
  325. // Global variables are file to access
  326. } else if (e->flags&EntityFlag_Static) {
  327. // Allow static/thread_local variables to be referenced
  328. } else {
  329. continue;
  330. }
  331. }
  332. }
  333. if (entity_) *entity_ = e;
  334. if (scope_) *scope_ = s;
  335. return;
  336. }
  337. if (s->flags&ScopeFlag_Proc) {
  338. gone_thru_proc = true;
  339. }
  340. if (s->flags&ScopeFlag_Pkg) {
  341. gone_thru_package = true;
  342. }
  343. }
  344. }
  345. if (entity_) *entity_ = nullptr;
  346. if (scope_) *scope_ = nullptr;
  347. }
  348. gb_internal Entity *scope_lookup(Scope *s, String const &name) {
  349. Entity *entity = nullptr;
  350. scope_lookup_parent(s, name, nullptr, &entity);
  351. return entity;
  352. }
  353. gb_internal Entity *scope_insert_with_name_no_mutex(Scope *s, String const &name, Entity *entity) {
  354. if (name == "") {
  355. return nullptr;
  356. }
  357. StringHashKey key = string_hash_string(name);
  358. Entity **found = nullptr;
  359. Entity *result = nullptr;
  360. found = string_map_get(&s->elements, key);
  361. if (found) {
  362. if (entity != *found) {
  363. result = *found;
  364. }
  365. goto end;
  366. }
  367. if (s->parent != nullptr && (s->parent->flags & ScopeFlag_Proc) != 0) {
  368. found = string_map_get(&s->parent->elements, key);
  369. if (found) {
  370. if ((*found)->flags & EntityFlag_Result) {
  371. if (entity != *found) {
  372. result = *found;
  373. }
  374. goto end;
  375. }
  376. }
  377. }
  378. string_map_set(&s->elements, key, entity);
  379. if (entity->scope == nullptr) {
  380. entity->scope = s;
  381. }
  382. end:;
  383. return result;
  384. }
  385. gb_internal Entity *scope_insert_with_name(Scope *s, String const &name, Entity *entity) {
  386. if (name == "") {
  387. return nullptr;
  388. }
  389. StringHashKey key = string_hash_string(name);
  390. Entity **found = nullptr;
  391. Entity *result = nullptr;
  392. rw_mutex_lock(&s->mutex);
  393. found = string_map_get(&s->elements, key);
  394. if (found) {
  395. if (entity != *found) {
  396. result = *found;
  397. }
  398. goto end;
  399. }
  400. if (s->parent != nullptr && (s->parent->flags & ScopeFlag_Proc) != 0) {
  401. found = string_map_get(&s->parent->elements, key);
  402. if (found) {
  403. if ((*found)->flags & EntityFlag_Result) {
  404. if (entity != *found) {
  405. result = *found;
  406. }
  407. goto end;
  408. }
  409. }
  410. }
  411. string_map_set(&s->elements, key, entity);
  412. if (entity->scope == nullptr) {
  413. entity->scope = s;
  414. }
  415. end:;
  416. rw_mutex_unlock(&s->mutex);
  417. return result;
  418. }
  419. gb_global bool in_single_threaded_checker_stage = false;
  420. gb_internal Entity *scope_insert(Scope *s, Entity *entity) {
  421. String name = entity->token.string;
  422. if (in_single_threaded_checker_stage) {
  423. return scope_insert_with_name_no_mutex(s, name, entity);
  424. } else {
  425. return scope_insert_with_name(s, name, entity);
  426. }
  427. }
  428. gb_internal Entity *scope_insert_no_mutex(Scope *s, Entity *entity) {
  429. String name = entity->token.string;
  430. return scope_insert_with_name_no_mutex(s, name, entity);
  431. }
  432. gb_internal GB_COMPARE_PROC(entity_variable_pos_cmp) {
  433. Entity *x = *cast(Entity **)a;
  434. Entity *y = *cast(Entity **)b;
  435. return token_pos_cmp(x->token.pos, y->token.pos);
  436. }
  437. gb_internal u64 check_vet_flags(CheckerContext *c) {
  438. AstFile *file = c->file;
  439. if (file == nullptr &&
  440. c->curr_proc_decl &&
  441. c->curr_proc_decl->proc_lit) {
  442. file = c->curr_proc_decl->proc_lit->file();
  443. }
  444. if (file && file->vet_flags_set) {
  445. return file->vet_flags;
  446. }
  447. return build_context.vet_flags;
  448. }
  449. gb_internal u64 check_vet_flags(Ast *node) {
  450. AstFile *file = node->file();
  451. if (file && file->vet_flags_set) {
  452. return file->vet_flags;
  453. }
  454. return build_context.vet_flags;
  455. }
  456. enum VettedEntityKind {
  457. VettedEntity_Invalid,
  458. VettedEntity_Unused,
  459. VettedEntity_Shadowed,
  460. VettedEntity_Shadowed_And_Unused,
  461. };
  462. struct VettedEntity {
  463. VettedEntityKind kind;
  464. Entity *entity;
  465. Entity *other;
  466. };
  467. gb_internal GB_COMPARE_PROC(vetted_entity_variable_pos_cmp) {
  468. Entity *x = (cast(VettedEntity *)a)->entity;
  469. Entity *y = (cast(VettedEntity *)b)->entity;
  470. GB_ASSERT(x != nullptr);
  471. GB_ASSERT(y != nullptr);
  472. return token_pos_cmp(x->token.pos, y->token.pos);
  473. }
  474. gb_internal bool check_vet_shadowing_assignment(Checker *c, Entity *shadowed, Ast *expr) {
  475. Ast *init = unparen_expr(expr);
  476. if (init == nullptr) {
  477. return false;
  478. }
  479. if (init->kind == Ast_Ident) {
  480. // TODO(bill): Which logic is better? Same name or same entity
  481. // bool ignore = init->Ident.token.string == name;
  482. bool ignore = init->Ident.entity == shadowed;
  483. if (ignore) {
  484. return true;
  485. }
  486. } else if (init->kind == Ast_TernaryIfExpr) {
  487. bool x = check_vet_shadowing_assignment(c, shadowed, init->TernaryIfExpr.x);
  488. bool y = check_vet_shadowing_assignment(c, shadowed, init->TernaryIfExpr.y);
  489. if (x || y) {
  490. return true;
  491. }
  492. }
  493. return false;
  494. }
  495. gb_internal bool check_vet_shadowing(Checker *c, Entity *e, VettedEntity *ve) {
  496. if (e->kind != Entity_Variable) {
  497. return false;
  498. }
  499. String name = e->token.string;
  500. if (name == "_") {
  501. return false;
  502. }
  503. if (e->flags & EntityFlag_Param) {
  504. return false;
  505. }
  506. if (e->scope->flags & (ScopeFlag_Global|ScopeFlag_File|ScopeFlag_Proc)) {
  507. return false;
  508. }
  509. Scope *parent = e->scope->parent;
  510. if (parent->flags & (ScopeFlag_Global|ScopeFlag_File)) {
  511. return false;
  512. }
  513. Entity *shadowed = scope_lookup(parent, name);
  514. if (shadowed == nullptr) {
  515. return false;
  516. }
  517. if (shadowed->kind != Entity_Variable) {
  518. return false;
  519. }
  520. if (shadowed->scope->flags & (ScopeFlag_Global|ScopeFlag_File)) {
  521. // return false;
  522. }
  523. // NOTE(bill): The entities must be in the same file
  524. if (e->token.pos.file_id != shadowed->token.pos.file_id) {
  525. return false;
  526. }
  527. // NOTE(bill): The shaded identifier must appear before this one to be an
  528. // instance of shadowing
  529. if (token_pos_cmp(shadowed->token.pos, e->token.pos) > 0) {
  530. return false;
  531. }
  532. // NOTE(bill): If the types differ, don't complain
  533. if (!are_types_identical(e->type, shadowed->type)) {
  534. return false;
  535. }
  536. // NOTE(bill): Ignore intentional redeclaration
  537. // x := x
  538. // Suggested in issue #637 (2020-05-11)
  539. // Also allow the following
  540. // x := x if cond else y
  541. // x := z if cond else x
  542. if ((e->flags & EntityFlag_Using) == 0 && e->kind == Entity_Variable) {
  543. if (check_vet_shadowing_assignment(c, shadowed, e->Variable.init_expr)) {
  544. return false;
  545. }
  546. }
  547. gb_zero_item(ve);
  548. ve->kind = VettedEntity_Shadowed;
  549. ve->entity = e;
  550. ve->other = shadowed;
  551. return true;
  552. }
  553. gb_internal bool check_vet_unused(Checker *c, Entity *e, VettedEntity *ve) {
  554. if ((e->flags&EntityFlag_Used) == 0) {
  555. switch (e->kind) {
  556. case Entity_Variable:
  557. if (e->scope->flags & (ScopeFlag_Global|ScopeFlag_Type|ScopeFlag_File)) {
  558. return false;
  559. } else if (e->flags & EntityFlag_Static) {
  560. // ignore these for the time being
  561. return false;
  562. }
  563. case Entity_ImportName:
  564. case Entity_LibraryName:
  565. gb_zero_item(ve);
  566. ve->kind = VettedEntity_Unused;
  567. ve->entity = e;
  568. return true;
  569. }
  570. }
  571. return false;
  572. }
  573. gb_internal void check_scope_usage(Checker *c, Scope *scope, u64 vet_flags) {
  574. bool vet_unused = (vet_flags & VetFlag_Unused) != 0;
  575. bool vet_shadowing = (vet_flags & (VetFlag_Shadowing|VetFlag_Using)) != 0;
  576. Array<VettedEntity> vetted_entities = {};
  577. array_init(&vetted_entities, heap_allocator());
  578. rw_mutex_shared_lock(&scope->mutex);
  579. for (auto const &entry : scope->elements) {
  580. Entity *e = entry.value;
  581. if (e == nullptr) continue;
  582. VettedEntity ve_unused = {};
  583. VettedEntity ve_shadowed = {};
  584. bool is_unused = vet_unused && check_vet_unused(c, e, &ve_unused);
  585. bool is_shadowed = vet_shadowing && check_vet_shadowing(c, e, &ve_shadowed);
  586. if (is_unused && is_shadowed) {
  587. VettedEntity ve_both = ve_shadowed;
  588. ve_both.kind = VettedEntity_Shadowed_And_Unused;
  589. array_add(&vetted_entities, ve_both);
  590. } else if (is_unused) {
  591. array_add(&vetted_entities, ve_unused);
  592. } else if (is_shadowed) {
  593. array_add(&vetted_entities, ve_shadowed);
  594. } else if (e->kind == Entity_Variable && (e->flags & (EntityFlag_Param|EntityFlag_Using|EntityFlag_Static)) == 0 && !e->Variable.is_global) {
  595. i64 sz = type_size_of(e->type);
  596. // TODO(bill): When is a good size warn?
  597. // Is >256 KiB good enough?
  598. if (sz > 1ll<<18) {
  599. gbString type_str = type_to_string(e->type);
  600. warning(e->token, "Declaration of '%.*s' may cause a stack overflow due to its type '%s' having a size of %lld bytes", LIT(e->token.string), type_str, cast(long long)sz);
  601. gb_string_free(type_str);
  602. }
  603. }
  604. }
  605. rw_mutex_shared_unlock(&scope->mutex);
  606. gb_sort(vetted_entities.data, vetted_entities.count, gb_size_of(VettedEntity), vetted_entity_variable_pos_cmp);
  607. for (auto const &ve : vetted_entities) {
  608. Entity *e = ve.entity;
  609. Entity *other = ve.other;
  610. String name = e->token.string;
  611. if (ve.kind == VettedEntity_Shadowed_And_Unused) {
  612. error(e->token, "'%.*s' declared but not used, possibly shadows declaration at line %d", LIT(name), other->token.pos.line);
  613. } else if (vet_flags) {
  614. switch (ve.kind) {
  615. case VettedEntity_Unused:
  616. if (e->kind == Entity_Variable && (vet_flags & VetFlag_UnusedVariables) != 0) {
  617. error(e->token, "'%.*s' declared but not used", LIT(name));
  618. }
  619. if ((e->kind == Entity_ImportName || e->kind == Entity_LibraryName) && (vet_flags & VetFlag_UnusedImports) != 0) {
  620. error(e->token, "'%.*s' declared but not used", LIT(name));
  621. }
  622. break;
  623. case VettedEntity_Shadowed:
  624. if ((vet_flags & (VetFlag_Shadowing|VetFlag_Using)) != 0 && e->flags&EntityFlag_Using) {
  625. error(e->token, "Declaration of '%.*s' from 'using' shadows declaration at line %d", LIT(name), other->token.pos.line);
  626. } else if ((vet_flags & (VetFlag_Shadowing)) != 0) {
  627. error(e->token, "Declaration of '%.*s' shadows declaration at line %d", LIT(name), other->token.pos.line);
  628. }
  629. break;
  630. default:
  631. break;
  632. }
  633. }
  634. }
  635. array_free(&vetted_entities);
  636. for (Scope *child = scope->head_child; child != nullptr; child = child->next) {
  637. if (child->flags & (ScopeFlag_Proc|ScopeFlag_Type|ScopeFlag_File)) {
  638. // Ignore these
  639. } else {
  640. check_scope_usage(c, child, vet_flags);
  641. }
  642. }
  643. }
  644. gb_internal void add_dependency(CheckerInfo *info, DeclInfo *d, Entity *e) {
  645. rw_mutex_lock(&d->deps_mutex);
  646. ptr_set_add(&d->deps, e);
  647. rw_mutex_unlock(&d->deps_mutex);
  648. }
  649. gb_internal void add_type_info_dependency(CheckerInfo *info, DeclInfo *d, Type *type) {
  650. if (d == nullptr) {
  651. return;
  652. }
  653. rw_mutex_lock(&d->type_info_deps_mutex);
  654. ptr_set_add(&d->type_info_deps, type);
  655. rw_mutex_unlock(&d->type_info_deps_mutex);
  656. }
  657. gb_internal AstPackage *get_runtime_package(CheckerInfo *info) {
  658. String name = str_lit("runtime");
  659. gbAllocator a = heap_allocator();
  660. String path = get_fullpath_base_collection(a, name, nullptr);
  661. defer (gb_free(a, path.text));
  662. auto found = string_map_get(&info->packages, path);
  663. if (found == nullptr) {
  664. gb_printf_err("Name: %.*s\n", LIT(name));
  665. gb_printf_err("Fullpath: %.*s\n", LIT(path));
  666. for (auto const &entry : info->packages) {
  667. gb_printf_err("%.*s\n", LIT(entry.key));
  668. }
  669. GB_ASSERT_MSG(found != nullptr, "Missing core package %.*s", LIT(name));
  670. }
  671. return *found;
  672. }
  673. gb_internal AstPackage *get_core_package(CheckerInfo *info, String name) {
  674. if (name == "runtime") {
  675. return get_runtime_package(info);
  676. }
  677. gbAllocator a = heap_allocator();
  678. String path = get_fullpath_core_collection(a, name, nullptr);
  679. defer (gb_free(a, path.text));
  680. auto found = string_map_get(&info->packages, path);
  681. if (found == nullptr) {
  682. gb_printf_err("Name: %.*s\n", LIT(name));
  683. gb_printf_err("Fullpath: %.*s\n", LIT(path));
  684. for (auto const &entry : info->packages) {
  685. gb_printf_err("%.*s\n", LIT(entry.key));
  686. }
  687. GB_ASSERT_MSG(found != nullptr, "Missing core package %.*s", LIT(name));
  688. }
  689. return *found;
  690. }
  691. gb_internal void add_package_dependency(CheckerContext *c, char const *package_name, char const *name, bool required=false) {
  692. String n = make_string_c(name);
  693. AstPackage *p = get_core_package(&c->checker->info, make_string_c(package_name));
  694. Entity *e = scope_lookup(p->scope, n);
  695. GB_ASSERT_MSG(e != nullptr, "%s", name);
  696. GB_ASSERT(c->decl != nullptr);
  697. e->flags |= EntityFlag_Used;
  698. if (required) {
  699. e->flags |= EntityFlag_Require;
  700. }
  701. add_dependency(c->info, c->decl, e);
  702. }
  703. gb_internal void try_to_add_package_dependency(CheckerContext *c, char const *package_name, char const *name) {
  704. String n = make_string_c(name);
  705. AstPackage *p = get_core_package(&c->checker->info, make_string_c(package_name));
  706. Entity *e = scope_lookup(p->scope, n);
  707. if (e == nullptr) {
  708. return;
  709. }
  710. GB_ASSERT(c->decl != nullptr);
  711. e->flags |= EntityFlag_Used;
  712. add_dependency(c->info, c->decl, e);
  713. }
  714. gb_internal void add_declaration_dependency(CheckerContext *c, Entity *e) {
  715. if (e == nullptr) {
  716. return;
  717. }
  718. if (e->flags & EntityFlag_Disabled) {
  719. // ignore the dependencies if it has been `@(disabled=true)`
  720. return;
  721. }
  722. if (c->decl != nullptr) {
  723. add_dependency(c->info, c->decl, e);
  724. }
  725. }
  726. gb_internal Entity *add_global_entity(Entity *entity, Scope *scope=builtin_pkg->scope) {
  727. String name = entity->token.string;
  728. defer (entity->state = EntityState_Resolved);
  729. if (gb_memchr(name.text, ' ', name.len)) {
  730. return entity; // NOTE(bill): Usually an 'untyped thing'
  731. }
  732. if (scope_insert(scope, entity)) {
  733. compiler_error("double declaration");
  734. }
  735. return entity;
  736. }
  737. gb_internal void add_global_constant(char const *name, Type *type, ExactValue value) {
  738. Entity *entity = alloc_entity(Entity_Constant, nullptr, make_token_ident(name), type);
  739. entity->Constant.value = value;
  740. add_global_entity(entity);
  741. }
  742. gb_internal void add_global_string_constant(char const *name, String const &value) {
  743. add_global_constant(name, t_untyped_string, exact_value_string(value));
  744. }
  745. gb_internal void add_global_bool_constant(char const *name, bool value) {
  746. add_global_constant(name, t_untyped_bool, exact_value_bool(value));
  747. }
  748. gb_internal void add_global_type_entity(String name, Type *type) {
  749. add_global_entity(alloc_entity_type_name(nullptr, make_token_ident(name), type));
  750. }
  751. gb_internal AstPackage *create_builtin_package(char const *name) {
  752. gbAllocator a = permanent_allocator();
  753. AstPackage *pkg = gb_alloc_item(a, AstPackage);
  754. pkg->name = make_string_c(name);
  755. pkg->kind = Package_Builtin;
  756. pkg->scope = create_scope(nullptr, nullptr);
  757. pkg->scope->flags |= ScopeFlag_Pkg | ScopeFlag_Global | ScopeFlag_Builtin;
  758. pkg->scope->pkg = pkg;
  759. return pkg;
  760. }
  761. struct GlobalEnumValue {
  762. char const *name;
  763. i64 value;
  764. };
  765. gb_internal Slice<Entity *> add_global_enum_type(String const &type_name, GlobalEnumValue *values, isize value_count, Type **enum_type_ = nullptr) {
  766. Scope *scope = create_scope(nullptr, builtin_pkg->scope);
  767. Entity *entity = alloc_entity_type_name(scope, make_token_ident(type_name), nullptr, EntityState_Resolved);
  768. Type *enum_type = alloc_type_enum();
  769. Type *named_type = alloc_type_named(type_name, enum_type, entity);
  770. set_base_type(named_type, enum_type);
  771. enum_type->Enum.base_type = t_int;
  772. enum_type->Enum.scope = scope;
  773. entity->type = named_type;
  774. auto fields = array_make<Entity *>(permanent_allocator(), value_count);
  775. for (isize i = 0; i < value_count; i++) {
  776. i64 value = values[i].value;
  777. Entity *e = alloc_entity_constant(scope, make_token_ident(values[i].name), named_type, exact_value_i64(value));
  778. e->flags |= EntityFlag_Visited;
  779. e->state = EntityState_Resolved;
  780. fields[i] = e;
  781. Entity *ie = scope_insert(scope, e);
  782. GB_ASSERT(ie == nullptr);
  783. }
  784. enum_type->Enum.fields = fields;
  785. enum_type->Enum.min_value_index = 0;
  786. enum_type->Enum.max_value_index = value_count-1;
  787. enum_type->Enum.min_value = &enum_type->Enum.fields[enum_type->Enum.min_value_index]->Constant.value;
  788. enum_type->Enum.max_value = &enum_type->Enum.fields[enum_type->Enum.max_value_index]->Constant.value;
  789. if (enum_type_) *enum_type_ = named_type;
  790. return slice_from_array(fields);
  791. }
  792. gb_internal void add_global_enum_constant(Slice<Entity *> const &fields, char const *name, i64 value) {
  793. for (Entity *field : fields) {
  794. GB_ASSERT(field->kind == Entity_Constant);
  795. if (value == exact_value_to_i64(field->Constant.value)) {
  796. add_global_constant(name, field->type, field->Constant.value);
  797. return;
  798. }
  799. }
  800. GB_PANIC("Unfound enum value for global constant: %s %lld", name, cast(long long)value);
  801. }
  802. gb_internal Type *add_global_type_name(Scope *scope, String const &type_name, Type *backing_type) {
  803. Entity *e = alloc_entity_type_name(scope, make_token_ident(type_name), nullptr, EntityState_Resolved);
  804. Type *named_type = alloc_type_named(type_name, backing_type, e);
  805. e->type = named_type;
  806. set_base_type(named_type, backing_type);
  807. if (scope_insert(scope, e)) {
  808. compiler_error("double declaration of %.*s", LIT(e->token.string));
  809. }
  810. return named_type;
  811. }
  812. gb_internal i64 odin_compile_timestamp(void) {
  813. i64 us_after_1601 = cast(i64)gb_utc_time_now();
  814. i64 us_after_1970 = us_after_1601 - 11644473600000000ll;
  815. i64 ns_after_1970 = us_after_1970*1000ll;
  816. return ns_after_1970;
  817. }
  818. gb_internal bool lb_use_new_pass_system(void);
  819. gb_internal void init_universal(void) {
  820. BuildContext *bc = &build_context;
  821. builtin_pkg = create_builtin_package("builtin");
  822. intrinsics_pkg = create_builtin_package("intrinsics");
  823. config_pkg = create_builtin_package("config");
  824. // Types
  825. for (isize i = 0; i < gb_count_of(basic_types); i++) {
  826. String const &name = basic_types[i].Basic.name;
  827. add_global_type_entity(name, &basic_types[i]);
  828. }
  829. add_global_type_entity(str_lit("byte"), &basic_types[Basic_u8]);
  830. {
  831. Type *equal_args[2] = {t_rawptr, t_rawptr};
  832. t_equal_proc = alloc_type_proc_from_types(equal_args, gb_count_of(equal_args), t_bool, false, ProcCC_Contextless);
  833. Type *hasher_args[2] = {t_rawptr, t_uintptr};
  834. t_hasher_proc = alloc_type_proc_from_types(hasher_args, gb_count_of(hasher_args), t_uintptr, false, ProcCC_Contextless);
  835. Type *map_get_args[3] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr};
  836. t_map_get_proc = alloc_type_proc_from_types(map_get_args, gb_count_of(map_get_args), t_rawptr, false, ProcCC_Contextless);
  837. }
  838. // Constants
  839. add_global_entity(alloc_entity_nil(str_lit("nil"), t_untyped_nil));
  840. add_global_bool_constant("true", true);
  841. add_global_bool_constant("false", false);
  842. add_global_string_constant("ODIN_VENDOR", bc->ODIN_VENDOR);
  843. add_global_string_constant("ODIN_VERSION", bc->ODIN_VERSION);
  844. add_global_string_constant("ODIN_ROOT", bc->ODIN_ROOT);
  845. add_global_string_constant("ODIN_BUILD_PROJECT_NAME", bc->ODIN_BUILD_PROJECT_NAME);
  846. add_global_string_constant("ODIN_WINDOWS_SUBSYSTEM", bc->ODIN_WINDOWS_SUBSYSTEM);
  847. {
  848. GlobalEnumValue values[TargetOs_COUNT] = {
  849. {"Unknown", TargetOs_Invalid},
  850. {"Windows", TargetOs_windows},
  851. {"Darwin", TargetOs_darwin},
  852. {"Linux", TargetOs_linux},
  853. {"Essence", TargetOs_essence},
  854. {"FreeBSD", TargetOs_freebsd},
  855. {"Haiku", TargetOs_haiku},
  856. {"OpenBSD", TargetOs_openbsd},
  857. {"NetBSD", TargetOs_netbsd},
  858. {"WASI", TargetOs_wasi},
  859. {"JS", TargetOs_js},
  860. {"Orca", TargetOs_orca},
  861. {"Freestanding", TargetOs_freestanding},
  862. };
  863. auto fields = add_global_enum_type(str_lit("Odin_OS_Type"), values, gb_count_of(values));
  864. add_global_enum_constant(fields, "ODIN_OS", bc->metrics.os);
  865. add_global_string_constant("ODIN_OS_STRING", target_os_names[bc->metrics.os]);
  866. }
  867. {
  868. GlobalEnumValue values[TargetArch_COUNT] = {
  869. {"Unknown", TargetArch_Invalid},
  870. {"amd64", TargetArch_amd64},
  871. {"i386", TargetArch_i386},
  872. {"arm32", TargetArch_arm32},
  873. {"arm64", TargetArch_arm64},
  874. {"wasm32", TargetArch_wasm32},
  875. {"wasm64p32", TargetArch_wasm64p32},
  876. };
  877. auto fields = add_global_enum_type(str_lit("Odin_Arch_Type"), values, gb_count_of(values));
  878. add_global_enum_constant(fields, "ODIN_ARCH", bc->metrics.arch);
  879. add_global_string_constant("ODIN_ARCH_STRING", target_arch_names[bc->metrics.arch]);
  880. }
  881. add_global_string_constant("ODIN_MICROARCH_STRING", get_final_microarchitecture());
  882. {
  883. GlobalEnumValue values[BuildMode_COUNT] = {
  884. {"Executable", BuildMode_Executable},
  885. {"Dynamic", BuildMode_DynamicLibrary},
  886. {"Static", BuildMode_StaticLibrary},
  887. {"Object", BuildMode_Object},
  888. {"Assembly", BuildMode_Assembly},
  889. {"LLVM_IR", BuildMode_LLVM_IR},
  890. };
  891. auto fields = add_global_enum_type(str_lit("Odin_Build_Mode_Type"), values, gb_count_of(values));
  892. add_global_enum_constant(fields, "ODIN_BUILD_MODE", bc->build_mode);
  893. }
  894. {
  895. GlobalEnumValue values[TargetEndian_COUNT] = {
  896. {"Little", TargetEndian_Little},
  897. {"Big", TargetEndian_Big},
  898. };
  899. auto fields = add_global_enum_type(str_lit("Odin_Endian_Type"), values, gb_count_of(values));
  900. add_global_enum_constant(fields, "ODIN_ENDIAN", target_endians[bc->metrics.arch]);
  901. add_global_string_constant("ODIN_ENDIAN_STRING", target_endian_names[target_endians[bc->metrics.arch]]);
  902. }
  903. {
  904. GlobalEnumValue values[Subtarget_COUNT] = {
  905. {"Default", Subtarget_Default},
  906. {"iOS", Subtarget_iOS},
  907. };
  908. auto fields = add_global_enum_type(str_lit("Odin_Platform_Subtarget_Type"), values, gb_count_of(values));
  909. add_global_enum_constant(fields, "ODIN_PLATFORM_SUBTARGET", selected_subtarget);
  910. }
  911. {
  912. GlobalEnumValue values[ErrorPosStyle_COUNT] = {
  913. {"Default", ErrorPosStyle_Default},
  914. {"Unix", ErrorPosStyle_Unix},
  915. };
  916. auto fields = add_global_enum_type(str_lit("Odin_Error_Pos_Style_Type"), values, gb_count_of(values));
  917. add_global_enum_constant(fields, "ODIN_ERROR_POS_STYLE", build_context.ODIN_ERROR_POS_STYLE);
  918. }
  919. {
  920. GlobalEnumValue values[OdinAtomicMemoryOrder_COUNT] = {
  921. {OdinAtomicMemoryOrder_strings[OdinAtomicMemoryOrder_relaxed], OdinAtomicMemoryOrder_relaxed},
  922. {OdinAtomicMemoryOrder_strings[OdinAtomicMemoryOrder_consume], OdinAtomicMemoryOrder_consume},
  923. {OdinAtomicMemoryOrder_strings[OdinAtomicMemoryOrder_acquire], OdinAtomicMemoryOrder_acquire},
  924. {OdinAtomicMemoryOrder_strings[OdinAtomicMemoryOrder_release], OdinAtomicMemoryOrder_release},
  925. {OdinAtomicMemoryOrder_strings[OdinAtomicMemoryOrder_acq_rel], OdinAtomicMemoryOrder_acq_rel},
  926. {OdinAtomicMemoryOrder_strings[OdinAtomicMemoryOrder_seq_cst], OdinAtomicMemoryOrder_seq_cst},
  927. };
  928. add_global_enum_type(str_lit("Atomic_Memory_Order"), values, gb_count_of(values), &t_atomic_memory_order);
  929. GB_ASSERT(t_atomic_memory_order->kind == Type_Named);
  930. scope_insert(intrinsics_pkg->scope, t_atomic_memory_order->Named.type_name);
  931. }
  932. {
  933. int minimum_os_version = 0;
  934. if (build_context.minimum_os_version_string != "") {
  935. int major, minor, revision = 0;
  936. #if defined(GB_SYSTEM_WINDOWS)
  937. sscanf_s(cast(const char *)(build_context.minimum_os_version_string.text), "%d.%d.%d", &major, &minor, &revision);
  938. #else
  939. sscanf(cast(const char *)(build_context.minimum_os_version_string.text), "%d.%d.%d", &major, &minor, &revision);
  940. #endif
  941. minimum_os_version = (major*10000)+(minor*100)+revision;
  942. }
  943. add_global_constant("ODIN_MINIMUM_OS_VERSION", t_untyped_integer, exact_value_i64(minimum_os_version));
  944. }
  945. add_global_bool_constant("ODIN_DEBUG", bc->ODIN_DEBUG);
  946. add_global_bool_constant("ODIN_DISABLE_ASSERT", bc->ODIN_DISABLE_ASSERT);
  947. add_global_bool_constant("ODIN_DEFAULT_TO_NIL_ALLOCATOR", bc->ODIN_DEFAULT_TO_NIL_ALLOCATOR);
  948. add_global_bool_constant("ODIN_NO_BOUNDS_CHECK", build_context.no_bounds_check);
  949. add_global_bool_constant("ODIN_NO_TYPE_ASSERT", build_context.no_type_assert);
  950. add_global_bool_constant("ODIN_DEFAULT_TO_PANIC_ALLOCATOR", bc->ODIN_DEFAULT_TO_PANIC_ALLOCATOR);
  951. add_global_bool_constant("ODIN_NO_DYNAMIC_LITERALS", bc->no_dynamic_literals);
  952. add_global_bool_constant("ODIN_NO_CRT", bc->no_crt);
  953. add_global_bool_constant("ODIN_USE_SEPARATE_MODULES", bc->use_separate_modules);
  954. add_global_bool_constant("ODIN_TEST", bc->command_kind == Command_test);
  955. add_global_bool_constant("ODIN_NO_ENTRY_POINT", bc->no_entry_point);
  956. add_global_bool_constant("ODIN_FOREIGN_ERROR_PROCEDURES", bc->ODIN_FOREIGN_ERROR_PROCEDURES);
  957. add_global_bool_constant("ODIN_NO_RTTI", bc->no_rtti);
  958. add_global_bool_constant("ODIN_VALGRIND_SUPPORT", bc->ODIN_VALGRIND_SUPPORT);
  959. add_global_bool_constant("ODIN_TILDE", bc->tilde_backend);
  960. add_global_constant("ODIN_COMPILE_TIMESTAMP", t_untyped_integer, exact_value_i64(odin_compile_timestamp()));
  961. {
  962. String version = {};
  963. #ifdef GIT_SHA
  964. version.text = cast(u8 *)GIT_SHA;
  965. version.len = gb_strlen(GIT_SHA);
  966. #endif
  967. add_global_string_constant("ODIN_VERSION_HASH", version);
  968. }
  969. {
  970. bool f16_supported = lb_use_new_pass_system();
  971. if (is_arch_wasm()) {
  972. f16_supported = false;
  973. } else if (build_context.metrics.os == TargetOs_darwin && build_context.metrics.arch == TargetArch_amd64) {
  974. // NOTE(laytan): See #3222 for my ramblings on this.
  975. f16_supported = false;
  976. }
  977. add_global_bool_constant("__ODIN_LLVM_F16_SUPPORTED", f16_supported);
  978. }
  979. {
  980. GlobalEnumValue values[3] = {
  981. {"Address", 0},
  982. {"Memory", 1},
  983. {"Thread", 2},
  984. };
  985. Type *enum_type = nullptr;
  986. auto flags = add_global_enum_type(str_lit("Odin_Sanitizer_Flag"), values, gb_count_of(values), &enum_type);
  987. Type *bit_set_type = alloc_type_bit_set();
  988. bit_set_type->BitSet.elem = enum_type;
  989. bit_set_type->BitSet.underlying = t_u32;
  990. bit_set_type->BitSet.lower = 0;
  991. bit_set_type->BitSet.upper = 2;
  992. type_size_of(bit_set_type);
  993. String type_name = str_lit("Odin_Sanitizer_Flags");
  994. Scope *scope = create_scope(nullptr, builtin_pkg->scope);
  995. Entity *entity = alloc_entity_type_name(scope, make_token_ident(type_name), nullptr, EntityState_Resolved);
  996. Type *named_type = alloc_type_named(type_name, bit_set_type, entity);
  997. set_base_type(named_type, bit_set_type);
  998. add_global_constant("ODIN_SANITIZER_FLAGS", named_type, exact_value_u64(bc->sanitizer_flags));
  999. }
  1000. {
  1001. GlobalEnumValue values[5] = {
  1002. {"None", -1},
  1003. {"Minimal", 0},
  1004. {"Size", 1},
  1005. {"Speed", 2},
  1006. {"Aggressive", 3},
  1007. };
  1008. auto fields = add_global_enum_type(str_lit("Odin_Optimization_Mode"), values, gb_count_of(values));
  1009. add_global_enum_constant(fields, "ODIN_OPTIMIZATION_MODE", bc->optimization_level);
  1010. }
  1011. // Builtin Procedures
  1012. for (isize i = 0; i < gb_count_of(builtin_procs); i++) {
  1013. BuiltinProcId id = cast(BuiltinProcId)i;
  1014. String name = builtin_procs[i].name;
  1015. if (name != "") {
  1016. Entity *entity = alloc_entity(Entity_Builtin, nullptr, make_token_ident(name), t_invalid);
  1017. entity->Builtin.id = id;
  1018. switch (builtin_procs[i].pkg) {
  1019. case BuiltinProcPkg_builtin:
  1020. add_global_entity(entity, builtin_pkg->scope);
  1021. break;
  1022. case BuiltinProcPkg_intrinsics:
  1023. add_global_entity(entity, intrinsics_pkg->scope);
  1024. GB_ASSERT(scope_lookup_current(intrinsics_pkg->scope, name) != nullptr);
  1025. break;
  1026. }
  1027. }
  1028. }
  1029. {
  1030. BuiltinProcId id = BuiltinProc_expand_values;
  1031. String name = str_lit("expand_to_tuple");
  1032. Entity *entity = alloc_entity(Entity_Builtin, nullptr, make_token_ident(name), t_invalid);
  1033. entity->Builtin.id = id;
  1034. add_global_entity(entity, builtin_pkg->scope);
  1035. }
  1036. bool defined_values_double_declaration = false;
  1037. for (auto const &entry : bc->defined_values) {
  1038. char const *name = entry.key;
  1039. ExactValue value = entry.value;
  1040. GB_ASSERT(value.kind != ExactValue_Invalid);
  1041. Type *type = nullptr;
  1042. switch (value.kind) {
  1043. case ExactValue_Bool:
  1044. type = t_untyped_bool;
  1045. break;
  1046. case ExactValue_String:
  1047. type = t_untyped_string;
  1048. break;
  1049. case ExactValue_Integer:
  1050. type = t_untyped_integer;
  1051. break;
  1052. case ExactValue_Float:
  1053. type = t_untyped_float;
  1054. break;
  1055. }
  1056. GB_ASSERT(type != nullptr);
  1057. Entity *entity = alloc_entity_constant(nullptr, make_token_ident(name), type, value);
  1058. entity->state = EntityState_Resolved;
  1059. if (scope_insert(config_pkg->scope, entity)) {
  1060. error(entity->token, "'%s' defined as an argument is already declared at the global scope", name);
  1061. defined_values_double_declaration = true;
  1062. // NOTE(bill): Just exit early before anything, even though the compiler will do that anyway
  1063. }
  1064. }
  1065. if (defined_values_double_declaration) {
  1066. exit_with_errors();
  1067. }
  1068. t_u8_ptr = alloc_type_pointer(t_u8);
  1069. t_u8_multi_ptr = alloc_type_multi_pointer(t_u8);
  1070. t_int_ptr = alloc_type_pointer(t_int);
  1071. t_i64_ptr = alloc_type_pointer(t_i64);
  1072. t_f64_ptr = alloc_type_pointer(t_f64);
  1073. t_u8_slice = alloc_type_slice(t_u8);
  1074. t_string_slice = alloc_type_slice(t_string);
  1075. // intrinsics types for objective-c stuff
  1076. {
  1077. t_objc_object = add_global_type_name(intrinsics_pkg->scope, str_lit("objc_object"), alloc_type_struct_complete());
  1078. t_objc_selector = add_global_type_name(intrinsics_pkg->scope, str_lit("objc_selector"), alloc_type_struct_complete());
  1079. t_objc_class = add_global_type_name(intrinsics_pkg->scope, str_lit("objc_class"), alloc_type_struct_complete());
  1080. t_objc_id = alloc_type_pointer(t_objc_object);
  1081. t_objc_SEL = alloc_type_pointer(t_objc_selector);
  1082. t_objc_Class = alloc_type_pointer(t_objc_class);
  1083. }
  1084. }
  1085. gb_internal void init_checker_info(CheckerInfo *i) {
  1086. gbAllocator a = heap_allocator();
  1087. TIME_SECTION("checker info: general");
  1088. array_init(&i->definitions, a);
  1089. array_init(&i->entities, a);
  1090. map_init(&i->global_untyped);
  1091. string_map_init(&i->foreigns);
  1092. // map_init(&i->gen_procs);
  1093. map_init(&i->gen_types);
  1094. array_init(&i->type_info_types, a);
  1095. map_init(&i->type_info_map);
  1096. string_map_init(&i->files);
  1097. string_map_init(&i->packages);
  1098. array_init(&i->variable_init_order, a);
  1099. array_init(&i->testing_procedures, a, 0, 0);
  1100. array_init(&i->init_procedures, a, 0, 0);
  1101. array_init(&i->fini_procedures, a, 0, 0);
  1102. array_init(&i->required_foreign_imports_through_force, a, 0, 0);
  1103. array_init(&i->defineables, a);
  1104. map_init(&i->objc_msgSend_types);
  1105. string_map_init(&i->load_file_cache);
  1106. array_init(&i->all_procedures, heap_allocator());
  1107. mpsc_init(&i->entity_queue, a); // 1<<20);
  1108. mpsc_init(&i->definition_queue, a); //); // 1<<20);
  1109. mpsc_init(&i->required_global_variable_queue, a); // 1<<10);
  1110. mpsc_init(&i->required_foreign_imports_through_force_queue, a); // 1<<10);
  1111. mpsc_init(&i->foreign_imports_to_check_fullpaths, a); // 1<<10);
  1112. mpsc_init(&i->intrinsics_entry_point_usage, a); // 1<<10); // just waste some memory here, even if it probably never used
  1113. string_map_init(&i->load_directory_cache);
  1114. map_init(&i->load_directory_map);
  1115. }
  1116. gb_internal void destroy_checker_info(CheckerInfo *i) {
  1117. array_free(&i->definitions);
  1118. array_free(&i->entities);
  1119. map_destroy(&i->global_untyped);
  1120. string_map_destroy(&i->foreigns);
  1121. // map_destroy(&i->gen_procs);
  1122. map_destroy(&i->gen_types);
  1123. array_free(&i->type_info_types);
  1124. map_destroy(&i->type_info_map);
  1125. string_map_destroy(&i->files);
  1126. string_map_destroy(&i->packages);
  1127. array_free(&i->variable_init_order);
  1128. array_free(&i->required_foreign_imports_through_force);
  1129. array_free(&i->defineables);
  1130. mpsc_destroy(&i->entity_queue);
  1131. mpsc_destroy(&i->definition_queue);
  1132. mpsc_destroy(&i->required_global_variable_queue);
  1133. mpsc_destroy(&i->required_foreign_imports_through_force_queue);
  1134. mpsc_destroy(&i->foreign_imports_to_check_fullpaths);
  1135. map_destroy(&i->objc_msgSend_types);
  1136. string_map_destroy(&i->load_file_cache);
  1137. string_map_destroy(&i->load_directory_cache);
  1138. map_destroy(&i->load_directory_map);
  1139. }
  1140. gb_internal CheckerContext make_checker_context(Checker *c) {
  1141. CheckerContext ctx = {};
  1142. ctx.checker = c;
  1143. ctx.info = &c->info;
  1144. ctx.scope = builtin_pkg->scope;
  1145. ctx.pkg = builtin_pkg;
  1146. ctx.type_path = new_checker_type_path();
  1147. ctx.type_level = 0;
  1148. return ctx;
  1149. }
  1150. gb_internal void destroy_checker_context(CheckerContext *ctx) {
  1151. destroy_checker_type_path(ctx->type_path);
  1152. }
  1153. gb_internal bool add_curr_ast_file(CheckerContext *ctx, AstFile *file) {
  1154. if (file != nullptr) {
  1155. ctx->file = file;
  1156. ctx->decl = file->pkg->decl_info;
  1157. ctx->scope = file->scope;
  1158. ctx->pkg = file->pkg;
  1159. return true;
  1160. }
  1161. return false;
  1162. }
  1163. gb_internal void reset_checker_context(CheckerContext *ctx, AstFile *file, UntypedExprInfoMap *untyped) {
  1164. if (ctx == nullptr) {
  1165. return;
  1166. }
  1167. GB_ASSERT(ctx->checker != nullptr);
  1168. mutex_lock(&ctx->mutex);
  1169. auto type_path = ctx->type_path;
  1170. array_clear(type_path);
  1171. gb_zero_size(&ctx->pkg, gb_size_of(CheckerContext) - gb_offset_of(CheckerContext, pkg));
  1172. ctx->file = nullptr;
  1173. ctx->scope = builtin_pkg->scope;
  1174. ctx->pkg = builtin_pkg;
  1175. ctx->decl = nullptr;
  1176. ctx->type_path = type_path;
  1177. ctx->type_level = 0;
  1178. add_curr_ast_file(ctx, file);
  1179. ctx->untyped = untyped;
  1180. mutex_unlock(&ctx->mutex);
  1181. }
  1182. gb_internal void init_checker(Checker *c) {
  1183. gbAllocator a = heap_allocator();
  1184. TIME_SECTION("init checker info");
  1185. init_checker_info(&c->info);
  1186. c->info.checker = c;
  1187. TIME_SECTION("init proc queues");
  1188. mpsc_init(&c->procs_with_deferred_to_check, a); //, 1<<10);
  1189. // NOTE(bill): 1 Mi elements should be enough on average
  1190. array_init(&c->procs_to_check, heap_allocator(), 0, 1<<20);
  1191. array_init(&c->nested_proc_lits, heap_allocator(), 0, 1<<20);
  1192. mpsc_init(&c->global_untyped_queue, a); // , 1<<20);
  1193. mpsc_init(&c->soa_types_to_complete, a); // , 1<<20);
  1194. c->builtin_ctx = make_checker_context(c);
  1195. }
  1196. gb_internal void destroy_checker(Checker *c) {
  1197. destroy_checker_info(&c->info);
  1198. destroy_checker_context(&c->builtin_ctx);
  1199. array_free(&c->nested_proc_lits);
  1200. array_free(&c->procs_to_check);
  1201. mpsc_destroy(&c->global_untyped_queue);
  1202. mpsc_destroy(&c->soa_types_to_complete);
  1203. }
  1204. gb_internal TypeAndValue type_and_value_of_expr(Ast *expr) {
  1205. TypeAndValue tav = {};
  1206. if (expr != nullptr) {
  1207. tav = expr->tav;
  1208. }
  1209. return tav;
  1210. }
  1211. gb_internal Type *type_of_expr(Ast *expr) {
  1212. TypeAndValue tav = expr->tav;
  1213. if (tav.mode != Addressing_Invalid) {
  1214. return tav.type;
  1215. }
  1216. {
  1217. Entity *entity = entity_of_node(expr);
  1218. if (entity) {
  1219. return entity->type;
  1220. }
  1221. }
  1222. return nullptr;
  1223. }
  1224. gb_internal Entity *implicit_entity_of_node(Ast *clause) {
  1225. if (clause != nullptr && clause->kind == Ast_CaseClause) {
  1226. return clause->CaseClause.implicit_entity;
  1227. }
  1228. return nullptr;
  1229. }
  1230. gb_internal Entity *entity_of_node(Ast *expr) {
  1231. retry:;
  1232. expr = unparen_expr(expr);
  1233. switch (expr->kind) {
  1234. case_ast_node(ident, Ident, expr);
  1235. Entity *e = ident->entity;
  1236. if (e && e->flags & EntityFlag_Overridden) {
  1237. // GB_PANIC("use of an overriden entity: %.*s", LIT(e->token.string));
  1238. }
  1239. return e;
  1240. case_end;
  1241. case_ast_node(se, SelectorExpr, expr);
  1242. Ast *s = unselector_expr(se->selector);
  1243. return entity_of_node(s);
  1244. case_end;
  1245. case_ast_node(cc, CaseClause, expr);
  1246. return cc->implicit_entity;
  1247. case_end;
  1248. case_ast_node(ce, CallExpr, expr);
  1249. return ce->entity_procedure_of;
  1250. case_end;
  1251. case_ast_node(we, TernaryWhenExpr, expr);
  1252. if (we->cond == nullptr) {
  1253. break;
  1254. }
  1255. if (we->cond->tav.value.kind != ExactValue_Bool) {
  1256. break;
  1257. }
  1258. expr = we->cond->tav.value.value_bool ? we->x : we->y;
  1259. goto retry;
  1260. case_end;
  1261. }
  1262. return nullptr;
  1263. }
  1264. gb_internal DeclInfo *decl_info_of_entity(Entity *e) {
  1265. if (e != nullptr) {
  1266. return e->decl_info;
  1267. }
  1268. return nullptr;
  1269. }
  1270. // gb_internal DeclInfo *decl_info_of_ident(Ast *ident) {
  1271. // return decl_info_of_entity(entity_of_node(ident));
  1272. // }
  1273. // gb_internal AstFile *ast_file_of_filename(CheckerInfo *i, String filename) {
  1274. // AstFile **found = string_map_get(&i->files, filename);
  1275. // if (found != nullptr) {
  1276. // return *found;
  1277. // }
  1278. // return nullptr;
  1279. // }
  1280. gb_internal ExprInfo *check_get_expr_info(CheckerContext *c, Ast *expr) {
  1281. if (c->untyped != nullptr) {
  1282. ExprInfo **found = map_get(c->untyped, expr);
  1283. if (found) {
  1284. return *found;
  1285. }
  1286. return nullptr;
  1287. } else {
  1288. rw_mutex_shared_lock(&c->info->global_untyped_mutex);
  1289. ExprInfo **found = map_get(&c->info->global_untyped, expr);
  1290. rw_mutex_shared_unlock(&c->info->global_untyped_mutex);
  1291. if (found) {
  1292. return *found;
  1293. }
  1294. return nullptr;
  1295. }
  1296. }
  1297. gb_internal void check_set_expr_info(CheckerContext *c, Ast *expr, AddressingMode mode, Type *type, ExactValue value) {
  1298. if (c->untyped != nullptr) {
  1299. map_set(c->untyped, expr, make_expr_info(mode, type, value, false));
  1300. } else {
  1301. rw_mutex_lock(&c->info->global_untyped_mutex);
  1302. map_set(&c->info->global_untyped, expr, make_expr_info(mode, type, value, false));
  1303. rw_mutex_unlock(&c->info->global_untyped_mutex);
  1304. }
  1305. }
  1306. gb_internal void check_remove_expr_info(CheckerContext *c, Ast *e) {
  1307. if (c->untyped != nullptr) {
  1308. map_remove(c->untyped, e);
  1309. GB_ASSERT(map_get(c->untyped, e) == nullptr);
  1310. } else {
  1311. auto *untyped = &c->info->global_untyped;
  1312. rw_mutex_lock(&c->info->global_untyped_mutex);
  1313. map_remove(untyped, e);
  1314. GB_ASSERT(map_get(untyped, e) == nullptr);
  1315. rw_mutex_unlock(&c->info->global_untyped_mutex);
  1316. }
  1317. }
  1318. gb_internal isize type_info_index(CheckerInfo *info, Type *type, bool error_on_failure) {
  1319. type = default_type(type);
  1320. if (type == t_llvm_bool) {
  1321. type = t_bool;
  1322. }
  1323. mutex_lock(&info->type_info_mutex);
  1324. isize entry_index = -1;
  1325. isize *found_entry_index = map_get(&info->type_info_map, type);
  1326. if (found_entry_index) {
  1327. entry_index = *found_entry_index;
  1328. }
  1329. if (entry_index < 0) {
  1330. // NOTE(bill): Do manual linear search
  1331. for (auto const &e : info->type_info_map) {
  1332. if (are_types_identical_unique_tuples(e.key, type)) {
  1333. entry_index = e.value;
  1334. // NOTE(bill): Add it to the search map
  1335. map_set(&info->type_info_map, type, entry_index);
  1336. break;
  1337. }
  1338. }
  1339. }
  1340. mutex_unlock(&info->type_info_mutex);
  1341. if (error_on_failure && entry_index < 0) {
  1342. compiler_error("Type_Info for '%s' could not be found", type_to_string(type));
  1343. }
  1344. return entry_index;
  1345. }
  1346. gb_internal void add_untyped(CheckerContext *c, Ast *expr, AddressingMode mode, Type *type, ExactValue const &value) {
  1347. if (expr == nullptr) {
  1348. return;
  1349. }
  1350. if (mode == Addressing_Invalid) {
  1351. return;
  1352. }
  1353. if (mode == Addressing_Constant && type == t_invalid) {
  1354. compiler_error("add_untyped - invalid type: %s", type_to_string(type));
  1355. }
  1356. if (!is_type_untyped(type)) {
  1357. return;
  1358. }
  1359. check_set_expr_info(c, expr, mode, type, value);
  1360. }
  1361. gb_internal void add_type_and_value(CheckerContext *ctx, Ast *expr, AddressingMode mode, Type *type, ExactValue const &value) {
  1362. if (expr == nullptr) {
  1363. return;
  1364. }
  1365. if (mode == Addressing_Invalid) {
  1366. return;
  1367. }
  1368. if (mode == Addressing_Constant && type == t_invalid) {
  1369. return;
  1370. }
  1371. BlockingMutex *mutex = &ctx->info->type_and_value_mutex;
  1372. if (ctx->decl) {
  1373. mutex = &ctx->decl->type_and_value_mutex;
  1374. } else if (ctx->pkg) {
  1375. mutex = &ctx->pkg->type_and_value_mutex;
  1376. }
  1377. mutex_lock(mutex);
  1378. Ast *prev_expr = nullptr;
  1379. while (prev_expr != expr) {
  1380. prev_expr = expr;
  1381. expr->tav.mode = mode;
  1382. if (type != nullptr && expr->tav.type != nullptr &&
  1383. is_type_any(type) && is_type_untyped(expr->tav.type)) {
  1384. // ignore
  1385. } else {
  1386. expr->tav.type = type;
  1387. }
  1388. if (mode == Addressing_Constant || mode == Addressing_Invalid) {
  1389. expr->tav.value = value;
  1390. } else if (mode == Addressing_Value && type != nullptr && is_type_typeid(type)) {
  1391. expr->tav.value = value;
  1392. } else if (mode == Addressing_Value && type != nullptr && is_type_proc(type)) {
  1393. expr->tav.value = value;
  1394. }
  1395. expr = unparen_expr(expr);
  1396. }
  1397. mutex_unlock(mutex);
  1398. }
  1399. gb_internal void add_entity_definition(CheckerInfo *i, Ast *identifier, Entity *entity) {
  1400. GB_ASSERT(identifier != nullptr);
  1401. if (identifier->kind != Ast_Ident) {
  1402. return;
  1403. }
  1404. if (identifier->Ident.entity != nullptr) {
  1405. // NOTE(bill): Identifier has already been handled
  1406. return;
  1407. }
  1408. GB_ASSERT(entity != nullptr);
  1409. identifier->Ident.entity = entity;
  1410. entity->identifier = identifier;
  1411. mpsc_enqueue(&i->definition_queue, entity);
  1412. }
  1413. gb_internal bool redeclaration_error(String name, Entity *prev, Entity *found) {
  1414. TokenPos pos = found->token.pos;
  1415. Entity *up = found->using_parent;
  1416. if (up != nullptr) {
  1417. if (pos == up->token.pos) {
  1418. // NOTE(bill): Error should have been handled already
  1419. return false;
  1420. }
  1421. if (found->flags & EntityFlag_Result) {
  1422. error(prev->token,
  1423. "Direct shadowing of the named return value '%.*s' in this scope through 'using'\n"
  1424. "\tat %s",
  1425. LIT(name),
  1426. token_pos_to_string(up->token.pos));
  1427. } else {
  1428. error(prev->token,
  1429. "Redeclaration of '%.*s' in this scope through 'using'\n"
  1430. "\tat %s",
  1431. LIT(name),
  1432. token_pos_to_string(up->token.pos));
  1433. }
  1434. } else {
  1435. if (pos == prev->token.pos) {
  1436. // NOTE(bill): Error should have been handled already
  1437. return false;
  1438. }
  1439. if (found->flags & EntityFlag_Result) {
  1440. error(prev->token,
  1441. "Direct shadowing of the named return value '%.*s' in this scope\n"
  1442. "\tat %s",
  1443. LIT(name),
  1444. token_pos_to_string(pos));
  1445. } else {
  1446. error(prev->token,
  1447. "Redeclaration of '%.*s' in this scope\n"
  1448. "\tat %s",
  1449. LIT(name),
  1450. token_pos_to_string(pos));
  1451. }
  1452. }
  1453. return false;
  1454. }
  1455. gb_internal void add_entity_flags_from_file(CheckerContext *c, Entity *e, Scope *scope) {
  1456. if (c->file != nullptr && (c->file->flags & AstFile_IsLazy) != 0 && scope->flags & ScopeFlag_File) {
  1457. AstPackage *pkg = c->file->pkg;
  1458. if (pkg->kind == Package_Init && e->kind == Entity_Procedure && e->token.string == "main") {
  1459. // Do nothing
  1460. } else if (e->flags & (EntityFlag_Test|EntityFlag_Init|EntityFlag_Fini)) {
  1461. // Do nothing
  1462. } else {
  1463. e->flags |= EntityFlag_Lazy;
  1464. }
  1465. }
  1466. }
  1467. gb_internal bool add_entity_with_name(CheckerContext *c, Scope *scope, Ast *identifier, Entity *entity, String name) {
  1468. if (scope == nullptr) {
  1469. return false;
  1470. }
  1471. if (!is_blank_ident(name)) {
  1472. Entity *ie = scope_insert(scope, entity);
  1473. if (ie != nullptr) {
  1474. return redeclaration_error(name, entity, ie);
  1475. }
  1476. }
  1477. if (identifier != nullptr) {
  1478. if (entity->file == nullptr) {
  1479. entity->file = c->file;
  1480. }
  1481. add_entity_definition(c->info, identifier, entity);
  1482. }
  1483. return true;
  1484. }
  1485. gb_internal bool add_entity_with_name(CheckerInfo *info, Scope *scope, Ast *identifier, Entity *entity, String name) {
  1486. if (scope == nullptr) {
  1487. return false;
  1488. }
  1489. if (!is_blank_ident(name)) {
  1490. Entity *ie = scope_insert(scope, entity);
  1491. if (ie != nullptr) {
  1492. return redeclaration_error(name, entity, ie);
  1493. }
  1494. }
  1495. if (identifier != nullptr) {
  1496. GB_ASSERT(entity->file != nullptr);
  1497. add_entity_definition(info, identifier, entity);
  1498. }
  1499. return true;
  1500. }
  1501. gb_internal bool add_entity(CheckerContext *c, Scope *scope, Ast *identifier, Entity *entity) {
  1502. return add_entity_with_name(c, scope, identifier, entity, entity->token.string);
  1503. }
  1504. gb_internal void add_entity_use(CheckerContext *c, Ast *identifier, Entity *entity) {
  1505. if (entity == nullptr) {
  1506. return;
  1507. }
  1508. add_declaration_dependency(c, entity);
  1509. entity->flags |= EntityFlag_Used;
  1510. if (entity_has_deferred_procedure(entity)) {
  1511. Entity *deferred = entity->Procedure.deferred_procedure.entity;
  1512. add_entity_use(c, nullptr, deferred);
  1513. }
  1514. if (identifier == nullptr || identifier->kind != Ast_Ident) {
  1515. return;
  1516. }
  1517. entity->identifier.store(identifier);
  1518. identifier->Ident.entity = entity;
  1519. String dmsg = entity->deprecated_message;
  1520. if (dmsg.len > 0) {
  1521. warning(identifier, "%.*s is deprecated: %.*s", LIT(entity->token.string), LIT(dmsg));
  1522. }
  1523. String wmsg = entity->warning_message;
  1524. if (wmsg.len > 0) {
  1525. warning(identifier, "%.*s: %.*s", LIT(entity->token.string), LIT(wmsg));
  1526. }
  1527. }
  1528. gb_internal bool could_entity_be_lazy(Entity *e, DeclInfo *d) {
  1529. if ((e->flags & EntityFlag_Lazy) == 0) {
  1530. return false;
  1531. }
  1532. if (e->flags & (EntityFlag_Test|EntityFlag_Init|EntityFlag_Fini)) {
  1533. return false;
  1534. } else if (e->kind == Entity_Variable && e->Variable.is_export) {
  1535. return false;
  1536. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  1537. return false;
  1538. }
  1539. for (Ast *attr : d->attributes) {
  1540. if (attr->kind != Ast_Attribute) continue;
  1541. for (Ast *elem : attr->Attribute.elems) {
  1542. String name = {};
  1543. switch (elem->kind) {
  1544. case_ast_node(i, Ident, elem);
  1545. name = i->token.string;
  1546. case_end;
  1547. case_ast_node(i, Implicit, elem);
  1548. name = i->string;
  1549. case_end;
  1550. case_ast_node(fv, FieldValue, elem);
  1551. if (fv->field->kind == Ast_Ident) {
  1552. name = fv->field->Ident.token.string;
  1553. }
  1554. case_end;
  1555. }
  1556. if (name.len != 0) {
  1557. if (name == "test") {
  1558. return false;
  1559. } else if (name == "export") {
  1560. return false;
  1561. } else if (name == "init") {
  1562. return false;
  1563. } else if (name == "linkage") {
  1564. return false;
  1565. }
  1566. }
  1567. }
  1568. }
  1569. return true;
  1570. }
  1571. gb_internal void add_entity_and_decl_info(CheckerContext *c, Ast *identifier, Entity *e, DeclInfo *d, bool is_exported) {
  1572. if (identifier == nullptr) {
  1573. // NOTE(bill): Should only happen on errors
  1574. error(e->token, "Invalid variable declaration");
  1575. return;
  1576. }
  1577. if (identifier->kind != Ast_Ident) {
  1578. // NOTE(bill): This is a safety check
  1579. gbString s = expr_to_string(identifier);
  1580. error(identifier, "A variable declaration must be an identifer, got %s", s);
  1581. gb_string_free(s);
  1582. return;
  1583. }
  1584. GB_ASSERT(e != nullptr && d != nullptr);
  1585. GB_ASSERT(identifier->Ident.token.string == e->token.string);
  1586. if (!could_entity_be_lazy(e, d)) {
  1587. e->flags &= ~EntityFlag_Lazy;
  1588. }
  1589. if (e->scope != nullptr) {
  1590. Scope *scope = e->scope;
  1591. if (scope->flags & ScopeFlag_File && is_entity_kind_exported(e->kind) && is_exported) {
  1592. AstPackage *pkg = scope->file->pkg;
  1593. GB_ASSERT(pkg->scope == scope->parent);
  1594. GB_ASSERT(c->pkg == pkg);
  1595. // NOTE(bill): as multiple threads could be accessing this, it needs to be wrapped
  1596. // The current hash map for scopes is not thread safe
  1597. AstPackageExportedEntity ee = {identifier, e};
  1598. mpmc_enqueue(&pkg->exported_entity_queue, ee);
  1599. // mutex_lock(&c->info->scope_mutex);
  1600. // add_entity(c, pkg->scope, identifier, e);
  1601. // mutex_unlock(&c->info->scope_mutex);
  1602. } else {
  1603. add_entity(c, scope, identifier, e);
  1604. }
  1605. }
  1606. CheckerInfo *info = c->info;
  1607. add_entity_definition(info, identifier, e);
  1608. GB_ASSERT(e->decl_info == nullptr);
  1609. e->decl_info = d;
  1610. d->entity = e;
  1611. e->pkg = c->pkg;
  1612. isize queue_count = -1;
  1613. bool is_lazy = false;
  1614. is_lazy = (e->flags & EntityFlag_Lazy) == EntityFlag_Lazy;
  1615. if (!is_lazy) {
  1616. queue_count = mpsc_enqueue(&info->entity_queue, e);
  1617. }
  1618. if (e->token.pos.file_id != 0) {
  1619. e->order_in_src = cast(u64)(e->token.pos.file_id)<<32 | u32(e->token.pos.offset);
  1620. } else {
  1621. GB_ASSERT(!is_lazy);
  1622. e->order_in_src = cast(u64)(1+queue_count);
  1623. }
  1624. }
  1625. gb_internal void add_implicit_entity(CheckerContext *c, Ast *clause, Entity *e) {
  1626. GB_ASSERT(clause != nullptr);
  1627. GB_ASSERT(e != nullptr);
  1628. GB_ASSERT(clause->kind == Ast_CaseClause);
  1629. clause->CaseClause.implicit_entity = e;
  1630. }
  1631. gb_internal void add_type_info_type_internal(CheckerContext *c, Type *t);
  1632. gb_internal void add_type_info_type(CheckerContext *c, Type *t) {
  1633. if (build_context.no_rtti) {
  1634. return;
  1635. }
  1636. if (t == nullptr) {
  1637. return;
  1638. }
  1639. t = default_type(t);
  1640. if (is_type_untyped(t)) {
  1641. return; // Could be nil
  1642. }
  1643. if (is_type_polymorphic(t)) {
  1644. return;
  1645. }
  1646. add_type_info_type_internal(c, t);
  1647. }
  1648. gb_internal void add_type_info_type_internal(CheckerContext *c, Type *t) {
  1649. if (t == nullptr) {
  1650. return;
  1651. }
  1652. add_type_info_dependency(c->info, c->decl, t);
  1653. MUTEX_GUARD_BLOCK(&c->info->type_info_mutex) {
  1654. auto found = map_get(&c->info->type_info_map, t);
  1655. if (found != nullptr) {
  1656. // Types have already been added
  1657. return;
  1658. }
  1659. bool prev = false;
  1660. isize ti_index = -1;
  1661. // NOTE(bill): this is a linear lookup, and is most likely very costly
  1662. // as this map keeps growing linearly
  1663. for (auto const &e : c->info->type_info_map) {
  1664. if (are_types_identical_unique_tuples(t, e.key)) {
  1665. // Duplicate entry
  1666. ti_index = e.value;
  1667. prev = true;
  1668. break;
  1669. }
  1670. }
  1671. if (ti_index < 0) {
  1672. // Unique entry
  1673. // NOTE(bill): map entries grow linearly and in order
  1674. ti_index = c->info->type_info_types.count;
  1675. array_add(&c->info->type_info_types, t);
  1676. }
  1677. map_set(&c->checker->info.type_info_map, t, ti_index);
  1678. if (prev) {
  1679. // NOTE(bill): If a previous one exists already, no need to continue
  1680. return;
  1681. }
  1682. }
  1683. // Add nested types
  1684. if (t->kind == Type_Named) {
  1685. // NOTE(bill): Just in case
  1686. add_type_info_type_internal(c, t->Named.base);
  1687. return;
  1688. }
  1689. Type *bt = base_type(t);
  1690. add_type_info_type_internal(c, bt);
  1691. switch (bt->kind) {
  1692. case Type_Invalid:
  1693. break;
  1694. case Type_Basic:
  1695. switch (bt->Basic.kind) {
  1696. case Basic_cstring:
  1697. add_type_info_type_internal(c, t_u8_ptr);
  1698. break;
  1699. case Basic_string:
  1700. add_type_info_type_internal(c, t_u8_ptr);
  1701. add_type_info_type_internal(c, t_int);
  1702. break;
  1703. case Basic_any:
  1704. add_type_info_type_internal(c, t_type_info_ptr);
  1705. add_type_info_type_internal(c, t_rawptr);
  1706. break;
  1707. case Basic_typeid:
  1708. break;
  1709. case Basic_complex64:
  1710. add_type_info_type_internal(c, t_type_info_float);
  1711. add_type_info_type_internal(c, t_f32);
  1712. break;
  1713. case Basic_complex128:
  1714. add_type_info_type_internal(c, t_type_info_float);
  1715. add_type_info_type_internal(c, t_f64);
  1716. break;
  1717. case Basic_quaternion128:
  1718. add_type_info_type_internal(c, t_type_info_float);
  1719. add_type_info_type_internal(c, t_f32);
  1720. break;
  1721. case Basic_quaternion256:
  1722. add_type_info_type_internal(c, t_type_info_float);
  1723. add_type_info_type_internal(c, t_f64);
  1724. break;
  1725. }
  1726. break;
  1727. case Type_BitSet:
  1728. add_type_info_type_internal(c, bt->BitSet.elem);
  1729. add_type_info_type_internal(c, bt->BitSet.underlying);
  1730. break;
  1731. case Type_Pointer:
  1732. add_type_info_type_internal(c, bt->Pointer.elem);
  1733. break;
  1734. case Type_MultiPointer:
  1735. add_type_info_type_internal(c, bt->MultiPointer.elem);
  1736. break;
  1737. case Type_Array:
  1738. add_type_info_type_internal(c, bt->Array.elem);
  1739. add_type_info_type_internal(c, alloc_type_pointer(bt->Array.elem));
  1740. add_type_info_type_internal(c, t_int);
  1741. break;
  1742. case Type_EnumeratedArray:
  1743. add_type_info_type_internal(c, bt->EnumeratedArray.index);
  1744. add_type_info_type_internal(c, t_int);
  1745. add_type_info_type_internal(c, bt->EnumeratedArray.elem);
  1746. add_type_info_type_internal(c, alloc_type_pointer(bt->EnumeratedArray.elem));
  1747. break;
  1748. case Type_DynamicArray:
  1749. add_type_info_type_internal(c, bt->DynamicArray.elem);
  1750. add_type_info_type_internal(c, alloc_type_pointer(bt->DynamicArray.elem));
  1751. add_type_info_type_internal(c, t_int);
  1752. add_type_info_type_internal(c, t_allocator);
  1753. break;
  1754. case Type_Slice:
  1755. add_type_info_type_internal(c, bt->Slice.elem);
  1756. add_type_info_type_internal(c, alloc_type_pointer(bt->Slice.elem));
  1757. add_type_info_type_internal(c, t_int);
  1758. break;
  1759. case Type_Enum:
  1760. add_type_info_type_internal(c, bt->Enum.base_type);
  1761. break;
  1762. case Type_Union:
  1763. if (union_tag_size(t) > 0) {
  1764. add_type_info_type_internal(c, union_tag_type(t));
  1765. } else {
  1766. add_type_info_type_internal(c, t_type_info_ptr);
  1767. }
  1768. add_type_info_type_internal(c, bt->Union.polymorphic_params);
  1769. for_array(i, bt->Union.variants) {
  1770. add_type_info_type_internal(c, bt->Union.variants[i]);
  1771. }
  1772. if (bt->Union.scope != nullptr) {
  1773. for (auto const &entry : bt->Union.scope->elements) {
  1774. Entity *e = entry.value;
  1775. add_type_info_type_internal(c, e->type);
  1776. }
  1777. }
  1778. break;
  1779. case Type_Struct:
  1780. if (bt->Struct.fields_wait_signal.futex.load() == 0)
  1781. return;
  1782. if (bt->Struct.scope != nullptr) {
  1783. for (auto const &entry : bt->Struct.scope->elements) {
  1784. Entity *e = entry.value;
  1785. switch (bt->Struct.soa_kind) {
  1786. case StructSoa_Dynamic:
  1787. add_type_info_type_internal(c, t_allocator);
  1788. /*fallthrough*/
  1789. case StructSoa_Slice:
  1790. case StructSoa_Fixed:
  1791. add_type_info_type_internal(c, alloc_type_pointer(e->type));
  1792. break;
  1793. default:
  1794. add_type_info_type_internal(c, e->type);
  1795. break;
  1796. }
  1797. }
  1798. }
  1799. add_type_info_type_internal(c, bt->Struct.polymorphic_params);
  1800. for_array(i, bt->Struct.fields) {
  1801. Entity *f = bt->Struct.fields[i];
  1802. if (f && f->type) {
  1803. add_type_info_type_internal(c, f->type);
  1804. }
  1805. }
  1806. add_comparison_procedures_for_fields(c, bt);
  1807. break;
  1808. case Type_Map:
  1809. init_map_internal_types(bt);
  1810. add_type_info_type_internal(c, bt->Map.key);
  1811. add_type_info_type_internal(c, bt->Map.value);
  1812. add_type_info_type_internal(c, t_uintptr); // hash value
  1813. add_type_info_type_internal(c, t_allocator);
  1814. break;
  1815. case Type_Tuple:
  1816. for_array(i, bt->Tuple.variables) {
  1817. Entity *var = bt->Tuple.variables[i];
  1818. add_type_info_type_internal(c, var->type);
  1819. }
  1820. break;
  1821. case Type_Proc:
  1822. add_type_info_type_internal(c, bt->Proc.params);
  1823. add_type_info_type_internal(c, bt->Proc.results);
  1824. break;
  1825. case Type_SimdVector:
  1826. add_type_info_type_internal(c, bt->SimdVector.elem);
  1827. break;
  1828. case Type_RelativePointer:
  1829. add_type_info_type_internal(c, bt->RelativePointer.pointer_type);
  1830. add_type_info_type_internal(c, bt->RelativePointer.base_integer);
  1831. break;
  1832. case Type_RelativeMultiPointer:
  1833. add_type_info_type_internal(c, bt->RelativeMultiPointer.pointer_type);
  1834. add_type_info_type_internal(c, bt->RelativeMultiPointer.base_integer);
  1835. break;
  1836. case Type_Matrix:
  1837. add_type_info_type_internal(c, bt->Matrix.elem);
  1838. break;
  1839. case Type_SoaPointer:
  1840. add_type_info_type_internal(c, bt->SoaPointer.elem);
  1841. break;
  1842. case Type_BitField:
  1843. add_type_info_type_internal(c, bt->BitField.backing_type);
  1844. for (Entity *f : bt->BitField.fields) {
  1845. add_type_info_type_internal(c, f->type);
  1846. }
  1847. break;
  1848. case Type_Generic:
  1849. break;
  1850. default:
  1851. GB_PANIC("Unhandled type: %*.s %d", LIT(type_strings[bt->kind]), bt->kind);
  1852. break;
  1853. }
  1854. }
  1855. gb_global std::atomic<bool> global_procedure_body_in_worker_queue;
  1856. gb_global std::atomic<bool> global_after_checking_procedure_bodies;
  1857. gb_internal WORKER_TASK_PROC(check_proc_info_worker_proc);
  1858. gb_internal void check_procedure_later(Checker *c, ProcInfo *info) {
  1859. GB_ASSERT(info != nullptr);
  1860. GB_ASSERT(info->decl != nullptr);
  1861. if (global_after_checking_procedure_bodies) {
  1862. Entity *e = info->decl->entity;
  1863. debugf("CHECK PROCEDURE LATER! %.*s :: %s {...}\n", LIT(e->token.string), type_to_string(e->type));
  1864. }
  1865. if (global_procedure_body_in_worker_queue.load()) {
  1866. thread_pool_add_task(check_proc_info_worker_proc, info);
  1867. } else {
  1868. array_add(&c->procs_to_check, info);
  1869. }
  1870. if (DEBUG_CHECK_ALL_PROCEDURES) {
  1871. MUTEX_GUARD_BLOCK(&c->info.all_procedures_mutex) {
  1872. GB_ASSERT(info != nullptr);
  1873. GB_ASSERT(info->decl != nullptr);
  1874. array_add(&c->info.all_procedures, info);
  1875. }
  1876. }
  1877. }
  1878. gb_internal void check_procedure_later(Checker *c, AstFile *file, Token token, DeclInfo *decl, Type *type, Ast *body, u64 tags) {
  1879. ProcInfo *info = gb_alloc_item(permanent_allocator(), ProcInfo);
  1880. info->file = file;
  1881. info->token = token;
  1882. info->decl = decl;
  1883. info->type = type;
  1884. info->body = body;
  1885. info->tags = tags;
  1886. check_procedure_later(c, info);
  1887. }
  1888. gb_internal void add_min_dep_type_info(Checker *c, Type *t) {
  1889. if (t == nullptr) {
  1890. return;
  1891. }
  1892. t = default_type(t);
  1893. if (is_type_untyped(t)) {
  1894. return; // Could be nil
  1895. }
  1896. if (is_type_polymorphic(base_type(t))) {
  1897. return;
  1898. }
  1899. auto *set = &c->info.minimum_dependency_type_info_set;
  1900. isize ti_index = type_info_index(&c->info, t, false);
  1901. if (ti_index < 0) {
  1902. add_type_info_type(&c->builtin_ctx, t); // Missing the type information
  1903. ti_index = type_info_index(&c->info, t, false);
  1904. }
  1905. GB_ASSERT(ti_index >= 0);
  1906. // IMPORTANT NOTE(bill): this must be copied as `map_set` takes a const ref
  1907. // and effectively assigns the `+1` of the value
  1908. isize const count = set->count;
  1909. if (map_set_if_not_previously_exists(set, ti_index+1, count)) {
  1910. // Type already exists;
  1911. return;
  1912. }
  1913. // Add nested types
  1914. if (t->kind == Type_Named) {
  1915. // NOTE(bill): Just in case
  1916. add_min_dep_type_info(c, t->Named.base);
  1917. return;
  1918. }
  1919. Type *bt = base_type(t);
  1920. add_min_dep_type_info(c, bt);
  1921. switch (bt->kind) {
  1922. case Type_Invalid:
  1923. break;
  1924. case Type_Basic:
  1925. switch (bt->Basic.kind) {
  1926. case Basic_string:
  1927. add_min_dep_type_info(c, t_u8_ptr);
  1928. add_min_dep_type_info(c, t_int);
  1929. break;
  1930. case Basic_any:
  1931. add_min_dep_type_info(c, t_rawptr);
  1932. add_min_dep_type_info(c, t_typeid);
  1933. break;
  1934. case Basic_complex64:
  1935. add_min_dep_type_info(c, t_type_info_float);
  1936. add_min_dep_type_info(c, t_f32);
  1937. break;
  1938. case Basic_complex128:
  1939. add_min_dep_type_info(c, t_type_info_float);
  1940. add_min_dep_type_info(c, t_f64);
  1941. break;
  1942. case Basic_quaternion128:
  1943. add_min_dep_type_info(c, t_type_info_float);
  1944. add_min_dep_type_info(c, t_f32);
  1945. break;
  1946. case Basic_quaternion256:
  1947. add_min_dep_type_info(c, t_type_info_float);
  1948. add_min_dep_type_info(c, t_f64);
  1949. break;
  1950. }
  1951. break;
  1952. case Type_BitSet:
  1953. add_min_dep_type_info(c, bt->BitSet.elem);
  1954. add_min_dep_type_info(c, bt->BitSet.underlying);
  1955. break;
  1956. case Type_Pointer:
  1957. add_min_dep_type_info(c, bt->Pointer.elem);
  1958. break;
  1959. case Type_MultiPointer:
  1960. add_min_dep_type_info(c, bt->MultiPointer.elem);
  1961. break;
  1962. case Type_Array:
  1963. add_min_dep_type_info(c, bt->Array.elem);
  1964. add_min_dep_type_info(c, alloc_type_pointer(bt->Array.elem));
  1965. add_min_dep_type_info(c, t_int);
  1966. break;
  1967. case Type_EnumeratedArray:
  1968. add_min_dep_type_info(c, bt->EnumeratedArray.index);
  1969. add_min_dep_type_info(c, t_int);
  1970. add_min_dep_type_info(c, bt->EnumeratedArray.elem);
  1971. add_min_dep_type_info(c, alloc_type_pointer(bt->EnumeratedArray.elem));
  1972. break;
  1973. case Type_DynamicArray:
  1974. add_min_dep_type_info(c, bt->DynamicArray.elem);
  1975. add_min_dep_type_info(c, alloc_type_pointer(bt->DynamicArray.elem));
  1976. add_min_dep_type_info(c, t_int);
  1977. add_min_dep_type_info(c, t_allocator);
  1978. break;
  1979. case Type_Slice:
  1980. add_min_dep_type_info(c, bt->Slice.elem);
  1981. add_min_dep_type_info(c, alloc_type_pointer(bt->Slice.elem));
  1982. add_min_dep_type_info(c, t_int);
  1983. break;
  1984. case Type_Enum:
  1985. add_min_dep_type_info(c, bt->Enum.base_type);
  1986. break;
  1987. case Type_Union:
  1988. if (union_tag_size(t) > 0) {
  1989. add_min_dep_type_info(c, union_tag_type(t));
  1990. } else {
  1991. add_min_dep_type_info(c, t_type_info_ptr);
  1992. }
  1993. add_min_dep_type_info(c, bt->Union.polymorphic_params);
  1994. for_array(i, bt->Union.variants) {
  1995. add_min_dep_type_info(c, bt->Union.variants[i]);
  1996. }
  1997. break;
  1998. case Type_Struct:
  1999. if (bt->Struct.scope != nullptr) {
  2000. for (auto const &entry : bt->Struct.scope->elements) {
  2001. Entity *e = entry.value;
  2002. switch (bt->Struct.soa_kind) {
  2003. case StructSoa_Dynamic:
  2004. add_min_dep_type_info(c, t_type_info_ptr); // append_soa
  2005. add_min_dep_type_info(c, t_allocator);
  2006. /*fallthrough*/
  2007. case StructSoa_Slice:
  2008. add_min_dep_type_info(c, t_int);
  2009. add_min_dep_type_info(c, t_uint);
  2010. /*fallthrough*/
  2011. case StructSoa_Fixed:
  2012. add_min_dep_type_info(c, alloc_type_pointer(e->type));
  2013. break;
  2014. default:
  2015. add_min_dep_type_info(c, e->type);
  2016. break;
  2017. }
  2018. }
  2019. }
  2020. add_min_dep_type_info(c, bt->Struct.polymorphic_params);
  2021. for_array(i, bt->Struct.fields) {
  2022. Entity *f = bt->Struct.fields[i];
  2023. add_min_dep_type_info(c, f->type);
  2024. }
  2025. break;
  2026. case Type_Map:
  2027. init_map_internal_types(bt);
  2028. add_min_dep_type_info(c, bt->Map.key);
  2029. add_min_dep_type_info(c, bt->Map.value);
  2030. add_min_dep_type_info(c, t_uintptr); // hash value
  2031. add_min_dep_type_info(c, t_allocator);
  2032. break;
  2033. case Type_Tuple:
  2034. for_array(i, bt->Tuple.variables) {
  2035. Entity *var = bt->Tuple.variables[i];
  2036. add_min_dep_type_info(c, var->type);
  2037. }
  2038. break;
  2039. case Type_Proc:
  2040. add_min_dep_type_info(c, bt->Proc.params);
  2041. add_min_dep_type_info(c, bt->Proc.results);
  2042. break;
  2043. case Type_SimdVector:
  2044. add_min_dep_type_info(c, bt->SimdVector.elem);
  2045. break;
  2046. case Type_RelativePointer:
  2047. add_min_dep_type_info(c, bt->RelativePointer.pointer_type);
  2048. add_min_dep_type_info(c, bt->RelativePointer.base_integer);
  2049. break;
  2050. case Type_RelativeMultiPointer:
  2051. add_min_dep_type_info(c, bt->RelativeMultiPointer.pointer_type);
  2052. add_min_dep_type_info(c, bt->RelativeMultiPointer.base_integer);
  2053. break;
  2054. case Type_Matrix:
  2055. add_min_dep_type_info(c, bt->Matrix.elem);
  2056. break;
  2057. case Type_SoaPointer:
  2058. add_min_dep_type_info(c, bt->SoaPointer.elem);
  2059. break;
  2060. case Type_BitField:
  2061. add_min_dep_type_info(c, bt->BitField.backing_type);
  2062. for (Entity *f : bt->BitField.fields) {
  2063. add_min_dep_type_info(c, f->type);
  2064. }
  2065. break;
  2066. default:
  2067. GB_PANIC("Unhandled type: %*.s", LIT(type_strings[bt->kind]));
  2068. break;
  2069. }
  2070. }
  2071. gb_internal void add_dependency_to_set(Checker *c, Entity *entity) {
  2072. if (entity == nullptr) {
  2073. return;
  2074. }
  2075. CheckerInfo *info = &c->info;
  2076. auto *set = &info->minimum_dependency_set;
  2077. if (entity->type != nullptr &&
  2078. is_type_polymorphic(entity->type)) {
  2079. DeclInfo *decl = decl_info_of_entity(entity);
  2080. if (decl != nullptr && decl->gen_proc_type == nullptr) {
  2081. return;
  2082. }
  2083. }
  2084. if (ptr_set_update(set, entity)) {
  2085. return;
  2086. }
  2087. DeclInfo *decl = decl_info_of_entity(entity);
  2088. if (decl == nullptr) {
  2089. return;
  2090. }
  2091. for (Type *t : decl->type_info_deps) {
  2092. add_min_dep_type_info(c, t);
  2093. }
  2094. for (Entity *e : decl->deps) {
  2095. add_dependency_to_set(c, e);
  2096. if (e->kind == Entity_Procedure && e->Procedure.is_foreign) {
  2097. Entity *fl = e->Procedure.foreign_library;
  2098. if (fl != nullptr) {
  2099. GB_ASSERT_MSG(fl->kind == Entity_LibraryName &&
  2100. (fl->flags&EntityFlag_Used),
  2101. "%.*s", LIT(entity->token.string));
  2102. add_dependency_to_set(c, fl);
  2103. }
  2104. } else if (e->kind == Entity_Variable && e->Variable.is_foreign) {
  2105. Entity *fl = e->Variable.foreign_library;
  2106. if (fl != nullptr) {
  2107. GB_ASSERT_MSG(fl->kind == Entity_LibraryName &&
  2108. (fl->flags&EntityFlag_Used),
  2109. "%.*s", LIT(entity->token.string));
  2110. add_dependency_to_set(c, fl);
  2111. }
  2112. }
  2113. }
  2114. }
  2115. gb_internal void force_add_dependency_entity(Checker *c, Scope *scope, String const &name) {
  2116. Entity *e = scope_lookup(scope, name);
  2117. if (e == nullptr) {
  2118. return;
  2119. }
  2120. GB_ASSERT_MSG(e != nullptr, "unable to find %.*s", LIT(name));
  2121. e->flags |= EntityFlag_Used;
  2122. add_dependency_to_set(c, e);
  2123. }
  2124. gb_internal void collect_testing_procedures_of_package(Checker *c, AstPackage *pkg) {
  2125. AstPackage *testing_package = get_core_package(&c->info, str_lit("testing"));
  2126. Scope *testing_scope = testing_package->scope;
  2127. Entity *test_signature = scope_lookup_current(testing_scope, str_lit("Test_Signature"));
  2128. Scope *s = pkg->scope;
  2129. for (auto const &entry : s->elements) {
  2130. Entity *e = entry.value;
  2131. if (e->kind != Entity_Procedure) {
  2132. continue;
  2133. }
  2134. if ((e->flags & EntityFlag_Test) == 0) {
  2135. continue;
  2136. }
  2137. String name = e->token.string;
  2138. bool is_tester = true;
  2139. Type *t = base_type(e->type);
  2140. GB_ASSERT(t->kind == Type_Proc);
  2141. if (are_types_identical(t, base_type(test_signature->type))) {
  2142. // Good
  2143. } else {
  2144. gbString str = type_to_string(t);
  2145. error(e->token, "Testing procedures must have a signature type of proc(^testing.T), got %s", str);
  2146. gb_string_free(str);
  2147. is_tester = false;
  2148. }
  2149. if (is_tester) {
  2150. add_dependency_to_set(c, e);
  2151. array_add(&c->info.testing_procedures, e);
  2152. }
  2153. }
  2154. }
  2155. gb_internal void generate_minimum_dependency_set_internal(Checker *c, Entity *start) {
  2156. for_array(i, c->info.definitions) {
  2157. Entity *e = c->info.definitions[i];
  2158. if (e->scope == builtin_pkg->scope) {
  2159. if (e->type == nullptr) {
  2160. add_dependency_to_set(c, e);
  2161. }
  2162. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  2163. add_dependency_to_set(c, e);
  2164. } else if (e->kind == Entity_Variable && e->Variable.is_export) {
  2165. add_dependency_to_set(c, e);
  2166. }
  2167. }
  2168. for (Entity *e; mpsc_dequeue(&c->info.required_foreign_imports_through_force_queue, &e); /**/) {
  2169. array_add(&c->info.required_foreign_imports_through_force, e);
  2170. add_dependency_to_set(c, e);
  2171. }
  2172. for (Entity *e; mpsc_dequeue(&c->info.required_global_variable_queue, &e); /**/) {
  2173. e->flags |= EntityFlag_Used;
  2174. add_dependency_to_set(c, e);
  2175. }
  2176. for_array(i, c->info.entities) {
  2177. Entity *e = c->info.entities[i];
  2178. switch (e->kind) {
  2179. case Entity_Variable:
  2180. if (e->Variable.is_export) {
  2181. add_dependency_to_set(c, e);
  2182. } else if (e->flags & EntityFlag_Require) {
  2183. add_dependency_to_set(c, e);
  2184. }
  2185. break;
  2186. case Entity_Procedure:
  2187. if (e->Procedure.is_export) {
  2188. add_dependency_to_set(c, e);
  2189. } else if (e->flags & EntityFlag_Require) {
  2190. add_dependency_to_set(c, e);
  2191. }
  2192. if (e->flags & EntityFlag_Init) {
  2193. Type *t = base_type(e->type);
  2194. GB_ASSERT(t->kind == Type_Proc);
  2195. bool is_init = true;
  2196. if (t->Proc.param_count != 0 || t->Proc.result_count != 0) {
  2197. gbString str = type_to_string(t);
  2198. error(e->token, "@(init) procedures must have a signature type with no parameters nor results, got %s", str);
  2199. gb_string_free(str);
  2200. is_init = false;
  2201. }
  2202. if ((e->scope->flags & (ScopeFlag_File|ScopeFlag_Pkg)) == 0) {
  2203. error(e->token, "@(init) procedures must be declared at the file scope");
  2204. is_init = false;
  2205. }
  2206. if ((e->flags & EntityFlag_Disabled) != 0) {
  2207. warning(e->token, "This @(init) procedure is disabled; you must call it manually");
  2208. is_init = false;
  2209. }
  2210. if (is_init) {
  2211. add_dependency_to_set(c, e);
  2212. array_add(&c->info.init_procedures, e);
  2213. }
  2214. } else if (e->flags & EntityFlag_Fini) {
  2215. Type *t = base_type(e->type);
  2216. GB_ASSERT(t->kind == Type_Proc);
  2217. bool is_fini = true;
  2218. if (t->Proc.param_count != 0 || t->Proc.result_count != 0) {
  2219. gbString str = type_to_string(t);
  2220. error(e->token, "@(fini) procedures must have a signature type with no parameters nor results, got %s", str);
  2221. gb_string_free(str);
  2222. is_fini = false;
  2223. }
  2224. if ((e->scope->flags & (ScopeFlag_File|ScopeFlag_Pkg)) == 0) {
  2225. error(e->token, "@(fini) procedures must be declared at the file scope");
  2226. is_fini = false;
  2227. }
  2228. if (is_fini) {
  2229. add_dependency_to_set(c, e);
  2230. array_add(&c->info.fini_procedures, e);
  2231. }
  2232. }
  2233. break;
  2234. }
  2235. }
  2236. if (build_context.command_kind == Command_test) {
  2237. AstPackage *testing_package = get_core_package(&c->info, str_lit("testing"));
  2238. Scope *testing_scope = testing_package->scope;
  2239. // Add all of testing library as a dependency
  2240. for (auto const &entry : testing_scope->elements) {
  2241. Entity *e = entry.value;
  2242. if (e != nullptr) {
  2243. e->flags |= EntityFlag_Used;
  2244. add_dependency_to_set(c, e);
  2245. }
  2246. }
  2247. AstPackage *pkg = c->info.init_package;
  2248. collect_testing_procedures_of_package(c, pkg);
  2249. if (build_context.test_all_packages) {
  2250. for (auto const &entry : c->info.packages) {
  2251. AstPackage *pkg = entry.value;
  2252. collect_testing_procedures_of_package(c, pkg);
  2253. }
  2254. }
  2255. } else if (start != nullptr) {
  2256. start->flags |= EntityFlag_Used;
  2257. add_dependency_to_set(c, start);
  2258. }
  2259. }
  2260. gb_internal void generate_minimum_dependency_set(Checker *c, Entity *start) {
  2261. isize entity_count = c->info.entities.count;
  2262. isize min_dep_set_cap = next_pow2_isize(entity_count*4); // empirically determined factor
  2263. ptr_set_init(&c->info.minimum_dependency_set, min_dep_set_cap);
  2264. map_init(&c->info.minimum_dependency_type_info_set);
  2265. #define FORCE_ADD_RUNTIME_ENTITIES(condition, ...) do { \
  2266. if (condition) { \
  2267. String entities[] = {__VA_ARGS__}; \
  2268. for (isize i = 0; i < gb_count_of(entities); i++) { \
  2269. force_add_dependency_entity(c, c->info.runtime_package->scope, entities[i]); \
  2270. } \
  2271. } \
  2272. } while (0)
  2273. // required runtime entities
  2274. FORCE_ADD_RUNTIME_ENTITIES(true,
  2275. // Odin types
  2276. str_lit("Source_Code_Location"),
  2277. str_lit("Context"),
  2278. str_lit("Allocator"),
  2279. str_lit("Logger"),
  2280. // Odin internal procedures
  2281. str_lit("__init_context"),
  2282. // str_lit("cstring_to_string"),
  2283. str_lit("_cleanup_runtime"),
  2284. // Pseudo-CRT required procedures
  2285. str_lit("memset"),
  2286. // Utility procedures
  2287. str_lit("memory_equal"),
  2288. str_lit("memory_compare"),
  2289. str_lit("memory_compare_zero"),
  2290. );
  2291. // Only required if no CRT is present
  2292. FORCE_ADD_RUNTIME_ENTITIES(build_context.no_crt,
  2293. str_lit("memcpy"),
  2294. str_lit("memmove"),
  2295. );
  2296. FORCE_ADD_RUNTIME_ENTITIES(build_context.metrics.arch == TargetArch_arm32,
  2297. str_lit("aeabi_d2h")
  2298. );
  2299. FORCE_ADD_RUNTIME_ENTITIES(is_arch_wasm() && !build_context.tilde_backend,
  2300. // // Extended data type internal procedures
  2301. // str_lit("umodti3"),
  2302. // str_lit("udivti3"),
  2303. // str_lit("modti3"),
  2304. // str_lit("divti3"),
  2305. // str_lit("fixdfti"),
  2306. // str_lit("fixunsdfti"),
  2307. // str_lit("fixunsdfdi"),
  2308. // str_lit("floattidf"),
  2309. // str_lit("floattidf_unsigned"),
  2310. // str_lit("truncsfhf2"),
  2311. // str_lit("truncdfhf2"),
  2312. // str_lit("gnu_h2f_ieee"),
  2313. // str_lit("gnu_f2h_ieee"),
  2314. // str_lit("extendhfsf2"),
  2315. // WASM Specific
  2316. str_lit("__ashlti3"),
  2317. str_lit("__multi3"),
  2318. str_lit("__lshrti3"),
  2319. );
  2320. FORCE_ADD_RUNTIME_ENTITIES(!build_context.no_rtti,
  2321. // Odin types
  2322. str_lit("Type_Info"),
  2323. // Global variables
  2324. str_lit("type_table"),
  2325. str_lit("__type_info_of"),
  2326. );
  2327. FORCE_ADD_RUNTIME_ENTITIES(!build_context.no_entry_point,
  2328. // Global variables
  2329. str_lit("args__"),
  2330. );
  2331. FORCE_ADD_RUNTIME_ENTITIES((build_context.no_crt && !is_arch_wasm()),
  2332. // NOTE(bill): Only if these exist
  2333. str_lit("_tls_index"),
  2334. str_lit("_fltused"),
  2335. );
  2336. FORCE_ADD_RUNTIME_ENTITIES(!build_context.no_bounds_check,
  2337. // Bounds checking related procedures
  2338. str_lit("bounds_check_error"),
  2339. str_lit("matrix_bounds_check_error"),
  2340. str_lit("slice_expr_error_hi"),
  2341. str_lit("slice_expr_error_lo_hi"),
  2342. str_lit("multi_pointer_slice_expr_error"),
  2343. );
  2344. add_dependency_to_set(c, c->info.instrumentation_enter_entity);
  2345. add_dependency_to_set(c, c->info.instrumentation_exit_entity);
  2346. generate_minimum_dependency_set_internal(c, start);
  2347. #undef FORCE_ADD_RUNTIME_ENTITIES
  2348. }
  2349. gb_internal bool is_entity_a_dependency(Entity *e) {
  2350. if (e == nullptr) return false;
  2351. switch (e->kind) {
  2352. case Entity_Procedure:
  2353. return true;
  2354. case Entity_Constant:
  2355. case Entity_Variable:
  2356. return e->pkg != nullptr;
  2357. case Entity_TypeName:
  2358. return false;
  2359. }
  2360. return false;
  2361. }
  2362. gb_internal Array<EntityGraphNode *> generate_entity_dependency_graph(CheckerInfo *info, gbAllocator allocator) {
  2363. PtrMap<Entity *, EntityGraphNode *> M = {};
  2364. map_init(&M, info->entities.count);
  2365. defer (map_destroy(&M));
  2366. for_array(i, info->entities) {
  2367. Entity *e = info->entities[i];
  2368. if (is_entity_a_dependency(e)) {
  2369. EntityGraphNode *n = gb_alloc_item(allocator, EntityGraphNode);
  2370. n->entity = e;
  2371. map_set(&M, e, n);
  2372. }
  2373. }
  2374. TIME_SECTION("generate_entity_dependency_graph: Calculate edges for graph M - Part 1");
  2375. // Calculate edges for graph M
  2376. for (auto const &entry : M) {
  2377. EntityGraphNode *n = entry.value;
  2378. Entity *e = n->entity;
  2379. DeclInfo *decl = decl_info_of_entity(e);
  2380. GB_ASSERT(decl != nullptr);
  2381. for (Entity *dep : decl->deps) {
  2382. if (dep->flags & EntityFlag_Field) {
  2383. continue;
  2384. }
  2385. GB_ASSERT(dep != nullptr);
  2386. if (is_entity_a_dependency(dep)) {
  2387. EntityGraphNode *m = map_must_get(&M, dep);
  2388. entity_graph_node_set_add(&n->succ, m);
  2389. entity_graph_node_set_add(&m->pred, n);
  2390. }
  2391. }
  2392. }
  2393. TIME_SECTION("generate_entity_dependency_graph: Calculate edges for graph M - Part 2");
  2394. auto G = array_make<EntityGraphNode *>(allocator, 0, M.count);
  2395. for (auto const &m_entry : M) {
  2396. auto *e = m_entry.key;
  2397. EntityGraphNode *n = m_entry.value;
  2398. if (e->kind == Entity_Procedure) {
  2399. // Connect each pred 'p' of 'n' with each succ 's' and from
  2400. // the procedure node
  2401. for (EntityGraphNode *p : n->pred) {
  2402. // Ignore self-cycles
  2403. if (p != n) {
  2404. // Each succ 's' of 'n' becomes a succ of 'p', and
  2405. // each pred 'p' of 'n' becomes a pred of 's'
  2406. for (EntityGraphNode *s : n->succ) {
  2407. // Ignore self-cycles
  2408. if (s != n) {
  2409. if (p->entity->kind == Entity_Procedure &&
  2410. s->entity->kind == Entity_Procedure) {
  2411. // NOTE(bill, 2020-11-15): Only care about variable initialization ordering
  2412. // TODO(bill): This is probably wrong!!!!
  2413. continue;
  2414. }
  2415. // IMPORTANT NOTE/TODO(bill, 2020-11-15): These three calls take the majority of the
  2416. // the time to process
  2417. entity_graph_node_set_add(&p->succ, s);
  2418. entity_graph_node_set_add(&s->pred, p);
  2419. // Remove edge to 'n'
  2420. entity_graph_node_set_remove(&s->pred, n);
  2421. }
  2422. }
  2423. // Remove edge to 'n'
  2424. entity_graph_node_set_remove(&p->succ, n);
  2425. }
  2426. }
  2427. } else if (e->kind == Entity_Variable) {
  2428. array_add(&G, n);
  2429. }
  2430. }
  2431. TIME_SECTION("generate_entity_dependency_graph: Dependency Count Checker");
  2432. for_array(i, G) {
  2433. EntityGraphNode *n = G[i];
  2434. n->index = i;
  2435. n->dep_count = n->succ.count;
  2436. GB_ASSERT(n->dep_count >= 0);
  2437. }
  2438. // f64 succ_count = 0.0;
  2439. // f64 pred_count = 0.0;
  2440. // f64 succ_capacity = 0.0;
  2441. // f64 pred_capacity = 0.0;
  2442. // f64 succ_max = 0.0;
  2443. // f64 pred_max = 0.0;
  2444. // for_array(i, G) {
  2445. // EntityGraphNode *n = G[i];
  2446. // succ_count += n->succ.entries.count;
  2447. // pred_count += n->pred.entries.count;
  2448. // succ_capacity += n->succ.entries.capacity;
  2449. // pred_capacity += n->pred.entries.capacity;
  2450. // succ_max = gb_max(succ_max, n->succ.entries.capacity);
  2451. // pred_max = gb_max(pred_max, n->pred.entries.capacity);
  2452. // }
  2453. // f64 count = cast(f64)G.count;
  2454. // gb_printf_err(">>>count pred: %f succ: %f\n", pred_count/count, succ_count/count);
  2455. // gb_printf_err(">>>capacity pred: %f succ: %f\n", pred_capacity/count, succ_capacity/count);
  2456. // gb_printf_err(">>>max pred: %f succ: %f\n", pred_max, succ_max);
  2457. return G;
  2458. }
  2459. gb_internal void check_single_global_entity(Checker *c, Entity *e, DeclInfo *d);
  2460. gb_internal Entity *find_core_entity(Checker *c, String name) {
  2461. Entity *e = scope_lookup_current(c->info.runtime_package->scope, name);
  2462. if (e == nullptr) {
  2463. compiler_error("Could not find type declaration for '%.*s'\n"
  2464. , LIT(name));
  2465. // NOTE(bill): This will exit the program as it's cannot continue without it!
  2466. }
  2467. return e;
  2468. }
  2469. gb_internal Type *find_core_type(Checker *c, String name) {
  2470. Entity *e = scope_lookup_current(c->info.runtime_package->scope, name);
  2471. if (e == nullptr) {
  2472. compiler_error("Could not find type declaration for '%.*s'\n"
  2473. , LIT(name));
  2474. // NOTE(bill): This will exit the program as it's cannot continue without it!
  2475. }
  2476. if (e->type == nullptr) {
  2477. check_single_global_entity(c, e, e->decl_info);
  2478. }
  2479. GB_ASSERT(e->type != nullptr);
  2480. return e->type;
  2481. }
  2482. gb_internal Entity *find_entity_in_pkg(CheckerInfo *info, String const &pkg, String const &name) {
  2483. AstPackage *package = get_core_package(info, pkg);
  2484. Entity *e = scope_lookup_current(package->scope, name);
  2485. if (e == nullptr) {
  2486. compiler_error("Could not find type declaration for '%.*s.%.*s'\n", LIT(pkg), LIT(name));
  2487. // NOTE(bill): This will exit the program as it's cannot continue without it!
  2488. }
  2489. return e;
  2490. }
  2491. gb_internal Type *find_type_in_pkg(CheckerInfo *info, String const &pkg, String const &name) {
  2492. AstPackage *package = get_core_package(info, pkg);
  2493. Entity *e = scope_lookup_current(package->scope, name);
  2494. if (e == nullptr) {
  2495. compiler_error("Could not find type declaration for '%.*s.%.*s'\n", LIT(pkg), LIT(name));
  2496. // NOTE(bill): This will exit the program as it's cannot continue without it!
  2497. }
  2498. GB_ASSERT(e->type != nullptr);
  2499. return e->type;
  2500. }
  2501. gb_internal CheckerTypePath *new_checker_type_path() {
  2502. gbAllocator a = heap_allocator();
  2503. auto *tp = gb_alloc_item(a, CheckerTypePath);
  2504. array_init(tp, a, 0, 16);
  2505. return tp;
  2506. }
  2507. gb_internal void destroy_checker_type_path(CheckerTypePath *tp) {
  2508. array_free(tp);
  2509. gb_free(heap_allocator(), tp);
  2510. }
  2511. gb_internal void check_type_path_push(CheckerContext *c, Entity *e) {
  2512. GB_ASSERT(c->type_path != nullptr);
  2513. GB_ASSERT(e != nullptr);
  2514. array_add(c->type_path, e);
  2515. }
  2516. gb_internal Entity *check_type_path_pop(CheckerContext *c) {
  2517. GB_ASSERT(c->type_path != nullptr);
  2518. return array_pop(c->type_path);
  2519. }
  2520. gb_internal Array<Entity *> proc_group_entities(CheckerContext *c, Operand o) {
  2521. Array<Entity *> procs = {};
  2522. if (o.mode == Addressing_ProcGroup) {
  2523. GB_ASSERT(o.proc_group != nullptr);
  2524. if (o.proc_group->kind == Entity_ProcGroup) {
  2525. check_entity_decl(c, o.proc_group, nullptr, nullptr);
  2526. return o.proc_group->ProcGroup.entities;
  2527. }
  2528. }
  2529. return procs;
  2530. }
  2531. gb_internal Array<Entity *> proc_group_entities_cloned(CheckerContext *c, Operand o) {
  2532. auto entities = proc_group_entities(c, o);
  2533. if (entities.count == 0) {
  2534. return {};
  2535. }
  2536. return array_clone(permanent_allocator(), entities);
  2537. }
  2538. gb_internal void init_core_type_info(Checker *c) {
  2539. if (t_type_info != nullptr) {
  2540. return;
  2541. }
  2542. Entity *type_info_entity = find_core_entity(c, str_lit("Type_Info"));
  2543. GB_ASSERT(type_info_entity != nullptr);
  2544. if (type_info_entity->type == nullptr) {
  2545. check_single_global_entity(c, type_info_entity, type_info_entity->decl_info);
  2546. }
  2547. GB_ASSERT(type_info_entity->type != nullptr);
  2548. t_type_info = type_info_entity->type;
  2549. t_type_info_ptr = alloc_type_pointer(t_type_info);
  2550. GB_ASSERT(is_type_struct(type_info_entity->type));
  2551. TypeStruct *tis = &base_type(type_info_entity->type)->Struct;
  2552. Entity *type_info_enum_value = find_core_entity(c, str_lit("Type_Info_Enum_Value"));
  2553. t_type_info_enum_value = type_info_enum_value->type;
  2554. t_type_info_enum_value_ptr = alloc_type_pointer(t_type_info_enum_value);
  2555. GB_ASSERT(tis->fields.count == 5);
  2556. Entity *type_info_variant = tis->fields[4];
  2557. Type *tiv_type = type_info_variant->type;
  2558. GB_ASSERT(is_type_union(tiv_type));
  2559. t_type_info_named = find_core_type(c, str_lit("Type_Info_Named"));
  2560. t_type_info_integer = find_core_type(c, str_lit("Type_Info_Integer"));
  2561. t_type_info_rune = find_core_type(c, str_lit("Type_Info_Rune"));
  2562. t_type_info_float = find_core_type(c, str_lit("Type_Info_Float"));
  2563. t_type_info_quaternion = find_core_type(c, str_lit("Type_Info_Quaternion"));
  2564. t_type_info_complex = find_core_type(c, str_lit("Type_Info_Complex"));
  2565. t_type_info_string = find_core_type(c, str_lit("Type_Info_String"));
  2566. t_type_info_boolean = find_core_type(c, str_lit("Type_Info_Boolean"));
  2567. t_type_info_any = find_core_type(c, str_lit("Type_Info_Any"));
  2568. t_type_info_typeid = find_core_type(c, str_lit("Type_Info_Type_Id"));
  2569. t_type_info_pointer = find_core_type(c, str_lit("Type_Info_Pointer"));
  2570. t_type_info_multi_pointer = find_core_type(c, str_lit("Type_Info_Multi_Pointer"));
  2571. t_type_info_procedure = find_core_type(c, str_lit("Type_Info_Procedure"));
  2572. t_type_info_array = find_core_type(c, str_lit("Type_Info_Array"));
  2573. t_type_info_enumerated_array = find_core_type(c, str_lit("Type_Info_Enumerated_Array"));
  2574. t_type_info_dynamic_array = find_core_type(c, str_lit("Type_Info_Dynamic_Array"));
  2575. t_type_info_slice = find_core_type(c, str_lit("Type_Info_Slice"));
  2576. t_type_info_parameters = find_core_type(c, str_lit("Type_Info_Parameters"));
  2577. t_type_info_struct = find_core_type(c, str_lit("Type_Info_Struct"));
  2578. t_type_info_union = find_core_type(c, str_lit("Type_Info_Union"));
  2579. t_type_info_enum = find_core_type(c, str_lit("Type_Info_Enum"));
  2580. t_type_info_map = find_core_type(c, str_lit("Type_Info_Map"));
  2581. t_type_info_bit_set = find_core_type(c, str_lit("Type_Info_Bit_Set"));
  2582. t_type_info_simd_vector = find_core_type(c, str_lit("Type_Info_Simd_Vector"));
  2583. t_type_info_relative_pointer = find_core_type(c, str_lit("Type_Info_Relative_Pointer"));
  2584. t_type_info_relative_multi_pointer = find_core_type(c, str_lit("Type_Info_Relative_Multi_Pointer"));
  2585. t_type_info_matrix = find_core_type(c, str_lit("Type_Info_Matrix"));
  2586. t_type_info_soa_pointer = find_core_type(c, str_lit("Type_Info_Soa_Pointer"));
  2587. t_type_info_bit_field = find_core_type(c, str_lit("Type_Info_Bit_Field"));
  2588. t_type_info_named_ptr = alloc_type_pointer(t_type_info_named);
  2589. t_type_info_integer_ptr = alloc_type_pointer(t_type_info_integer);
  2590. t_type_info_rune_ptr = alloc_type_pointer(t_type_info_rune);
  2591. t_type_info_float_ptr = alloc_type_pointer(t_type_info_float);
  2592. t_type_info_quaternion_ptr = alloc_type_pointer(t_type_info_quaternion);
  2593. t_type_info_complex_ptr = alloc_type_pointer(t_type_info_complex);
  2594. t_type_info_string_ptr = alloc_type_pointer(t_type_info_string);
  2595. t_type_info_boolean_ptr = alloc_type_pointer(t_type_info_boolean);
  2596. t_type_info_any_ptr = alloc_type_pointer(t_type_info_any);
  2597. t_type_info_typeid_ptr = alloc_type_pointer(t_type_info_typeid);
  2598. t_type_info_pointer_ptr = alloc_type_pointer(t_type_info_pointer);
  2599. t_type_info_multi_pointer_ptr = alloc_type_pointer(t_type_info_multi_pointer);
  2600. t_type_info_procedure_ptr = alloc_type_pointer(t_type_info_procedure);
  2601. t_type_info_array_ptr = alloc_type_pointer(t_type_info_array);
  2602. t_type_info_enumerated_array_ptr = alloc_type_pointer(t_type_info_enumerated_array);
  2603. t_type_info_dynamic_array_ptr = alloc_type_pointer(t_type_info_dynamic_array);
  2604. t_type_info_slice_ptr = alloc_type_pointer(t_type_info_slice);
  2605. t_type_info_parameters_ptr = alloc_type_pointer(t_type_info_parameters);
  2606. t_type_info_struct_ptr = alloc_type_pointer(t_type_info_struct);
  2607. t_type_info_union_ptr = alloc_type_pointer(t_type_info_union);
  2608. t_type_info_enum_ptr = alloc_type_pointer(t_type_info_enum);
  2609. t_type_info_map_ptr = alloc_type_pointer(t_type_info_map);
  2610. t_type_info_bit_set_ptr = alloc_type_pointer(t_type_info_bit_set);
  2611. t_type_info_simd_vector_ptr = alloc_type_pointer(t_type_info_simd_vector);
  2612. t_type_info_relative_pointer_ptr = alloc_type_pointer(t_type_info_relative_pointer);
  2613. t_type_info_relative_multi_pointer_ptr = alloc_type_pointer(t_type_info_relative_multi_pointer);
  2614. t_type_info_matrix_ptr = alloc_type_pointer(t_type_info_matrix);
  2615. t_type_info_soa_pointer_ptr = alloc_type_pointer(t_type_info_soa_pointer);
  2616. t_type_info_bit_field_ptr = alloc_type_pointer(t_type_info_bit_field);
  2617. }
  2618. gb_internal void init_mem_allocator(Checker *c) {
  2619. if (t_allocator != nullptr) {
  2620. return;
  2621. }
  2622. t_allocator = find_core_type(c, str_lit("Allocator"));
  2623. t_allocator_ptr = alloc_type_pointer(t_allocator);
  2624. t_allocator_error = find_core_type(c, str_lit("Allocator_Error"));
  2625. }
  2626. gb_internal void init_core_context(Checker *c) {
  2627. if (t_context != nullptr) {
  2628. return;
  2629. }
  2630. t_context = find_core_type(c, str_lit("Context"));
  2631. t_context_ptr = alloc_type_pointer(t_context);
  2632. }
  2633. gb_internal void init_core_source_code_location(Checker *c) {
  2634. if (t_source_code_location != nullptr) {
  2635. return;
  2636. }
  2637. t_source_code_location = find_core_type(c, str_lit("Source_Code_Location"));
  2638. t_source_code_location_ptr = alloc_type_pointer(t_source_code_location);
  2639. }
  2640. gb_internal void init_core_load_directory_file(Checker *c) {
  2641. if (t_load_directory_file != nullptr) {
  2642. return;
  2643. }
  2644. t_load_directory_file = find_core_type(c, str_lit("Load_Directory_File"));
  2645. t_load_directory_file_ptr = alloc_type_pointer(t_load_directory_file);
  2646. t_load_directory_file_slice = alloc_type_slice(t_load_directory_file);
  2647. }
  2648. gb_internal void init_core_map_type(Checker *c) {
  2649. if (t_map_info != nullptr) {
  2650. return;
  2651. }
  2652. init_mem_allocator(c);
  2653. t_map_info = find_core_type(c, str_lit("Map_Info"));
  2654. t_map_cell_info = find_core_type(c, str_lit("Map_Cell_Info"));
  2655. t_raw_map = find_core_type(c, str_lit("Raw_Map"));
  2656. t_map_info_ptr = alloc_type_pointer(t_map_info);
  2657. t_map_cell_info_ptr = alloc_type_pointer(t_map_cell_info);
  2658. t_raw_map_ptr = alloc_type_pointer(t_raw_map);
  2659. }
  2660. gb_internal void init_preload(Checker *c) {
  2661. init_core_type_info(c);
  2662. init_mem_allocator(c);
  2663. init_core_context(c);
  2664. init_core_source_code_location(c);
  2665. init_core_map_type(c);
  2666. }
  2667. gb_internal ExactValue check_decl_attribute_value(CheckerContext *c, Ast *value) {
  2668. ExactValue ev = {};
  2669. if (value != nullptr) {
  2670. Operand op = {};
  2671. check_expr(c, &op, value);
  2672. if (op.mode) {
  2673. if (op.mode == Addressing_Constant) {
  2674. ev = op.value;
  2675. } else {
  2676. error(value, "Expected a constant attribute element");
  2677. }
  2678. }
  2679. }
  2680. return ev;
  2681. }
  2682. #define ATTRIBUTE_USER_TAG_NAME "tag"
  2683. gb_internal DECL_ATTRIBUTE_PROC(foreign_block_decl_attribute) {
  2684. ExactValue ev = check_decl_attribute_value(c, value);
  2685. if (name == ATTRIBUTE_USER_TAG_NAME) {
  2686. if (ev.kind != ExactValue_String) {
  2687. error(elem, "Expected a string value for '%.*s'", LIT(name));
  2688. }
  2689. return true;
  2690. } else if (name == "default_calling_convention") {
  2691. if (ev.kind == ExactValue_String) {
  2692. auto cc = string_to_calling_convention(ev.value_string);
  2693. if (cc == ProcCC_Invalid) {
  2694. error(elem, "Unknown procedure calling convention: '%.*s'", LIT(ev.value_string));
  2695. } else {
  2696. c->foreign_context.default_cc = cc;
  2697. }
  2698. } else {
  2699. error(elem, "Expected a string value for '%.*s'", LIT(name));
  2700. }
  2701. return true;
  2702. } else if (name == "link_prefix") {
  2703. if (ev.kind == ExactValue_String) {
  2704. String link_prefix = ev.value_string;
  2705. if (!is_foreign_name_valid(link_prefix)) {
  2706. error(elem, "Invalid link prefix: '%.*s'", LIT(link_prefix));
  2707. } else {
  2708. c->foreign_context.link_prefix = link_prefix;
  2709. }
  2710. } else {
  2711. error(elem, "Expected a string value for '%.*s'", LIT(name));
  2712. }
  2713. return true;
  2714. } else if (name == "link_suffix") {
  2715. if (ev.kind == ExactValue_String) {
  2716. String link_suffix = ev.value_string;
  2717. if (!is_foreign_name_valid(link_suffix)) {
  2718. error(elem, "Invalid link suffix: '%.*s'", LIT(link_suffix));
  2719. } else {
  2720. c->foreign_context.link_suffix = link_suffix;
  2721. }
  2722. } else {
  2723. error(elem, "Expected a string value for '%.*s'", LIT(name));
  2724. }
  2725. return true;
  2726. } else if (name == "private") {
  2727. EntityVisiblityKind kind = EntityVisiblity_PrivateToPackage;
  2728. if (ev.kind == ExactValue_Invalid) {
  2729. // Okay
  2730. } else if (ev.kind == ExactValue_String) {
  2731. String v = ev.value_string;
  2732. if (v == "file") {
  2733. kind = EntityVisiblity_PrivateToFile;
  2734. } else if (v == "package") {
  2735. kind = EntityVisiblity_PrivateToPackage;
  2736. } else {
  2737. error(value, "'%.*s' expects no parameter, or a string literal containing \"file\" or \"package\"", LIT(name));
  2738. }
  2739. } else {
  2740. error(value, "'%.*s' expects no parameter, or a string literal containing \"file\" or \"package\"", LIT(name));
  2741. }
  2742. c->foreign_context.visibility_kind = kind;
  2743. return true;
  2744. } else if (name == "require_results") {
  2745. if (value != nullptr) {
  2746. error(elem, "Expected no value for '%.*s'", LIT(name));
  2747. }
  2748. c->foreign_context.require_results = true;
  2749. return true;
  2750. }
  2751. return false;
  2752. }
  2753. gb_internal DECL_ATTRIBUTE_PROC(proc_group_attribute) {
  2754. if (name == ATTRIBUTE_USER_TAG_NAME) {
  2755. ExactValue ev = check_decl_attribute_value(c, value);
  2756. if (ev.kind != ExactValue_String) {
  2757. error(elem, "Expected a string value for '%.*s'", LIT(name));
  2758. }
  2759. return true;
  2760. } else if (name == "objc_name") {
  2761. ExactValue ev = check_decl_attribute_value(c, value);
  2762. if (ev.kind == ExactValue_String) {
  2763. if (string_is_valid_identifier(ev.value_string)) {
  2764. ac->objc_name = ev.value_string;
  2765. } else {
  2766. error(elem, "Invalid identifier for '%.*s', got '%.*s'", LIT(name), LIT(ev.value_string));
  2767. }
  2768. } else {
  2769. error(elem, "Expected a string value for '%.*s'", LIT(name));
  2770. }
  2771. return true;
  2772. } else if (name == "objc_is_class_method") {
  2773. ExactValue ev = check_decl_attribute_value(c, value);
  2774. if (ev.kind == ExactValue_Bool) {
  2775. ac->objc_is_class_method = ev.value_bool;
  2776. } else {
  2777. error(elem, "Expected a boolean value for '%.*s'", LIT(name));
  2778. }
  2779. return true;
  2780. } else if (name == "objc_type") {
  2781. if (value == nullptr) {
  2782. error(elem, "Expected a type for '%.*s'", LIT(name));
  2783. } else {
  2784. Type *objc_type = check_type(c, value);
  2785. if (objc_type != nullptr) {
  2786. if (!has_type_got_objc_class_attribute(objc_type)) {
  2787. gbString t = type_to_string(objc_type);
  2788. error(value, "'%.*s' expected a named type with the attribute @(obj_class=<string>), got type %s", LIT(name), t);
  2789. gb_string_free(t);
  2790. } else {
  2791. ac->objc_type = objc_type;
  2792. }
  2793. }
  2794. }
  2795. return true;
  2796. } else if (name == "require_results") {
  2797. if (value != nullptr) {
  2798. error(elem, "Expected no value for '%.*s'", LIT(name));
  2799. }
  2800. ac->require_results = true;
  2801. return true;
  2802. }
  2803. return false;
  2804. }
  2805. gb_internal DECL_ATTRIBUTE_PROC(proc_decl_attribute) {
  2806. if (name == ATTRIBUTE_USER_TAG_NAME) {
  2807. ExactValue ev = check_decl_attribute_value(c, value);
  2808. if (ev.kind != ExactValue_String) {
  2809. error(elem, "Expected a string value for '%.*s'", LIT(name));
  2810. }
  2811. return true;
  2812. } else if (name == "test") {
  2813. if (value != nullptr) {
  2814. error(value, "'%.*s' expects no parameter, or a string literal containing \"file\" or \"package\"", LIT(name));
  2815. }
  2816. ac->test = true;
  2817. return true;
  2818. } else if (name == "export") {
  2819. ExactValue ev = check_decl_attribute_value(c, value);
  2820. if (ev.kind == ExactValue_Invalid) {
  2821. ac->is_export = true;
  2822. } else if (ev.kind == ExactValue_Bool) {
  2823. ac->is_export = ev.value_bool;
  2824. } else {
  2825. error(value, "Expected either a boolean or no parameter for 'export'");
  2826. return false;
  2827. }
  2828. return true;
  2829. } else if (name == "linkage") {
  2830. ExactValue ev = check_decl_attribute_value(c, value);
  2831. if (ev.kind != ExactValue_String) {
  2832. error(value, "Expected either a string 'linkage'");
  2833. return false;
  2834. }
  2835. String linkage = ev.value_string;
  2836. if (linkage == "internal" ||
  2837. linkage == "strong" ||
  2838. linkage == "weak" ||
  2839. linkage == "link_once") {
  2840. ac->linkage = linkage;
  2841. } else {
  2842. ERROR_BLOCK();
  2843. error(elem, "Invalid linkage '%.*s'. Valid kinds:", LIT(linkage));
  2844. error_line("\tinternal\n");
  2845. error_line("\tstrong\n");
  2846. error_line("\tweak\n");
  2847. error_line("\tlink_once\n");
  2848. }
  2849. return true;
  2850. } else if (name == "require") {
  2851. ExactValue ev = check_decl_attribute_value(c, value);
  2852. if (ev.kind == ExactValue_Invalid) {
  2853. ac->require_declaration = true;
  2854. } else if (ev.kind == ExactValue_Bool) {
  2855. ac->require_declaration = ev.value_bool;
  2856. } else {
  2857. error(value, "Expected either a boolean or no parameter for 'require'");
  2858. }
  2859. return true;
  2860. } else if (name == "init") {
  2861. if (value != nullptr) {
  2862. error(value, "'%.*s' expects no parameter, or a string literal containing \"file\" or \"package\"", LIT(name));
  2863. }
  2864. ac->init = true;
  2865. return true;
  2866. } else if (name == "fini") {
  2867. if (value != nullptr) {
  2868. error(value, "'%.*s' expects no parameter, or a string literal containing \"file\" or \"package\"", LIT(name));
  2869. }
  2870. ac->fini = true;
  2871. return true;
  2872. } else if (name == "deferred") {
  2873. if (value != nullptr) {
  2874. Operand o = {};
  2875. check_expr(c, &o, value);
  2876. Entity *e = entity_of_node(o.expr);
  2877. if (e != nullptr && e->kind == Entity_Procedure) {
  2878. error(elem, "'%.*s' is not allowed any more, please use one of the following instead: 'deferred_none', 'deferred_in', 'deferred_out'", LIT(name));
  2879. if (ac->deferred_procedure.entity != nullptr) {
  2880. error(elem, "Previous usage of a 'deferred_*' attribute");
  2881. }
  2882. ac->deferred_procedure.kind = DeferredProcedure_out;
  2883. ac->deferred_procedure.entity = e;
  2884. return true;
  2885. }
  2886. }
  2887. error(elem, "Expected a procedure entity for '%.*s'", LIT(name));
  2888. return false;
  2889. } else if (name == "deferred_none") {
  2890. if (value != nullptr) {
  2891. Operand o = {};
  2892. check_expr(c, &o, value);
  2893. Entity *e = entity_of_node(o.expr);
  2894. if (e != nullptr && e->kind == Entity_Procedure) {
  2895. ac->deferred_procedure.kind = DeferredProcedure_none;
  2896. ac->deferred_procedure.entity = e;
  2897. return true;
  2898. }
  2899. }
  2900. error(elem, "Expected a procedure entity for '%.*s'", LIT(name));
  2901. return false;
  2902. } else if (name == "deferred_in") {
  2903. if (value != nullptr) {
  2904. Operand o = {};
  2905. check_expr(c, &o, value);
  2906. Entity *e = entity_of_node(o.expr);
  2907. if (e != nullptr && e->kind == Entity_Procedure) {
  2908. if (ac->deferred_procedure.entity != nullptr) {
  2909. error(elem, "Previous usage of a 'deferred_*' attribute");
  2910. }
  2911. ac->deferred_procedure.kind = DeferredProcedure_in;
  2912. ac->deferred_procedure.entity = e;
  2913. return true;
  2914. }
  2915. }
  2916. error(elem, "Expected a procedure entity for '%.*s'", LIT(name));
  2917. return false;
  2918. } else if (name == "deferred_out") {
  2919. if (value != nullptr) {
  2920. Operand o = {};
  2921. check_expr(c, &o, value);
  2922. Entity *e = entity_of_node(o.expr);
  2923. if (e != nullptr && e->kind == Entity_Procedure) {
  2924. if (ac->deferred_procedure.entity != nullptr) {
  2925. error(elem, "Previous usage of a 'deferred_*' attribute");
  2926. }
  2927. ac->deferred_procedure.kind = DeferredProcedure_out;
  2928. ac->deferred_procedure.entity = e;
  2929. return true;
  2930. }
  2931. }
  2932. error(elem, "Expected a procedure entity for '%.*s'", LIT(name));
  2933. return false;
  2934. } else if (name == "deferred_in_out") {
  2935. if (value != nullptr) {
  2936. Operand o = {};
  2937. check_expr(c, &o, value);
  2938. Entity *e = entity_of_node(o.expr);
  2939. if (e != nullptr && e->kind == Entity_Procedure) {
  2940. if (ac->deferred_procedure.entity != nullptr) {
  2941. error(elem, "Previous usage of a 'deferred_*' attribute");
  2942. }
  2943. ac->deferred_procedure.kind = DeferredProcedure_in_out;
  2944. ac->deferred_procedure.entity = e;
  2945. return true;
  2946. }
  2947. }
  2948. error(elem, "Expected a procedure entity for '%.*s'", LIT(name));
  2949. return false;
  2950. } else if (name == "deferred_in_by_ptr") {
  2951. if (value != nullptr) {
  2952. Operand o = {};
  2953. check_expr(c, &o, value);
  2954. Entity *e = entity_of_node(o.expr);
  2955. if (e != nullptr && e->kind == Entity_Procedure) {
  2956. if (ac->deferred_procedure.entity != nullptr) {
  2957. error(elem, "Previous usage of a 'deferred_*' attribute");
  2958. }
  2959. ac->deferred_procedure.kind = DeferredProcedure_in_by_ptr;
  2960. ac->deferred_procedure.entity = e;
  2961. return true;
  2962. }
  2963. }
  2964. error(elem, "Expected a procedure entity for '%.*s'", LIT(name));
  2965. return false;
  2966. } else if (name == "deferred_out_by_ptr") {
  2967. if (value != nullptr) {
  2968. Operand o = {};
  2969. check_expr(c, &o, value);
  2970. Entity *e = entity_of_node(o.expr);
  2971. if (e != nullptr && e->kind == Entity_Procedure) {
  2972. if (ac->deferred_procedure.entity != nullptr) {
  2973. error(elem, "Previous usage of a 'deferred_*' attribute");
  2974. }
  2975. ac->deferred_procedure.kind = DeferredProcedure_out_by_ptr;
  2976. ac->deferred_procedure.entity = e;
  2977. return true;
  2978. }
  2979. }
  2980. error(elem, "Expected a procedure entity for '%.*s'", LIT(name));
  2981. return false;
  2982. } else if (name == "deferred_in_out_by_ptr") {
  2983. if (value != nullptr) {
  2984. Operand o = {};
  2985. check_expr(c, &o, value);
  2986. Entity *e = entity_of_node(o.expr);
  2987. if (e != nullptr && e->kind == Entity_Procedure) {
  2988. if (ac->deferred_procedure.entity != nullptr) {
  2989. error(elem, "Previous usage of a 'deferred_*' attribute");
  2990. }
  2991. ac->deferred_procedure.kind = DeferredProcedure_in_out_by_ptr;
  2992. ac->deferred_procedure.entity = e;
  2993. return true;
  2994. }
  2995. }
  2996. error(elem, "Expected a procedure entity for '%.*s'", LIT(name));
  2997. return false;
  2998. } else if (name == "link_name") {
  2999. ExactValue ev = check_decl_attribute_value(c, value);
  3000. if (ev.kind == ExactValue_String) {
  3001. ac->link_name = ev.value_string;
  3002. if (!is_foreign_name_valid(ac->link_name)) {
  3003. error(elem, "Invalid link name: %.*s", LIT(ac->link_name));
  3004. }
  3005. } else {
  3006. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3007. }
  3008. return true;
  3009. } else if (name == "link_prefix") {
  3010. ExactValue ev = check_decl_attribute_value(c, value);
  3011. if (ev.kind == ExactValue_String) {
  3012. ac->link_prefix = ev.value_string;
  3013. if (!is_foreign_name_valid(ac->link_prefix)) {
  3014. error(elem, "Invalid link prefix: %.*s", LIT(ac->link_prefix));
  3015. }
  3016. } else {
  3017. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3018. }
  3019. return true;
  3020. } else if (name == "link_suffix") {
  3021. ExactValue ev = check_decl_attribute_value(c, value);
  3022. if (ev.kind == ExactValue_String) {
  3023. ac->link_suffix = ev.value_string;
  3024. if (!is_foreign_name_valid(ac->link_suffix)) {
  3025. error(elem, "Invalid link suffix: %.*s", LIT(ac->link_suffix));
  3026. }
  3027. } else {
  3028. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3029. }
  3030. return true;
  3031. } else if (name == "deprecated") {
  3032. ExactValue ev = check_decl_attribute_value(c, value);
  3033. if (ev.kind == ExactValue_String) {
  3034. String msg = ev.value_string;
  3035. if (msg.len == 0) {
  3036. error(elem, "Deprecation message cannot be an empty string");
  3037. } else {
  3038. ac->deprecated_message = msg;
  3039. }
  3040. } else {
  3041. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3042. }
  3043. return true;
  3044. } else if (name == "require_results") {
  3045. if (value != nullptr) {
  3046. error(elem, "Expected no value for '%.*s'", LIT(name));
  3047. }
  3048. ac->require_results = true;
  3049. return true;
  3050. } else if (name == "disabled") {
  3051. ExactValue ev = check_decl_attribute_value(c, value);
  3052. if (ev.kind == ExactValue_Bool) {
  3053. ac->has_disabled_proc = true;
  3054. ac->disabled_proc = ev.value_bool;
  3055. } else {
  3056. error(elem, "Expected a boolean value for '%.*s'", LIT(name));
  3057. }
  3058. return true;
  3059. } else if (name == "cold") {
  3060. if (value == nullptr) {
  3061. ac->set_cold = true;
  3062. } else {
  3063. ExactValue ev = check_decl_attribute_value(c, value);
  3064. if (ev.kind == ExactValue_Bool) {
  3065. ac->set_cold = ev.value_bool;
  3066. } else {
  3067. error(elem, "Expected a boolean value for '%.*s' or no value whatsoever", LIT(name));
  3068. }
  3069. }
  3070. return true;
  3071. } else if (name == "optimization_mode") {
  3072. ExactValue ev = check_decl_attribute_value(c, value);
  3073. if (ev.kind == ExactValue_String) {
  3074. String mode = ev.value_string;
  3075. if (mode == "none") {
  3076. ac->optimization_mode = ProcedureOptimizationMode_None;
  3077. } else if (mode == "favor_size") {
  3078. ac->optimization_mode = ProcedureOptimizationMode_FavorSize;
  3079. } else if (mode == "minimal") {
  3080. error(elem, "Invalid optimization_mode 'minimal' for '%.*s', mode has been removed due to confusion, but 'none' has the same behaviour", LIT(name));
  3081. } else if (mode == "size") {
  3082. error(elem, "Invalid optimization_mode 'size' for '%.*s', mode has been removed due to confusion, but 'favor_size' has the same behaviour", LIT(name));
  3083. } else if (mode == "speed") {
  3084. error(elem, "Invalid optimization_mode 'speed' for '%.*s', mode has been removed due to confusion, but 'favor_size' has the same behaviour", LIT(name));
  3085. } else {
  3086. ERROR_BLOCK();
  3087. error(elem, "Invalid optimization_mode for '%.*s'. Valid modes:", LIT(name));
  3088. error_line("\tnone\n");
  3089. error_line("\tfavor_size\n");
  3090. }
  3091. } else {
  3092. error(elem, "Expected a string for '%.*s'", LIT(name));
  3093. }
  3094. return true;
  3095. } else if (name == "objc_name") {
  3096. ExactValue ev = check_decl_attribute_value(c, value);
  3097. if (ev.kind == ExactValue_String) {
  3098. if (string_is_valid_identifier(ev.value_string)) {
  3099. ac->objc_name = ev.value_string;
  3100. } else {
  3101. error(elem, "Invalid identifier for '%.*s', got '%.*s'", LIT(name), LIT(ev.value_string));
  3102. }
  3103. } else {
  3104. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3105. }
  3106. return true;
  3107. } else if (name == "objc_is_class_method") {
  3108. ExactValue ev = check_decl_attribute_value(c, value);
  3109. if (ev.kind == ExactValue_Bool) {
  3110. ac->objc_is_class_method = ev.value_bool;
  3111. } else {
  3112. error(elem, "Expected a boolean value for '%.*s'", LIT(name));
  3113. }
  3114. return true;
  3115. } else if (name == "objc_type") {
  3116. if (value == nullptr) {
  3117. error(elem, "Expected a type for '%.*s'", LIT(name));
  3118. } else {
  3119. Type *objc_type = check_type(c, value);
  3120. if (objc_type != nullptr) {
  3121. if (!has_type_got_objc_class_attribute(objc_type)) {
  3122. gbString t = type_to_string(objc_type);
  3123. error(value, "'%.*s' expected a named type with the attribute @(obj_class=<string>), got type %s", LIT(name), t);
  3124. gb_string_free(t);
  3125. } else {
  3126. ac->objc_type = objc_type;
  3127. }
  3128. }
  3129. }
  3130. return true;
  3131. } else if (name == "require_target_feature") {
  3132. ExactValue ev = check_decl_attribute_value(c, value);
  3133. if (ev.kind == ExactValue_String) {
  3134. ac->require_target_feature = ev.value_string;
  3135. } else {
  3136. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3137. }
  3138. return true;
  3139. } else if (name == "enable_target_feature") {
  3140. ExactValue ev = check_decl_attribute_value(c, value);
  3141. if (ev.kind == ExactValue_String) {
  3142. ac->enable_target_feature = ev.value_string;
  3143. } else {
  3144. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3145. }
  3146. return true;
  3147. } else if (name == "entry_point_only") {
  3148. if (value != nullptr) {
  3149. error(value, "'%.*s' expects no parameter", LIT(name));
  3150. }
  3151. ac->entry_point_only = true;
  3152. return true;
  3153. } else if (name == "no_instrumentation") {
  3154. ExactValue ev = check_decl_attribute_value(c, value);
  3155. if (ev.kind == ExactValue_Invalid) {
  3156. ac->no_instrumentation = Instrumentation_Disabled;
  3157. } else if (ev.kind == ExactValue_Bool) {
  3158. if (ev.value_bool) {
  3159. ac->no_instrumentation = Instrumentation_Disabled;
  3160. } else {
  3161. ac->no_instrumentation = Instrumentation_Enabled;
  3162. }
  3163. } else {
  3164. error(value, "Expected either a boolean or no parameter for '%.*s'", LIT(name));
  3165. return false;
  3166. }
  3167. return true;
  3168. } else if (name == "instrumentation_enter") {
  3169. if (value != nullptr) {
  3170. error(value, "'%.*s' expects no parameter", LIT(name));
  3171. }
  3172. ac->instrumentation_enter = true;
  3173. return true;
  3174. } else if (name == "instrumentation_exit") {
  3175. if (value != nullptr) {
  3176. error(value, "'%.*s' expects no parameter", LIT(name));
  3177. }
  3178. ac->instrumentation_exit = true;
  3179. return true;
  3180. }
  3181. return false;
  3182. }
  3183. gb_internal DECL_ATTRIBUTE_PROC(var_decl_attribute) {
  3184. if (name == ATTRIBUTE_USER_TAG_NAME) {
  3185. ExactValue ev = check_decl_attribute_value(c, value);
  3186. if (ev.kind != ExactValue_String) {
  3187. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3188. }
  3189. return true;
  3190. } else if (name == "static") {
  3191. if (value != nullptr) {
  3192. error(elem, "'static' does not have any parameters");
  3193. }
  3194. ac->is_static = true;
  3195. return true;
  3196. } else if (name == "rodata") {
  3197. if (value != nullptr) {
  3198. error(elem, "'rodata' does not have any parameters");
  3199. }
  3200. ac->rodata = true;
  3201. return true;
  3202. } else if (name == "thread_local") {
  3203. ExactValue ev = check_decl_attribute_value(c, value);
  3204. if (ac->init_expr_list_count > 0) {
  3205. error(elem, "A thread local variable declaration cannot have initialization values");
  3206. } else if (c->foreign_context.curr_library) {
  3207. error(elem, "A foreign block variable cannot be thread local");
  3208. } else if (ac->is_export) {
  3209. error(elem, "An exported variable cannot be thread local");
  3210. } else if (ev.kind == ExactValue_Invalid) {
  3211. ac->thread_local_model = str_lit("default");
  3212. } else if (ev.kind == ExactValue_String) {
  3213. String model = ev.value_string;
  3214. if (model == "default" ||
  3215. model == "localdynamic" ||
  3216. model == "initialexec" ||
  3217. model == "localexec") {
  3218. ac->thread_local_model = model;
  3219. } else {
  3220. ERROR_BLOCK();
  3221. error(elem, "Invalid thread local model '%.*s'. Valid models:", LIT(model));
  3222. error_line("\tdefault\n");
  3223. error_line("\tlocaldynamic\n");
  3224. error_line("\tinitialexec\n");
  3225. error_line("\tlocalexec\n");
  3226. }
  3227. } else {
  3228. error(elem, "Expected either no value or a string for '%.*s'", LIT(name));
  3229. }
  3230. return true;
  3231. }
  3232. if (c->curr_proc_decl != nullptr) {
  3233. error(elem, "Only a variable at file scope can have a '%.*s'", LIT(name));
  3234. return true;
  3235. }
  3236. if (name == "require") {
  3237. if (value != nullptr) {
  3238. error(elem, "'require' does not have any parameters");
  3239. }
  3240. ac->require_declaration = true;
  3241. return true;
  3242. } else if (name == "export") {
  3243. ExactValue ev = check_decl_attribute_value(c, value);
  3244. if (ev.kind == ExactValue_Invalid) {
  3245. ac->is_export = true;
  3246. } else if (ev.kind == ExactValue_Bool) {
  3247. ac->is_export = ev.value_bool;
  3248. } else {
  3249. error(value, "Expected either a boolean or no parameter for 'export'");
  3250. return false;
  3251. }
  3252. if (ac->thread_local_model != "") {
  3253. error(elem, "An exported variable cannot be thread local");
  3254. }
  3255. return true;
  3256. } else if (name == "linkage") {
  3257. ExactValue ev = check_decl_attribute_value(c, value);
  3258. if (ev.kind != ExactValue_String) {
  3259. error(value, "Expected either a string 'linkage'");
  3260. return false;
  3261. }
  3262. String linkage = ev.value_string;
  3263. if (linkage == "internal" ||
  3264. linkage == "strong" ||
  3265. linkage == "weak" ||
  3266. linkage == "link_once") {
  3267. ac->linkage = linkage;
  3268. } else {
  3269. ERROR_BLOCK();
  3270. error(elem, "Invalid linkage '%.*s'. Valid kinds:", LIT(linkage));
  3271. error_line("\tinternal\n");
  3272. error_line("\tstrong\n");
  3273. error_line("\tweak\n");
  3274. error_line("\tlink_once\n");
  3275. }
  3276. return true;
  3277. } else if (name == "link_name") {
  3278. ExactValue ev = check_decl_attribute_value(c, value);
  3279. if (ev.kind == ExactValue_String) {
  3280. ac->link_name = ev.value_string;
  3281. if (!is_foreign_name_valid(ac->link_name)) {
  3282. error(elem, "Invalid link name: %.*s", LIT(ac->link_name));
  3283. }
  3284. } else {
  3285. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3286. }
  3287. return true;
  3288. } else if (name == "link_prefix") {
  3289. ExactValue ev = check_decl_attribute_value(c, value);
  3290. if (ev.kind == ExactValue_String) {
  3291. ac->link_prefix = ev.value_string;
  3292. if (!is_foreign_name_valid(ac->link_prefix)) {
  3293. error(elem, "Invalid link prefix: %.*s", LIT(ac->link_prefix));
  3294. }
  3295. } else {
  3296. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3297. }
  3298. return true;
  3299. } else if (name == "link_suffix") {
  3300. ExactValue ev = check_decl_attribute_value(c, value);
  3301. if (ev.kind == ExactValue_String) {
  3302. ac->link_suffix = ev.value_string;
  3303. if (!is_foreign_name_valid(ac->link_suffix)) {
  3304. error(elem, "Invalid link suffix: %.*s", LIT(ac->link_suffix));
  3305. }
  3306. } else {
  3307. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3308. }
  3309. return true;
  3310. } else if (name == "link_section") {
  3311. ExactValue ev = check_decl_attribute_value(c, value);
  3312. if (ev.kind == ExactValue_String) {
  3313. ac->link_section = ev.value_string;
  3314. if (!is_foreign_name_valid(ac->link_section)) {
  3315. error(elem, "Invalid link section: %.*s", LIT(ac->link_section));
  3316. }
  3317. } else {
  3318. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3319. }
  3320. return true;
  3321. }
  3322. return false;
  3323. }
  3324. gb_internal DECL_ATTRIBUTE_PROC(const_decl_attribute) {
  3325. if (name == ATTRIBUTE_USER_TAG_NAME) {
  3326. ExactValue ev = check_decl_attribute_value(c, value);
  3327. if (ev.kind != ExactValue_String) {
  3328. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3329. }
  3330. return true;
  3331. } else if (name == "private") {
  3332. // NOTE(bill): Handled elsewhere `check_collect_value_decl`
  3333. return true;
  3334. } else if (name == "static" ||
  3335. name == "thread_local" ||
  3336. name == "require" ||
  3337. name == "linkage" ||
  3338. name == "link_name" ||
  3339. name == "link_prefix" ||
  3340. name == "link_suffix" ||
  3341. false) {
  3342. error(elem, "@(%.*s) is not supported for compile time constant value declarations", LIT(name));
  3343. return true;
  3344. }
  3345. return false;
  3346. }
  3347. gb_internal DECL_ATTRIBUTE_PROC(type_decl_attribute) {
  3348. if (name == ATTRIBUTE_USER_TAG_NAME) {
  3349. ExactValue ev = check_decl_attribute_value(c, value);
  3350. if (ev.kind != ExactValue_String) {
  3351. error(elem, "Expected a string value for '%.*s'", LIT(name));
  3352. }
  3353. return true;
  3354. } else if (name == "private") {
  3355. // NOTE(bill): Handled elsewhere `check_collect_value_decl`
  3356. return true;
  3357. } else if (name == "objc_class") {
  3358. ExactValue ev = check_decl_attribute_value(c, value);
  3359. if (ev.kind != ExactValue_String || ev.value_string == "") {
  3360. error(elem, "Expected a non-empty string value for '%.*s'", LIT(name));
  3361. } else {
  3362. ac->objc_class = ev.value_string;
  3363. }
  3364. return true;
  3365. }
  3366. return false;
  3367. }
  3368. #include "check_expr.cpp"
  3369. #include "check_builtin.cpp"
  3370. #include "check_type.cpp"
  3371. #include "check_decl.cpp"
  3372. #include "check_stmt.cpp"
  3373. gb_internal void check_decl_attributes(CheckerContext *c, Array<Ast *> const &attributes, DeclAttributeProc *proc, AttributeContext *ac) {
  3374. if (attributes.count == 0) return;
  3375. String original_link_prefix = {};
  3376. String original_link_suffix = {};
  3377. if (ac) {
  3378. original_link_prefix = ac->link_prefix;
  3379. original_link_suffix = ac->link_suffix;
  3380. }
  3381. StringSet set = {};
  3382. defer (string_set_destroy(&set));
  3383. bool is_runtime = false;
  3384. if (c->scope && c->scope->file && (c->scope->flags & ScopeFlag_File) &&
  3385. c->scope->file->pkg &&
  3386. c->scope->file->pkg->kind == Package_Runtime) {
  3387. is_runtime = true;
  3388. } else if (c->scope && c->scope->parent &&
  3389. (c->scope->flags & ScopeFlag_Proc) &&
  3390. (c->scope->parent->flags & ScopeFlag_File) &&
  3391. c->scope->parent->file->pkg &&
  3392. c->scope->parent->file->pkg->kind == Package_Runtime) {
  3393. is_runtime = true;
  3394. }
  3395. for_array(i, attributes) {
  3396. Ast *attr = attributes[i];
  3397. if (attr->kind != Ast_Attribute) continue;
  3398. for_array(j, attr->Attribute.elems) {
  3399. Ast *elem = attr->Attribute.elems[j];
  3400. String name = {};
  3401. Ast *value = nullptr;
  3402. switch (elem->kind) {
  3403. case_ast_node(i, Ident, elem);
  3404. name = i->token.string;
  3405. case_end;
  3406. case_ast_node(i, Implicit, elem);
  3407. name = i->string;
  3408. case_end;
  3409. case_ast_node(fv, FieldValue, elem);
  3410. if (fv->field->kind == Ast_Ident) {
  3411. name = fv->field->Ident.token.string;
  3412. } else if (fv->field->kind == Ast_Implicit) {
  3413. name = fv->field->Implicit.string;
  3414. } else {
  3415. GB_PANIC("Unknown Field Value name");
  3416. }
  3417. value = fv->value;
  3418. case_end;
  3419. default:
  3420. error(elem, "Invalid attribute element");
  3421. continue;
  3422. }
  3423. if (string_set_update(&set, name)) {
  3424. error(elem, "Previous declaration of '%.*s'", LIT(name));
  3425. continue;
  3426. }
  3427. if (name == "builtin" && is_runtime) {
  3428. continue;
  3429. }
  3430. if (!proc(c, elem, name, value, ac)) {
  3431. if (!build_context.ignore_unknown_attributes &&
  3432. !string_set_exists(&build_context.custom_attributes, name)) {
  3433. ERROR_BLOCK();
  3434. error(elem, "Unknown attribute element name '%.*s'", LIT(name));
  3435. error_line("\tDid you forget to use the build flag '-ignore-unknown-attributes' or '-custom-attribute:%.*s'?\n", LIT(name));
  3436. }
  3437. }
  3438. }
  3439. }
  3440. if (ac) {
  3441. if (ac->link_prefix.text == original_link_prefix.text) {
  3442. if (ac->link_name.len > 0) {
  3443. ac->link_prefix.text = nullptr;
  3444. ac->link_prefix.len = 0;
  3445. }
  3446. }
  3447. if (ac->link_suffix.text == original_link_suffix.text) {
  3448. if (ac->link_name.len > 0) {
  3449. ac->link_suffix.text = nullptr;
  3450. ac->link_suffix.len = 0;
  3451. }
  3452. }
  3453. }
  3454. }
  3455. gb_internal isize get_total_value_count(Slice<Ast *> const &values) {
  3456. isize count = 0;
  3457. for_array(i, values) {
  3458. Type *t = type_of_expr(values[i]);
  3459. if (t == nullptr) {
  3460. count += 1;
  3461. continue;
  3462. }
  3463. t = core_type(t);
  3464. if (t->kind == Type_Tuple) {
  3465. count += t->Tuple.variables.count;
  3466. } else {
  3467. count += 1;
  3468. }
  3469. }
  3470. return count;
  3471. }
  3472. gb_internal bool check_arity_match(CheckerContext *c, AstValueDecl *vd, bool is_global) {
  3473. isize lhs = vd->names.count;
  3474. isize rhs = 0;
  3475. if (is_global) {
  3476. // NOTE(bill): Disallow global variables to be multi-valued for a few reasons
  3477. rhs = vd->values.count;
  3478. } else {
  3479. rhs = get_total_value_count(vd->values);
  3480. }
  3481. if (rhs == 0) {
  3482. if (vd->type == nullptr) {
  3483. error(vd->names[0], "Missing type or initial expression");
  3484. return false;
  3485. }
  3486. } else if (lhs < rhs) {
  3487. if (lhs < vd->values.count) {
  3488. Ast *n = vd->values[lhs];
  3489. gbString str = expr_to_string(n);
  3490. error(n, "Extra initial expression '%s'", str);
  3491. gb_string_free(str);
  3492. } else {
  3493. error(vd->names[0], "Extra initial expression");
  3494. }
  3495. return false;
  3496. } else if (lhs > rhs) {
  3497. if (!is_global && rhs != 1) {
  3498. Ast *n = vd->names[rhs];
  3499. gbString str = expr_to_string(n);
  3500. error(n, "Missing expression for '%s'", str);
  3501. gb_string_free(str);
  3502. return false;
  3503. } else if (is_global) {
  3504. ERROR_BLOCK();
  3505. Ast *n = vd->values[rhs-1];
  3506. error(n, "Expected %td expressions on the right hand side, got %td", lhs, rhs);
  3507. error_line("Note: Global declarations do not allow for multi-valued expressions");
  3508. return false;
  3509. }
  3510. }
  3511. return true;
  3512. }
  3513. gb_internal void check_collect_entities_from_when_stmt(CheckerContext *c, AstWhenStmt *ws) {
  3514. Operand operand = {Addressing_Invalid};
  3515. if (!ws->is_cond_determined) {
  3516. check_expr(c, &operand, ws->cond);
  3517. if (operand.mode != Addressing_Invalid && !is_type_boolean(operand.type)) {
  3518. error(ws->cond, "Non-boolean condition in 'when' statement");
  3519. }
  3520. if (operand.mode != Addressing_Constant) {
  3521. error(ws->cond, "Non-constant condition in 'when' statement");
  3522. }
  3523. ws->is_cond_determined = true;
  3524. ws->determined_cond = operand.value.kind == ExactValue_Bool && operand.value.value_bool;
  3525. }
  3526. if (ws->body == nullptr || ws->body->kind != Ast_BlockStmt) {
  3527. error(ws->cond, "Invalid body for 'when' statement");
  3528. } else {
  3529. if (ws->determined_cond) {
  3530. check_collect_entities(c, ws->body->BlockStmt.stmts);
  3531. } else if (ws->else_stmt) {
  3532. switch (ws->else_stmt->kind) {
  3533. case Ast_BlockStmt:
  3534. check_collect_entities(c, ws->else_stmt->BlockStmt.stmts);
  3535. break;
  3536. case Ast_WhenStmt:
  3537. check_collect_entities_from_when_stmt(c, &ws->else_stmt->WhenStmt);
  3538. break;
  3539. default:
  3540. error(ws->else_stmt, "Invalid 'else' statement in 'when' statement");
  3541. break;
  3542. }
  3543. }
  3544. }
  3545. }
  3546. gb_internal void check_builtin_attributes(CheckerContext *ctx, Entity *e, Array<Ast *> *attributes) {
  3547. switch (e->kind) {
  3548. case Entity_ProcGroup:
  3549. case Entity_Procedure:
  3550. case Entity_TypeName:
  3551. case Entity_Constant:
  3552. // Okay
  3553. break;
  3554. default:
  3555. return;
  3556. }
  3557. if (!((ctx->scope->flags&ScopeFlag_File) && ctx->scope->file->pkg->kind == Package_Runtime)) {
  3558. return;
  3559. }
  3560. for_array(j, *attributes) {
  3561. Ast *attr = (*attributes)[j];
  3562. if (attr->kind != Ast_Attribute) continue;
  3563. for (isize k = 0; k < attr->Attribute.elems.count; k++) {
  3564. Ast *elem = attr->Attribute.elems[k];
  3565. String name = {};
  3566. Ast *value = nullptr;
  3567. switch (elem->kind) {
  3568. case_ast_node(i, Ident, elem);
  3569. name = i->token.string;
  3570. case_end;
  3571. case_ast_node(fv, FieldValue, elem);
  3572. GB_ASSERT(fv->field->kind == Ast_Ident);
  3573. name = fv->field->Ident.token.string;
  3574. value = fv->value;
  3575. case_end;
  3576. default:
  3577. continue;
  3578. }
  3579. if (name == "builtin") {
  3580. mutex_lock(&ctx->info->builtin_mutex);
  3581. add_entity(ctx, builtin_pkg->scope, nullptr, e);
  3582. GB_ASSERT(scope_lookup(builtin_pkg->scope, e->token.string) != nullptr);
  3583. if (value != nullptr) {
  3584. error(value, "'builtin' cannot have a field value");
  3585. }
  3586. // Remove the builtin tag
  3587. // attr->Attribute.elems[k] = attr->Attribute.elems[attr->Attribute.elems.count-1];
  3588. // attr->Attribute.elems.count -= 1;
  3589. // k--;
  3590. mutex_unlock(&ctx->info->builtin_mutex);
  3591. }
  3592. }
  3593. }
  3594. for (isize i = 0; i < attributes->count; i++) {
  3595. Ast *attr = (*attributes)[i];
  3596. if (attr->kind != Ast_Attribute) continue;
  3597. if (attr->Attribute.elems.count == 0) {
  3598. (*attributes)[i] = (*attributes)[attributes->count-1];
  3599. attributes->count--;
  3600. i--;
  3601. }
  3602. }
  3603. }
  3604. gb_internal void check_collect_value_decl(CheckerContext *c, Ast *decl) {
  3605. if (decl->state_flags & StateFlag_BeenHandled) return;
  3606. decl->state_flags |= StateFlag_BeenHandled;
  3607. ast_node(vd, ValueDecl, decl);
  3608. EntityVisiblityKind entity_visibility_kind = c->foreign_context.visibility_kind;
  3609. bool is_test = false;
  3610. bool is_init = false;
  3611. bool is_fini = false;
  3612. bool is_priv = false;
  3613. for_array(i, vd->attributes) {
  3614. Ast *attr = vd->attributes[i];
  3615. if (attr->kind != Ast_Attribute) continue;
  3616. auto *elems = &attr->Attribute.elems;
  3617. for (isize j = 0; j < elems->count; j++) {
  3618. Ast *elem = (*elems)[j];
  3619. String name = {};
  3620. Ast *value = nullptr;
  3621. switch (elem->kind) {
  3622. case_ast_node(i, Ident, elem);
  3623. name = i->token.string;
  3624. case_end;
  3625. case_ast_node(fv, FieldValue, elem);
  3626. GB_ASSERT(fv->field->kind == Ast_Ident);
  3627. name = fv->field->Ident.token.string;
  3628. value = fv->value;
  3629. case_end;
  3630. default:
  3631. continue;
  3632. }
  3633. if (name == "private") {
  3634. EntityVisiblityKind kind = EntityVisiblity_PrivateToPackage;
  3635. bool success = false;
  3636. if (value != nullptr) {
  3637. if (value->kind == Ast_BasicLit && value->BasicLit.token.kind == Token_String) {
  3638. String v = {};
  3639. if (value->tav.value.kind == ExactValue_String) {
  3640. v = value->tav.value.value_string;
  3641. }
  3642. if (v == "file") {
  3643. kind = EntityVisiblity_PrivateToFile;
  3644. success = true;
  3645. } else if (v == "package") {
  3646. kind = EntityVisiblity_PrivateToPackage;
  3647. success = true;
  3648. }
  3649. }
  3650. } else {
  3651. success = true;
  3652. }
  3653. if (!success) {
  3654. error(value, "'%.*s' expects no parameter, or a string literal containing \"file\" or \"package\"", LIT(name));
  3655. } else {
  3656. is_priv = true;
  3657. }
  3658. if (entity_visibility_kind >= kind) {
  3659. error(elem, "Previous declaration of '%.*s'", LIT(name));
  3660. } else {
  3661. entity_visibility_kind = kind;
  3662. }
  3663. slice_unordered_remove(elems, j);
  3664. j -= 1;
  3665. } else if (name == "test") {
  3666. is_test = true;
  3667. } else if (name == "init") {
  3668. is_init = true;
  3669. } else if (name == "fini") {
  3670. is_fini = true;
  3671. }
  3672. }
  3673. }
  3674. if (is_priv && is_test) {
  3675. error(decl, "Attribute 'private' is not allowed on a test case");
  3676. return;
  3677. }
  3678. if (entity_visibility_kind == EntityVisiblity_Public &&
  3679. (c->scope->flags&ScopeFlag_File) &&
  3680. c->scope->file) {
  3681. if (c->scope->file->flags & AstFile_IsPrivateFile) {
  3682. entity_visibility_kind = EntityVisiblity_PrivateToFile;
  3683. } else if (c->scope->file->flags & AstFile_IsPrivatePkg) {
  3684. entity_visibility_kind = EntityVisiblity_PrivateToPackage;
  3685. }
  3686. }
  3687. if (entity_visibility_kind != EntityVisiblity_Public && !(c->scope->flags&ScopeFlag_File)) {
  3688. error(decl, "Attribute 'private' is not allowed on a non file scope entity");
  3689. }
  3690. if (vd->is_mutable) {
  3691. if (!(c->scope->flags&ScopeFlag_File)) {
  3692. // NOTE(bill): local scope -> handle later and in order
  3693. return;
  3694. }
  3695. for_array(i, vd->names) {
  3696. Ast *name = vd->names[i];
  3697. Ast *value = nullptr;
  3698. if (i < vd->values.count) {
  3699. value = vd->values[i];
  3700. }
  3701. if (name->kind != Ast_Ident) {
  3702. error(name, "A declaration's name must be an identifier, got %.*s", LIT(ast_strings[name->kind]));
  3703. continue;
  3704. }
  3705. Entity *e = alloc_entity_variable(c->scope, name->Ident.token, nullptr);
  3706. e->identifier = name;
  3707. e->file = c->file;
  3708. e->Variable.is_global = true;
  3709. if (entity_visibility_kind != EntityVisiblity_Public) {
  3710. e->flags |= EntityFlag_NotExported;
  3711. }
  3712. if (vd->is_using) {
  3713. vd->is_using = false; // NOTE(bill): This error will be only caught once
  3714. error(name, "'using' is not allowed at the file scope");
  3715. }
  3716. Ast *fl = c->foreign_context.curr_library;
  3717. if (fl != nullptr) {
  3718. GB_ASSERT(fl->kind == Ast_Ident);
  3719. e->Variable.is_foreign = true;
  3720. e->Variable.foreign_library_ident = fl;
  3721. e->Variable.link_prefix = c->foreign_context.link_prefix;
  3722. e->Variable.link_suffix = c->foreign_context.link_suffix;
  3723. }
  3724. Ast *init_expr = value;
  3725. DeclInfo *d = make_decl_info(c->scope, c->decl);
  3726. d->decl_node = decl;
  3727. d->comment = vd->comment;
  3728. d->docs = vd->docs;
  3729. d->entity = e;
  3730. d->type_expr = vd->type;
  3731. d->init_expr = init_expr;
  3732. d->attributes = vd->attributes;
  3733. bool is_exported = entity_visibility_kind != EntityVisiblity_PrivateToFile;
  3734. add_entity_and_decl_info(c, name, e, d, is_exported);
  3735. }
  3736. check_arity_match(c, vd, true);
  3737. } else {
  3738. for_array(i, vd->names) {
  3739. Ast *name = vd->names[i];
  3740. if (name->kind != Ast_Ident) {
  3741. error(name, "A declaration's name must be an identifier, got %.*s", LIT(ast_strings[name->kind]));
  3742. continue;
  3743. }
  3744. Ast *init = unparen_expr(vd->values[i]);
  3745. if (init == nullptr) {
  3746. error(name, "Expected a value for this constant value declaration");
  3747. continue;
  3748. }
  3749. Token token = name->Ident.token;
  3750. Ast *fl = c->foreign_context.curr_library;
  3751. Entity *e = nullptr;
  3752. DeclInfo *d = make_decl_info(c->scope, c->decl);
  3753. d->decl_node = decl;
  3754. d->comment = vd->comment;
  3755. d->docs = vd->docs;
  3756. d->attributes = vd->attributes;
  3757. d->type_expr = vd->type;
  3758. d->init_expr = init;
  3759. if (is_ast_type(init)) {
  3760. e = alloc_entity_type_name(d->scope, token, nullptr);
  3761. } else if (init->kind == Ast_ProcLit) {
  3762. if (c->scope->flags&ScopeFlag_Type) {
  3763. error(name, "Procedure declarations are not allowed within a struct");
  3764. continue;
  3765. }
  3766. ast_node(pl, ProcLit, init);
  3767. e = alloc_entity_procedure(d->scope, token, nullptr, pl->tags);
  3768. d->foreign_require_results = c->foreign_context.require_results;
  3769. if (fl != nullptr) {
  3770. GB_ASSERT(fl->kind == Ast_Ident);
  3771. e->Procedure.foreign_library_ident = fl;
  3772. e->Procedure.is_foreign = true;
  3773. GB_ASSERT(pl->type->kind == Ast_ProcType);
  3774. auto cc = pl->type->ProcType.calling_convention;
  3775. if (cc == ProcCC_ForeignBlockDefault) {
  3776. cc = ProcCC_CDecl;
  3777. if (c->foreign_context.default_cc > 0) {
  3778. cc = c->foreign_context.default_cc;
  3779. } else if (is_arch_wasm()) {
  3780. ERROR_BLOCK();
  3781. error(init, "For wasm related targets, it is required that you either define the"
  3782. " @(default_calling_convention=<string>) on the foreign block or"
  3783. " explicitly assign it on the procedure signature");
  3784. error_line("\tSuggestion: when dealing with normal Odin code (e.g. js_wasm32), use \"contextless\"; when dealing with Emscripten like code, use \"c\"\n");
  3785. }
  3786. }
  3787. e->Procedure.link_prefix = c->foreign_context.link_prefix;
  3788. e->Procedure.link_suffix = c->foreign_context.link_suffix;
  3789. GB_ASSERT(cc != ProcCC_Invalid);
  3790. pl->type->ProcType.calling_convention = cc;
  3791. }
  3792. d->proc_lit = init;
  3793. d->init_expr = init;
  3794. if (is_test) {
  3795. e->flags |= EntityFlag_Test;
  3796. }
  3797. if (is_init && is_fini) {
  3798. error(name, "A procedure cannot be both declared as @(init) and @(fini)");
  3799. } else if (is_init) {
  3800. e->flags |= EntityFlag_Init;
  3801. } else if (is_fini) {
  3802. e->flags |= EntityFlag_Fini;
  3803. }
  3804. } else if (init->kind == Ast_ProcGroup) {
  3805. ast_node(pg, ProcGroup, init);
  3806. e = alloc_entity_proc_group(d->scope, token, nullptr);
  3807. if (fl != nullptr) {
  3808. error(name, "Procedure groups are not allowed within a foreign block");
  3809. }
  3810. } else {
  3811. e = alloc_entity_constant(d->scope, token, nullptr, empty_exact_value);
  3812. }
  3813. e->identifier = name;
  3814. if (entity_visibility_kind != EntityVisiblity_Public) {
  3815. e->flags |= EntityFlag_NotExported;
  3816. }
  3817. add_entity_flags_from_file(c, e, c->scope);
  3818. if (vd->is_using) {
  3819. if (e->kind == Entity_TypeName && init->kind == Ast_EnumType) {
  3820. d->is_using = true;
  3821. } else {
  3822. error(name, "'using' is not allowed on this constant value declaration");
  3823. }
  3824. }
  3825. if (e->kind != Entity_Procedure) {
  3826. if (fl != nullptr) {
  3827. ERROR_BLOCK();
  3828. AstKind kind = init->kind;
  3829. error(name, "Only procedures and variables are allowed to be in a foreign block, got %.*s", LIT(ast_strings[kind]));
  3830. if (kind == Ast_ProcType) {
  3831. error_line("\tDid you forget to append '---' to the procedure?\n");
  3832. }
  3833. }
  3834. }
  3835. check_builtin_attributes(c, e, &d->attributes);
  3836. bool is_exported = entity_visibility_kind != EntityVisiblity_PrivateToFile;
  3837. add_entity_and_decl_info(c, name, e, d, is_exported);
  3838. }
  3839. check_arity_match(c, vd, true);
  3840. }
  3841. }
  3842. gb_internal bool collect_file_decls(CheckerContext *ctx, Slice<Ast *> const &decls);
  3843. gb_internal bool check_add_foreign_block_decl(CheckerContext *ctx, Ast *decl) {
  3844. ast_node(fb, ForeignBlockDecl, decl);
  3845. Ast *foreign_library = fb->foreign_library;
  3846. CheckerContext c = *ctx;
  3847. if (foreign_library->kind == Ast_Ident) {
  3848. c.foreign_context.curr_library = foreign_library;
  3849. } else {
  3850. error(foreign_library, "Foreign block name must be an identifier or 'export'");
  3851. c.foreign_context.curr_library = nullptr;
  3852. }
  3853. check_decl_attributes(&c, fb->attributes, foreign_block_decl_attribute, nullptr);
  3854. ast_node(block, BlockStmt, fb->body);
  3855. if (c.collect_delayed_decls && (c.scope->flags&ScopeFlag_File) != 0) {
  3856. return collect_file_decls(&c, block->stmts);
  3857. }
  3858. check_collect_entities(&c, block->stmts);
  3859. return false;
  3860. }
  3861. gb_internal bool correct_single_type_alias(CheckerContext *c, Entity *e) {
  3862. if (e->kind == Entity_Constant) {
  3863. DeclInfo *d = e->decl_info;
  3864. if (d != nullptr && d->init_expr != nullptr) {
  3865. Ast *init = d->init_expr;
  3866. Entity *alias_of = check_entity_from_ident_or_selector(c, init, true);
  3867. if (alias_of != nullptr && alias_of->kind == Entity_TypeName) {
  3868. e->kind = Entity_TypeName;
  3869. return true;
  3870. }
  3871. }
  3872. }
  3873. return false;
  3874. }
  3875. gb_internal bool correct_type_alias_in_scope_backwards(CheckerContext *c, Scope *s) {
  3876. bool correction = false;
  3877. for (u32 n = s->elements.count, i = n-1; i < n; i--) {
  3878. auto const &entry = s->elements.entries[i];
  3879. Entity *e = entry.value;
  3880. if (entry.hash && e != nullptr) {
  3881. correction |= correct_single_type_alias(c, e);
  3882. }
  3883. }
  3884. return correction;
  3885. }
  3886. gb_internal bool correct_type_alias_in_scope_forwards(CheckerContext *c, Scope *s) {
  3887. bool correction = false;
  3888. for (auto const &entry : s->elements) {
  3889. Entity *e = entry.value;
  3890. if (e != nullptr) {
  3891. correction |= correct_single_type_alias(c, entry.value);
  3892. }
  3893. }
  3894. return correction;
  3895. }
  3896. gb_internal void correct_type_aliases_in_scope(CheckerContext *c, Scope *s) {
  3897. // NOTE(bill, 2022-02-04): This is used to solve the problem caused by type aliases
  3898. // of type aliases being "confused" as constants
  3899. //
  3900. // A :: C
  3901. // B :: A
  3902. // C :: struct {b: ^B}
  3903. //
  3904. // See @TypeAliasingProblem for more information
  3905. for (;;) {
  3906. bool corrections = false;
  3907. corrections |= correct_type_alias_in_scope_backwards(c, s);
  3908. corrections |= correct_type_alias_in_scope_forwards(c, s);
  3909. if (!corrections) {
  3910. return;
  3911. }
  3912. }
  3913. }
  3914. // NOTE(bill): If file_scopes == nullptr, this will act like a local scope
  3915. gb_internal void check_collect_entities(CheckerContext *c, Slice<Ast *> const &nodes) {
  3916. AstFile *curr_file = nullptr;
  3917. if ((c->scope->flags&ScopeFlag_File) != 0) {
  3918. curr_file = c->scope->file;
  3919. GB_ASSERT(curr_file != nullptr);
  3920. }
  3921. for_array(decl_index, nodes) {
  3922. Ast *decl = nodes[decl_index];
  3923. if (!is_ast_decl(decl) && !is_ast_when_stmt(decl)) {
  3924. if (curr_file && decl->kind == Ast_ExprStmt) {
  3925. Ast *expr = decl->ExprStmt.expr;
  3926. if (expr->kind == Ast_CallExpr && expr->CallExpr.proc->kind == Ast_BasicDirective) {
  3927. if (c->collect_delayed_decls) {
  3928. if (decl->state_flags & StateFlag_BeenHandled) return;
  3929. decl->state_flags |= StateFlag_BeenHandled;
  3930. array_add(&curr_file->delayed_decls_queues[AstDelayQueue_Expr], expr);
  3931. }
  3932. continue;
  3933. }
  3934. }
  3935. continue;
  3936. }
  3937. switch (decl->kind) {
  3938. case_ast_node(bd, BadDecl, decl);
  3939. case_end;
  3940. case_ast_node(ws, WhenStmt, decl);
  3941. // Will be handled later
  3942. case_end;
  3943. case_ast_node(vd, ValueDecl, decl);
  3944. check_collect_value_decl(c, decl);
  3945. case_end;
  3946. case_ast_node(id, ImportDecl, decl);
  3947. if (curr_file == nullptr) {
  3948. error(decl, "import declarations are only allowed in the file scope");
  3949. // NOTE(bill): _Should_ be caught by the parser
  3950. continue;
  3951. }
  3952. // Will be handled later
  3953. array_add(&curr_file->delayed_decls_queues[AstDelayQueue_Import], decl);
  3954. case_end;
  3955. case_ast_node(fl, ForeignImportDecl, decl);
  3956. if ((c->scope->flags&ScopeFlag_File) == 0) {
  3957. error(decl, "%.*s declarations are only allowed in the file scope", LIT(fl->token.string));
  3958. // NOTE(bill): _Should_ be caught by the parser
  3959. continue;
  3960. }
  3961. check_add_foreign_import_decl(c, decl);
  3962. case_end;
  3963. case_ast_node(fb, ForeignBlockDecl, decl);
  3964. check_add_foreign_block_decl(c, decl);
  3965. case_end;
  3966. default:
  3967. if (c->scope->flags&ScopeFlag_File) {
  3968. error(decl, "Only declarations are allowed at file scope");
  3969. }
  3970. break;
  3971. }
  3972. }
  3973. // correct_type_aliases(c);
  3974. // NOTE(bill): 'when' stmts need to be handled after the other as the condition may refer to something
  3975. // declared after this stmt in source
  3976. if (curr_file == nullptr) {
  3977. for_array(decl_index, nodes) {
  3978. Ast *decl = nodes[decl_index];
  3979. if (decl->kind == Ast_WhenStmt) {
  3980. check_collect_entities_from_when_stmt(c, &decl->WhenStmt);
  3981. }
  3982. }
  3983. }
  3984. }
  3985. gb_internal CheckerContext *create_checker_context(Checker *c) {
  3986. CheckerContext *ctx = gb_alloc_item(permanent_allocator(), CheckerContext);
  3987. *ctx = make_checker_context(c);
  3988. return ctx;
  3989. }
  3990. gb_internal void check_single_global_entity(Checker *c, Entity *e, DeclInfo *d) {
  3991. GB_ASSERT(e != nullptr);
  3992. GB_ASSERT(d != nullptr);
  3993. if (d->scope != e->scope) {
  3994. return;
  3995. }
  3996. if (e->state == EntityState_Resolved) {
  3997. return;
  3998. }
  3999. CheckerContext *ctx = create_checker_context(c);
  4000. GB_ASSERT(d->scope->flags&ScopeFlag_File);
  4001. AstFile *file = d->scope->file;
  4002. add_curr_ast_file(ctx, file);
  4003. AstPackage *pkg = file->pkg;
  4004. GB_ASSERT(ctx->pkg != nullptr);
  4005. GB_ASSERT(e->pkg != nullptr);
  4006. ctx->decl = d;
  4007. ctx->scope = d->scope;
  4008. if (pkg->kind == Package_Init) {
  4009. if (e->kind != Entity_Procedure && e->token.string == "main") {
  4010. error(e->token, "'main' is reserved as the entry point procedure in the initial scope");
  4011. return;
  4012. }
  4013. }
  4014. check_entity_decl(ctx, e, d, nullptr);
  4015. }
  4016. gb_internal void check_all_global_entities(Checker *c) {
  4017. in_single_threaded_checker_stage = true;
  4018. // NOTE(bill): This must be single threaded
  4019. // Don't bother trying
  4020. for_array(i, c->info.entities) {
  4021. Entity *e = c->info.entities[i];
  4022. GB_ASSERT(e != nullptr);
  4023. if (e->flags & EntityFlag_Lazy) {
  4024. continue;
  4025. }
  4026. DeclInfo *d = e->decl_info;
  4027. check_single_global_entity(c, e, d);
  4028. if (e->type != nullptr && is_type_typed(e->type)) {
  4029. for (Type *t = nullptr; mpsc_dequeue(&c->soa_types_to_complete, &t); /**/) {
  4030. complete_soa_type(c, t, false);
  4031. }
  4032. (void)type_size_of(e->type);
  4033. (void)type_align_of(e->type);
  4034. }
  4035. }
  4036. in_single_threaded_checker_stage = false;
  4037. }
  4038. gb_internal bool is_string_an_identifier(String s) {
  4039. isize offset = 0;
  4040. if (s.len < 1) {
  4041. return false;
  4042. }
  4043. while (offset < s.len) {
  4044. bool ok = false;
  4045. Rune r = -1;
  4046. isize size = utf8_decode(s.text+offset, s.len-offset, &r);
  4047. if (offset == 0) {
  4048. ok = rune_is_letter(r);
  4049. } else {
  4050. ok = rune_is_letter(r) || rune_is_digit(r);
  4051. }
  4052. if (!ok) {
  4053. return false;
  4054. }
  4055. offset += size;
  4056. }
  4057. return offset == s.len;
  4058. }
  4059. gb_internal String path_to_entity_name(String name, String fullpath, bool strip_extension=true) {
  4060. if (name.len != 0) {
  4061. return name;
  4062. }
  4063. // NOTE(bill): use file name (without extension) as the identifier
  4064. // If it is a valid identifier
  4065. String filename = fullpath;
  4066. isize slash = 0;
  4067. isize dot = 0;
  4068. for (isize i = filename.len-1; i >= 0; i--) {
  4069. u8 c = filename[i];
  4070. if (c == '/' || c == '\\') {
  4071. break;
  4072. }
  4073. slash = i;
  4074. }
  4075. filename = substring(filename, slash, filename.len);
  4076. if (strip_extension) {
  4077. dot = filename.len;
  4078. while (dot --> 0) {
  4079. u8 c = filename[dot];
  4080. if (c == '.') {
  4081. break;
  4082. }
  4083. }
  4084. if (dot > 0) {
  4085. filename = substring(filename, 0, dot);
  4086. }
  4087. }
  4088. if (is_string_an_identifier(filename)) {
  4089. return filename;
  4090. } else {
  4091. return str_lit("_");
  4092. }
  4093. }
  4094. #if 1
  4095. gb_internal void add_import_dependency_node(Checker *c, Ast *decl, PtrMap<AstPackage *, ImportGraphNode *> *M) {
  4096. AstPackage *parent_pkg = decl->file()->pkg;
  4097. switch (decl->kind) {
  4098. case_ast_node(id, ImportDecl, decl);
  4099. String path = id->fullpath;
  4100. if (is_package_name_reserved(path)) {
  4101. return;
  4102. }
  4103. AstPackage **found = string_map_get(&c->info.packages, path);
  4104. if (found == nullptr) {
  4105. Token token = ast_token(decl);
  4106. error(token, "Unable to find package: %.*s", LIT(path));
  4107. exit_with_errors();
  4108. }
  4109. AstPackage *pkg = *found;
  4110. GB_ASSERT(pkg->scope != nullptr);
  4111. id->package = pkg;
  4112. ImportGraphNode **found_node = nullptr;
  4113. ImportGraphNode *m = nullptr;
  4114. ImportGraphNode *n = nullptr;
  4115. found_node = map_get(M, pkg);
  4116. GB_ASSERT(found_node != nullptr);
  4117. m = *found_node;
  4118. found_node = map_get(M, parent_pkg);
  4119. GB_ASSERT(found_node != nullptr);
  4120. n = *found_node;
  4121. import_graph_node_set_add(&n->succ, m);
  4122. import_graph_node_set_add(&m->pred, n);
  4123. ptr_set_add(&m->scope->imported, n->scope);
  4124. case_end;
  4125. case_ast_node(ws, WhenStmt, decl);
  4126. if (ws->body != nullptr) {
  4127. auto stmts = ws->body->BlockStmt.stmts;
  4128. for_array(i, stmts) {
  4129. add_import_dependency_node(c, stmts[i], M);
  4130. }
  4131. }
  4132. if (ws->else_stmt != nullptr) {
  4133. switch (ws->else_stmt->kind) {
  4134. case Ast_BlockStmt: {
  4135. auto stmts = ws->else_stmt->BlockStmt.stmts;
  4136. for_array(i, stmts) {
  4137. add_import_dependency_node(c, stmts[i], M);
  4138. }
  4139. break;
  4140. }
  4141. case Ast_WhenStmt:
  4142. add_import_dependency_node(c, ws->else_stmt, M);
  4143. break;
  4144. }
  4145. }
  4146. case_end;
  4147. }
  4148. }
  4149. gb_internal Array<ImportGraphNode *> generate_import_dependency_graph(Checker *c) {
  4150. PtrMap<AstPackage *, ImportGraphNode *> M = {};
  4151. map_init(&M, 2*c->parser->packages.count);
  4152. defer (map_destroy(&M));
  4153. for_array(i, c->parser->packages) {
  4154. AstPackage *pkg = c->parser->packages[i];
  4155. ImportGraphNode *n = import_graph_node_create(heap_allocator(), pkg);
  4156. map_set(&M, pkg, n);
  4157. }
  4158. // Calculate edges for graph M
  4159. for_array(i, c->parser->packages) {
  4160. AstPackage *p = c->parser->packages[i];
  4161. for_array(j, p->files) {
  4162. AstFile *f = p->files[j];
  4163. for_array(k, f->decls) {
  4164. Ast *decl = f->decls[k];
  4165. add_import_dependency_node(c, decl, &M);
  4166. }
  4167. }
  4168. }
  4169. Array<ImportGraphNode *> G = {};
  4170. array_init(&G, heap_allocator(), 0, M.count);
  4171. isize i = 0;
  4172. for (auto const &entry : M) {
  4173. auto n = entry.value;
  4174. n->index = i++;
  4175. n->dep_count = n->succ.count;
  4176. GB_ASSERT(n->dep_count >= 0);
  4177. array_add(&G, n);
  4178. }
  4179. return G;
  4180. }
  4181. struct ImportPathItem {
  4182. AstPackage *pkg;
  4183. Ast * decl;
  4184. };
  4185. gb_internal Array<ImportPathItem> find_import_path(Checker *c, AstPackage *start, AstPackage *end, PtrSet<AstPackage *> *visited) {
  4186. Array<ImportPathItem> empty_path = {};
  4187. if (ptr_set_update(visited, start)) {
  4188. return empty_path;
  4189. }
  4190. String path = start->fullpath;
  4191. AstPackage **found = string_map_get(&c->info.packages, path);
  4192. if (found) {
  4193. AstPackage *pkg = *found;
  4194. GB_ASSERT(pkg != nullptr);
  4195. for_array(i, pkg->files) {
  4196. AstFile *f = pkg->files[i];
  4197. for_array(j, f->imports) {
  4198. AstPackage *pkg = nullptr;
  4199. Ast *decl = f->imports[j];
  4200. if (decl->kind == Ast_ImportDecl) {
  4201. pkg = decl->ImportDecl.package;
  4202. } else {
  4203. continue;
  4204. }
  4205. if (pkg == nullptr || pkg->scope == nullptr) {
  4206. continue;
  4207. }
  4208. // if (pkg->kind == Package_Runtime) {
  4209. // // NOTE(bill): Allow cyclic imports within the runtime package for the time being
  4210. // continue;
  4211. // }
  4212. ImportPathItem item = {pkg, decl};
  4213. if (pkg == end) {
  4214. auto path = array_make<ImportPathItem>(heap_allocator());
  4215. array_add(&path, item);
  4216. return path;
  4217. }
  4218. auto next_path = find_import_path(c, pkg, end, visited);
  4219. if (next_path.count > 0) {
  4220. array_add(&next_path, item);
  4221. return next_path;
  4222. }
  4223. }
  4224. }
  4225. }
  4226. return empty_path;
  4227. }
  4228. #endif
  4229. gb_internal String get_invalid_import_name(String input) {
  4230. isize slash = 0;
  4231. for (isize i = input.len-1; i >= 0; i--) {
  4232. if (input[i] == '/' || input[i] == '\\') {
  4233. break;
  4234. }
  4235. slash = i;
  4236. }
  4237. input = substring(input, slash, input.len);
  4238. return input;
  4239. }
  4240. gb_internal DECL_ATTRIBUTE_PROC(import_decl_attribute) {
  4241. if (name == ATTRIBUTE_USER_TAG_NAME) {
  4242. ExactValue ev = check_decl_attribute_value(c, value);
  4243. if (ev.kind != ExactValue_String) {
  4244. error(elem, "Expected a string value for '%.*s'", LIT(name));
  4245. }
  4246. return true;
  4247. } else if (name == "require") {
  4248. if (value != nullptr) {
  4249. error(elem, "Expected no parameter for '%.*s'", LIT(name));
  4250. }
  4251. ac->require_declaration = true;
  4252. return true;
  4253. }
  4254. return false;
  4255. }
  4256. gb_internal void check_add_import_decl(CheckerContext *ctx, Ast *decl) {
  4257. if (decl->state_flags & StateFlag_BeenHandled) return;
  4258. decl->state_flags |= StateFlag_BeenHandled;
  4259. ast_node(id, ImportDecl, decl);
  4260. Token token = id->relpath;
  4261. Scope *parent_scope = ctx->scope;
  4262. GB_ASSERT(parent_scope->flags&ScopeFlag_File);
  4263. auto *pkgs = &ctx->checker->info.packages;
  4264. Scope *scope = nullptr;
  4265. bool force_use = false;
  4266. if (id->fullpath == "builtin") {
  4267. scope = builtin_pkg->scope;
  4268. force_use = true;
  4269. } else if (id->fullpath == "intrinsics") {
  4270. scope = intrinsics_pkg->scope;
  4271. force_use = true;
  4272. } else {
  4273. AstPackage **found = string_map_get(pkgs, id->fullpath);
  4274. if (found == nullptr) {
  4275. for (auto const &entry : *pkgs) {
  4276. AstPackage *pkg = entry.value;
  4277. gb_printf_err("%.*s\n", LIT(pkg->fullpath));
  4278. }
  4279. gb_printf_err("%s\n", token_pos_to_string(token.pos));
  4280. GB_PANIC("Unable to find scope for package: %.*s", LIT(id->fullpath));
  4281. } else {
  4282. AstPackage *pkg = *found;
  4283. scope = pkg->scope;
  4284. }
  4285. }
  4286. GB_ASSERT(scope->flags&ScopeFlag_Pkg);
  4287. if (ptr_set_update(&parent_scope->imported, scope)) {
  4288. // error(token, "Multiple import of the same file within this scope");
  4289. }
  4290. String import_name = path_to_entity_name(id->import_name.string, id->fullpath, false);
  4291. if (is_blank_ident(import_name)) {
  4292. force_use = true;
  4293. }
  4294. AttributeContext ac = {};
  4295. check_decl_attributes(ctx, id->attributes, import_decl_attribute, &ac);
  4296. if (ac.require_declaration) {
  4297. force_use = true;
  4298. }
  4299. if (import_name.len == 0) {
  4300. String invalid_name = id->fullpath;
  4301. invalid_name = get_invalid_import_name(invalid_name);
  4302. error(id->token, "Import name %.*s, is not a valid identifier. Perhaps you want to reference the package by a different name like this: import <new_name> \"%.*s\" ", LIT(invalid_name), LIT(invalid_name));
  4303. error(token, "Import name, %.*s, cannot be use as an import name as it is not a valid identifier", LIT(id->import_name.string));
  4304. } else {
  4305. GB_ASSERT(id->import_name.pos.line != 0);
  4306. id->import_name.string = import_name;
  4307. Entity *e = alloc_entity_import_name(parent_scope, id->import_name, t_invalid,
  4308. id->fullpath, id->import_name.string,
  4309. scope);
  4310. add_entity(ctx, parent_scope, nullptr, e);
  4311. if (force_use) {
  4312. add_entity_use(ctx, nullptr, e);
  4313. }
  4314. }
  4315. scope->flags |= ScopeFlag_HasBeenImported;
  4316. }
  4317. gb_internal DECL_ATTRIBUTE_PROC(foreign_import_decl_attribute) {
  4318. if (name == ATTRIBUTE_USER_TAG_NAME) {
  4319. ExactValue ev = check_decl_attribute_value(c, value);
  4320. if (ev.kind != ExactValue_String) {
  4321. error(elem, "Expected a string value for '%.*s'", LIT(name));
  4322. }
  4323. return true;
  4324. } else if (name == "force" || name == "require") {
  4325. if (value != nullptr) {
  4326. error(elem, "Expected no parameter for '%.*s'", LIT(name));
  4327. } else if (name == "force") {
  4328. error(elem, "'force' was replaced with 'require'");
  4329. }
  4330. ac->require_declaration = true;
  4331. return true;
  4332. } else if (name == "priority_index") {
  4333. ExactValue ev = check_decl_attribute_value(c, value);
  4334. if (ev.kind != ExactValue_Integer) {
  4335. error(elem, "Expected an integer value for '%.*s'", LIT(name));
  4336. } else {
  4337. ac->foreign_import_priority_index = exact_value_to_i64(ev);
  4338. }
  4339. return true;
  4340. } else if (name == "extra_linker_flags") {
  4341. ExactValue ev = check_decl_attribute_value(c, value);
  4342. if (ev.kind != ExactValue_String) {
  4343. error(elem, "Expected a string value for '%.*s'", LIT(name));
  4344. } else {
  4345. ac->extra_linker_flags = ev.value_string;
  4346. }
  4347. return true;
  4348. }
  4349. return false;
  4350. }
  4351. gb_internal void check_foreign_import_fullpaths(Checker *c) {
  4352. CheckerContext ctx = make_checker_context(c);
  4353. UntypedExprInfoMap untyped = {};
  4354. defer (map_destroy(&untyped));
  4355. for (Entity *e = nullptr; mpsc_dequeue(&c->info.foreign_imports_to_check_fullpaths, &e); /**/) {
  4356. GB_ASSERT(e != nullptr);
  4357. GB_ASSERT(e->kind == Entity_LibraryName);
  4358. Ast *decl = e->LibraryName.decl;
  4359. ast_node(fl, ForeignImportDecl, decl);
  4360. AstFile *f = decl->file();
  4361. reset_checker_context(&ctx, f, &untyped);
  4362. ctx.collect_delayed_decls = false;
  4363. GB_ASSERT(ctx.scope == e->scope);
  4364. if (fl->fullpaths.count == 0) {
  4365. String base_dir = dir_from_path(decl->file()->fullpath);
  4366. auto fullpaths = array_make<String>(permanent_allocator(), 0, fl->filepaths.count);
  4367. for (Ast *fp_node : fl->filepaths) {
  4368. Operand op = {};
  4369. check_expr(&ctx, &op, fp_node);
  4370. if (op.mode != Addressing_Constant && op.value.kind != ExactValue_String) {
  4371. gbString s = expr_to_string(op.expr);
  4372. error(fp_node, "Expected a constant string value, got '%s'", s);
  4373. gb_string_free(s);
  4374. continue;
  4375. }
  4376. if (!is_type_string(op.type)) {
  4377. gbString s = type_to_string(op.type);
  4378. error(fp_node, "Expected a constant string value, got value of type '%s'", s);
  4379. gb_string_free(s);
  4380. continue;
  4381. }
  4382. String file_str = op.value.value_string;
  4383. file_str = string_trim_whitespace(file_str);
  4384. String fullpath = file_str;
  4385. if (!is_arch_wasm() || string_ends_with(file_str, str_lit(".o"))) {
  4386. String foreign_path = {};
  4387. bool ok = determine_path_from_string(nullptr, decl, base_dir, file_str, &foreign_path, /*use error not syntax_error*/true);
  4388. if (ok) {
  4389. fullpath = foreign_path;
  4390. }
  4391. }
  4392. array_add(&fullpaths, fullpath);
  4393. }
  4394. fl->fullpaths = slice_from_array(fullpaths);
  4395. }
  4396. for (String const &path : fl->fullpaths) {
  4397. String ext = path_extension(path);
  4398. if (str_eq_ignore_case(ext, ".c") ||
  4399. str_eq_ignore_case(ext, ".cpp") ||
  4400. str_eq_ignore_case(ext, ".cxx") ||
  4401. str_eq_ignore_case(ext, ".h") ||
  4402. str_eq_ignore_case(ext, ".hpp") ||
  4403. str_eq_ignore_case(ext, ".hxx") ||
  4404. false
  4405. ) {
  4406. error(fl->token, "With 'foreign import', you cannot import a %.*s file/directory, you must precompile the library and link against that", LIT(ext));
  4407. break;
  4408. }
  4409. }
  4410. add_untyped_expressions(ctx.info, &untyped);
  4411. e->LibraryName.paths = fl->fullpaths;
  4412. }
  4413. }
  4414. gb_internal void check_add_foreign_import_decl(CheckerContext *ctx, Ast *decl) {
  4415. if (decl->state_flags & StateFlag_BeenHandled) return;
  4416. decl->state_flags |= StateFlag_BeenHandled;
  4417. ast_node(fl, ForeignImportDecl, decl);
  4418. Scope *parent_scope = ctx->scope;
  4419. GB_ASSERT(parent_scope->flags&ScopeFlag_File);
  4420. String library_name = fl->library_name.string;
  4421. if (library_name.len == 0 && fl->fullpaths.count != 0) {
  4422. String fullpath = fl->fullpaths[0];
  4423. library_name = path_to_entity_name(fl->library_name.string, fullpath);
  4424. }
  4425. if (library_name.len == 0 || is_blank_ident(library_name)) {
  4426. error(fl->token, "File name, '%.*s', cannot be as a library name as it is not a valid identifier", LIT(library_name));
  4427. return;
  4428. }
  4429. GB_ASSERT(fl->library_name.pos.line != 0);
  4430. fl->library_name.string = library_name;
  4431. Entity *e = alloc_entity_library_name(parent_scope, fl->library_name, t_invalid,
  4432. fl->fullpaths, library_name);
  4433. e->LibraryName.decl = decl;
  4434. add_entity_flags_from_file(ctx, e, parent_scope);
  4435. add_entity(ctx, parent_scope, nullptr, e);
  4436. AttributeContext ac = {};
  4437. check_decl_attributes(ctx, fl->attributes, foreign_import_decl_attribute, &ac);
  4438. if (ac.require_declaration) {
  4439. mpsc_enqueue(&ctx->info->required_foreign_imports_through_force_queue, e);
  4440. add_entity_use(ctx, nullptr, e);
  4441. }
  4442. if (ac.foreign_import_priority_index != 0) {
  4443. e->LibraryName.priority_index = ac.foreign_import_priority_index;
  4444. }
  4445. String extra_linker_flags = string_trim_whitespace(ac.extra_linker_flags);
  4446. if (extra_linker_flags.len != 0) {
  4447. e->LibraryName.extra_linker_flags = extra_linker_flags;
  4448. }
  4449. mpsc_enqueue(&ctx->info->foreign_imports_to_check_fullpaths, e);
  4450. }
  4451. // Returns true if a new package is present
  4452. gb_internal bool collect_file_decls(CheckerContext *ctx, Slice<Ast *> const &decls);
  4453. gb_internal bool collect_file_decls_from_when_stmt(CheckerContext *ctx, AstWhenStmt *ws);
  4454. gb_internal bool collect_when_stmt_from_file(CheckerContext *ctx, AstWhenStmt *ws) {
  4455. Operand operand = {Addressing_Invalid};
  4456. if (!ws->is_cond_determined) {
  4457. check_expr(ctx, &operand, ws->cond);
  4458. if (operand.mode != Addressing_Invalid && !is_type_boolean(operand.type)) {
  4459. error(ws->cond, "Non-boolean condition in 'when' statement");
  4460. }
  4461. if (operand.mode != Addressing_Constant) {
  4462. error(ws->cond, "Non-constant condition in 'when' statement");
  4463. }
  4464. ws->is_cond_determined = true;
  4465. ws->determined_cond = operand.value.kind == ExactValue_Bool && operand.value.value_bool;
  4466. }
  4467. if (ws->body == nullptr || ws->body->kind != Ast_BlockStmt) {
  4468. error(ws->cond, "Invalid body for 'when' statement");
  4469. } else {
  4470. if (ws->determined_cond) {
  4471. check_collect_entities(ctx, ws->body->BlockStmt.stmts);
  4472. return true;
  4473. } else if (ws->else_stmt) {
  4474. switch (ws->else_stmt->kind) {
  4475. case Ast_BlockStmt:
  4476. check_collect_entities(ctx, ws->else_stmt->BlockStmt.stmts);
  4477. return true;
  4478. case Ast_WhenStmt:
  4479. collect_when_stmt_from_file(ctx, &ws->else_stmt->WhenStmt);
  4480. return true;
  4481. default:
  4482. error(ws->else_stmt, "Invalid 'else' statement in 'when' statement");
  4483. break;
  4484. }
  4485. }
  4486. }
  4487. return false;
  4488. }
  4489. gb_internal bool collect_file_decls_from_when_stmt(CheckerContext *ctx, AstWhenStmt *ws) {
  4490. Operand operand = {Addressing_Invalid};
  4491. if (!ws->is_cond_determined) {
  4492. check_expr(ctx, &operand, ws->cond);
  4493. if (operand.mode != Addressing_Invalid && !is_type_boolean(operand.type)) {
  4494. error(ws->cond, "Non-boolean condition in 'when' statement");
  4495. }
  4496. if (operand.mode != Addressing_Constant) {
  4497. error(ws->cond, "Non-constant condition in 'when' statement");
  4498. }
  4499. ws->is_cond_determined = true;
  4500. ws->determined_cond = operand.value.kind == ExactValue_Bool && operand.value.value_bool;
  4501. }
  4502. if (ws->body == nullptr || ws->body->kind != Ast_BlockStmt) {
  4503. error(ws->cond, "Invalid body for 'when' statement");
  4504. } else {
  4505. if (ws->determined_cond) {
  4506. return collect_file_decls(ctx, ws->body->BlockStmt.stmts);
  4507. } else if (ws->else_stmt) {
  4508. switch (ws->else_stmt->kind) {
  4509. case Ast_BlockStmt:
  4510. return collect_file_decls(ctx, ws->else_stmt->BlockStmt.stmts);
  4511. case Ast_WhenStmt:
  4512. return collect_file_decls_from_when_stmt(ctx, &ws->else_stmt->WhenStmt);
  4513. default:
  4514. error(ws->else_stmt, "Invalid 'else' statement in 'when' statement");
  4515. break;
  4516. }
  4517. }
  4518. }
  4519. return false;
  4520. }
  4521. gb_internal bool collect_file_decl(CheckerContext *ctx, Ast *decl) {
  4522. GB_ASSERT(ctx->scope->flags&ScopeFlag_File);
  4523. AstFile *curr_file = ctx->scope->file;
  4524. GB_ASSERT(curr_file != nullptr);
  4525. if (decl->state_flags & StateFlag_BeenHandled) {
  4526. return false;
  4527. }
  4528. switch (decl->kind) {
  4529. case_ast_node(vd, ValueDecl, decl);
  4530. check_collect_value_decl(ctx, decl);
  4531. case_end;
  4532. case_ast_node(id, ImportDecl, decl);
  4533. check_add_import_decl(ctx, decl);
  4534. case_end;
  4535. case_ast_node(fl, ForeignImportDecl, decl);
  4536. check_add_foreign_import_decl(ctx, decl);
  4537. case_end;
  4538. case_ast_node(fb, ForeignBlockDecl, decl);
  4539. if (check_add_foreign_block_decl(ctx, decl)) {
  4540. return true;
  4541. }
  4542. case_end;
  4543. case_ast_node(ws, WhenStmt, decl);
  4544. if (!ws->is_cond_determined) {
  4545. if (collect_when_stmt_from_file(ctx, ws)) {
  4546. return true;
  4547. }
  4548. CheckerContext nctx = *ctx;
  4549. nctx.collect_delayed_decls = true;
  4550. if (collect_file_decls_from_when_stmt(&nctx, ws)) {
  4551. return true;
  4552. }
  4553. } else {
  4554. CheckerContext nctx = *ctx;
  4555. nctx.collect_delayed_decls = true;
  4556. if (collect_file_decls_from_when_stmt(&nctx, ws)) {
  4557. return true;
  4558. }
  4559. }
  4560. case_end;
  4561. case_ast_node(es, ExprStmt, decl);
  4562. GB_ASSERT(ctx->collect_delayed_decls);
  4563. decl->state_flags |= StateFlag_BeenHandled;
  4564. if (es->expr->kind == Ast_CallExpr) {
  4565. ast_node(ce, CallExpr, es->expr);
  4566. if (ce->proc->kind == Ast_BasicDirective) {
  4567. array_add(&curr_file->delayed_decls_queues[AstDelayQueue_Expr], es->expr);
  4568. }
  4569. }
  4570. case_end;
  4571. }
  4572. return false;
  4573. }
  4574. gb_internal bool collect_file_decls(CheckerContext *ctx, Slice<Ast *> const &decls) {
  4575. GB_ASSERT(ctx->scope->flags&ScopeFlag_File);
  4576. for_array(i, decls) {
  4577. if (collect_file_decl(ctx, decls[i])) {
  4578. correct_type_aliases_in_scope(ctx, ctx->scope);
  4579. return true;
  4580. }
  4581. }
  4582. correct_type_aliases_in_scope(ctx, ctx->scope);
  4583. return false;
  4584. }
  4585. gb_internal GB_COMPARE_PROC(sort_file_by_name) {
  4586. AstFile const *x = *cast(AstFile const **)a;
  4587. AstFile const *y = *cast(AstFile const **)b;
  4588. String x_name = filename_from_path(x->fullpath);
  4589. String y_name = filename_from_path(y->fullpath);
  4590. return string_compare(x_name, y_name);
  4591. }
  4592. gb_internal void check_create_file_scopes(Checker *c) {
  4593. for_array(i, c->parser->packages) {
  4594. AstPackage *pkg = c->parser->packages[i];
  4595. array_sort(pkg->files, sort_file_by_name);
  4596. isize total_pkg_decl_count = 0;
  4597. for_array(j, pkg->files) {
  4598. AstFile *f = pkg->files[j];
  4599. string_map_set(&c->info.files, f->fullpath, f);
  4600. create_scope_from_file(nullptr, f);
  4601. total_pkg_decl_count += f->total_file_decl_count;
  4602. }
  4603. mpmc_init(&pkg->exported_entity_queue, total_pkg_decl_count);
  4604. }
  4605. }
  4606. struct CollectEntityWorkerData {
  4607. Checker *c;
  4608. CheckerContext ctx;
  4609. UntypedExprInfoMap untyped;
  4610. };
  4611. gb_global CollectEntityWorkerData *collect_entity_worker_data;
  4612. gb_internal WORKER_TASK_PROC(check_collect_entities_all_worker_proc) {
  4613. CollectEntityWorkerData *wd = &collect_entity_worker_data[current_thread_index()];
  4614. Checker *c = wd->c;
  4615. CheckerContext *ctx = &wd->ctx;
  4616. UntypedExprInfoMap *untyped = &wd->untyped;
  4617. AstFile *f = cast(AstFile *)data;
  4618. reset_checker_context(ctx, f, untyped);
  4619. check_collect_entities(ctx, f->decls);
  4620. GB_ASSERT(ctx->collect_delayed_decls == false);
  4621. add_untyped_expressions(&c->info, ctx->untyped);
  4622. return 0;
  4623. }
  4624. gb_internal void check_collect_entities_all(Checker *c) {
  4625. isize thread_count = global_thread_pool.threads.count;
  4626. collect_entity_worker_data = gb_alloc_array(permanent_allocator(), CollectEntityWorkerData, thread_count);
  4627. for (isize i = 0; i < thread_count; i++) {
  4628. auto *wd = &collect_entity_worker_data[i];
  4629. wd->c = c;
  4630. wd->ctx = make_checker_context(c);
  4631. map_init(&wd->untyped);
  4632. }
  4633. for (auto const &entry : c->info.files) {
  4634. AstFile *f = entry.value;
  4635. thread_pool_add_task(check_collect_entities_all_worker_proc, f);
  4636. }
  4637. thread_pool_wait();
  4638. }
  4639. gb_internal void check_export_entities_in_pkg(CheckerContext *ctx, AstPackage *pkg, UntypedExprInfoMap *untyped) {
  4640. if (pkg->files.count != 0) {
  4641. AstPackageExportedEntity item = {};
  4642. while (mpmc_dequeue(&pkg->exported_entity_queue, &item)) {
  4643. AstFile *f = item.entity->file;
  4644. if (ctx->file != f) {
  4645. reset_checker_context(ctx, f, untyped);
  4646. }
  4647. add_entity(ctx, pkg->scope, item.identifier, item.entity);
  4648. add_untyped_expressions(ctx->info, untyped);
  4649. }
  4650. }
  4651. }
  4652. gb_internal WORKER_TASK_PROC(check_export_entities_worker_proc) {
  4653. AstPackage *pkg = (AstPackage *)data;
  4654. auto *wd = &collect_entity_worker_data[current_thread_index()];
  4655. check_export_entities_in_pkg(&wd->ctx, pkg, &wd->untyped);
  4656. return 0;
  4657. }
  4658. gb_internal void check_export_entities(Checker *c) {
  4659. isize thread_count = global_thread_pool.threads.count;
  4660. // NOTE(bill): reuse `collect_entity_worker_data`
  4661. for (isize i = 0; i < thread_count; i++) {
  4662. auto *wd = &collect_entity_worker_data[i];
  4663. map_clear(&wd->untyped);
  4664. wd->ctx = make_checker_context(c);
  4665. }
  4666. for (auto const &entry : c->info.packages) {
  4667. AstPackage *pkg = entry.value;
  4668. thread_pool_add_task(check_export_entities_worker_proc, pkg);
  4669. }
  4670. thread_pool_wait();
  4671. }
  4672. gb_internal void check_import_entities(Checker *c) {
  4673. Array<ImportGraphNode *> dep_graph = generate_import_dependency_graph(c);
  4674. defer ({
  4675. for_array(i, dep_graph) {
  4676. import_graph_node_destroy(dep_graph[i], heap_allocator());
  4677. }
  4678. array_free(&dep_graph);
  4679. });
  4680. TIME_SECTION("check_import_entities - sort packages");
  4681. // NOTE(bill): Priority queue
  4682. auto pq = priority_queue_create(dep_graph, import_graph_node_cmp, import_graph_node_swap);
  4683. PtrSet<AstPackage *> emitted = {};
  4684. defer (ptr_set_destroy(&emitted));
  4685. Array<ImportGraphNode *> package_order = {};
  4686. array_init(&package_order, heap_allocator(), 0, c->parser->packages.count);
  4687. defer (array_free(&package_order));
  4688. while (pq.queue.count > 0) {
  4689. ImportGraphNode *n = priority_queue_pop(&pq);
  4690. AstPackage *pkg = n->pkg;
  4691. if (n->dep_count > 0) {
  4692. PtrSet<AstPackage *> visited = {};
  4693. defer (ptr_set_destroy(&visited));
  4694. auto path = find_import_path(c, pkg, pkg, &visited);
  4695. defer (array_free(&path));
  4696. if (path.count > 1) {
  4697. ImportPathItem item = path[path.count-1];
  4698. String pkg_name = item.pkg->name;
  4699. error(item.decl, "Cyclic importation of '%.*s'", LIT(pkg_name));
  4700. for (isize i = 0; i < path.count; i++) {
  4701. error(item.decl, "'%.*s' refers to", LIT(pkg_name));
  4702. item = path[i];
  4703. pkg_name = item.pkg->name;
  4704. }
  4705. error(item.decl, "'%.*s'", LIT(pkg_name));
  4706. }
  4707. }
  4708. for (ImportGraphNode *p : n->pred) {
  4709. p->dep_count = gb_max(p->dep_count-1, 0);
  4710. priority_queue_fix(&pq, p->index);
  4711. }
  4712. if (pkg == nullptr) {
  4713. continue;
  4714. }
  4715. if (ptr_set_update(&emitted, pkg)) {
  4716. continue;
  4717. }
  4718. array_add(&package_order, n);
  4719. }
  4720. TIME_SECTION("check_import_entities - collect file decls");
  4721. CheckerContext ctx = make_checker_context(c);
  4722. UntypedExprInfoMap untyped = {};
  4723. defer (map_destroy(&untyped));
  4724. isize min_pkg_index = 0;
  4725. for (isize pkg_index = 0; pkg_index < package_order.count; pkg_index++) {
  4726. ImportGraphNode *node = package_order[pkg_index];
  4727. AstPackage *pkg = node->pkg;
  4728. pkg->order = 1+pkg_index;
  4729. for_array(i, pkg->files) {
  4730. AstFile *f = pkg->files[i];
  4731. reset_checker_context(&ctx, f, &untyped);
  4732. ctx.collect_delayed_decls = true;
  4733. // Check import declarations first to simplify things
  4734. for (Ast *decl : f->delayed_decls_queues[AstDelayQueue_Import]) {
  4735. check_add_import_decl(&ctx, decl);
  4736. }
  4737. array_clear(&f->delayed_decls_queues[AstDelayQueue_Import]);
  4738. if (collect_file_decls(&ctx, f->decls)) {
  4739. check_export_entities_in_pkg(&ctx, pkg, &untyped);
  4740. pkg_index = min_pkg_index-1;
  4741. break;
  4742. }
  4743. add_untyped_expressions(ctx.info, &untyped);
  4744. }
  4745. if (pkg_index < 0) {
  4746. continue;
  4747. }
  4748. min_pkg_index = pkg_index;
  4749. }
  4750. TIME_SECTION("check_import_entities - check delayed entities");
  4751. for_array(i, package_order) {
  4752. ImportGraphNode *node = package_order[i];
  4753. GB_ASSERT(node->scope->flags&ScopeFlag_Pkg);
  4754. AstPackage *pkg = node->scope->pkg;
  4755. for_array(i, pkg->files) {
  4756. AstFile *f = pkg->files[i];
  4757. reset_checker_context(&ctx, f, &untyped);
  4758. for (Ast *decl : f->delayed_decls_queues[AstDelayQueue_Import]) {
  4759. check_add_import_decl(&ctx, decl);
  4760. }
  4761. array_clear(&f->delayed_decls_queues[AstDelayQueue_Import]);
  4762. add_untyped_expressions(ctx.info, &untyped);
  4763. }
  4764. for_array(i, pkg->files) {
  4765. AstFile *f = pkg->files[i];
  4766. reset_checker_context(&ctx, f, &untyped);
  4767. ctx.collect_delayed_decls = false;
  4768. correct_type_aliases_in_scope(&ctx, pkg->scope);
  4769. }
  4770. for_array(i, pkg->files) {
  4771. AstFile *f = pkg->files[i];
  4772. reset_checker_context(&ctx, f, &untyped);
  4773. for (Ast *expr : f->delayed_decls_queues[AstDelayQueue_Expr]) {
  4774. Operand o = {};
  4775. check_expr(&ctx, &o, expr);
  4776. }
  4777. array_clear(&f->delayed_decls_queues[AstDelayQueue_Expr]);
  4778. add_untyped_expressions(ctx.info, &untyped);
  4779. }
  4780. }
  4781. }
  4782. gb_internal Array<Entity *> find_entity_path(Entity *start, Entity *end, PtrSet<Entity *> *visited = nullptr);
  4783. gb_internal bool find_entity_path_tuple(Type *tuple, Entity *end, PtrSet<Entity *> *visited, Array<Entity *> *path_) {
  4784. GB_ASSERT(path_ != nullptr);
  4785. if (tuple == nullptr) {
  4786. return false;
  4787. }
  4788. GB_ASSERT(tuple->kind == Type_Tuple);
  4789. for_array(i, tuple->Tuple.variables) {
  4790. Entity *var = tuple->Tuple.variables[i];
  4791. DeclInfo *var_decl = var->decl_info;
  4792. if (var_decl == nullptr) {
  4793. continue;
  4794. }
  4795. for (Entity *dep : var_decl->deps) {
  4796. if (dep == end) {
  4797. auto path = array_make<Entity *>(heap_allocator());
  4798. array_add(&path, dep);
  4799. *path_ = path;
  4800. return true;
  4801. }
  4802. auto next_path = find_entity_path(dep, end, visited);
  4803. if (next_path.count > 0) {
  4804. array_add(&next_path, dep);
  4805. *path_ = next_path;
  4806. return true;
  4807. }
  4808. }
  4809. }
  4810. return false;
  4811. }
  4812. gb_internal Array<Entity *> find_entity_path(Entity *start, Entity *end, PtrSet<Entity *> *visited) {
  4813. PtrSet<Entity *> visited_ = {};
  4814. bool made_visited = false;
  4815. if (visited == nullptr) {
  4816. made_visited = true;
  4817. visited = &visited_;
  4818. }
  4819. defer (if (made_visited) {
  4820. ptr_set_destroy(&visited_);
  4821. });
  4822. Array<Entity *> empty_path = {};
  4823. if (ptr_set_update(visited, start)) {
  4824. return empty_path;
  4825. }
  4826. DeclInfo *decl = start->decl_info;
  4827. if (decl) {
  4828. if (start->kind == Entity_Procedure) {
  4829. Type *t = base_type(start->type);
  4830. GB_ASSERT(t->kind == Type_Proc);
  4831. Array<Entity *> path = {};
  4832. if (find_entity_path_tuple(t->Proc.params, end, visited, &path)) {
  4833. return path;
  4834. }
  4835. if (find_entity_path_tuple(t->Proc.results, end, visited, &path)) {
  4836. return path;
  4837. }
  4838. } else {
  4839. for (Entity *dep : decl->deps) {
  4840. if (dep == end) {
  4841. auto path = array_make<Entity *>(heap_allocator());
  4842. array_add(&path, dep);
  4843. return path;
  4844. }
  4845. auto next_path = find_entity_path(dep, end, visited);
  4846. if (next_path.count > 0) {
  4847. array_add(&next_path, dep);
  4848. return next_path;
  4849. }
  4850. }
  4851. }
  4852. }
  4853. return empty_path;
  4854. }
  4855. gb_internal void calculate_global_init_order(Checker *c) {
  4856. CheckerInfo *info = &c->info;
  4857. TIME_SECTION("calculate_global_init_order: generate entity dependency graph");
  4858. Array<EntityGraphNode *> dep_graph = generate_entity_dependency_graph(info, heap_allocator());
  4859. defer ({
  4860. for_array(i, dep_graph) {
  4861. entity_graph_node_destroy(dep_graph[i], heap_allocator());
  4862. }
  4863. array_free(&dep_graph);
  4864. });
  4865. TIME_SECTION("calculate_global_init_order: priority queue create");
  4866. // NOTE(bill): Priority queue
  4867. auto pq = priority_queue_create(dep_graph, entity_graph_node_cmp, entity_graph_node_swap);
  4868. PtrSet<DeclInfo *> emitted = {};
  4869. defer (ptr_set_destroy(&emitted));
  4870. TIME_SECTION("calculate_global_init_order: queue sort");
  4871. while (pq.queue.count > 0) {
  4872. EntityGraphNode *n = priority_queue_pop(&pq);
  4873. Entity *e = n->entity;
  4874. if (n->dep_count > 0) {
  4875. auto path = find_entity_path(e, e);
  4876. defer (array_free(&path));
  4877. if (path.count > 0) {
  4878. Entity *e = path[0];
  4879. error(e->token, "Cyclic initialization of '%.*s'", LIT(e->token.string));
  4880. for (isize i = path.count-1; i >= 0; i--) {
  4881. error(e->token, "\t'%.*s' refers to", LIT(e->token.string));
  4882. e = path[i];
  4883. }
  4884. error(e->token, "\t'%.*s'", LIT(e->token.string));
  4885. }
  4886. }
  4887. for (EntityGraphNode *p : n->pred) {
  4888. p->dep_count -= 1;
  4889. p->dep_count = gb_max(p->dep_count, 0);
  4890. priority_queue_fix(&pq, p->index);
  4891. }
  4892. DeclInfo *d = decl_info_of_entity(e);
  4893. if (e->kind != Entity_Variable) {
  4894. continue;
  4895. }
  4896. // IMPORTANT NOTE(bill, 2019-08-29): Just add it regardless of the ordering
  4897. // because it does not need any initialization other than zero
  4898. // if (!decl_info_has_init(d)) {
  4899. // continue;
  4900. // }
  4901. if (ptr_set_update(&emitted, d)) {
  4902. continue;
  4903. }
  4904. array_add(&info->variable_init_order, d);
  4905. }
  4906. if (false) {
  4907. gb_printf("Variable Initialization Order:\n");
  4908. for_array(i, info->variable_init_order) {
  4909. DeclInfo *d = info->variable_init_order[i];
  4910. Entity *e = d->entity;
  4911. gb_printf("\t'%.*s' %llu\n", LIT(e->token.string), cast(unsigned long long)e->order_in_src);
  4912. }
  4913. gb_printf("\n");
  4914. }
  4915. }
  4916. gb_internal void check_procedure_later_from_entity(Checker *c, Entity *e, char const *from_msg) {
  4917. if (e == nullptr || e->kind != Entity_Procedure) {
  4918. return;
  4919. }
  4920. if (e->Procedure.is_foreign) {
  4921. return;
  4922. }
  4923. if ((e->flags & EntityFlag_ProcBodyChecked) != 0) {
  4924. return;
  4925. }
  4926. if ((e->flags & EntityFlag_Overridden) != 0) {
  4927. // NOTE (zen3ger) Delay checking of a proc alias until the underlying proc is checked.
  4928. GB_ASSERT(e->aliased_of != nullptr);
  4929. GB_ASSERT(e->aliased_of->kind == Entity_Procedure);
  4930. if ((e->aliased_of->flags & EntityFlag_ProcBodyChecked) != 0) {
  4931. e->flags |= EntityFlag_ProcBodyChecked;
  4932. return;
  4933. }
  4934. // NOTE (zen3ger) A proc alias *does not* have a body and tags!
  4935. check_procedure_later(c, e->file, e->token, e->decl_info, e->type, nullptr, 0);
  4936. return;
  4937. }
  4938. Type *type = base_type(e->type);
  4939. if (type == t_invalid) {
  4940. return;
  4941. }
  4942. GB_ASSERT_MSG(type->kind == Type_Proc, "%s", type_to_string(e->type));
  4943. if (is_type_polymorphic(type) && !type->Proc.is_poly_specialized) {
  4944. return;
  4945. }
  4946. GB_ASSERT(e->decl_info != nullptr);
  4947. ProcInfo *pi = gb_alloc_item(permanent_allocator(), ProcInfo);
  4948. pi->file = e->file;
  4949. pi->token = e->token;
  4950. pi->decl = e->decl_info;
  4951. pi->type = e->type;
  4952. Ast *pl = e->decl_info->proc_lit;
  4953. GB_ASSERT(pl != nullptr);
  4954. pi->body = pl->ProcLit.body;
  4955. pi->tags = pl->ProcLit.tags;
  4956. if (pi->body == nullptr) {
  4957. return;
  4958. }
  4959. if (from_msg != nullptr) {
  4960. debugf("CHECK PROCEDURE LATER [FROM %s]! %.*s :: %s {...}\n", from_msg, LIT(e->token.string), type_to_string(e->type));
  4961. }
  4962. check_procedure_later(c, pi);
  4963. }
  4964. gb_internal bool check_proc_info(Checker *c, ProcInfo *pi, UntypedExprInfoMap *untyped) {
  4965. if (pi == nullptr) {
  4966. return false;
  4967. }
  4968. if (pi->type == nullptr) {
  4969. return false;
  4970. }
  4971. if (!mutex_try_lock(&pi->decl->proc_checked_mutex)) {
  4972. return false;
  4973. }
  4974. defer (mutex_unlock(&pi->decl->proc_checked_mutex));
  4975. Entity *e = pi->decl->entity;
  4976. switch (pi->decl->proc_checked_state.load()) {
  4977. case ProcCheckedState_InProgress:
  4978. if (e) {
  4979. GB_ASSERT(global_procedure_body_in_worker_queue.load());
  4980. }
  4981. return false;
  4982. case ProcCheckedState_Checked:
  4983. if (e != nullptr) {
  4984. GB_ASSERT(e->flags & EntityFlag_ProcBodyChecked);
  4985. }
  4986. return true;
  4987. case ProcCheckedState_Unchecked:
  4988. // okay
  4989. break;
  4990. }
  4991. pi->decl->proc_checked_state.store(ProcCheckedState_InProgress);
  4992. GB_ASSERT(pi->type->kind == Type_Proc);
  4993. TypeProc *pt = &pi->type->Proc;
  4994. String name = pi->token.string;
  4995. if (pt->is_polymorphic && !pt->is_poly_specialized) {
  4996. Token token = pi->token;
  4997. if (pi->poly_def_node != nullptr) {
  4998. token = ast_token(pi->poly_def_node);
  4999. }
  5000. error(token, "Unspecialized polymorphic procedure '%.*s'", LIT(name));
  5001. pi->decl->proc_checked_state.store(ProcCheckedState_Unchecked);
  5002. return false;
  5003. }
  5004. if (pt->is_polymorphic && pt->is_poly_specialized) {
  5005. Entity *e = pi->decl->entity;
  5006. GB_ASSERT(e != nullptr);
  5007. if ((e->flags & EntityFlag_Used) == 0) {
  5008. // NOTE(bill, 2019-08-31): It was never used, don't check
  5009. // NOTE(bill, 2023-01-02): This may need to be checked again if it is used elsewhere?
  5010. pi->decl->proc_checked_state.store(ProcCheckedState_Unchecked);
  5011. return false;
  5012. }
  5013. }
  5014. CheckerContext ctx = make_checker_context(c);
  5015. defer (destroy_checker_context(&ctx));
  5016. reset_checker_context(&ctx, pi->file, untyped);
  5017. ctx.decl = pi->decl;
  5018. bool bounds_check = (pi->tags & ProcTag_bounds_check) != 0;
  5019. bool no_bounds_check = (pi->tags & ProcTag_no_bounds_check) != 0;
  5020. bool type_assert = (pi->tags & ProcTag_type_assert) != 0;
  5021. bool no_type_assert = (pi->tags & ProcTag_no_type_assert) != 0;
  5022. if (bounds_check) {
  5023. ctx.state_flags |= StateFlag_bounds_check;
  5024. ctx.state_flags &= ~StateFlag_no_bounds_check;
  5025. } else if (no_bounds_check) {
  5026. ctx.state_flags |= StateFlag_no_bounds_check;
  5027. ctx.state_flags &= ~StateFlag_bounds_check;
  5028. }
  5029. if (type_assert) {
  5030. ctx.state_flags |= StateFlag_type_assert;
  5031. ctx.state_flags &= ~StateFlag_no_type_assert;
  5032. } else if (no_type_assert) {
  5033. ctx.state_flags |= StateFlag_no_type_assert;
  5034. ctx.state_flags &= ~StateFlag_type_assert;
  5035. }
  5036. bool body_was_checked = check_proc_body(&ctx, pi->token, pi->decl, pi->type, pi->body);
  5037. if (body_was_checked) {
  5038. pi->decl->proc_checked_state.store(ProcCheckedState_Checked);
  5039. if (pi->body) {
  5040. Entity *e = pi->decl->entity;
  5041. if (e != nullptr) {
  5042. e->flags |= EntityFlag_ProcBodyChecked;
  5043. }
  5044. }
  5045. } else {
  5046. pi->decl->proc_checked_state.store(ProcCheckedState_Unchecked);
  5047. if (pi->body) {
  5048. Entity *e = pi->decl->entity;
  5049. if (e != nullptr) {
  5050. e->flags &= ~EntityFlag_ProcBodyChecked;
  5051. }
  5052. }
  5053. }
  5054. add_untyped_expressions(&c->info, ctx.untyped);
  5055. rw_mutex_shared_lock(&ctx.decl->deps_mutex);
  5056. for (Entity *dep : ctx.decl->deps) {
  5057. if (dep && dep->kind == Entity_Procedure &&
  5058. (dep->flags & EntityFlag_ProcBodyChecked) == 0) {
  5059. check_procedure_later_from_entity(c, dep, NULL);
  5060. }
  5061. }
  5062. rw_mutex_shared_unlock(&ctx.decl->deps_mutex);
  5063. return true;
  5064. }
  5065. GB_STATIC_ASSERT(sizeof(isize) == sizeof(void *));
  5066. gb_internal bool consume_proc_info(Checker *c, ProcInfo *pi, UntypedExprInfoMap *untyped);
  5067. gb_internal void check_unchecked_bodies(Checker *c) {
  5068. // NOTE(2021-02-26, bill): Sanity checker
  5069. // This is a partial hack to make sure all procedure bodies have been checked
  5070. // even ones which should not exist, due to the multithreaded nature of the parser
  5071. // HACK TODO(2021-02-26, bill): Actually fix this race condition
  5072. GB_ASSERT(c->procs_to_check.count == 0);
  5073. UntypedExprInfoMap untyped = {};
  5074. defer (map_destroy(&untyped));
  5075. // use the `procs_to_check` array
  5076. global_procedure_body_in_worker_queue = false;
  5077. for (Entity *e : c->info.minimum_dependency_set) {
  5078. check_procedure_later_from_entity(c, e, "check_unchecked_bodies");
  5079. }
  5080. if (!global_procedure_body_in_worker_queue) {
  5081. for_array(i, c->procs_to_check) {
  5082. ProcInfo *pi = c->procs_to_check[i];
  5083. consume_proc_info(c, pi, &untyped);
  5084. }
  5085. array_clear(&c->procs_to_check);
  5086. } else {
  5087. thread_pool_wait();
  5088. }
  5089. global_procedure_body_in_worker_queue = false;
  5090. global_after_checking_procedure_bodies = true;
  5091. }
  5092. gb_internal void check_safety_all_procedures_for_unchecked(Checker *c) {
  5093. GB_ASSERT(DEBUG_CHECK_ALL_PROCEDURES);
  5094. UntypedExprInfoMap untyped = {};
  5095. defer (map_destroy(&untyped));
  5096. for_array(i, c->info.all_procedures) {
  5097. ProcInfo *pi = c->info.all_procedures[i];
  5098. GB_ASSERT(pi != nullptr);
  5099. GB_ASSERT(pi->decl != nullptr);
  5100. Entity *e = pi->decl->entity;
  5101. auto proc_checked_state = pi->decl->proc_checked_state.load();
  5102. gb_unused(proc_checked_state);
  5103. if (e && ((e->flags & EntityFlag_ProcBodyChecked) == 0)) {
  5104. if ((e->flags & EntityFlag_Used) != 0) {
  5105. // debugf("%.*s :: %s\n", LIT(e->token.string), type_to_string(e->type));
  5106. // debugf("proc body unchecked\n");
  5107. // debugf("Checked State: %s\n\n", ProcCheckedState_strings[proc_checked_state]);
  5108. consume_proc_info(c, pi, &untyped);
  5109. }
  5110. }
  5111. }
  5112. }
  5113. gb_internal GB_COMPARE_PROC(init_procedures_cmp);
  5114. gb_internal GB_COMPARE_PROC(fini_procedures_cmp);
  5115. gb_internal void remove_neighbouring_duplicate_entires_from_sorted_array(Array<Entity *> *array) {
  5116. Entity *prev = nullptr;
  5117. for (isize i = 0; i < array->count; /**/) {
  5118. Entity *curr = array->data[i];
  5119. if (prev == curr) {
  5120. array_ordered_remove(array, i);
  5121. } else {
  5122. prev = curr;
  5123. i += 1;
  5124. }
  5125. }
  5126. }
  5127. gb_internal void check_test_procedures(Checker *c) {
  5128. array_sort(c->info.testing_procedures, init_procedures_cmp);
  5129. remove_neighbouring_duplicate_entires_from_sorted_array(&c->info.testing_procedures);
  5130. }
  5131. gb_global std::atomic<isize> total_bodies_checked;
  5132. gb_internal bool consume_proc_info(Checker *c, ProcInfo *pi, UntypedExprInfoMap *untyped) {
  5133. GB_ASSERT(pi->decl != nullptr);
  5134. switch (pi->decl->proc_checked_state.load()) {
  5135. case ProcCheckedState_InProgress:
  5136. return false;
  5137. case ProcCheckedState_Checked:
  5138. return true;
  5139. }
  5140. if (pi->decl->parent && pi->decl->parent->entity) {
  5141. Entity *parent = pi->decl->parent->entity;
  5142. // NOTE(bill): Only check a nested procedure if its parent's body has been checked first
  5143. // This is prevent any possible race conditions in evaluation when multithreaded
  5144. // NOTE(bill): In single threaded mode, this should never happen
  5145. if (parent->kind == Entity_Procedure && (parent->flags & EntityFlag_ProcBodyChecked) == 0) {
  5146. check_procedure_later(c, pi);
  5147. return false;
  5148. }
  5149. }
  5150. if (untyped) {
  5151. map_clear(untyped);
  5152. }
  5153. if (check_proc_info(c, pi, untyped)) {
  5154. total_bodies_checked.fetch_add(1, std::memory_order_relaxed);
  5155. return true;
  5156. }
  5157. return false;
  5158. }
  5159. struct CheckProcedureBodyWorkerData {
  5160. Checker *c;
  5161. UntypedExprInfoMap untyped;
  5162. };
  5163. gb_global CheckProcedureBodyWorkerData *check_procedure_bodies_worker_data;
  5164. gb_internal WORKER_TASK_PROC(check_proc_info_worker_proc) {
  5165. auto *wd = &check_procedure_bodies_worker_data[current_thread_index()];
  5166. UntypedExprInfoMap *untyped = &wd->untyped;
  5167. Checker *c = wd->c;
  5168. ProcInfo *pi = cast(ProcInfo *)data;
  5169. GB_ASSERT(pi->decl != nullptr);
  5170. if (pi->decl->parent && pi->decl->parent->entity) {
  5171. Entity *parent = pi->decl->parent->entity;
  5172. // NOTE(bill): Only check a nested procedure if its parent's body has been checked first
  5173. // This is prevent any possible race conditions in evaluation when multithreaded
  5174. // NOTE(bill): In single threaded mode, this should never happen
  5175. if (parent->kind == Entity_Procedure && (parent->flags & EntityFlag_ProcBodyChecked) == 0) {
  5176. thread_pool_add_task(check_proc_info_worker_proc, pi);
  5177. return 1;
  5178. }
  5179. }
  5180. map_clear(untyped);
  5181. if (check_proc_info(c, pi, untyped)) {
  5182. total_bodies_checked.fetch_add(1, std::memory_order_relaxed);
  5183. return 0;
  5184. }
  5185. return 1;
  5186. }
  5187. gb_internal void check_init_worker_data(Checker *c) {
  5188. u32 thread_count = cast(u32)global_thread_pool.threads.count;
  5189. check_procedure_bodies_worker_data = gb_alloc_array(permanent_allocator(), CheckProcedureBodyWorkerData, thread_count);
  5190. for (isize i = 0; i < thread_count; i++) {
  5191. check_procedure_bodies_worker_data[i].c = c;
  5192. map_init(&check_procedure_bodies_worker_data[i].untyped);
  5193. }
  5194. }
  5195. gb_internal void check_procedure_bodies(Checker *c) {
  5196. GB_ASSERT(c != nullptr);
  5197. u32 thread_count = cast(u32)global_thread_pool.threads.count;
  5198. if (build_context.no_threaded_checker) {
  5199. thread_count = 1;
  5200. }
  5201. if (thread_count == 1) {
  5202. UntypedExprInfoMap *untyped = &check_procedure_bodies_worker_data[0].untyped;
  5203. for_array(i, c->procs_to_check) {
  5204. consume_proc_info(c, c->procs_to_check[i], untyped);
  5205. }
  5206. array_clear(&c->procs_to_check);
  5207. debugf("Total Procedure Bodies Checked: %td\n", total_bodies_checked.load(std::memory_order_relaxed));
  5208. return;
  5209. }
  5210. global_procedure_body_in_worker_queue = true;
  5211. isize prev_procs_to_check_count = c->procs_to_check.count;
  5212. for_array(i, c->procs_to_check) {
  5213. thread_pool_add_task(check_proc_info_worker_proc, c->procs_to_check[i]);
  5214. }
  5215. GB_ASSERT(prev_procs_to_check_count == c->procs_to_check.count);
  5216. array_clear(&c->procs_to_check);
  5217. thread_pool_wait();
  5218. global_procedure_body_in_worker_queue = false;
  5219. }
  5220. gb_internal void add_untyped_expressions(CheckerInfo *cinfo, UntypedExprInfoMap *untyped) {
  5221. if (untyped == nullptr) {
  5222. return;
  5223. }
  5224. for (auto const &entry : *untyped) {
  5225. Ast *expr = entry.key;
  5226. ExprInfo *info = entry.value;
  5227. if (expr != nullptr && info != nullptr) {
  5228. mpsc_enqueue(&cinfo->checker->global_untyped_queue, UntypedExprInfo{expr, info});
  5229. }
  5230. }
  5231. map_clear(untyped);
  5232. }
  5233. gb_internal Type *tuple_to_pointers(Type *ot) {
  5234. if (ot == nullptr) {
  5235. return nullptr;
  5236. }
  5237. GB_ASSERT(ot->kind == Type_Tuple);
  5238. Type *t = alloc_type_tuple();
  5239. t->Tuple.variables = slice_make<Entity *>(heap_allocator(), ot->Tuple.variables.count);
  5240. Scope *scope = nullptr;
  5241. for_array(i, t->Tuple.variables) {
  5242. Entity *e = ot->Tuple.variables[i];
  5243. t->Tuple.variables[i] = alloc_entity_variable(scope, e->token, alloc_type_pointer(e->type));
  5244. }
  5245. t->Tuple.is_packed = ot->Tuple.is_packed;
  5246. return t;
  5247. }
  5248. gb_internal void check_deferred_procedures(Checker *c) {
  5249. for (Entity *src = nullptr; mpsc_dequeue(&c->procs_with_deferred_to_check, &src); /**/) {
  5250. GB_ASSERT(src->kind == Entity_Procedure);
  5251. DeferredProcedureKind dst_kind = src->Procedure.deferred_procedure.kind;
  5252. Entity *dst = src->Procedure.deferred_procedure.entity;
  5253. GB_ASSERT(dst != nullptr);
  5254. GB_ASSERT(dst->kind == Entity_Procedure);
  5255. char const *attribute = "deferred_none";
  5256. switch (dst_kind) {
  5257. case DeferredProcedure_none: attribute = "deferred_none"; break;
  5258. case DeferredProcedure_in: attribute = "deferred_in"; break;
  5259. case DeferredProcedure_out: attribute = "deferred_out"; break;
  5260. case DeferredProcedure_in_out: attribute = "deferred_in_out"; break;
  5261. case DeferredProcedure_in_by_ptr: attribute = "deferred_in_by_ptr"; break;
  5262. case DeferredProcedure_out_by_ptr: attribute = "deferred_out_by_ptr"; break;
  5263. case DeferredProcedure_in_out_by_ptr: attribute = "deferred_in_out_by_ptr"; break;
  5264. }
  5265. if (is_type_polymorphic(src->type) || is_type_polymorphic(dst->type)) {
  5266. error(src->token, "'%s' cannot be used with a polymorphic procedure", attribute);
  5267. continue;
  5268. }
  5269. GB_ASSERT(is_type_proc(src->type));
  5270. GB_ASSERT(is_type_proc(dst->type));
  5271. Type *src_params = base_type(src->type)->Proc.params;
  5272. Type *src_results = base_type(src->type)->Proc.results;
  5273. Type *dst_params = base_type(dst->type)->Proc.params;
  5274. bool by_ptr = false;
  5275. switch (dst_kind) {
  5276. case DeferredProcedure_in_by_ptr:
  5277. by_ptr = true;
  5278. src_params = tuple_to_pointers(src_params);
  5279. break;
  5280. case DeferredProcedure_out_by_ptr:
  5281. by_ptr = true;
  5282. src_results = tuple_to_pointers(src_results);
  5283. break;
  5284. case DeferredProcedure_in_out_by_ptr:
  5285. by_ptr = true;
  5286. src_params = tuple_to_pointers(src_params);
  5287. src_results = tuple_to_pointers(src_results);
  5288. break;
  5289. }
  5290. switch (dst_kind) {
  5291. case DeferredProcedure_none:
  5292. {
  5293. if (dst_params == nullptr) {
  5294. // Okay
  5295. continue;
  5296. }
  5297. error(src->token, "Deferred procedure '%.*s' must have no input parameters", LIT(dst->token.string));
  5298. } break;
  5299. case DeferredProcedure_in:
  5300. case DeferredProcedure_in_by_ptr:
  5301. {
  5302. if (src_params == nullptr && dst_params == nullptr) {
  5303. // Okay
  5304. continue;
  5305. }
  5306. if ((src_params == nullptr && dst_params != nullptr) ||
  5307. (src_params != nullptr && dst_params == nullptr)) {
  5308. error(src->token, "Deferred procedure '%.*s' parameters do not match the inputs of initial procedure '%.*s'", LIT(src->token.string), LIT(dst->token.string));
  5309. continue;
  5310. }
  5311. GB_ASSERT(src_params->kind == Type_Tuple);
  5312. GB_ASSERT(dst_params->kind == Type_Tuple);
  5313. if (are_types_identical(src_params, dst_params)) {
  5314. // Okay!
  5315. } else {
  5316. gbString s = type_to_string(src_params);
  5317. gbString d = type_to_string(dst_params);
  5318. error(src->token, "Deferred procedure '%.*s' parameters do not match the inputs of initial procedure '%.*s':\n\t(%s) =/= (%s)",
  5319. LIT(src->token.string), LIT(dst->token.string),
  5320. s, d
  5321. );
  5322. gb_string_free(d);
  5323. gb_string_free(s);
  5324. continue;
  5325. }
  5326. } break;
  5327. case DeferredProcedure_out:
  5328. case DeferredProcedure_out_by_ptr:
  5329. {
  5330. if (src_results == nullptr && dst_params == nullptr) {
  5331. // Okay
  5332. continue;
  5333. }
  5334. if ((src_results == nullptr && dst_params != nullptr) ||
  5335. (src_results != nullptr && dst_params == nullptr)) {
  5336. error(src->token, "Deferred procedure '%.*s' parameters do not match the results of initial procedure '%.*s'", LIT(src->token.string), LIT(dst->token.string));
  5337. continue;
  5338. }
  5339. GB_ASSERT(src_results->kind == Type_Tuple);
  5340. GB_ASSERT(dst_params->kind == Type_Tuple);
  5341. if (are_types_identical(src_results, dst_params)) {
  5342. // Okay!
  5343. } else {
  5344. gbString s = type_to_string(src_results);
  5345. gbString d = type_to_string(dst_params);
  5346. error(src->token, "Deferred procedure '%.*s' parameters do not match the results of initial procedure '%.*s':\n\t(%s) =/= (%s)",
  5347. LIT(src->token.string), LIT(dst->token.string),
  5348. s, d
  5349. );
  5350. gb_string_free(d);
  5351. gb_string_free(s);
  5352. continue;
  5353. }
  5354. } break;
  5355. case DeferredProcedure_in_out:
  5356. case DeferredProcedure_in_out_by_ptr:
  5357. {
  5358. if (src_params == nullptr && src_results == nullptr && dst_params == nullptr) {
  5359. // Okay
  5360. continue;
  5361. }
  5362. GB_ASSERT(dst_params->kind == Type_Tuple);
  5363. Type *tsrc = alloc_type_tuple();
  5364. auto &sv = tsrc->Tuple.variables;
  5365. auto const &dv = dst_params->Tuple.variables;
  5366. gb_unused(dv);
  5367. isize len = 0;
  5368. if (src_params != nullptr) {
  5369. GB_ASSERT(src_params->kind == Type_Tuple);
  5370. len += src_params->Tuple.variables.count;
  5371. }
  5372. if (src_results != nullptr) {
  5373. GB_ASSERT(src_results->kind == Type_Tuple);
  5374. len += src_results->Tuple.variables.count;
  5375. }
  5376. slice_init(&sv, heap_allocator(), len);
  5377. isize offset = 0;
  5378. if (src_params != nullptr) {
  5379. for_array(i, src_params->Tuple.variables) {
  5380. sv[offset++] = src_params->Tuple.variables[i];
  5381. }
  5382. }
  5383. if (src_results != nullptr) {
  5384. for_array(i, src_results->Tuple.variables) {
  5385. sv[offset++] = src_results->Tuple.variables[i];
  5386. }
  5387. }
  5388. GB_ASSERT(offset == len);
  5389. if (are_types_identical(tsrc, dst_params)) {
  5390. // Okay!
  5391. } else {
  5392. gbString s = type_to_string(tsrc);
  5393. gbString d = type_to_string(dst_params);
  5394. error(src->token, "Deferred procedure '%.*s' parameters do not match the results of initial procedure '%.*s':\n\t(%s) =/= (%s)",
  5395. LIT(src->token.string), LIT(dst->token.string),
  5396. s, d
  5397. );
  5398. gb_string_free(d);
  5399. gb_string_free(s);
  5400. continue;
  5401. }
  5402. } break;
  5403. }
  5404. }
  5405. }
  5406. gb_internal void check_unique_package_names(Checker *c) {
  5407. ERROR_BLOCK();
  5408. StringMap<AstPackage *> pkgs = {}; // Key: package name
  5409. string_map_init(&pkgs, 2*c->info.packages.count);
  5410. defer (string_map_destroy(&pkgs));
  5411. for (auto const &entry : c->info.packages) {
  5412. AstPackage *pkg = entry.value;
  5413. if (pkg->files.count == 0) {
  5414. continue; // Sanity check
  5415. }
  5416. String name = pkg->name;
  5417. auto key = string_hash_string(name);
  5418. auto *found = string_map_get(&pkgs, key);
  5419. if (found == nullptr) {
  5420. string_map_set(&pkgs, key, pkg);
  5421. continue;
  5422. }
  5423. auto *curr = pkg->files[0]->pkg_decl;
  5424. auto *prev = (*found)->files[0]->pkg_decl;
  5425. if (curr == prev) {
  5426. // NOTE(bill): A false positive was found, ignore it
  5427. continue;
  5428. }
  5429. begin_error_block();
  5430. error(curr, "Duplicate declaration of 'package %.*s'", LIT(name));
  5431. error_line("\tA package name must be unique\n"
  5432. "\tThere is no relation between a package name and the directory that contains it, so they can be completely different\n"
  5433. "\tA package name is required for link name prefixing to have a consistent ABI\n");
  5434. error_line("%s found at previous location\n", token_pos_to_string(ast_token(prev).pos));
  5435. end_error_block();
  5436. }
  5437. }
  5438. gb_internal void check_add_entities_from_queues(Checker *c) {
  5439. isize cap = c->info.entities.count + c->info.entity_queue.count.load(std::memory_order_relaxed);
  5440. array_reserve(&c->info.entities, cap);
  5441. for (Entity *e; mpsc_dequeue(&c->info.entity_queue, &e); /**/) {
  5442. array_add(&c->info.entities, e);
  5443. }
  5444. }
  5445. gb_internal void check_add_definitions_from_queues(Checker *c) {
  5446. isize cap = c->info.definitions.count + c->info.definition_queue.count.load(std::memory_order_relaxed);
  5447. array_reserve(&c->info.definitions, cap);
  5448. for (Entity *e; mpsc_dequeue(&c->info.definition_queue, &e); /**/) {
  5449. array_add(&c->info.definitions, e);
  5450. }
  5451. }
  5452. gb_internal void check_merge_queues_into_arrays(Checker *c) {
  5453. for (Type *t = nullptr; mpsc_dequeue(&c->soa_types_to_complete, &t); /**/) {
  5454. complete_soa_type(c, t, false);
  5455. }
  5456. check_add_entities_from_queues(c);
  5457. check_add_definitions_from_queues(c);
  5458. }
  5459. gb_internal GB_COMPARE_PROC(init_procedures_cmp) {
  5460. int cmp = 0;
  5461. Entity *x = *(Entity **)a;
  5462. Entity *y = *(Entity **)b;
  5463. if (x == y) {
  5464. cmp = 0;
  5465. return cmp;
  5466. }
  5467. if (x->pkg != y->pkg) {
  5468. isize order_x = x->pkg ? x->pkg->order : 0;
  5469. isize order_y = y->pkg ? y->pkg->order : 0;
  5470. cmp = isize_cmp(order_x, order_y);
  5471. if (cmp) {
  5472. return cmp;
  5473. }
  5474. }
  5475. if (x->file != y->file) {
  5476. String fullpath_x = x->file ? x->file->fullpath : (String{});
  5477. String fullpath_y = y->file ? y->file->fullpath : (String{});
  5478. String file_x = filename_from_path(fullpath_x);
  5479. String file_y = filename_from_path(fullpath_y);
  5480. cmp = string_compare(file_x, file_y);
  5481. if (cmp) {
  5482. return cmp;
  5483. }
  5484. }
  5485. cmp = u64_cmp(x->order_in_src, y->order_in_src);
  5486. if (cmp) {
  5487. return cmp;
  5488. }
  5489. return i32_cmp(x->token.pos.offset, y->token.pos.offset);
  5490. }
  5491. gb_internal GB_COMPARE_PROC(fini_procedures_cmp) {
  5492. return init_procedures_cmp(b, a);
  5493. }
  5494. gb_internal void check_sort_init_and_fini_procedures(Checker *c) {
  5495. array_sort(c->info.init_procedures, init_procedures_cmp);
  5496. array_sort(c->info.fini_procedures, fini_procedures_cmp);
  5497. // NOTE(bill): remove possible duplicates from the init/fini lists
  5498. // NOTE(bill): because the arrays are sorted, you only need to check the previous element
  5499. remove_neighbouring_duplicate_entires_from_sorted_array(&c->info.init_procedures);
  5500. remove_neighbouring_duplicate_entires_from_sorted_array(&c->info.fini_procedures);
  5501. }
  5502. gb_internal void add_type_info_for_type_definitions(Checker *c) {
  5503. for_array(i, c->info.definitions) {
  5504. Entity *e = c->info.definitions[i];
  5505. if (e->kind == Entity_TypeName && e->type != nullptr) {
  5506. i64 align = type_align_of(e->type);
  5507. if (align > 0 && ptr_set_exists(&c->info.minimum_dependency_set, e)) {
  5508. add_type_info_type(&c->builtin_ctx, e->type);
  5509. }
  5510. }
  5511. }
  5512. }
  5513. gb_internal void check_walk_all_dependencies(DeclInfo *decl) {
  5514. if (decl == nullptr) {
  5515. return;
  5516. }
  5517. for (DeclInfo *child = decl->next_child; child != nullptr; child = child->next_sibling) {
  5518. check_walk_all_dependencies(child);
  5519. }
  5520. add_deps_from_child_to_parent(decl);
  5521. }
  5522. gb_internal void check_update_dependency_tree_for_procedures(Checker *c) {
  5523. mutex_lock(&c->nested_proc_lits_mutex);
  5524. for (DeclInfo *decl : c->nested_proc_lits) {
  5525. check_walk_all_dependencies(decl);
  5526. }
  5527. mutex_unlock(&c->nested_proc_lits_mutex);
  5528. for (Entity *e : c->info.entities) {
  5529. DeclInfo *decl = e->decl_info;
  5530. check_walk_all_dependencies(decl);
  5531. }
  5532. }
  5533. gb_internal void check_parsed_files(Checker *c) {
  5534. TIME_SECTION("map full filepaths to scope");
  5535. add_type_info_type(&c->builtin_ctx, t_invalid);
  5536. // Map full filepaths to Scopes
  5537. for_array(i, c->parser->packages) {
  5538. AstPackage *p = c->parser->packages[i];
  5539. Scope *scope = create_scope_from_package(&c->builtin_ctx, p);
  5540. p->decl_info = make_decl_info(scope, c->builtin_ctx.decl);
  5541. string_map_set(&c->info.packages, p->fullpath, p);
  5542. if (scope->flags&ScopeFlag_Init) {
  5543. c->info.init_package = p;
  5544. c->info.init_scope = scope;
  5545. }
  5546. if (p->kind == Package_Runtime) {
  5547. GB_ASSERT(c->info.runtime_package == nullptr);
  5548. c->info.runtime_package = p;
  5549. }
  5550. }
  5551. TIME_SECTION("init worker data");
  5552. check_init_worker_data(c);
  5553. TIME_SECTION("create file scopes");
  5554. check_create_file_scopes(c);
  5555. TIME_SECTION("collect entities");
  5556. check_collect_entities_all(c);
  5557. TIME_SECTION("export entities - pre");
  5558. check_export_entities(c);
  5559. // NOTE: Timing Section handled internally
  5560. check_import_entities(c);
  5561. TIME_SECTION("export entities - post");
  5562. check_export_entities(c);
  5563. TIME_SECTION("add entities from packages");
  5564. check_merge_queues_into_arrays(c);
  5565. TIME_SECTION("check all global entities");
  5566. check_all_global_entities(c);
  5567. TIME_SECTION("init preload");
  5568. init_preload(c);
  5569. TIME_SECTION("add global untyped expression to queue");
  5570. add_untyped_expressions(&c->info, &c->info.global_untyped);
  5571. CheckerContext prev_context = c->builtin_ctx;
  5572. defer (c->builtin_ctx = prev_context);
  5573. c->builtin_ctx.decl = make_decl_info(nullptr, nullptr);
  5574. TIME_SECTION("check procedure bodies");
  5575. check_procedure_bodies(c);
  5576. TIME_SECTION("check foreign import fullpaths");
  5577. check_foreign_import_fullpaths(c);
  5578. TIME_SECTION("add entities from procedure bodies");
  5579. check_merge_queues_into_arrays(c);
  5580. TIME_SECTION("check scope usage");
  5581. for (auto const &entry : c->info.files) {
  5582. AstFile *f = entry.value;
  5583. u64 vet_flags = build_context.vet_flags;
  5584. if (f->vet_flags_set) {
  5585. vet_flags = f->vet_flags;
  5586. }
  5587. check_scope_usage(c, f->scope, vet_flags);
  5588. }
  5589. TIME_SECTION("add basic type information");
  5590. // Add "Basic" type information
  5591. for (isize i = 0; i < Basic_COUNT; i++) {
  5592. Type *t = &basic_types[i];
  5593. if (t->Basic.size > 0 &&
  5594. (t->Basic.flags & BasicFlag_LLVM) == 0) {
  5595. add_type_info_type(&c->builtin_ctx, t);
  5596. }
  5597. }
  5598. check_merge_queues_into_arrays(c);
  5599. TIME_SECTION("check for type cycles and inline cycles");
  5600. // NOTE(bill): Check for illegal cyclic type declarations
  5601. for_array(i, c->info.definitions) {
  5602. Entity *e = c->info.definitions[i];
  5603. if (e->kind == Entity_TypeName && e->type != nullptr) {
  5604. (void)type_align_of(e->type);
  5605. } else if (e->kind == Entity_Procedure) {
  5606. DeclInfo *decl = e->decl_info;
  5607. ast_node(pl, ProcLit, decl->proc_lit);
  5608. if (pl->inlining == ProcInlining_inline) {
  5609. for (Entity *dep : decl->deps) {
  5610. if (dep == e) {
  5611. error(e->token, "Cannot inline recursive procedure '%.*s'", LIT(e->token.string));
  5612. break;
  5613. }
  5614. }
  5615. }
  5616. }
  5617. }
  5618. TIME_SECTION("check deferred procedures");
  5619. check_deferred_procedures(c);
  5620. TIME_SECTION("calculate global init order");
  5621. calculate_global_init_order(c);
  5622. TIME_SECTION("add type info for type definitions");
  5623. add_type_info_for_type_definitions(c);
  5624. check_merge_queues_into_arrays(c);
  5625. TIME_SECTION("update dependency tree for procedures");
  5626. check_update_dependency_tree_for_procedures(c);
  5627. TIME_SECTION("generate minimum dependency set");
  5628. generate_minimum_dependency_set(c, c->info.entry_point);
  5629. TIME_SECTION("check bodies have all been checked");
  5630. check_unchecked_bodies(c);
  5631. TIME_SECTION("check #soa types");
  5632. check_merge_queues_into_arrays(c);
  5633. thread_pool_wait();
  5634. TIME_SECTION("update minimum dependency set");
  5635. generate_minimum_dependency_set_internal(c, c->info.entry_point);
  5636. // NOTE(laytan): has to be ran after generate_minimum_dependency_set,
  5637. // because that collects the test procedures.
  5638. TIME_SECTION("check test procedures");
  5639. check_test_procedures(c);
  5640. check_merge_queues_into_arrays(c);
  5641. thread_pool_wait();
  5642. TIME_SECTION("check entry point");
  5643. if (build_context.build_mode == BuildMode_Executable && !build_context.no_entry_point && build_context.command_kind != Command_test) {
  5644. Scope *s = c->info.init_scope;
  5645. GB_ASSERT(s != nullptr);
  5646. GB_ASSERT(s->flags&ScopeFlag_Init);
  5647. Entity *e = scope_lookup_current(s, str_lit("main"));
  5648. if (e == nullptr) {
  5649. Token token = {};
  5650. token.pos.file_id = 0;
  5651. token.pos.line = 1;
  5652. token.pos.column = 1;
  5653. if (s->pkg->files.count > 0) {
  5654. AstFile *f = s->pkg->files[0];
  5655. if (f->tokens.count > 0) {
  5656. token = f->tokens[0];
  5657. }
  5658. }
  5659. error(token, "Undefined entry point procedure 'main'");
  5660. }
  5661. } else if (build_context.build_mode == BuildMode_DynamicLibrary && build_context.no_entry_point) {
  5662. c->info.entry_point = nullptr;
  5663. }
  5664. thread_pool_wait();
  5665. GB_ASSERT(c->procs_to_check.count == 0);
  5666. if (DEBUG_CHECK_ALL_PROCEDURES) {
  5667. TIME_SECTION("check unchecked (safety measure)");
  5668. check_safety_all_procedures_for_unchecked(c);
  5669. }
  5670. debugf("Total Procedure Bodies Checked: %td\n", total_bodies_checked.load(std::memory_order_relaxed));
  5671. TIME_SECTION("check unique package names");
  5672. check_unique_package_names(c);
  5673. TIME_SECTION("sanity checks");
  5674. check_merge_queues_into_arrays(c);
  5675. GB_ASSERT(c->info.entity_queue.count.load(std::memory_order_relaxed) == 0);
  5676. GB_ASSERT(c->info.definition_queue.count.load(std::memory_order_relaxed) == 0);
  5677. TIME_SECTION("check instrumentation calls");
  5678. {
  5679. if ((c->info.instrumentation_enter_entity != nullptr) ^
  5680. (c->info.instrumentation_exit_entity != nullptr)) {
  5681. Entity *e = c->info.instrumentation_enter_entity;
  5682. if (!e) e = c->info.instrumentation_exit_entity;
  5683. error(e->token, "Both @(instrumentation_enter) and @(instrumentation_exit) must be defined");
  5684. }
  5685. }
  5686. TIME_SECTION("add untyped expression values");
  5687. // Add untyped expression values
  5688. for (UntypedExprInfo u = {}; mpsc_dequeue(&c->global_untyped_queue, &u); /**/) {
  5689. GB_ASSERT(u.expr != nullptr && u.info != nullptr);
  5690. if (is_type_typed(u.info->type)) {
  5691. compiler_error("%s (type %s) is typed!", expr_to_string(u.expr), type_to_string(u.info->type));
  5692. }
  5693. add_type_and_value(&c->builtin_ctx, u.expr, u.info->mode, u.info->type, u.info->value);
  5694. }
  5695. TIME_SECTION("sort init and fini procedures");
  5696. check_sort_init_and_fini_procedures(c);
  5697. if (c->info.intrinsics_entry_point_usage.count > 0) {
  5698. TIME_SECTION("check intrinsics.__entry_point usage");
  5699. Ast *node = nullptr;
  5700. while (mpsc_dequeue(&c->info.intrinsics_entry_point_usage, &node)) {
  5701. if (c->info.entry_point == nullptr && node != nullptr) {
  5702. if (node->file()->pkg->kind != Package_Runtime) {
  5703. error(node, "usage of intrinsics.__entry_point will be a no-op");
  5704. }
  5705. }
  5706. }
  5707. }
  5708. TIME_SECTION("type check finish");
  5709. }