checker.cpp 170 KB

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