checker.cpp 189 KB

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