checker.cpp 152 KB

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