checker.cpp 186 KB

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