checker.cpp 177 KB

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