checker.cpp 200 KB

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