checker.cpp 168 KB

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