2
0

checker.cpp 168 KB

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