checker.cpp 149 KB

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