checker.cpp 166 KB

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