check_expr.cpp 368 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572
  1. enum CallArgumentError {
  2. CallArgumentError_None,
  3. CallArgumentError_NoneProcedureType,
  4. CallArgumentError_WrongTypes,
  5. CallArgumentError_NonVariadicExpand,
  6. CallArgumentError_VariadicTuple,
  7. CallArgumentError_MultipleVariadicExpand,
  8. CallArgumentError_AmbiguousPolymorphicVariadic,
  9. CallArgumentError_ArgumentCount,
  10. CallArgumentError_TooFewArguments,
  11. CallArgumentError_TooManyArguments,
  12. CallArgumentError_InvalidFieldValue,
  13. CallArgumentError_ParameterNotFound,
  14. CallArgumentError_ParameterMissing,
  15. CallArgumentError_DuplicateParameter,
  16. CallArgumentError_NoneConstantParameter,
  17. CallArgumentError_OutOfOrderParameters,
  18. CallArgumentError_MAX,
  19. };
  20. gb_global char const *CallArgumentError_strings[CallArgumentError_MAX] = {
  21. "None",
  22. "NoneProcedureType",
  23. "WrongTypes",
  24. "NonVariadicExpand",
  25. "VariadicTuple",
  26. "MultipleVariadicExpand",
  27. "AmbiguousPolymorphicVariadic",
  28. "ArgumentCount",
  29. "TooFewArguments",
  30. "TooManyArguments",
  31. "InvalidFieldValue",
  32. "ParameterNotFound",
  33. "ParameterMissing",
  34. "DuplicateParameter",
  35. "NoneConstantParameter",
  36. "OutOfOrderParameters",
  37. };
  38. enum struct CallArgumentErrorMode {
  39. NoErrors,
  40. ShowErrors,
  41. };
  42. struct CallArgumentData {
  43. Entity *gen_entity;
  44. i64 score;
  45. Type * result_type;
  46. };
  47. struct PolyProcData {
  48. Entity * gen_entity;
  49. ProcInfo *proc_info;
  50. };
  51. struct ValidIndexAndScore {
  52. isize index;
  53. i64 score;
  54. };
  55. gb_internal int valid_index_and_score_cmp(void const *a, void const *b) {
  56. i64 si = (cast(ValidIndexAndScore const *)a)->score;
  57. i64 sj = (cast(ValidIndexAndScore const *)b)->score;
  58. return sj < si ? -1 : sj > si;
  59. }
  60. gb_internal void check_expr (CheckerContext *c, Operand *operand, Ast *expression);
  61. gb_internal void check_multi_expr (CheckerContext *c, Operand *operand, Ast *expression);
  62. gb_internal void check_multi_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression);
  63. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint);
  64. gb_internal void check_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  65. gb_internal ExprKind check_expr_base (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  66. gb_internal void check_expr_with_type_hint (CheckerContext *c, Operand *o, Ast *e, Type *t);
  67. gb_internal Type * check_type (CheckerContext *c, Ast *expression);
  68. gb_internal Type * check_type_expr (CheckerContext *c, Ast *expression, Type *named_type);
  69. gb_internal Type * make_optional_ok_type (Type *value, bool typed=true);
  70. gb_internal Entity * check_selector (CheckerContext *c, Operand *operand, Ast *node, Type *type_hint);
  71. gb_internal Entity * check_ident (CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name);
  72. gb_internal void check_not_tuple (CheckerContext *c, Operand *operand);
  73. gb_internal void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
  74. gb_internal gbString expr_to_string (Ast *expression);
  75. gb_internal gbString expr_to_string (Ast *expression, gbAllocator allocator);
  76. gb_internal void update_untyped_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
  77. gb_internal bool check_is_terminating (Ast *node, String const &label);
  78. gb_internal bool check_has_break (Ast *stmt, String const &label, bool implicit);
  79. gb_internal void check_stmt (CheckerContext *c, Ast *node, u32 flags);
  80. gb_internal void check_stmt_list (CheckerContext *c, Slice<Ast *> const &stmts, u32 flags);
  81. gb_internal void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
  82. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
  83. gb_internal bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> const *operands = nullptr);
  84. gb_internal void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
  85. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  86. gb_internal void check_union_type (CheckerContext *c, Type *union_type, Ast *node, Array<Operand> *poly_operands,
  87. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  88. gb_internal Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  89. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0);
  90. gb_internal void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
  91. gb_internal Type *make_soa_struct_fixed(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem, i64 count, Type *generic_type);
  92. gb_internal Type *make_soa_struct_slice(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  93. gb_internal Type *make_soa_struct_dynamic_array(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  94. gb_internal bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint);
  95. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand=true);
  96. gb_internal void check_or_else_right_type(CheckerContext *c, Ast *expr, String const &name, Type *right_type);
  97. gb_internal void check_or_else_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  98. gb_internal void check_or_else_expr_no_value_error(CheckerContext *c, String const &name, Operand const &x, Type *type_hint);
  99. gb_internal void check_or_return_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  100. gb_internal bool is_diverging_expr(Ast *expr);
  101. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_);
  102. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr);
  103. gb_internal Entity *find_polymorphic_record_entity(GenTypesData *found_gen_types, isize param_count, Array<Operand> const &ordered_operands);
  104. gb_internal bool complete_soa_type(Checker *checker, Type *t, bool wait_to_finish);
  105. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y);
  106. gb_internal bool is_exact_value_zero(ExactValue const &v);
  107. gb_internal IntegerDivisionByZeroKind check_for_integer_division_by_zero(CheckerContext *c, Ast *node);
  108. enum LoadDirectiveResult {
  109. LoadDirective_Success = 0,
  110. LoadDirective_Error = 1,
  111. LoadDirective_NotFound = 2,
  112. };
  113. gb_internal bool is_load_directive_call(Ast *call) {
  114. call = unparen_expr(call);
  115. if (call->kind != Ast_CallExpr) {
  116. return false;
  117. }
  118. ast_node(ce, CallExpr, call);
  119. if (ce->proc->kind != Ast_BasicDirective) {
  120. return false;
  121. }
  122. ast_node(bd, BasicDirective, ce->proc);
  123. String name = bd->name.string;
  124. return name == "load";
  125. }
  126. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  127. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  128. auto results = did_you_mean_results(d);
  129. if (results.count != 0) {
  130. error_line("\tSuggestion: Did you mean?\n");
  131. for (auto const &result : results) {
  132. String const &target = result.target;
  133. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  134. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  135. }
  136. }
  137. }
  138. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  139. if (e->kind != Entity_TypeName) {
  140. return;
  141. }
  142. if (e->TypeName.objc_metadata == nullptr) {
  143. return;
  144. }
  145. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  146. Type *t = base_type(e->type);
  147. GB_ASSERT(t->kind == Type_Struct);
  148. if (is_type) {
  149. for (auto const &entry : objc_metadata->type_entries) {
  150. string_set_add(set, entry.name);
  151. }
  152. } else {
  153. for (auto const &entry : objc_metadata->value_entries) {
  154. string_set_add(set, entry.name);
  155. }
  156. }
  157. for (Entity *f : t->Struct.fields) {
  158. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  159. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  160. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  161. }
  162. }
  163. }
  164. }
  165. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  166. if (build_context.terse_errors) { return; }
  167. ERROR_BLOCK();
  168. GB_ASSERT(e->kind == Entity_TypeName);
  169. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  170. auto *objc_metadata = e->TypeName.objc_metadata;
  171. MUTEX_GUARD(objc_metadata->mutex);
  172. StringSet set = {};
  173. defer (string_set_destroy(&set));
  174. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  175. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  176. defer (did_you_mean_destroy(&d));
  177. for (String const &target : set) {
  178. did_you_mean_append(&d, target);
  179. }
  180. check_did_you_mean_print(&d, prefix);
  181. }
  182. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  183. if (build_context.terse_errors) { return; }
  184. ERROR_BLOCK();
  185. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  186. defer (did_you_mean_destroy(&d));
  187. for (Entity *e : fields) {
  188. did_you_mean_append(&d, e->token.string);
  189. }
  190. check_did_you_mean_print(&d, prefix);
  191. }
  192. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  193. if (build_context.terse_errors) { return; }
  194. ERROR_BLOCK();
  195. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  196. defer (did_you_mean_destroy(&d));
  197. for (Entity *e : fields) {
  198. did_you_mean_append(&d, e->token.string);
  199. }
  200. check_did_you_mean_print(&d, prefix);
  201. }
  202. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  203. if (build_context.terse_errors) { return; }
  204. ERROR_BLOCK();
  205. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  206. defer (did_you_mean_destroy(&d));
  207. rw_mutex_shared_lock(&scope->mutex);
  208. for (auto const &entry : scope->elements) {
  209. Entity *e = entry.value;
  210. did_you_mean_append(&d, e->token.string);
  211. }
  212. rw_mutex_shared_unlock(&scope->mutex);
  213. check_did_you_mean_print(&d, prefix);
  214. }
  215. gb_internal Entity *entity_from_expr(Ast *expr) {
  216. expr = unparen_expr(expr);
  217. if (expr == nullptr) {
  218. return nullptr;
  219. }
  220. switch (expr->kind) {
  221. case Ast_Ident:
  222. return expr->Ident.entity;
  223. case Ast_SelectorExpr:
  224. return entity_from_expr(expr->SelectorExpr.selector);
  225. }
  226. return nullptr;
  227. }
  228. gb_internal void error_operand_not_expression(Operand *o) {
  229. if (o->mode == Addressing_Type) {
  230. gbString err = expr_to_string(o->expr);
  231. error(o->expr, "'%s' is not an expression but a type", err);
  232. gb_string_free(err);
  233. o->mode = Addressing_Invalid;
  234. }
  235. }
  236. gb_internal void error_operand_no_value(Operand *o) {
  237. if (o->mode == Addressing_NoValue) {
  238. Ast *x = unparen_expr(o->expr);
  239. if (x != nullptr && x->kind == Ast_CallExpr) {
  240. Ast *p = unparen_expr(x->CallExpr.proc);
  241. if (p->kind == Ast_BasicDirective) {
  242. String tag = p->BasicDirective.name.string;
  243. if (tag == "panic" ||
  244. tag == "assert") {
  245. return;
  246. }
  247. }
  248. }
  249. gbString err = expr_to_string(o->expr);
  250. if (x != nullptr && x->kind == Ast_CallExpr) {
  251. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  252. } else {
  253. error(o->expr, "'%s' used as a value", err);
  254. }
  255. gb_string_free(err);
  256. o->mode = Addressing_Invalid;
  257. }
  258. }
  259. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  260. if (build_context.dynamic_map_calls) {
  261. add_package_dependency(c, "runtime", "__dynamic_map_get");
  262. } else {
  263. add_package_dependency(c, "runtime", "map_desired_position");
  264. add_package_dependency(c, "runtime", "map_probe_distance");
  265. }
  266. }
  267. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  268. init_core_source_code_location(c->checker);
  269. if (t_map_set_proc == nullptr) {
  270. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  271. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  272. }
  273. if (build_context.dynamic_map_calls) {
  274. add_package_dependency(c, "runtime", "__dynamic_map_set");
  275. } else {
  276. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  277. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  278. }
  279. }
  280. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  281. init_core_source_code_location(c->checker);
  282. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  283. }
  284. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  285. Scope *s = c->scope;
  286. check_collect_entities(c, nodes);
  287. for (auto const &entry : s->elements) {
  288. Entity *e = entry.value;\
  289. switch (e->kind) {
  290. case Entity_Constant:
  291. case Entity_TypeName:
  292. case Entity_Procedure:
  293. break;
  294. default:
  295. continue;
  296. }
  297. DeclInfo *d = decl_info_of_entity(e);
  298. if (d != nullptr) {
  299. check_entity_decl(c, e, d, nullptr);
  300. }
  301. }
  302. }
  303. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  304. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  305. ///////////////////////////////////////////////////////////////////////////////
  306. // //
  307. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  308. // //
  309. ///////////////////////////////////////////////////////////////////////////////
  310. CheckerInfo *info = old_c->info;
  311. if (base_entity == nullptr) {
  312. return false;
  313. }
  314. if (!is_type_proc(base_entity->type)) {
  315. return false;
  316. }
  317. if (base_entity->flags & EntityFlag_Disabled) {
  318. return false;
  319. }
  320. String name = base_entity->token.string;
  321. Type *src = base_type(base_entity->type);
  322. Type *dst = nullptr;
  323. if (type != nullptr) {
  324. dst = base_type(type);
  325. }
  326. if (param_operands == nullptr) {
  327. GB_ASSERT(dst != nullptr);
  328. }
  329. if (param_operands != nullptr) {
  330. GB_ASSERT(dst == nullptr);
  331. }
  332. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  333. return false;
  334. }
  335. if (dst != nullptr) {
  336. if (dst->Proc.is_polymorphic) {
  337. return false;
  338. }
  339. if (dst->Proc.param_count != src->Proc.param_count ||
  340. dst->Proc.result_count != src->Proc.result_count) {
  341. return false;
  342. }
  343. }
  344. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  345. if (old_decl == nullptr) {
  346. return false;
  347. }
  348. gbAllocator a = heap_allocator();
  349. Array<Operand> operands = {};
  350. if (param_operands) {
  351. operands = *param_operands;
  352. } else {
  353. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  354. for (isize i = 0; i < dst->Proc.param_count; i++) {
  355. Entity *param = dst->Proc.params->Tuple.variables[i];
  356. Operand o = {Addressing_Value};
  357. o.type = param->type;
  358. array_add(&operands, o);
  359. }
  360. }
  361. defer (if (param_operands == nullptr) {
  362. array_free(&operands);
  363. });
  364. CheckerContext nctx = *old_c;
  365. Scope *scope = create_scope(info, base_entity->scope);
  366. scope->flags |= ScopeFlag_Proc;
  367. nctx.scope = scope;
  368. nctx.allow_polymorphic_types = true;
  369. if (nctx.polymorphic_scope == nullptr) {
  370. nctx.polymorphic_scope = scope;
  371. }
  372. auto *pt = &src->Proc;
  373. // NOTE(bill): This is slightly memory leaking if the type already exists
  374. // Maybe it's better to check with the previous types first?
  375. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  376. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  377. if (!success) {
  378. return false;
  379. }
  380. GenProcsData *gen_procs = nullptr;
  381. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  382. GB_ASSERT(base_entity->kind == Entity_Procedure);
  383. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  384. gen_procs = base_entity->Procedure.gen_procs;
  385. if (gen_procs) {
  386. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  387. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  388. for (Entity *other : gen_procs->procs) {
  389. Type *pt = base_type(other->type);
  390. if (are_types_identical(pt, final_proc_type)) {
  391. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  392. if (poly_proc_data) {
  393. poly_proc_data->gen_entity = other;
  394. }
  395. return true;
  396. }
  397. }
  398. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  399. } else {
  400. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  401. gen_procs->procs.allocator = heap_allocator();
  402. base_entity->Procedure.gen_procs = gen_procs;
  403. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  404. }
  405. {
  406. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  407. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  408. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  409. nctx.no_polymorphic_errors = false;
  410. // NOTE(bill): Reset scope from the failed procedure type
  411. scope->head_child.store(nullptr, std::memory_order_relaxed);
  412. string_map_clear(&scope->elements);
  413. ptr_set_clear(&scope->imported);
  414. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  415. Ast *cloned_proc_type_node = clone_ast(pt->node);
  416. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  417. if (!success) {
  418. return false;
  419. }
  420. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  421. for (Entity *other : gen_procs->procs) {
  422. Type *pt = base_type(other->type);
  423. if (are_types_identical(pt, final_proc_type)) {
  424. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  425. if (poly_proc_data) {
  426. poly_proc_data->gen_entity = other;
  427. }
  428. DeclInfo *decl = other->decl_info;
  429. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  430. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  431. proc_info->file = other->file;
  432. proc_info->token = other->token;
  433. proc_info->decl = decl;
  434. proc_info->type = other->type;
  435. proc_info->body = decl->proc_lit->ProcLit.body;
  436. proc_info->tags = other->Procedure.tags;;
  437. proc_info->generated_from_polymorphic = true;
  438. proc_info->poly_def_node = poly_def_node;
  439. check_procedure_later(nctx.checker, proc_info);
  440. }
  441. return true;
  442. }
  443. }
  444. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  445. }
  446. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  447. ast_node(pl, ProcLit, proc_lit);
  448. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  449. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  450. final_proc_type->Proc.is_poly_specialized = true;
  451. final_proc_type->Proc.is_polymorphic = true;
  452. final_proc_type->Proc.variadic = src->Proc.variadic;
  453. final_proc_type->Proc.require_results = src->Proc.require_results;
  454. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  455. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  456. final_proc_type->Proc.diverging = src->Proc.diverging;
  457. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  458. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  459. final_proc_type->Proc.enable_target_feature = src->Proc.enable_target_feature;
  460. final_proc_type->Proc.require_target_feature = src->Proc.require_target_feature;
  461. for (isize i = 0; i < operands.count; i++) {
  462. Operand o = operands[i];
  463. if (final_proc_type == o.type ||
  464. base_entity->type == o.type) {
  465. // NOTE(bill): Cycle
  466. final_proc_type->Proc.is_poly_specialized = false;
  467. break;
  468. }
  469. }
  470. u64 tags = base_entity->Procedure.tags;
  471. Ast *ident = clone_ast(base_entity->identifier);
  472. Token token = ident->Ident.token;
  473. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  474. d->gen_proc_type = final_proc_type;
  475. d->type_expr = pl->type;
  476. d->proc_lit = proc_lit;
  477. d->proc_checked_state = ProcCheckedState_Unchecked;
  478. d->defer_use_checked = false;
  479. d->para_poly_original = old_decl->entity;
  480. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  481. entity->state.store(EntityState_Resolved);
  482. entity->identifier = ident;
  483. add_entity_and_decl_info(&nctx, ident, entity, d);
  484. // NOTE(bill): Set the scope afterwards as this is not real overloading
  485. entity->scope = scope->parent;
  486. entity->file = base_entity->file;
  487. entity->pkg = base_entity->pkg;
  488. entity->flags = 0;
  489. entity->Procedure.optimization_mode = base_entity->Procedure.optimization_mode;
  490. if (base_entity->flags & EntityFlag_Cold) {
  491. entity->flags |= EntityFlag_Cold;
  492. }
  493. if (base_entity->flags & EntityFlag_Disabled) {
  494. entity->flags |= EntityFlag_Disabled;
  495. }
  496. d->entity.store(entity);
  497. AstFile *file = nullptr;
  498. {
  499. Scope *s = entity->scope;
  500. while (s != nullptr && s->file == nullptr) {
  501. file = s->file;
  502. s = s->parent;
  503. }
  504. }
  505. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  506. array_add(&gen_procs->procs, entity);
  507. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  508. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  509. proc_info->file = file;
  510. proc_info->token = token;
  511. proc_info->decl = d;
  512. proc_info->type = final_proc_type;
  513. proc_info->body = pl->body;
  514. proc_info->tags = tags;
  515. proc_info->generated_from_polymorphic = true;
  516. proc_info->poly_def_node = poly_def_node;
  517. if (poly_proc_data) {
  518. poly_proc_data->gen_entity = entity;
  519. poly_proc_data->proc_info = proc_info;
  520. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  521. }
  522. // NOTE(bill): Check the newly generated procedure body
  523. check_procedure_later(nctx.checker, proc_info);
  524. return true;
  525. }
  526. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  527. if (operand->expr == nullptr) return false;
  528. Entity *base_entity = entity_from_expr(operand->expr);
  529. if (base_entity == nullptr) return false;
  530. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  531. }
  532. gb_internal bool find_or_generate_polymorphic_procedure_from_parameters(CheckerContext *c, Entity *base_entity, Array<Operand> const *operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  533. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  534. }
  535. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  536. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  537. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  538. #define MAXIMUM_TYPE_DISTANCE 10
  539. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming) {
  540. if (c == nullptr) {
  541. GB_ASSERT(operand->mode == Addressing_Value);
  542. GB_ASSERT(is_type_typed(operand->type));
  543. }
  544. if (operand->mode == Addressing_Invalid ||
  545. type == t_invalid) {
  546. return -1;
  547. }
  548. if (operand->mode == Addressing_Builtin) {
  549. return -1;
  550. }
  551. if (operand->mode == Addressing_Type) {
  552. if (is_type_typeid(type)) {
  553. if (is_type_polymorphic(operand->type)) {
  554. return -1;
  555. }
  556. add_type_info_type(c, operand->type);
  557. return 4;
  558. }
  559. return -1;
  560. }
  561. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  562. return -1;
  563. }
  564. Type *s = operand->type;
  565. if (are_types_identical(s, type)) {
  566. return 0;
  567. }
  568. Type *src = base_type(s);
  569. Type *dst = base_type(type);
  570. if (is_type_untyped_uninit(src)) {
  571. return 1;
  572. }
  573. if (is_type_untyped_nil(src)) {
  574. if (type_has_nil(dst)) {
  575. return 1;
  576. }
  577. return -1;
  578. }
  579. if (is_type_untyped(src)) {
  580. if (is_type_any(dst)) {
  581. // NOTE(bill): Anything can cast to 'Any'
  582. add_type_info_type(c, s);
  583. return MAXIMUM_TYPE_DISTANCE;
  584. }
  585. if (dst->kind == Type_Basic) {
  586. if (operand->mode == Addressing_Constant) {
  587. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  588. if (is_type_typed(dst) && src->kind == Type_Basic) {
  589. switch (src->Basic.kind) {
  590. case Basic_UntypedBool:
  591. if (is_type_boolean(dst)) {
  592. return 1;
  593. }
  594. break;
  595. case Basic_UntypedRune:
  596. if (is_type_integer(dst) || is_type_rune(dst)) {
  597. return 1;
  598. }
  599. break;
  600. case Basic_UntypedInteger:
  601. if (is_type_integer(dst) || is_type_rune(dst)) {
  602. return 1;
  603. }
  604. break;
  605. case Basic_UntypedString:
  606. if (is_type_string(dst)) {
  607. return 1;
  608. }
  609. break;
  610. case Basic_UntypedFloat:
  611. if (is_type_float(dst)) {
  612. return 1;
  613. }
  614. break;
  615. case Basic_UntypedComplex:
  616. if (is_type_complex(dst)) {
  617. return 1;
  618. }
  619. if (is_type_quaternion(dst)) {
  620. return 2;
  621. }
  622. break;
  623. case Basic_UntypedQuaternion:
  624. if (is_type_quaternion(dst)) {
  625. return 1;
  626. }
  627. break;
  628. }
  629. }
  630. return 2;
  631. }
  632. return -1;
  633. }
  634. if (src->kind == Type_Basic) {
  635. Type *d = base_array_type(dst);
  636. i64 score = -1;
  637. switch (src->Basic.kind) {
  638. case Basic_UntypedBool:
  639. if (is_type_boolean(d)) {
  640. score = 1;
  641. }
  642. break;
  643. case Basic_UntypedRune:
  644. if (is_type_integer(d) || is_type_rune(d)) {
  645. score = 1;
  646. }
  647. break;
  648. case Basic_UntypedInteger:
  649. if (is_type_integer(d) || is_type_rune(d)) {
  650. score = 1;
  651. }
  652. break;
  653. case Basic_UntypedString:
  654. if (is_type_string(d)) {
  655. score = 1;
  656. }
  657. break;
  658. case Basic_UntypedFloat:
  659. if (is_type_float(d)) {
  660. score = 1;
  661. }
  662. break;
  663. case Basic_UntypedComplex:
  664. if (is_type_complex(d)) {
  665. score = 1;
  666. }
  667. if (is_type_quaternion(d)) {
  668. score = 2;
  669. }
  670. break;
  671. case Basic_UntypedQuaternion:
  672. if (is_type_quaternion(d)) {
  673. score = 1;
  674. }
  675. break;
  676. }
  677. if (score > 0) {
  678. if (is_type_typed(d)) {
  679. score += 1;
  680. }
  681. if (d != dst) {
  682. score += 6;
  683. }
  684. }
  685. return score;
  686. }
  687. }
  688. }
  689. if (c != nullptr) {
  690. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  691. if (c->in_enum_type) {
  692. return 3;
  693. }
  694. }
  695. }
  696. {
  697. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  698. if (subtype_level > 0) {
  699. return 4 + subtype_level;
  700. }
  701. }
  702. // rawptr <- ^T
  703. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  704. return 5;
  705. }
  706. // rawptr <- [^]T
  707. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  708. return 5;
  709. }
  710. // ^T <- [^]T
  711. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  712. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  713. return 4;
  714. }
  715. }
  716. // [^]T <- ^T
  717. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  718. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  719. return 4;
  720. }
  721. }
  722. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  723. bool modify_type = !c->no_polymorphic_errors;
  724. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  725. return 2;
  726. }
  727. }
  728. if (is_type_union(dst)) {
  729. for (Type *vt : dst->Union.variants) {
  730. if (are_types_identical(vt, s)) {
  731. return 1;
  732. }
  733. if (is_type_proc(vt)) {
  734. if (are_types_identical(base_type(vt), src)) {
  735. return 1;
  736. }
  737. }
  738. }
  739. if (dst->Union.variants.count == 1) {
  740. Type *vt = dst->Union.variants[0];
  741. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  742. if (score >= 0) {
  743. return score+2;
  744. }
  745. } else if (is_type_untyped(src)) {
  746. i64 prev_lowest_score = -1;
  747. i64 lowest_score = -1;
  748. for (Type *vt : dst->Union.variants) {
  749. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  750. if (score >= 0) {
  751. if (lowest_score < 0) {
  752. lowest_score = score;
  753. } else {
  754. if (prev_lowest_score < 0) {
  755. prev_lowest_score = lowest_score;
  756. } else {
  757. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  758. }
  759. lowest_score = gb_min(lowest_score, score);
  760. }
  761. }
  762. }
  763. if (lowest_score >= 0) {
  764. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  765. return lowest_score+2;
  766. }
  767. }
  768. }
  769. }
  770. if (is_type_proc(dst)) {
  771. if (are_types_identical(src, dst)) {
  772. return 3;
  773. }
  774. PolyProcData poly_proc_data = {};
  775. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  776. Entity *e = poly_proc_data.gen_entity;
  777. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  778. add_entity_use(c, operand->expr, e);
  779. return 4;
  780. }
  781. }
  782. if (is_type_complex_or_quaternion(dst)) {
  783. Type *elem = base_complex_elem_type(dst);
  784. if (are_types_identical(elem, base_type(src))) {
  785. return 5;
  786. }
  787. }
  788. if (allow_array_programming) {
  789. if (is_type_array(dst)) {
  790. Type *elem = base_array_type(dst);
  791. i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
  792. if (distance >= 0) {
  793. return distance + 6;
  794. }
  795. }
  796. if (is_type_simd_vector(dst)) {
  797. Type *dst_elem = base_array_type(dst);
  798. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  799. if (distance >= 0) {
  800. return distance + 6;
  801. }
  802. }
  803. }
  804. if (is_type_matrix(dst)) {
  805. if (are_types_identical(src, dst)) {
  806. return 5;
  807. }
  808. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  809. Type *dst_elem = base_array_type(dst);
  810. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  811. if (distance >= 0) {
  812. return distance + 7;
  813. }
  814. }
  815. }
  816. if (is_type_any(dst)) {
  817. if (!is_type_polymorphic(src)) {
  818. if (operand->mode == Addressing_Context && operand->type == t_context) {
  819. return -1;
  820. } else {
  821. // NOTE(bill): Anything can cast to 'Any'
  822. add_type_info_type(c, s);
  823. return MAXIMUM_TYPE_DISTANCE;
  824. }
  825. }
  826. }
  827. Ast *expr = unparen_expr(operand->expr);
  828. if (expr != nullptr) {
  829. if (expr->kind == Ast_AutoCast) {
  830. Operand x = *operand;
  831. x.expr = expr->AutoCast.expr;
  832. if (check_cast_internal(c, &x, type)) {
  833. return MAXIMUM_TYPE_DISTANCE;
  834. }
  835. }
  836. }
  837. return -1;
  838. }
  839. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  840. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  841. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  842. // TODO(bill): A decent score function
  843. i64 d = distance*distance; // x^2
  844. if (is_variadic && d >= 0) {
  845. d += distance + 1; // x^2 + x + 1
  846. }
  847. return gb_max(c - d, 0);
  848. }
  849. gb_internal bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_, bool is_variadic=false, bool allow_array_programming=true) {
  850. if (c == nullptr) {
  851. GB_ASSERT(operand->mode == Addressing_Value);
  852. GB_ASSERT(is_type_typed(operand->type));
  853. }
  854. if (operand->mode == Addressing_Invalid || type == t_invalid) {
  855. if (score_) *score_ = 0;
  856. return false;
  857. }
  858. // Handle polymorphic procedure used as default parameter
  859. if (operand->mode == Addressing_Value && is_type_proc(type) && is_type_proc(operand->type)) {
  860. Entity *e = entity_from_expr(operand->expr);
  861. if (e != nullptr && e->kind == Entity_Procedure && is_type_polymorphic(e->type) && !is_type_polymorphic(type)) {
  862. // Special case: Allow a polymorphic procedure to be used as default value for concrete proc type
  863. // during the initial check. It will be properly instantiated when actually used.
  864. if (score_) *score_ = assign_score_function(1);
  865. return true;
  866. }
  867. }
  868. i64 score = check_distance_between_types(c, operand, type, allow_array_programming);
  869. if (score >= 0) {
  870. if (score_) *score_ = assign_score_function(score, is_variadic);
  871. return true;
  872. }
  873. if (score_) *score_ = 0;
  874. return false;
  875. }
  876. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming=true) {
  877. i64 score = 0;
  878. return check_is_assignable_to_with_score(c, operand, type, &score, /*is_variadic*/false, allow_array_programming);
  879. }
  880. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  881. Operand x = {};
  882. x.type = src;
  883. x.mode = Addressing_Value;
  884. return check_is_assignable_to(nullptr, &x, dst);
  885. }
  886. gb_internal AstPackage *get_package_of_type(Type *type) {
  887. for (;;) {
  888. if (type == nullptr) {
  889. return nullptr;
  890. }
  891. switch (type->kind) {
  892. case Type_Basic:
  893. return builtin_pkg;
  894. case Type_Named:
  895. if (type->Named.type_name != nullptr) {
  896. return type->Named.type_name->pkg;
  897. }
  898. return nullptr;
  899. case Type_Pointer:
  900. type = type->Pointer.elem;
  901. continue;
  902. case Type_Array:
  903. type = type->Array.elem;
  904. continue;
  905. case Type_Slice:
  906. type = type->Slice.elem;
  907. continue;
  908. case Type_DynamicArray:
  909. type = type->DynamicArray.elem;
  910. continue;
  911. }
  912. return nullptr;
  913. }
  914. }
  915. // NOTE(bill): 'context_name' is for debugging and error messages
  916. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  917. check_not_tuple(c, operand);
  918. if (operand->mode == Addressing_Invalid) {
  919. return;
  920. }
  921. // Grab definite or indefinite article matching `context_name`, or "" if not found.
  922. String article = error_article(context_name);
  923. if (is_type_untyped(operand->type)) {
  924. Type *target_type = type;
  925. if (type == nullptr || is_type_any(type)) {
  926. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  927. error(operand->expr, "Use of --- in %.*s%.*s", LIT(article), LIT(context_name));
  928. operand->mode = Addressing_Invalid;
  929. return;
  930. }
  931. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  932. error(operand->expr, "Use of untyped nil in %.*s%.*s", LIT(article), LIT(context_name));
  933. operand->mode = Addressing_Invalid;
  934. return;
  935. }
  936. target_type = default_type(operand->type);
  937. if (type != nullptr && !is_type_any(type)) {
  938. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  939. }
  940. add_type_info_type(c, type);
  941. add_type_info_type(c, target_type);
  942. }
  943. convert_to_typed(c, operand, target_type);
  944. if (operand->mode == Addressing_Invalid) {
  945. return;
  946. }
  947. }
  948. if (type == nullptr) {
  949. return;
  950. }
  951. if (operand->mode == Addressing_ProcGroup) {
  952. bool good = false;
  953. if (type != nullptr && is_type_proc(type)) {
  954. Array<Entity *> procs = proc_group_entities(c, *operand);
  955. // NOTE(bill): These should be done
  956. for (Entity *e : procs) {
  957. Type *t = base_type(e->type);
  958. if (t == t_invalid) {
  959. continue;
  960. }
  961. Operand x = {};
  962. x.mode = Addressing_Value;
  963. x.type = t;
  964. if (check_is_assignable_to(c, &x, type)) {
  965. add_entity_use(c, operand->expr, e);
  966. good = true;
  967. break;
  968. }
  969. }
  970. }
  971. if (!good) {
  972. gbString expr_str = expr_to_string(operand->expr);
  973. gbString op_type_str = type_to_string(operand->type);
  974. gbString type_str = type_to_string(type);
  975. defer (gb_string_free(type_str));
  976. defer (gb_string_free(op_type_str));
  977. defer (gb_string_free(expr_str));
  978. // TODO(bill): is this a good enough error message?
  979. error(operand->expr,
  980. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s%.*s",
  981. expr_str,
  982. op_type_str,
  983. LIT(article),
  984. LIT(context_name));
  985. operand->mode = Addressing_Invalid;
  986. }
  987. convert_to_typed(c, operand, type);
  988. return;
  989. }
  990. if (check_is_assignable_to(c, operand, type)) {
  991. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  992. add_type_info_type(c, operand->type);
  993. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  994. }
  995. } else {
  996. gbString expr_str = expr_to_string(operand->expr);
  997. gbString op_type_str = type_to_string(operand->type);
  998. gbString type_str = type_to_string(type);
  999. defer (gb_string_free(type_str));
  1000. defer (gb_string_free(op_type_str));
  1001. defer (gb_string_free(expr_str));
  1002. switch (operand->mode) {
  1003. case Addressing_Builtin:
  1004. error(operand->expr,
  1005. "Cannot assign built-in procedure '%s' to %.*s%.*s",
  1006. expr_str,
  1007. LIT(article),
  1008. LIT(context_name));
  1009. break;
  1010. case Addressing_Type:
  1011. if (is_type_polymorphic(operand->type)) {
  1012. error(operand->expr,
  1013. "Cannot assign '%s', a polymorphic type, to %.*s%.*s",
  1014. op_type_str,
  1015. LIT(article),
  1016. LIT(context_name));
  1017. } else {
  1018. ERROR_BLOCK();
  1019. error(operand->expr,
  1020. "Cannot assign '%s', a type, to %.*s%.*s",
  1021. op_type_str,
  1022. LIT(article),
  1023. LIT(context_name));
  1024. if (type && are_types_identical(type, t_any)) {
  1025. error_line("\tSuggestion: 'typeid_of(%s)'", expr_str);
  1026. }
  1027. }
  1028. break;
  1029. default:
  1030. // TODO(bill): is this a good enough error message?
  1031. {
  1032. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  1033. gbString type_extra = gb_string_make(heap_allocator(), "");
  1034. defer (gb_string_free(op_type_extra));
  1035. defer (gb_string_free(type_extra));
  1036. isize on = gb_string_length(op_type_str);
  1037. isize tn = gb_string_length(type_str);
  1038. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  1039. AstPackage *op_pkg = get_package_of_type(operand->type);
  1040. AstPackage *type_pkg = get_package_of_type(type);
  1041. if (op_pkg != nullptr) {
  1042. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  1043. }
  1044. if (type_pkg != nullptr) {
  1045. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  1046. }
  1047. }
  1048. ERROR_BLOCK();
  1049. error(operand->expr,
  1050. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s%.*s",
  1051. expr_str,
  1052. op_type_str, op_type_extra,
  1053. type_str, type_extra,
  1054. LIT(article),
  1055. LIT(context_name));
  1056. check_assignment_error_suggestion(c, operand, type);
  1057. Type *src = base_type(operand->type);
  1058. Type *dst = base_type(type);
  1059. if (context_name == "procedure argument") {
  1060. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  1061. gbString a = expr_to_string(operand->expr);
  1062. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  1063. gb_string_free(a);
  1064. }
  1065. }
  1066. if (src->kind == dst->kind && src->kind == Type_Proc) {
  1067. Type *x = src;
  1068. Type *y = dst;
  1069. bool same_inputs = are_types_identical_internal(x->Proc.params, y->Proc.params, false);
  1070. bool same_outputs = are_types_identical_internal(x->Proc.results, y->Proc.results, false);
  1071. if (same_inputs && same_outputs &&
  1072. x->Proc.calling_convention != y->Proc.calling_convention) {
  1073. gbString s_expected = type_to_string(y);
  1074. gbString s_got = type_to_string(x);
  1075. error_line("\tNote: The calling conventions differ between the procedure signature types\n");
  1076. error_line("\t Expected \"%s\", got \"%s\"\n",
  1077. proc_calling_convention_strings[y->Proc.calling_convention],
  1078. proc_calling_convention_strings[x->Proc.calling_convention]);
  1079. error_line("\t Expected: %s\n", s_expected);
  1080. error_line("\t Got: %s\n", s_got);
  1081. gb_string_free(s_got);
  1082. gb_string_free(s_expected);
  1083. } else if (same_inputs && same_outputs &&
  1084. x->Proc.diverging != y->Proc.diverging) {
  1085. gbString s_expected = type_to_string(y);
  1086. if (y->Proc.diverging) {
  1087. s_expected = gb_string_appendc(s_expected, " -> !");
  1088. }
  1089. gbString s_got = type_to_string(x);
  1090. if (x->Proc.diverging) {
  1091. s_got = gb_string_appendc(s_got, " -> !");
  1092. }
  1093. error_line("\tNote: One of the procedures is diverging while the other isn't\n");
  1094. error_line("\t Expected: %s\n", s_expected);
  1095. error_line("\t Got: %s\n", s_got);
  1096. gb_string_free(s_got);
  1097. gb_string_free(s_expected);
  1098. } else if (same_inputs && !same_outputs) {
  1099. gbString s_expected = type_to_string(y->Proc.results);
  1100. gbString s_got = type_to_string(x->Proc.results);
  1101. error_line("\tNote: The return types differ between the procedure signature types\n");
  1102. error_line("\t Expected: %s\n", s_expected);
  1103. error_line("\t Got: %s\n", s_got);
  1104. gb_string_free(s_got);
  1105. gb_string_free(s_expected);
  1106. } else if (!same_inputs && same_outputs) {
  1107. gbString s_expected = type_to_string(y->Proc.params);
  1108. gbString s_got = type_to_string(x->Proc.params);
  1109. error_line("\tNote: The input parameter types differ between the procedure signature types\n");
  1110. error_line("\t Expected: %s\n", s_expected);
  1111. error_line("\t Got: %s\n", s_got);
  1112. gb_string_free(s_got);
  1113. gb_string_free(s_expected);
  1114. Type *tx = x->Proc.params->Tuple.variables[0]->type;
  1115. Type *ty = y->Proc.params->Tuple.variables[0]->type;
  1116. gb_printf_err("%s kind:%.*s e:%p ot:%p\n", type_to_string(tx), LIT(type_strings[tx->kind]), tx->Named.type_name, tx->Named.type_name->TypeName.original_type_for_parapoly);
  1117. gb_printf_err("%s kind:%.*s e:%p ot:%p\n", type_to_string(ty), LIT(type_strings[ty->kind]), ty->Named.type_name, ty->Named.type_name->TypeName.original_type_for_parapoly);
  1118. } else {
  1119. gbString s_expected = type_to_string(y);
  1120. gbString s_got = type_to_string(x);
  1121. error_line("\tNote: The signature type do not match whatsoever\n");
  1122. error_line("\t Expected: %s\n", s_expected);
  1123. error_line("\t Got: %s\n", s_got);
  1124. gb_string_free(s_got);
  1125. gb_string_free(s_expected);
  1126. }
  1127. }
  1128. }
  1129. break;
  1130. }
  1131. operand->mode = Addressing_Invalid;
  1132. return;
  1133. }
  1134. }
  1135. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1136. Type *gt = *gt_;
  1137. GB_ASSERT(gt->kind == Type_Generic);
  1138. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1139. GB_ASSERT(e != nullptr);
  1140. if (e->kind == Entity_TypeName) {
  1141. *gt_ = nullptr;
  1142. *dst_count = source_count;
  1143. e->kind = Entity_Constant;
  1144. e->Constant.value = exact_value_i64(source_count);
  1145. e->type = t_untyped_integer;
  1146. return true;
  1147. } else if (e->kind == Entity_Constant) {
  1148. *gt_ = nullptr;
  1149. if (e->Constant.value.kind != ExactValue_Integer) {
  1150. return false;
  1151. }
  1152. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1153. if (count != source_count) {
  1154. return false;
  1155. }
  1156. *dst_count = source_count;
  1157. return true;
  1158. }
  1159. return false;
  1160. }
  1161. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1162. Operand o = {Addressing_Value};
  1163. o.type = source;
  1164. switch (poly->kind) {
  1165. case Type_Basic:
  1166. if (compound) return are_types_identical(poly, source);
  1167. return check_is_assignable_to(c, &o, poly);
  1168. case Type_Named: {
  1169. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1170. return true;
  1171. }
  1172. if (compound || !is_type_generic(poly)) {
  1173. return are_types_identical(poly, source);
  1174. }
  1175. return check_is_assignable_to(c, &o, poly);
  1176. }
  1177. case Type_Generic: {
  1178. if (poly->Generic.specialized != nullptr) {
  1179. Type *s = poly->Generic.specialized;
  1180. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1181. return false;
  1182. }
  1183. }
  1184. if (modify_type) {
  1185. Type *ds = default_type(source);
  1186. gb_memmove(poly, ds, gb_size_of(Type));
  1187. }
  1188. return true;
  1189. }
  1190. case Type_Pointer:
  1191. if (source->kind == Type_Pointer) {
  1192. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1193. if (level > 0) {
  1194. return true;
  1195. }
  1196. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1197. } else if (source->kind == Type_MultiPointer) {
  1198. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1199. if (level > 0) {
  1200. return true;
  1201. }
  1202. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1203. }
  1204. return false;
  1205. case Type_MultiPointer:
  1206. if (source->kind == Type_MultiPointer) {
  1207. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1208. if (level > 0) {
  1209. return true;
  1210. }
  1211. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1212. } else if (source->kind == Type_Pointer) {
  1213. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1214. if (level > 0) {
  1215. return true;
  1216. }
  1217. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1218. }
  1219. return false;
  1220. case Type_Array:
  1221. if (source->kind == Type_Array) {
  1222. if (poly->Array.generic_count != nullptr) {
  1223. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1224. return false;
  1225. }
  1226. }
  1227. if (poly->Array.count == source->Array.count) {
  1228. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1229. }
  1230. } else if (source->kind == Type_EnumeratedArray) {
  1231. if (poly->Array.generic_count != nullptr) {
  1232. Type *gt = poly->Array.generic_count;
  1233. GB_ASSERT(gt->kind == Type_Generic);
  1234. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1235. GB_ASSERT(e != nullptr);
  1236. if (e->kind == Entity_TypeName) {
  1237. Type *index = source->EnumeratedArray.index;
  1238. Type *it = base_type(index);
  1239. if (it->kind != Type_Enum) {
  1240. return false;
  1241. }
  1242. poly->kind = Type_EnumeratedArray;
  1243. poly->cached_size = -1;
  1244. poly->cached_align = -1;
  1245. poly->flags.exchange(source->flags);
  1246. poly->failure = false;
  1247. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1248. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1249. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1250. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1251. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1252. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1253. e->kind = Entity_TypeName;
  1254. e->TypeName.is_type_alias = true;
  1255. e->type = index;
  1256. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1257. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1258. }
  1259. }
  1260. }
  1261. }
  1262. return false;
  1263. case Type_EnumeratedArray:
  1264. if (source->kind == Type_EnumeratedArray) {
  1265. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1266. return false;
  1267. }
  1268. if (poly->EnumeratedArray.op) {
  1269. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1270. return false;
  1271. }
  1272. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1273. return false;
  1274. }
  1275. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1276. return false;
  1277. }
  1278. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1279. }
  1280. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1281. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1282. return index || elem;
  1283. }
  1284. return false;
  1285. case Type_DynamicArray:
  1286. if (source->kind == Type_DynamicArray) {
  1287. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1288. }
  1289. return false;
  1290. case Type_Slice:
  1291. if (source->kind == Type_Slice) {
  1292. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1293. }
  1294. return false;
  1295. case Type_Enum:
  1296. return false;
  1297. case Type_BitSet:
  1298. if (source->kind == Type_BitSet) {
  1299. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1300. return false;
  1301. }
  1302. // For generic types like bit_set[$T] the upper and lower of the poly type will be zeroes since
  1303. // it could not figure that stuff out when the poly type was created.
  1304. if (poly->BitSet.upper == 0 && modify_type) {
  1305. poly->BitSet.upper = source->BitSet.upper;
  1306. }
  1307. if (poly->BitSet.lower == 0 && modify_type) {
  1308. poly->BitSet.lower = source->BitSet.lower;
  1309. }
  1310. if (poly->BitSet.underlying == nullptr) {
  1311. if (modify_type) {
  1312. poly->BitSet.underlying = source->BitSet.underlying;
  1313. }
  1314. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1315. return false;
  1316. }
  1317. return true;
  1318. }
  1319. return false;
  1320. case Type_Union:
  1321. if (source->kind == Type_Union) {
  1322. TypeUnion *x = &poly->Union;
  1323. TypeUnion *y = &source->Union;
  1324. if (x->variants.count != y->variants.count) {
  1325. return false;
  1326. }
  1327. for_array(i, x->variants) {
  1328. Type *a = x->variants[i];
  1329. Type *b = y->variants[i];
  1330. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1331. if (!ok) return false;
  1332. }
  1333. return true;
  1334. }
  1335. return false;
  1336. case Type_Struct:
  1337. if (source->kind == Type_Struct) {
  1338. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1339. poly->Struct.soa_kind != StructSoa_None) {
  1340. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1341. if (ok) switch (source->Struct.soa_kind) {
  1342. case StructSoa_None:
  1343. default:
  1344. GB_PANIC("Unhandled SOA Kind");
  1345. break;
  1346. case StructSoa_Fixed:
  1347. if (modify_type) {
  1348. Type *type = make_soa_struct_fixed(c, nullptr, poly->Struct.node, poly->Struct.soa_elem, poly->Struct.soa_count, nullptr);
  1349. gb_memmove(poly, type, gb_size_of(*type));
  1350. }
  1351. break;
  1352. case StructSoa_Slice:
  1353. if (modify_type) {
  1354. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1355. gb_memmove(poly, type, gb_size_of(*type));
  1356. }
  1357. break;
  1358. case StructSoa_Dynamic:
  1359. if (modify_type) {
  1360. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1361. gb_memmove(poly, type, gb_size_of(*type));
  1362. }
  1363. break;
  1364. }
  1365. return ok;
  1366. }
  1367. // NOTE(bill): Check for subtypes of
  1368. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1369. }
  1370. return false;
  1371. case Type_BitField:
  1372. if (source->kind == Type_BitField) {
  1373. return is_polymorphic_type_assignable(c, poly->BitField.backing_type, source->BitField.backing_type, true, modify_type);
  1374. }
  1375. return false;
  1376. case Type_Tuple:
  1377. GB_PANIC("This should never happen");
  1378. return false;
  1379. case Type_Proc:
  1380. if (source->kind == Type_Proc) {
  1381. TypeProc *x = &poly->Proc;
  1382. TypeProc *y = &source->Proc;
  1383. if (x->calling_convention != y->calling_convention) {
  1384. return false;
  1385. }
  1386. if (x->c_vararg != y->c_vararg) {
  1387. return false;
  1388. }
  1389. if (x->variadic != y->variadic) {
  1390. return false;
  1391. }
  1392. if (x->param_count != y->param_count) {
  1393. return false;
  1394. }
  1395. if (x->result_count != y->result_count) {
  1396. return false;
  1397. }
  1398. for (isize i = 0; i < x->param_count; i++) {
  1399. Entity *a = x->params->Tuple.variables[i];
  1400. Entity *b = y->params->Tuple.variables[i];
  1401. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1402. if (!ok) return false;
  1403. }
  1404. for (isize i = 0; i < x->result_count; i++) {
  1405. Entity *a = x->results->Tuple.variables[i];
  1406. Entity *b = y->results->Tuple.variables[i];
  1407. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1408. if (!ok) return false;
  1409. }
  1410. return true;
  1411. }
  1412. return false;
  1413. case Type_Map:
  1414. if (source->kind == Type_Map) {
  1415. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1416. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1417. if (key || value) {
  1418. poly->Map.lookup_result_type = nullptr;
  1419. init_map_internal_types(poly);
  1420. return true;
  1421. }
  1422. }
  1423. return false;
  1424. case Type_Matrix:
  1425. if (source->kind == Type_Matrix) {
  1426. if (poly->Matrix.generic_row_count != nullptr) {
  1427. poly->Matrix.stride_in_bytes = 0;
  1428. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1429. return false;
  1430. }
  1431. }
  1432. if (poly->Matrix.generic_column_count != nullptr) {
  1433. poly->Matrix.stride_in_bytes = 0;
  1434. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1435. return false;
  1436. }
  1437. }
  1438. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1439. poly->Matrix.column_count == source->Matrix.column_count) {
  1440. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1441. }
  1442. }
  1443. return false;
  1444. case Type_SimdVector:
  1445. if (source->kind == Type_SimdVector) {
  1446. if (poly->SimdVector.generic_count != nullptr) {
  1447. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1448. return false;
  1449. }
  1450. }
  1451. if (poly->SimdVector.count == source->SimdVector.count) {
  1452. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1453. }
  1454. }
  1455. return false;
  1456. }
  1457. return false;
  1458. }
  1459. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1460. if (curr->state != EntityState_InProgress) {
  1461. return false;
  1462. }
  1463. for_array(i, *c->type_path) {
  1464. Entity *prev = c->type_path->data[i];
  1465. if (prev == curr) {
  1466. if (report) {
  1467. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1468. for (isize j = i; j < c->type_path->count; j++) {
  1469. Entity *curr = (*c->type_path)[j];
  1470. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1471. }
  1472. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1473. curr->type = t_invalid;
  1474. }
  1475. return true;
  1476. }
  1477. }
  1478. return false;
  1479. }
  1480. struct CIdentSuggestion {
  1481. String name;
  1482. String msg;
  1483. };
  1484. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1485. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1486. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1487. {str_lit("sizeof"), str_lit("'size_of'?")},
  1488. {str_lit("alignof"), str_lit("'align_of'?")},
  1489. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1490. {str_lit("_Bool"), str_lit("'bool'?")},
  1491. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1492. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1493. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1494. {str_lit("float"), str_lit("'f32'?")},
  1495. {str_lit("double"), str_lit("'f64'?")},
  1496. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1497. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1498. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1499. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1500. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1501. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1502. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1503. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1504. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1505. {str_lit("uint8_t"), str_lit("'u8'?")},
  1506. {str_lit("int8_t"), str_lit("'i8'?")},
  1507. {str_lit("uint16_t"), str_lit("'u16'?")},
  1508. {str_lit("int16_t"), str_lit("'i16'?")},
  1509. {str_lit("uint32_t"), str_lit("'u32'?")},
  1510. {str_lit("int32_t"), str_lit("'i32'?")},
  1511. {str_lit("uint64_t"), str_lit("'u64'?")},
  1512. {str_lit("int64_t"), str_lit("'i64'?")},
  1513. {str_lit("uint128_t"), str_lit("'u128'?")},
  1514. {str_lit("int128_t"), str_lit("'i128'?")},
  1515. {str_lit("float32"), str_lit("'f32'?")},
  1516. {str_lit("float64"), str_lit("'f64'?")},
  1517. {str_lit("float32_t"), str_lit("'f32'?")},
  1518. {str_lit("float64_t"), str_lit("'f64'?")},
  1519. };
  1520. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1521. GB_ASSERT(n->kind == Ast_Ident);
  1522. o->mode = Addressing_Invalid;
  1523. o->expr = n;
  1524. String name = n->Ident.token.string;
  1525. Entity *e = scope_lookup(c->scope, name, n->Ident.hash);
  1526. if (e == nullptr) {
  1527. if (is_blank_ident(name)) {
  1528. error(n, "'_' cannot be used as a value");
  1529. } else {
  1530. ERROR_BLOCK();
  1531. error(n, "Undeclared name: %.*s", LIT(name));
  1532. // NOTE(bill): Loads of checks for C programmers
  1533. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1534. if (name == suggestion.name) {
  1535. error_line("\tSuggestion: Did you mean %.*s\n", LIT(suggestion.msg));
  1536. }
  1537. }
  1538. }
  1539. o->type = t_invalid;
  1540. o->mode = Addressing_Invalid;
  1541. if (named_type != nullptr) {
  1542. set_base_type(named_type, t_invalid);
  1543. }
  1544. return nullptr;
  1545. }
  1546. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1547. if (e->parent_proc_decl != nullptr &&
  1548. e->parent_proc_decl != c->curr_proc_decl) {
  1549. if (e->kind == Entity_Variable) {
  1550. if ((e->flags & EntityFlag_Static) == 0) {
  1551. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1552. return nullptr;
  1553. }
  1554. } else if (e->kind == Entity_Label) {
  1555. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1556. return nullptr;
  1557. }
  1558. }
  1559. if (e->kind == Entity_ProcGroup) {
  1560. auto *pge = &e->ProcGroup;
  1561. DeclInfo *d = decl_info_of_entity(e);
  1562. check_entity_decl(c, e, d, nullptr);
  1563. Array<Entity *> procs = pge->entities;
  1564. bool skip = false;
  1565. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1566. // NOTE(bill): These should be done
  1567. for (Entity *proc : procs) {
  1568. Type *t = base_type(proc->type);
  1569. if (t == t_invalid) {
  1570. continue;
  1571. }
  1572. Operand x = {};
  1573. x.mode = Addressing_Value;
  1574. x.type = t;
  1575. if (check_is_assignable_to(c, &x, type_hint)) {
  1576. e = proc;
  1577. add_entity_use(c, n, e);
  1578. skip = true;
  1579. break;
  1580. }
  1581. }
  1582. }
  1583. if (!skip) {
  1584. o->mode = Addressing_ProcGroup;
  1585. o->type = t_invalid;
  1586. o->proc_group = e;
  1587. return nullptr;
  1588. }
  1589. }
  1590. add_entity_use(c, n, e);
  1591. if (e->state == EntityState_Unresolved) {
  1592. check_entity_decl(c, e, nullptr, named_type);
  1593. }
  1594. if (e->type == nullptr) {
  1595. // TODO(bill): Which is correct? return or compiler_error?
  1596. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1597. return nullptr;
  1598. }
  1599. e->flags |= EntityFlag_Used;
  1600. Type *type = e->type;
  1601. o->type = type;
  1602. switch (e->kind) {
  1603. case Entity_Constant:
  1604. if (type == t_invalid) {
  1605. o->type = t_invalid;
  1606. return e;
  1607. }
  1608. o->value = e->Constant.value;
  1609. if (o->value.kind == ExactValue_Invalid) {
  1610. return e;
  1611. }
  1612. if (o->value.kind == ExactValue_Procedure) {
  1613. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1614. if (proc != nullptr) {
  1615. o->mode = Addressing_Value;
  1616. o->type = proc->type;
  1617. return proc;
  1618. }
  1619. }
  1620. o->mode = Addressing_Constant;
  1621. break;
  1622. case Entity_Variable:
  1623. e->flags |= EntityFlag_Used;
  1624. if (type == t_invalid) {
  1625. o->type = t_invalid;
  1626. return e;
  1627. }
  1628. o->mode = Addressing_Variable;
  1629. if (e->flags & EntityFlag_Value) {
  1630. o->mode = Addressing_Value;
  1631. }
  1632. break;
  1633. case Entity_Procedure:
  1634. o->mode = Addressing_Value;
  1635. o->value = exact_value_procedure(n);
  1636. break;
  1637. case Entity_Builtin:
  1638. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1639. o->mode = Addressing_Builtin;
  1640. break;
  1641. case Entity_TypeName:
  1642. o->mode = Addressing_Type;
  1643. if (check_cycle(c, e, true)) {
  1644. o->type = t_invalid;
  1645. }
  1646. if (o->type != nullptr && o->type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1647. Type *bt = base_type(o->type);
  1648. if (bt != nullptr) {
  1649. o->type = bt;
  1650. }
  1651. }
  1652. break;
  1653. case Entity_ImportName:
  1654. if (!allow_import_name) {
  1655. error(n, "Use of import name '%.*s' not in the form of 'x.y'", LIT(name));
  1656. }
  1657. return e;
  1658. case Entity_LibraryName:
  1659. if (!allow_import_name) {
  1660. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1661. }
  1662. return e;
  1663. case Entity_Label:
  1664. o->mode = Addressing_NoValue;
  1665. break;
  1666. case Entity_Nil:
  1667. o->mode = Addressing_Value;
  1668. break;
  1669. default:
  1670. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1671. break;
  1672. }
  1673. return e;
  1674. }
  1675. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1676. if (o->type == nullptr) {
  1677. gbString str = expr_to_string(o->expr);
  1678. error(o->expr, "Expression has no value '%s'", str);
  1679. gb_string_free(str);
  1680. return false;
  1681. }
  1682. if (o->mode == Addressing_Type) {
  1683. gbString str = type_to_string(o->type);
  1684. error(o->expr, "Expected an expression for operator '%.*s', got type '%s'", LIT(op.string), str);
  1685. gb_string_free(str);
  1686. return false;
  1687. }
  1688. Type *type = base_type(core_array_type(o->type));
  1689. gbString str = nullptr;
  1690. switch (op.kind) {
  1691. case Token_Add:
  1692. case Token_Sub:
  1693. if (!is_type_numeric(type)) {
  1694. str = expr_to_string(o->expr);
  1695. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1696. gb_string_free(str);
  1697. }
  1698. break;
  1699. case Token_Xor:
  1700. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1701. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1702. }
  1703. break;
  1704. case Token_Not:
  1705. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1706. ERROR_BLOCK();
  1707. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1708. if (is_type_integer(type)) {
  1709. str = expr_to_string(o->expr);
  1710. error_line("\tSuggestion: Did you mean to do one of the following?\n");
  1711. error_line("\t\t'%s == 0'?\n", str);
  1712. error_line("\t\tUse of the bitwise not operator '~'?\n");
  1713. gb_string_free(str);
  1714. }
  1715. } else {
  1716. o->type = t_untyped_bool;
  1717. }
  1718. break;
  1719. case Token_Mul:
  1720. {
  1721. ERROR_BLOCK();
  1722. error(op, "Operator '%.*s' is not a valid unary operator in Odin", LIT(op.string));
  1723. if (is_type_pointer(o->type)) {
  1724. str = expr_to_string(o->expr);
  1725. error_line("\tSuggestion: Did you mean '%s^'?\n", str);
  1726. o->type = type_deref(o->type);
  1727. } else if (is_type_multi_pointer(o->type)) {
  1728. str = expr_to_string(o->expr);
  1729. error_line("\tSuggestion: The value is a multi-pointer, did you mean '%s[0]'?\n", str);
  1730. o->type = type_deref(o->type, true);
  1731. }
  1732. }
  1733. break;
  1734. default:
  1735. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1736. return false;
  1737. }
  1738. return true;
  1739. }
  1740. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1741. Type *main_type = o->type;
  1742. Type *type = base_type(core_array_type(main_type));
  1743. Type *ct = core_type(type);
  1744. switch (op.kind) {
  1745. case Token_Sub:
  1746. case Token_SubEq:
  1747. if (is_type_bit_set(type)) {
  1748. return true;
  1749. } else if (!is_type_numeric(type)) {
  1750. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1751. return false;
  1752. }
  1753. break;
  1754. case Token_Quo:
  1755. case Token_QuoEq:
  1756. if (is_type_matrix(main_type)) {
  1757. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1758. return false;
  1759. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1760. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1761. return false;
  1762. }
  1763. /*fallthrough*/
  1764. case Token_Mul:
  1765. case Token_MulEq:
  1766. case Token_AddEq:
  1767. if (is_type_bit_set(type)) {
  1768. return true;
  1769. } else if (!is_type_numeric(type)) {
  1770. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1771. return false;
  1772. }
  1773. break;
  1774. case Token_Add:
  1775. if (is_type_string(type)) {
  1776. if (o->mode == Addressing_Constant) {
  1777. return true;
  1778. }
  1779. error(op, "String concatenation is only allowed with constant strings");
  1780. return false;
  1781. } else if (is_type_bit_set(type)) {
  1782. return true;
  1783. } else if (!is_type_numeric(type)) {
  1784. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1785. return false;
  1786. }
  1787. break;
  1788. case Token_And:
  1789. case Token_Or:
  1790. case Token_AndEq:
  1791. case Token_OrEq:
  1792. case Token_Xor:
  1793. case Token_XorEq:
  1794. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1795. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1796. return false;
  1797. }
  1798. break;
  1799. case Token_Mod:
  1800. case Token_ModMod:
  1801. case Token_ModEq:
  1802. case Token_ModModEq:
  1803. if (is_type_matrix(main_type)) {
  1804. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1805. return false;
  1806. }
  1807. if (!is_type_integer(type)) {
  1808. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1809. return false;
  1810. } else if (is_type_simd_vector(main_type)) {
  1811. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1812. return false;
  1813. }
  1814. break;
  1815. case Token_AndNot:
  1816. case Token_AndNotEq:
  1817. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1818. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1819. return false;
  1820. }
  1821. break;
  1822. case Token_CmpAnd:
  1823. case Token_CmpOr:
  1824. case Token_CmpAndEq:
  1825. case Token_CmpOrEq:
  1826. if (!is_type_boolean(type)) {
  1827. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1828. return false;
  1829. }
  1830. break;
  1831. default:
  1832. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1833. return false;
  1834. }
  1835. return true;
  1836. }
  1837. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1838. if (in_value.kind == ExactValue_Invalid) {
  1839. // NOTE(bill): There's already been an error
  1840. return true;
  1841. }
  1842. type = core_type(type);
  1843. if (type == t_invalid) {
  1844. return false;
  1845. } else if (is_type_boolean(type)) {
  1846. return in_value.kind == ExactValue_Bool;
  1847. } else if (is_type_string(type)) {
  1848. if (in_value.kind == ExactValue_String16) {
  1849. return is_type_string16(type) || is_type_cstring16(type);
  1850. }
  1851. return in_value.kind == ExactValue_String;
  1852. } else if (is_type_integer(type) || is_type_rune(type)) {
  1853. if (in_value.kind == ExactValue_Bool) {
  1854. return false;
  1855. }
  1856. ExactValue v = exact_value_to_integer(in_value);
  1857. if (v.kind != ExactValue_Integer) {
  1858. return false;
  1859. }
  1860. if (out_value) *out_value = v;
  1861. if (is_type_untyped(type)) {
  1862. return true;
  1863. }
  1864. BigInt i = v.value_integer;
  1865. i64 byte_size = type_size_of(type);
  1866. BigInt umax = {};
  1867. BigInt imin = {};
  1868. BigInt imax = {};
  1869. if (c->bit_field_bit_size > 0) {
  1870. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1871. big_int_from_u64(&umax, 1);
  1872. big_int_from_i64(&imin, 1);
  1873. big_int_from_i64(&imax, 1);
  1874. BigInt bu = {};
  1875. BigInt bi = {};
  1876. big_int_from_i64(&bu, bit_size);
  1877. big_int_from_i64(&bi, bit_size-1);
  1878. big_int_shl_eq(&umax, &bu);
  1879. mp_decr(&umax);
  1880. big_int_shl_eq(&imin, &bi);
  1881. big_int_neg(&imin, &imin);
  1882. big_int_shl_eq(&imax, &bi);
  1883. mp_decr(&imax);
  1884. } else {
  1885. if (byte_size < 16) {
  1886. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1887. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1888. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1889. } else {
  1890. big_int_from_u64(&umax, 1);
  1891. big_int_from_i64(&imin, 1);
  1892. big_int_from_i64(&imax, 1);
  1893. BigInt bi128 = {};
  1894. BigInt bi127 = {};
  1895. big_int_from_i64(&bi128, 128);
  1896. big_int_from_i64(&bi127, 127);
  1897. big_int_shl_eq(&umax, &bi128);
  1898. mp_decr(&umax);
  1899. big_int_shl_eq(&imin, &bi127);
  1900. big_int_neg(&imin, &imin);
  1901. big_int_shl_eq(&imax, &bi127);
  1902. mp_decr(&imax);
  1903. }
  1904. }
  1905. switch (type->Basic.kind) {
  1906. case Basic_rune:
  1907. case Basic_i8:
  1908. case Basic_i16:
  1909. case Basic_i32:
  1910. case Basic_i64:
  1911. case Basic_i128:
  1912. case Basic_int:
  1913. case Basic_i16le:
  1914. case Basic_i32le:
  1915. case Basic_i64le:
  1916. case Basic_i128le:
  1917. case Basic_i16be:
  1918. case Basic_i32be:
  1919. case Basic_i64be:
  1920. case Basic_i128be:
  1921. {
  1922. // return imin <= i && i <= imax;
  1923. int a = big_int_cmp(&imin, &i);
  1924. int b = big_int_cmp(&i, &imax);
  1925. return (a <= 0) && (b <= 0);
  1926. }
  1927. case Basic_u8:
  1928. case Basic_u16:
  1929. case Basic_u32:
  1930. case Basic_u64:
  1931. case Basic_u128:
  1932. case Basic_uint:
  1933. case Basic_uintptr:
  1934. case Basic_u16le:
  1935. case Basic_u32le:
  1936. case Basic_u64le:
  1937. case Basic_u128le:
  1938. case Basic_u16be:
  1939. case Basic_u32be:
  1940. case Basic_u64be:
  1941. case Basic_u128be:
  1942. {
  1943. // return 0ull <= i && i <= umax;
  1944. int b = big_int_cmp(&i, &umax);
  1945. return !i.sign && (b <= 0);
  1946. }
  1947. case Basic_UntypedInteger:
  1948. return true;
  1949. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1950. }
  1951. } else if (is_type_float(type)) {
  1952. ExactValue v = exact_value_to_float(in_value);
  1953. if (v.kind != ExactValue_Float) {
  1954. return false;
  1955. }
  1956. if (out_value) *out_value = v;
  1957. switch (type->Basic.kind) {
  1958. case Basic_f16:
  1959. case Basic_f32:
  1960. case Basic_f64:
  1961. return true;
  1962. case Basic_f16le:
  1963. case Basic_f16be:
  1964. case Basic_f32le:
  1965. case Basic_f32be:
  1966. case Basic_f64le:
  1967. case Basic_f64be:
  1968. return true;
  1969. case Basic_UntypedFloat:
  1970. return true;
  1971. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1972. }
  1973. } else if (is_type_complex(type)) {
  1974. ExactValue v = exact_value_to_complex(in_value);
  1975. if (v.kind != ExactValue_Complex) {
  1976. return false;
  1977. }
  1978. switch (type->Basic.kind) {
  1979. case Basic_complex32:
  1980. case Basic_complex64:
  1981. case Basic_complex128: {
  1982. ExactValue real = exact_value_real(v);
  1983. ExactValue imag = exact_value_imag(v);
  1984. if (real.kind != ExactValue_Invalid &&
  1985. imag.kind != ExactValue_Invalid) {
  1986. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1987. return true;
  1988. }
  1989. break;
  1990. }
  1991. case Basic_UntypedComplex:
  1992. return true;
  1993. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1994. }
  1995. return false;
  1996. } else if (is_type_quaternion(type)) {
  1997. ExactValue v = exact_value_to_quaternion(in_value);
  1998. if (v.kind != ExactValue_Quaternion) {
  1999. return false;
  2000. }
  2001. switch (type->Basic.kind) {
  2002. case Basic_quaternion64:
  2003. case Basic_quaternion128:
  2004. case Basic_quaternion256: {
  2005. ExactValue real = exact_value_real(v);
  2006. ExactValue imag = exact_value_imag(v);
  2007. ExactValue jmag = exact_value_jmag(v);
  2008. ExactValue kmag = exact_value_kmag(v);
  2009. if (real.kind != ExactValue_Invalid &&
  2010. imag.kind != ExactValue_Invalid) {
  2011. if (out_value) *out_value = exact_value_quaternion(exact_value_to_f64(real), exact_value_to_f64(imag), exact_value_to_f64(jmag), exact_value_to_f64(kmag));
  2012. return true;
  2013. }
  2014. break;
  2015. }
  2016. case Basic_UntypedComplex:
  2017. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  2018. return true;
  2019. case Basic_UntypedQuaternion:
  2020. return true;
  2021. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  2022. }
  2023. return false;
  2024. } else if (is_type_pointer(type)) {
  2025. if (in_value.kind == ExactValue_Pointer) {
  2026. return true;
  2027. }
  2028. if (in_value.kind == ExactValue_Integer) {
  2029. return false;
  2030. // return true;
  2031. }
  2032. if (in_value.kind == ExactValue_String) {
  2033. return false;
  2034. }
  2035. if (in_value.kind == ExactValue_String16) {
  2036. return false;
  2037. }
  2038. if (out_value) *out_value = in_value;
  2039. } else if (is_type_bit_set(type)) {
  2040. if (in_value.kind == ExactValue_Integer) {
  2041. return true;
  2042. }
  2043. } else if (is_type_typeid(type)) {
  2044. if (in_value.kind == ExactValue_Compound) {
  2045. ast_node(cl, CompoundLit, in_value.value_compound);
  2046. if (cl->elems.count == 0) {
  2047. in_value = exact_value_typeid(nullptr);
  2048. } else {
  2049. return false;
  2050. }
  2051. }
  2052. if (in_value.kind == ExactValue_Typeid) {
  2053. if (out_value) *out_value = in_value;
  2054. return true;
  2055. }
  2056. }
  2057. return false;
  2058. }
  2059. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  2060. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  2061. gbString b = type_to_string(type);
  2062. defer (gb_string_free(b));
  2063. if (is_type_enum(o->type)) {
  2064. if (check_is_castable_to(c, o, type)) {
  2065. gbString ot = type_to_string(o->type);
  2066. error_line("\tSuggestion: Try casting the '%s' expression to '%s'", ot, b);
  2067. gb_string_free(ot);
  2068. }
  2069. return true;
  2070. }
  2071. i64 sz = type_size_of(type);
  2072. i64 bit_size = 8*sz;
  2073. bool size_changed = false;
  2074. if (max_bit_size > 0) {
  2075. size_changed = (bit_size != max_bit_size);
  2076. bit_size = gb_min(bit_size, max_bit_size);
  2077. }
  2078. BigInt *bi = &o->value.value_integer;
  2079. if (is_type_unsigned(type)) {
  2080. BigInt one = big_int_make_u64(1);
  2081. BigInt max_size = big_int_make_u64(1);
  2082. BigInt bits = big_int_make_i64(bit_size);
  2083. big_int_shl_eq(&max_size, &bits);
  2084. big_int_sub_eq(&max_size, &one);
  2085. if (big_int_is_neg(bi)) {
  2086. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  2087. BigInt dst = {};
  2088. big_int_neg(&dst, bi);
  2089. if (big_int_cmp(&dst, &max_size) < 0) {
  2090. big_int_sub_eq(&dst, &one);
  2091. String dst_str = big_int_to_string(temporary_allocator(), &dst);
  2092. gbString t = type_to_string(type);
  2093. error_line("\tSuggestion: ~%s(%.*s)\n", t, LIT(dst_str));
  2094. gb_string_free(t);
  2095. }
  2096. } else {
  2097. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2098. if (size_changed) {
  2099. error_line("\tThe maximum value that can be represented with that bit_field's field of '%s | %u' is '%.*s'\n", b, bit_size, LIT(max_size_str));
  2100. } else {
  2101. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2102. }
  2103. }
  2104. } else {
  2105. BigInt zero = big_int_make_u64(0);
  2106. BigInt one = big_int_make_u64(1);
  2107. BigInt max_size = big_int_make_u64(1);
  2108. BigInt bits = big_int_make_i64(bit_size - 1);
  2109. big_int_shl_eq(&max_size, &bits);
  2110. String max_size_str = {};
  2111. if (big_int_is_neg(bi)) {
  2112. big_int_neg(&max_size, &max_size);
  2113. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2114. } else {
  2115. big_int_sub_eq(&max_size, &one);
  2116. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2117. }
  2118. if (size_changed) {
  2119. error_line("\tThe maximum value that can be represented with that bit_field's field of '%s | %u' is '%.*s'\n", b, bit_size, LIT(max_size_str));
  2120. } else {
  2121. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2122. }
  2123. }
  2124. return true;
  2125. }
  2126. return false;
  2127. }
  2128. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  2129. gbString a = expr_to_string(o->expr);
  2130. gbString b = type_to_string(type);
  2131. defer(
  2132. gb_string_free(b);
  2133. gb_string_free(a);
  2134. );
  2135. Type *src = base_type(o->type);
  2136. Type *dst = base_type(type);
  2137. if (is_type_array(src) && is_type_slice(dst)) {
  2138. Type *s = src->Array.elem;
  2139. Type *d = dst->Slice.elem;
  2140. if (are_types_identical(s, d)) {
  2141. error_line("\tSuggestion: The array expression may be sliced with %s[:]\n", a);
  2142. }
  2143. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  2144. Type *s = src->DynamicArray.elem;
  2145. Type *d = dst->Slice.elem;
  2146. if (are_types_identical(s, d)) {
  2147. error_line("\tSuggestion: The dynamic array expression may be sliced with %s[:]\n", a);
  2148. }
  2149. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  2150. error_line("\tSuggestion: The expression may be directly casted to type %s\n", b);
  2151. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2152. error_line("\tSuggestion: A string may be transmuted to %s\n", b);
  2153. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable,\n");
  2154. error_line("\t whereas slices in general are assumed to be mutable.\n");
  2155. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  2156. error_line("\tSuggestion: The expression may be casted to %s\n", b);
  2157. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  2158. return;
  2159. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  2160. gbString s = expr_to_string(c->type_hint_expr);
  2161. error_line("\tSuggestion: Make sure that `%s` is attached to the compound literal directly\n", s);
  2162. gb_string_free(s);
  2163. } else if (is_type_pointer(type) &&
  2164. o->mode == Addressing_Variable &&
  2165. are_types_identical(type_deref(type), o->type)) {
  2166. gbString s = expr_to_string(o->expr);
  2167. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  2168. gb_string_free(s);
  2169. } else if (is_type_pointer(o->type) &&
  2170. are_types_identical(type_deref(o->type), type)) {
  2171. gbString s = expr_to_string(o->expr);
  2172. if (s[0] == '&') error_line("\tSuggestion: Did you mean `%s`\n", &s[1]);
  2173. else error_line("\tSuggestion: Did you mean `%s^`\n", s);
  2174. gb_string_free(s);
  2175. }
  2176. }
  2177. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  2178. gbString a = expr_to_string(o->expr);
  2179. gbString b = type_to_string(type);
  2180. defer(
  2181. gb_string_free(b);
  2182. gb_string_free(a);
  2183. );
  2184. Type *src = base_type(o->type);
  2185. Type *dst = base_type(type);
  2186. if (is_type_array(src) && is_type_slice(dst)) {
  2187. Type *s = src->Array.elem;
  2188. Type *d = dst->Slice.elem;
  2189. if (are_types_identical(s, d)) {
  2190. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2191. }
  2192. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  2193. if (is_type_uintptr(type)) {
  2194. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  2195. } else {
  2196. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  2197. i64 x = type_size_of(o->type);
  2198. i64 y = type_size_of(type);
  2199. if (x != y) {
  2200. error_line("\tNote: the type of expression and the type of the cast have a different size in bytes, %lld vs %lld\n", x, y);
  2201. }
  2202. }
  2203. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2204. if (is_type_uintptr(o->type)) {
  2205. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2206. } else {
  2207. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2208. }
  2209. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2210. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2211. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2212. return;
  2213. }
  2214. }
  2215. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2216. GB_ASSERT(o->mode == Addressing_Constant);
  2217. ExactValue out_value = o->value;
  2218. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2219. o->value = out_value;
  2220. return true;
  2221. } else {
  2222. o->value = out_value;
  2223. gbString a = expr_to_string(o->expr);
  2224. gbString b = type_to_string(type);
  2225. gbString c = type_to_string(o->type);
  2226. gbString s = exact_value_to_string(o->value);
  2227. defer(
  2228. gb_string_free(s);
  2229. gb_string_free(c);
  2230. gb_string_free(b);
  2231. gb_string_free(a);
  2232. o->mode = Addressing_Invalid;
  2233. );
  2234. ERROR_BLOCK();
  2235. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2236. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2237. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2238. } else {
  2239. i64 max_bit_size = 0;
  2240. if (ctx->bit_field_bit_size) {
  2241. max_bit_size = ctx->bit_field_bit_size;
  2242. }
  2243. if (are_types_identical(o->type, type)) {
  2244. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2245. } else {
  2246. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2247. }
  2248. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2249. }
  2250. } else {
  2251. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2252. check_assignment_error_suggestion(ctx, o, type);
  2253. }
  2254. return false;
  2255. }
  2256. }
  2257. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2258. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2259. if (o->expr->SelectorExpr.is_bit_field) {
  2260. return true;
  2261. }
  2262. }
  2263. if (o->mode == Addressing_OptionalOk) {
  2264. Ast *expr = unselector_expr(o->expr);
  2265. if (expr->kind != Ast_TypeAssertion) {
  2266. return true;
  2267. }
  2268. ast_node(ta, TypeAssertion, expr);
  2269. TypeAndValue tv = ta->expr->tav;
  2270. if (is_type_pointer(tv.type)) {
  2271. return false;
  2272. }
  2273. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2274. return false;
  2275. }
  2276. if (is_type_any(tv.type)) {
  2277. return false;
  2278. }
  2279. return true;
  2280. }
  2281. if (o->mode == Addressing_MapIndex) {
  2282. return false;
  2283. }
  2284. Ast *expr = unparen_expr(o->expr);
  2285. if (expr->kind == Ast_CompoundLit) {
  2286. return false;
  2287. }
  2288. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2289. }
  2290. gb_internal ExactValue exact_bit_set_all_set_mask(Type *type) {
  2291. type = base_type(type);
  2292. GB_ASSERT(type->kind == Type_BitSet);
  2293. i64 lower = type->BitSet.lower;
  2294. i64 upper = type->BitSet.upper;
  2295. Type *elem = type->BitSet.elem;
  2296. Type *underlying = type->BitSet.underlying;
  2297. bool is_backed = underlying != nullptr;
  2298. gb_unused(is_backed);
  2299. BigInt b_lower = {};
  2300. BigInt b_upper = {};
  2301. big_int_from_i64(&b_lower, lower);
  2302. big_int_from_i64(&b_upper, upper);
  2303. BigInt one = {};
  2304. big_int_from_u64(&one, 1);
  2305. BigInt mask = {};
  2306. if (elem == nullptr) {
  2307. big_int_from_i64(&mask, -1);
  2308. } else if (is_type_enum(elem)) {
  2309. Type *e = base_type(elem);
  2310. GB_ASSERT(e->kind == Type_Enum);
  2311. gb_unused(e);
  2312. if ((big_int_cmp(&e->Enum.min_value->value_integer, &b_lower) == 0 || is_backed) &&
  2313. big_int_cmp(&e->Enum.max_value->value_integer, &b_upper) == 0) {
  2314. i64 lower_base = is_backed ? gb_min(0, lower) : lower;
  2315. BigInt b_lower_base = {};
  2316. big_int_from_i64(&b_lower_base, lower_base);
  2317. for (Entity *f : e->Enum.fields) {
  2318. if (f->kind != Entity_Constant) {
  2319. continue;
  2320. }
  2321. if (f->Constant.value.kind != ExactValue_Integer) {
  2322. continue;
  2323. }
  2324. BigInt shift_amount = {};
  2325. big_int_sub(&shift_amount, &f->Constant.value.value_integer, &b_lower_base);
  2326. BigInt value = {};
  2327. big_int_shl(&value, &one, &shift_amount);
  2328. big_int_or(&mask, &mask, &value);
  2329. }
  2330. } else {
  2331. // TODO(bill): enum range based");
  2332. big_int_from_i64(&mask, -1);
  2333. }
  2334. } else {
  2335. i64 lower_base = lower;
  2336. for (i64 x = lower; x <= upper; x++) {
  2337. BigInt shift_amount = {};
  2338. big_int_from_i64(&shift_amount, x - lower_base);
  2339. BigInt value = {};
  2340. big_int_shl(&value, &one, &shift_amount);
  2341. big_int_or(&mask, &mask, &value);
  2342. }
  2343. }
  2344. ExactValue res = {};
  2345. res.kind = ExactValue_Integer;
  2346. res.value_integer = mask;
  2347. return res;
  2348. }
  2349. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2350. switch (op.kind) {
  2351. case Token_And: { // Pointer address
  2352. if (check_is_not_addressable(c, o)) {
  2353. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2354. ast_node(ue, UnaryExpr, node);
  2355. gbString str = expr_to_string(ue->expr);
  2356. defer (gb_string_free(str));
  2357. Entity *e = entity_of_node(ue->expr);
  2358. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2359. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2360. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2361. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2362. } else {
  2363. switch (o->mode) {
  2364. case Addressing_Constant:
  2365. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2366. break;
  2367. case Addressing_SwizzleValue:
  2368. case Addressing_SwizzleVariable:
  2369. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2370. break;
  2371. default:
  2372. {
  2373. ERROR_BLOCK();
  2374. error(op, "Cannot take the pointer address of '%s'", str);
  2375. if (e == nullptr) {
  2376. break;
  2377. }
  2378. if ((e->flags & EntityFlag_ForValue) != 0) {
  2379. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2380. if (parent_type != nullptr && is_type_string(parent_type)) {
  2381. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2382. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2383. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2384. } else {
  2385. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2386. }
  2387. if (parent_type != nullptr && is_type_map(parent_type)) {
  2388. error_line("\t Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2389. } else {
  2390. error_line("\t Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2391. }
  2392. }
  2393. if ((e->flags & EntityFlag_SwitchValue) != 0) {
  2394. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2395. error_line("\t Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2396. }
  2397. }
  2398. break;
  2399. }
  2400. }
  2401. }
  2402. o->mode = Addressing_Invalid;
  2403. return;
  2404. }
  2405. if (o->mode == Addressing_SoaVariable) {
  2406. ast_node(ue, UnaryExpr, node);
  2407. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2408. ast_node(ie, IndexExpr, ue->expr);
  2409. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2410. GB_ASSERT(is_type_soa_struct(soa_type));
  2411. o->type = alloc_type_soa_pointer(soa_type);
  2412. } else {
  2413. o->type = alloc_type_pointer(o->type);
  2414. }
  2415. } else {
  2416. o->type = alloc_type_pointer(o->type);
  2417. }
  2418. switch (o->mode) {
  2419. case Addressing_OptionalOk:
  2420. case Addressing_MapIndex:
  2421. o->mode = Addressing_OptionalOkPtr;
  2422. break;
  2423. default:
  2424. o->mode = Addressing_Value;
  2425. break;
  2426. }
  2427. return;
  2428. }
  2429. }
  2430. if (!check_unary_op(c, o, op)) {
  2431. o->mode = Addressing_Invalid;
  2432. return;
  2433. }
  2434. if (o->mode == Addressing_Constant) {
  2435. Type *type = base_type(o->type);
  2436. if (!is_type_constant_type(o->type)) {
  2437. if (is_type_array_like(o->type)) {
  2438. o->mode = Addressing_Value;
  2439. return;
  2440. }
  2441. gbString xt = type_to_string(o->type);
  2442. gbString err_str = expr_to_string(node);
  2443. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2444. gb_string_free(err_str);
  2445. gb_string_free(xt);
  2446. o->mode = Addressing_Invalid;
  2447. return;
  2448. }
  2449. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2450. gbString err_str = expr_to_string(node);
  2451. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2452. gb_string_free(err_str);
  2453. o->mode = Addressing_Invalid;
  2454. return;
  2455. }
  2456. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2457. gbString err_str = expr_to_string(node);
  2458. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2459. gb_string_free(err_str);
  2460. o->mode = Addressing_Invalid;
  2461. return;
  2462. }
  2463. i32 precision = 0;
  2464. if (is_type_typed(type)) {
  2465. precision = cast(i32)(8 * type_size_of(type));
  2466. }
  2467. bool is_unsigned = is_type_unsigned(type);
  2468. if (is_type_rune(type)) {
  2469. GB_ASSERT(!is_unsigned);
  2470. }
  2471. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2472. if (op.kind == Token_Xor && is_type_bit_set(type)) {
  2473. ExactValue mask = exact_bit_set_all_set_mask(type);
  2474. o->value = exact_binary_operator_value(Token_And, o->value, mask);
  2475. }
  2476. if (is_type_typed(type)) {
  2477. if (node != nullptr) {
  2478. o->expr = node;
  2479. }
  2480. check_is_expressible(c, o, type);
  2481. }
  2482. return;
  2483. }
  2484. o->mode = Addressing_Value;
  2485. }
  2486. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2487. if (t == nullptr) {
  2488. return;
  2489. }
  2490. t = base_type(t);
  2491. if (!is_type_comparable(t)) {
  2492. return;
  2493. }
  2494. switch (t->kind) {
  2495. case Type_Basic:
  2496. switch (t->Basic.kind) {
  2497. case Basic_complex32:
  2498. add_package_dependency(c, "runtime", "complex32_eq");
  2499. add_package_dependency(c, "runtime", "complex32_ne");
  2500. break;
  2501. case Basic_complex64:
  2502. add_package_dependency(c, "runtime", "complex64_eq");
  2503. add_package_dependency(c, "runtime", "complex64_ne");
  2504. break;
  2505. case Basic_complex128:
  2506. add_package_dependency(c, "runtime", "complex128_eq");
  2507. add_package_dependency(c, "runtime", "complex128_ne");
  2508. break;
  2509. case Basic_quaternion64:
  2510. add_package_dependency(c, "runtime", "quaternion64_eq");
  2511. add_package_dependency(c, "runtime", "quaternion64_ne");
  2512. break;
  2513. case Basic_quaternion128:
  2514. add_package_dependency(c, "runtime", "quaternion128_eq");
  2515. add_package_dependency(c, "runtime", "quaternion128_ne");
  2516. break;
  2517. case Basic_quaternion256:
  2518. add_package_dependency(c, "runtime", "quaternion256_eq");
  2519. add_package_dependency(c, "runtime", "quaternion256_ne");
  2520. break;
  2521. case Basic_cstring:
  2522. add_package_dependency(c, "runtime", "cstring_eq");
  2523. add_package_dependency(c, "runtime", "cstring_ne");
  2524. break;
  2525. case Basic_string:
  2526. add_package_dependency(c, "runtime", "string_eq");
  2527. add_package_dependency(c, "runtime", "string_ne");
  2528. break;
  2529. case Basic_cstring16:
  2530. add_package_dependency(c, "runtime", "cstring16_eq");
  2531. add_package_dependency(c, "runtime", "cstring16_ne");
  2532. break;
  2533. case Basic_string16:
  2534. add_package_dependency(c, "runtime", "string16_eq");
  2535. add_package_dependency(c, "runtime", "string16_ne");
  2536. break;
  2537. }
  2538. break;
  2539. case Type_Struct:
  2540. for (Entity *field : t->Struct.fields) {
  2541. add_comparison_procedures_for_fields(c, field->type);
  2542. }
  2543. break;
  2544. }
  2545. }
  2546. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2547. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2548. bool comp = are_types_identical(x->type, y->type);
  2549. switch (op) {
  2550. case Token_CmpEq: /* comp = comp; */ break;
  2551. case Token_NotEq: comp = !comp; break;
  2552. }
  2553. x->mode = Addressing_Constant;
  2554. x->type = t_untyped_bool;
  2555. x->value = exact_value_bool(comp);
  2556. return;
  2557. }
  2558. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2559. add_type_info_type(c, x->type);
  2560. add_type_info_type(c, y->type);
  2561. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2562. x->mode = Addressing_Value;
  2563. x->type = t_untyped_bool;
  2564. return;
  2565. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2566. add_type_info_type(c, x->type);
  2567. add_type_info_type(c, y->type);
  2568. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2569. x->mode = Addressing_Value;
  2570. x->type = t_untyped_bool;
  2571. return;
  2572. }
  2573. TEMPORARY_ALLOCATOR_GUARD();
  2574. gbString err_str = nullptr;
  2575. if (check_is_assignable_to(c, x, y->type) ||
  2576. check_is_assignable_to(c, y, x->type)) {
  2577. Type *err_type = x->type;
  2578. bool defined = false;
  2579. switch (op) {
  2580. case Token_CmpEq:
  2581. case Token_NotEq:
  2582. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2583. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2584. (is_operand_nil(*y) && type_has_nil(x->type));
  2585. break;
  2586. case Token_Lt:
  2587. case Token_Gt:
  2588. case Token_LtEq:
  2589. case Token_GtEq:
  2590. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2591. defined = true;
  2592. } else {
  2593. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2594. }
  2595. break;
  2596. }
  2597. if (!defined) {
  2598. gbString xs = type_to_string(x->type, temporary_allocator());
  2599. gbString ys = type_to_string(y->type, temporary_allocator());
  2600. if (!is_type_comparable(x->type)) {
  2601. err_str = gb_string_make(temporary_allocator(),
  2602. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", xs, LIT(token_strings[op]))
  2603. );
  2604. } else if (!is_type_comparable(y->type)) {
  2605. err_str = gb_string_make(temporary_allocator(),
  2606. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", ys, LIT(token_strings[op]))
  2607. );
  2608. } else {
  2609. err_str = gb_string_make(temporary_allocator(),
  2610. gb_bprintf("Operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2611. );
  2612. }
  2613. } else {
  2614. Type *comparison_type = x->type;
  2615. if (x->type == err_type && is_operand_nil(*x)) {
  2616. comparison_type = y->type;
  2617. }
  2618. add_comparison_procedures_for_fields(c, comparison_type);
  2619. }
  2620. } else {
  2621. gbString xt, yt;
  2622. if (x->mode == Addressing_ProcGroup) {
  2623. xt = gb_string_make(temporary_allocator(), "procedure group");
  2624. } else {
  2625. xt = type_to_string(x->type);
  2626. }
  2627. if (y->mode == Addressing_ProcGroup) {
  2628. yt = gb_string_make(temporary_allocator(), "procedure group");
  2629. } else {
  2630. yt = type_to_string(y->type);
  2631. }
  2632. err_str = gb_string_make(temporary_allocator(), gb_bprintf("Mismatched types '%s' and '%s'", xt, yt));
  2633. }
  2634. if (err_str != nullptr) {
  2635. error(node, "Cannot compare expression. %s.", err_str);
  2636. x->type = t_untyped_bool;
  2637. } else {
  2638. if (x->mode == Addressing_Constant &&
  2639. y->mode == Addressing_Constant) {
  2640. if (is_type_constant_type(x->type)) {
  2641. if (is_type_bit_set(x->type)) {
  2642. switch (op) {
  2643. case Token_CmpEq:
  2644. case Token_NotEq:
  2645. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2646. break;
  2647. case Token_Lt:
  2648. case Token_LtEq:
  2649. {
  2650. ExactValue lhs = x->value;
  2651. ExactValue rhs = y->value;
  2652. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2653. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2654. if (op == Token_Lt) {
  2655. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2656. }
  2657. x->value = res;
  2658. break;
  2659. }
  2660. case Token_Gt:
  2661. case Token_GtEq:
  2662. {
  2663. ExactValue lhs = x->value;
  2664. ExactValue rhs = y->value;
  2665. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2666. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2667. if (op == Token_Gt) {
  2668. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2669. }
  2670. x->value = res;
  2671. break;
  2672. }
  2673. }
  2674. } else {
  2675. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2676. }
  2677. } else {
  2678. x->mode = Addressing_Value;
  2679. }
  2680. } else {
  2681. x->mode = Addressing_Value;
  2682. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2683. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2684. i64 size = 0;
  2685. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2686. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2687. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2688. switch (op) {
  2689. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2690. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2691. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2692. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2693. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2694. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2695. }
  2696. } else if (is_type_cstring16(x->type) && is_type_cstring16(y->type)) {
  2697. switch (op) {
  2698. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring16_eq"); break;
  2699. case Token_NotEq: add_package_dependency(c, "runtime", "cstring16_ne"); break;
  2700. case Token_Lt: add_package_dependency(c, "runtime", "cstring16_lt"); break;
  2701. case Token_Gt: add_package_dependency(c, "runtime", "cstring16_gt"); break;
  2702. case Token_LtEq: add_package_dependency(c, "runtime", "cstring16_le"); break;
  2703. case Token_GtEq: add_package_dependency(c, "runtime", "cstring16_gt"); break;
  2704. }
  2705. } else if (is_type_string16(x->type) || is_type_string16(y->type)) {
  2706. switch (op) {
  2707. case Token_CmpEq: add_package_dependency(c, "runtime", "string16_eq"); break;
  2708. case Token_NotEq: add_package_dependency(c, "runtime", "string16_ne"); break;
  2709. case Token_Lt: add_package_dependency(c, "runtime", "string16_lt"); break;
  2710. case Token_Gt: add_package_dependency(c, "runtime", "string16_gt"); break;
  2711. case Token_LtEq: add_package_dependency(c, "runtime", "string16_le"); break;
  2712. case Token_GtEq: add_package_dependency(c, "runtime", "string16_gt"); break;
  2713. }
  2714. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2715. switch (op) {
  2716. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2717. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2718. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2719. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2720. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2721. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2722. }
  2723. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2724. switch (op) {
  2725. case Token_CmpEq:
  2726. switch (8*size) {
  2727. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2728. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2729. }
  2730. break;
  2731. case Token_NotEq:
  2732. switch (8*size) {
  2733. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2734. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2735. }
  2736. break;
  2737. }
  2738. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2739. switch (op) {
  2740. case Token_CmpEq:
  2741. switch (8*size) {
  2742. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2743. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2744. }
  2745. break;
  2746. case Token_NotEq:
  2747. switch (8*size) {
  2748. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2749. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2750. }
  2751. break;
  2752. }
  2753. }
  2754. }
  2755. x->type = t_untyped_bool;
  2756. }
  2757. }
  2758. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2759. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2760. ast_node(be, BinaryExpr, node);
  2761. bool y_is_untyped = is_type_untyped(y->type);
  2762. if (y_is_untyped) {
  2763. convert_to_typed(c, y, t_untyped_integer);
  2764. if (y->mode == Addressing_Invalid) {
  2765. x->mode = Addressing_Invalid;
  2766. return;
  2767. }
  2768. } else if (!is_type_unsigned(y->type)) {
  2769. gbString y_str = expr_to_string(y->expr);
  2770. error(y->expr, "Shift amount '%s' must be an unsigned integer", y_str);
  2771. gb_string_free(y_str);
  2772. x->mode = Addressing_Invalid;
  2773. return;
  2774. }
  2775. bool x_is_untyped = is_type_untyped(x->type);
  2776. if (!(x_is_untyped || is_type_integer(x->type))) {
  2777. gbString x_str = expr_to_string(x->expr);
  2778. error(x->expr, "Shifted operand '%s' must be an integer", x_str);
  2779. gb_string_free(x_str);
  2780. x->mode = Addressing_Invalid;
  2781. return;
  2782. }
  2783. if (y->mode == Addressing_Constant) {
  2784. if (big_int_is_neg(&y->value.value_integer)) {
  2785. gbString y_str = expr_to_string(y->expr);
  2786. error(y->expr, "Shift amount '%s' cannot be negative", y_str);
  2787. gb_string_free(y_str);
  2788. x->mode = Addressing_Invalid;
  2789. return;
  2790. }
  2791. BigInt max_shift = {};
  2792. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2793. if (big_int_cmp(&y->value.value_integer, &max_shift) > 0) {
  2794. gbString y_str = expr_to_string(y->expr);
  2795. error(y->expr, "Shift amount '%s' must be <= %u", y_str, MAX_BIG_INT_SHIFT);
  2796. gb_string_free(y_str);
  2797. x->mode = Addressing_Invalid;
  2798. return;
  2799. }
  2800. if (x->mode == Addressing_Constant) {
  2801. if (x_is_untyped) {
  2802. convert_to_typed(c, x, t_untyped_integer);
  2803. if (x->mode == Addressing_Invalid) {
  2804. return;
  2805. }
  2806. x->expr = node;
  2807. x->value = exact_value_shift(be->op.kind, exact_value_to_integer(x->value), exact_value_to_integer(y->value));
  2808. return;
  2809. }
  2810. x->expr = node;
  2811. x->value = exact_value_shift(be->op.kind, x->value, y->value);
  2812. check_is_expressible(c, x, x->type);
  2813. return;
  2814. }
  2815. if (y_is_untyped) {
  2816. convert_to_typed(c, y, t_uint);
  2817. }
  2818. return;
  2819. }
  2820. if (x->mode == Addressing_Constant) {
  2821. if (x_is_untyped) {
  2822. if (type_hint) {
  2823. if (is_type_integer(type_hint)) {
  2824. convert_to_typed(c, x, type_hint);
  2825. } else if (is_type_any(type_hint)) {
  2826. convert_to_typed(c, x, default_type(t_untyped_integer));
  2827. } else {
  2828. gbString x_str = expr_to_string(x->expr);
  2829. gbString type_str = type_to_string(type_hint);
  2830. error(x->expr, "Shifted operand '%s' cannot convert to non-integer type '%s'", x_str, type_str);
  2831. gb_string_free(x_str);
  2832. gb_string_free(type_str);
  2833. x->mode = Addressing_Invalid;
  2834. return;
  2835. }
  2836. } else {
  2837. check_is_expressible(c, x, default_type(t_untyped_integer));
  2838. }
  2839. if (x->mode == Addressing_Invalid) {
  2840. return;
  2841. }
  2842. }
  2843. x->mode = Addressing_Value;
  2844. }
  2845. }
  2846. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2847. if (check_is_assignable_to(c, operand, y)) {
  2848. return true;
  2849. }
  2850. bool is_constant = operand->mode == Addressing_Constant;
  2851. Type *x = operand->type;
  2852. Type *src = core_type(x);
  2853. Type *dst = core_type(y);
  2854. if (are_types_identical(src, dst)) {
  2855. return true;
  2856. }
  2857. // if (is_type_tuple(src)) {
  2858. // Ast *expr = unparen_expr(operand->expr);
  2859. // if (expr && expr->kind == Ast_CallExpr) {
  2860. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2861. // ast_node(ce, CallExpr, expr);
  2862. // Type *pt = base_type(type_of_expr(ce->proc));
  2863. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2864. // if (pt->Proc.result_count > 0) {
  2865. // Operand op = *operand;
  2866. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2867. // bool ok = check_is_castable_to(c, &op, y);
  2868. // if (ok) {
  2869. // ce->optional_ok_one = true;
  2870. // }
  2871. // return ok;
  2872. // }
  2873. // }
  2874. // }
  2875. // }
  2876. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2877. if (is_type_u8_array(dst)) {
  2878. String s = operand->value.value_string;
  2879. return s.len == dst->Array.count;
  2880. }
  2881. if (is_type_rune_array(dst)) {
  2882. String s = operand->value.value_string;
  2883. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2884. }
  2885. }
  2886. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2887. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2888. return dst->Array.count == src->Array.count;
  2889. }
  2890. }
  2891. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2892. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2893. }
  2894. // Cast between booleans and integers
  2895. if (is_type_boolean(src) || is_type_integer(src)) {
  2896. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2897. return true;
  2898. }
  2899. }
  2900. // Cast between numbers
  2901. if (is_type_integer(src) || is_type_float(src)) {
  2902. if (is_type_integer(dst) || is_type_float(dst)) {
  2903. return true;
  2904. }
  2905. }
  2906. if (is_type_bit_field(src)) {
  2907. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2908. }
  2909. if (is_type_bit_field(dst)) {
  2910. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2911. }
  2912. if (is_type_integer(src) && is_type_rune(dst)) {
  2913. return true;
  2914. }
  2915. if (is_type_rune(src) && is_type_integer(dst)) {
  2916. return true;
  2917. }
  2918. if (is_type_complex(src) && is_type_complex(dst)) {
  2919. return true;
  2920. }
  2921. if (is_type_float(src) && is_type_complex(dst)) {
  2922. return true;
  2923. }
  2924. if (is_type_float(src) && is_type_quaternion(dst)) {
  2925. return true;
  2926. }
  2927. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2928. return true;
  2929. }
  2930. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2931. return true;
  2932. }
  2933. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2934. GB_ASSERT(src->kind == Type_Matrix);
  2935. GB_ASSERT(dst->kind == Type_Matrix);
  2936. Operand op = *operand;
  2937. op.type = src->Matrix.elem;
  2938. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2939. return false;
  2940. }
  2941. if (src->Matrix.row_count != src->Matrix.column_count) {
  2942. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2943. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2944. return src_count == dst_count;
  2945. }
  2946. return is_matrix_square(dst) && is_matrix_square(src);
  2947. }
  2948. // Cast between pointers
  2949. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2950. return true;
  2951. }
  2952. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2953. return true;
  2954. }
  2955. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2956. return true;
  2957. }
  2958. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2959. return true;
  2960. }
  2961. // uintptr <-> pointer
  2962. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2963. return true;
  2964. }
  2965. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2966. return true;
  2967. }
  2968. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2969. return true;
  2970. }
  2971. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2972. return true;
  2973. }
  2974. // []byte/[]u8 <-> string (not cstring)
  2975. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2976. return true;
  2977. }
  2978. // []u16 <-> string16 (not cstring16)
  2979. if (is_type_u16_slice(src) && (is_type_string16(dst) && !is_type_cstring16(dst))) {
  2980. return true;
  2981. }
  2982. // cstring -> string
  2983. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2984. if (operand->mode != Addressing_Constant) {
  2985. add_package_dependency(c, "runtime", "cstring_to_string");
  2986. }
  2987. return true;
  2988. }
  2989. // cstring16 -> string16
  2990. if (are_types_identical(src, t_cstring16) && are_types_identical(dst, t_string16)) {
  2991. if (operand->mode != Addressing_Constant) {
  2992. add_package_dependency(c, "runtime", "cstring16_to_string16");
  2993. }
  2994. return true;
  2995. }
  2996. // cstring -> ^u8
  2997. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2998. return !is_constant;
  2999. }
  3000. // cstring -> [^]u8
  3001. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  3002. return !is_constant;
  3003. }
  3004. // cstring -> rawptr
  3005. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  3006. return !is_constant;
  3007. }
  3008. // ^u8 -> cstring
  3009. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  3010. return !is_constant;
  3011. }
  3012. // [^]u8 -> cstring
  3013. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  3014. return !is_constant;
  3015. }
  3016. // rawptr -> cstring
  3017. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  3018. return !is_constant;
  3019. }
  3020. // cstring -> ^u16
  3021. if (are_types_identical(src, t_cstring16) && is_type_u16_ptr(dst)) {
  3022. return !is_constant;
  3023. }
  3024. // cstring -> [^]u16
  3025. if (are_types_identical(src, t_cstring16) && is_type_u16_multi_ptr(dst)) {
  3026. return !is_constant;
  3027. }
  3028. // cstring16 -> rawptr
  3029. if (are_types_identical(src, t_cstring16) && is_type_rawptr(dst)) {
  3030. return !is_constant;
  3031. }
  3032. // ^u16 -> cstring16
  3033. if (is_type_u16_ptr(src) && are_types_identical(dst, t_cstring16)) {
  3034. return !is_constant;
  3035. }
  3036. // [^]u16 -> cstring
  3037. if (is_type_u16_multi_ptr(src) && are_types_identical(dst, t_cstring16)) {
  3038. return !is_constant;
  3039. }
  3040. // rawptr -> cstring16
  3041. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring16)) {
  3042. return !is_constant;
  3043. }
  3044. // proc <-> proc
  3045. if (is_type_proc(src) && is_type_proc(dst)) {
  3046. if (is_type_polymorphic(dst)) {
  3047. if (is_type_polymorphic(src) &&
  3048. operand->mode == Addressing_Variable) {
  3049. return true;
  3050. }
  3051. return false;
  3052. }
  3053. return true;
  3054. }
  3055. // proc -> rawptr
  3056. if (is_type_proc(src) && is_type_rawptr(dst)) {
  3057. return true;
  3058. }
  3059. // rawptr -> proc
  3060. if (is_type_rawptr(src) && is_type_proc(dst)) {
  3061. return true;
  3062. }
  3063. if (is_type_array(dst)) {
  3064. Type *elem = base_array_type(dst);
  3065. if (check_is_castable_to(c, operand, elem)) {
  3066. return true;
  3067. }
  3068. }
  3069. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  3070. if (src->SimdVector.count != dst->SimdVector.count) {
  3071. return false;
  3072. }
  3073. Type *elem_src = base_array_type(src);
  3074. Type *elem_dst = base_array_type(dst);
  3075. Operand x = {};
  3076. x.type = elem_src;
  3077. x.mode = Addressing_Value;
  3078. return check_is_castable_to(c, &x, elem_dst);
  3079. }
  3080. if (is_type_simd_vector(dst)) {
  3081. Type *elem = base_array_type(dst);
  3082. if (check_is_castable_to(c, operand, elem)) {
  3083. return true;
  3084. }
  3085. }
  3086. return false;
  3087. }
  3088. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  3089. bool is_const_expr = x->mode == Addressing_Constant;
  3090. Type *bt = base_type(type);
  3091. if (is_const_expr && is_type_constant_type(bt)) {
  3092. if (core_type(bt)->kind == Type_Basic) {
  3093. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  3094. return true;
  3095. } else if (check_is_castable_to(c, x, type)) {
  3096. if (is_type_pointer(type)) {
  3097. return true;
  3098. }
  3099. }
  3100. } else if (check_is_castable_to(c, x, type)) {
  3101. x->value = {};
  3102. x->mode = Addressing_Value;
  3103. return true;
  3104. }
  3105. } else if (check_is_castable_to(c, x, type)) {
  3106. if (x->mode != Addressing_Constant) {
  3107. x->mode = Addressing_Value;
  3108. } else if (is_type_slice(type) && is_type_string(x->type)) {
  3109. x->mode = Addressing_Value;
  3110. } else if (is_type_union(type)) {
  3111. if (is_type_union_constantable(type)) {
  3112. return true;
  3113. }
  3114. x->mode = Addressing_Value;
  3115. }
  3116. if (x->mode == Addressing_Value) {
  3117. x->value = {};
  3118. }
  3119. return true;
  3120. }
  3121. return false;
  3122. }
  3123. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type, bool forbid_identical = false) {
  3124. if (!is_operand_value(*x)) {
  3125. error(x->expr, "Only values can be casted");
  3126. x->mode = Addressing_Invalid;
  3127. return;
  3128. }
  3129. bool is_const_expr = x->mode == Addressing_Constant;
  3130. bool can_convert = check_cast_internal(c, x, type);
  3131. if (!can_convert) {
  3132. TEMPORARY_ALLOCATOR_GUARD();
  3133. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  3134. gbString to_type = type_to_string(type, temporary_allocator());
  3135. gbString from_type = type_to_string(x->type, temporary_allocator());
  3136. x->mode = Addressing_Invalid;
  3137. ERROR_BLOCK();
  3138. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  3139. if (is_const_expr) {
  3140. gbString val_str = exact_value_to_string(x->value);
  3141. if (is_type_float(x->type) && is_type_integer(type)) {
  3142. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  3143. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3144. x->mode = Addressing_Constant;
  3145. x->type = type;
  3146. } else {
  3147. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  3148. if (is_type_numeric(type)) {
  3149. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3150. x->mode = Addressing_Constant;
  3151. x->type = type;
  3152. }
  3153. }
  3154. gb_string_free(val_str);
  3155. }
  3156. check_cast_error_suggestion(c, x, type);
  3157. return;
  3158. }
  3159. if (is_type_untyped(x->type)) {
  3160. Type *final_type = type;
  3161. if (is_const_expr && !is_type_constant_type(type)) {
  3162. if (is_type_union(type)) {
  3163. convert_to_typed(c, x, type);
  3164. }
  3165. final_type = default_type(x->type);
  3166. }
  3167. update_untyped_expr_type(c, x->expr, final_type, true);
  3168. } else {
  3169. Type *src = core_type(x->type);
  3170. Type *dst = core_type(type);
  3171. if (src != dst) {
  3172. bool const REQUIRE = true;
  3173. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  3174. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  3175. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  3176. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  3177. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  3178. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  3179. } else if (src == t_f16 && is_type_float(dst)) {
  3180. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  3181. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  3182. } else if (is_type_float(dst) && dst == t_f16) {
  3183. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  3184. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  3185. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  3186. }
  3187. }
  3188. // If we check polymorphic procedures, we risk erring on
  3189. // identical casts that cannot be foreseen or otherwise
  3190. // forbidden, so just skip them.
  3191. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3192. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig))) {
  3193. Type *src_exact = x->type;
  3194. Type *dst_exact = type;
  3195. if (src_exact != nullptr &&
  3196. dst_exact != nullptr &&
  3197. are_types_identical(src_exact, dst_exact)
  3198. ) {
  3199. gbString oper_str = expr_to_string(x->expr);
  3200. gbString to_type = type_to_string(dst_exact);
  3201. error(x->expr, "Unneeded cast of '%s' to identical type '%s'", oper_str, to_type);
  3202. gb_string_free(oper_str);
  3203. gb_string_free(to_type);
  3204. }
  3205. }
  3206. }
  3207. x->type = type;
  3208. }
  3209. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t, bool forbid_identical = false) {
  3210. if (!is_operand_value(*o)) {
  3211. error(o->expr, "'transmute' can only be applied to values");
  3212. o->mode = Addressing_Invalid;
  3213. return false;
  3214. }
  3215. Operand src = *o;
  3216. Type *src_t = o->type;
  3217. Type *dst_t = t;
  3218. Type *src_bt = base_type(src_t);
  3219. Type *dst_bt = base_type(dst_t);
  3220. if (is_type_untyped(src_t)) {
  3221. gbString expr_str = expr_to_string(o->expr);
  3222. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  3223. gb_string_free(expr_str);
  3224. o->mode = Addressing_Invalid;
  3225. o->expr = node;
  3226. return false;
  3227. }
  3228. if (dst_bt == nullptr || dst_bt == t_invalid) {
  3229. GB_ASSERT(global_error_collector.count != 0);
  3230. o->mode = Addressing_Invalid;
  3231. o->expr = node;
  3232. return false;
  3233. }
  3234. if (src_bt == nullptr || src_bt == t_invalid) {
  3235. // NOTE(bill): this should be an error
  3236. GB_ASSERT(global_error_collector.count != 0);
  3237. o->mode = Addressing_Value;
  3238. o->expr = node;
  3239. o->type = dst_t;
  3240. return true;
  3241. }
  3242. i64 srcz = type_size_of(src_t);
  3243. i64 dstz = type_size_of(dst_t);
  3244. if (srcz != dstz) {
  3245. gbString expr_str = expr_to_string(o->expr);
  3246. gbString type_str = type_to_string(dst_t);
  3247. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  3248. gb_string_free(type_str);
  3249. gb_string_free(expr_str);
  3250. o->mode = Addressing_Invalid;
  3251. o->expr = node;
  3252. return false;
  3253. }
  3254. o->expr = node;
  3255. o->type = dst_t;
  3256. if (o->mode == Addressing_Constant) {
  3257. if (are_types_identical(src_bt, dst_bt)) {
  3258. return true;
  3259. }
  3260. if ((is_type_integer(src_t) && is_type_integer(dst_t)) ||
  3261. is_type_integer(src_t) && is_type_bit_set(dst_t)) {
  3262. if (types_have_same_internal_endian(src_t, dst_t)) {
  3263. ExactValue src_v = exact_value_to_integer(o->value);
  3264. GB_ASSERT(src_v.kind == ExactValue_Integer || src_v.kind == ExactValue_Invalid);
  3265. BigInt v = src_v.value_integer;
  3266. BigInt smax = {};
  3267. BigInt umax = {};
  3268. big_int_from_u64(&smax, 0);
  3269. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  3270. big_int_from_u64(&umax, 1);
  3271. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  3272. big_int_shl_eq(&umax, &sz_in_bits);
  3273. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  3274. if (big_int_cmp(&v, &smax) >= 0) {
  3275. big_int_sub_eq(&v, &umax);
  3276. }
  3277. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  3278. if (big_int_is_neg(&v)) {
  3279. big_int_add_eq(&v, &umax);
  3280. }
  3281. }
  3282. o->value.kind = ExactValue_Integer;
  3283. o->value.value_integer = v;
  3284. return true;
  3285. }
  3286. }
  3287. } else {
  3288. // If we check polymorphic procedures, we risk erring on
  3289. // identical casts that cannot be foreseen or otherwise
  3290. // forbidden, so just skip them.
  3291. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3292. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig)) &&
  3293. check_is_castable_to(c, &src, dst_t)) {
  3294. if (are_types_identical(src_t, dst_t)) {
  3295. gbString oper_str = expr_to_string(o->expr);
  3296. gbString to_type = type_to_string(dst_t);
  3297. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3298. gb_string_free(oper_str);
  3299. gb_string_free(to_type);
  3300. } else if (is_type_internally_pointer_like(src_t) &&
  3301. is_type_internally_pointer_like(dst_t)) {
  3302. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since the types are pointer-like");
  3303. } else if (are_types_identical(src_bt, dst_bt)) {
  3304. gbString oper_str = expr_to_string(o->expr);
  3305. gbString to_type = type_to_string(dst_t);
  3306. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3307. gb_string_free(oper_str);
  3308. gb_string_free(to_type);
  3309. } else if (is_type_integer(src_t) && is_type_integer(dst_t) &&
  3310. types_have_same_internal_endian(src_t, dst_t) &&
  3311. type_endian_kind_of(src_t) == type_endian_kind_of(dst_t)) {
  3312. gbString oper_type = type_to_string(src_t);
  3313. gbString to_type = type_to_string(dst_t);
  3314. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since both are integers of the same endianness, from '%s' to '%s'", oper_type, to_type);
  3315. gb_string_free(to_type);
  3316. gb_string_free(oper_type);
  3317. }
  3318. }
  3319. }
  3320. o->mode = Addressing_Value;
  3321. o->value = {};
  3322. return true;
  3323. }
  3324. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  3325. if (is_type_array_like(x->type) || is_type_array_like(y->type)) {
  3326. if (op.kind == Token_CmpAnd || op.kind == Token_CmpOr) {
  3327. error(op, "Array programming is not allowed with the operator '%.*s'", LIT(op.string));
  3328. }
  3329. }
  3330. if (is_type_array(x->type) && !is_type_array(y->type)) {
  3331. if (check_is_assignable_to(c, y, x->type)) {
  3332. if (check_binary_op(c, x, op)) {
  3333. return true;
  3334. }
  3335. }
  3336. }
  3337. if (is_type_simd_vector(x->type) && !is_type_simd_vector(y->type)) {
  3338. if (check_is_assignable_to(c, y, x->type)) {
  3339. if (check_binary_op(c, x, op)) {
  3340. return true;
  3341. }
  3342. }
  3343. }
  3344. return false;
  3345. }
  3346. gb_internal bool is_ise_expr(Ast *node) {
  3347. node = unparen_expr(node);
  3348. return node->kind == Ast_ImplicitSelectorExpr;
  3349. }
  3350. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  3351. if (use_lhs_as_type_hint) { // RHS in this case
  3352. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  3353. }
  3354. return false;
  3355. }
  3356. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  3357. Type *xt = base_type(matrix);
  3358. if (type_hint != nullptr) {
  3359. Type *th = base_type(type_hint);
  3360. if (are_types_identical(th, xt)) {
  3361. return type_hint;
  3362. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  3363. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  3364. // ignore
  3365. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  3366. xt->Matrix.column_count == th->Matrix.column_count) {
  3367. return type_hint;
  3368. }
  3369. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  3370. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  3371. // ignore
  3372. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  3373. return type_hint;
  3374. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3375. return type_hint;
  3376. }
  3377. }
  3378. }
  3379. return matrix;
  3380. }
  3381. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3382. if (!check_binary_op(c, x, op)) {
  3383. x->mode = Addressing_Invalid;
  3384. return;
  3385. }
  3386. Type *xt = base_type(x->type);
  3387. Type *yt = base_type(y->type);
  3388. if (is_type_matrix(x->type)) {
  3389. GB_ASSERT(xt->kind == Type_Matrix);
  3390. if (op.kind == Token_Mul) {
  3391. if (yt->kind == Type_Matrix) {
  3392. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3393. goto matrix_error;
  3394. }
  3395. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3396. goto matrix_error;
  3397. }
  3398. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3399. goto matrix_error;
  3400. }
  3401. x->mode = Addressing_Value;
  3402. if (are_types_identical(xt, yt)) {
  3403. if (are_types_identical(x->type, y->type)) {
  3404. return;
  3405. }
  3406. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3407. // prefer the named type
  3408. x->type = y->type;
  3409. }
  3410. } else {
  3411. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3412. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3413. }
  3414. goto matrix_success;
  3415. } else if (yt->kind == Type_Array) {
  3416. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3417. goto matrix_error;
  3418. }
  3419. if (xt->Matrix.column_count != yt->Array.count) {
  3420. goto matrix_error;
  3421. }
  3422. // Treat arrays as column vectors
  3423. x->mode = Addressing_Value;
  3424. if (xt->Matrix.row_count == yt->Array.count) {
  3425. x->type = y->type;
  3426. } else {
  3427. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3428. }
  3429. goto matrix_success;
  3430. }
  3431. }
  3432. if (!are_types_identical(xt, yt)) {
  3433. goto matrix_error;
  3434. }
  3435. x->mode = Addressing_Value;
  3436. x->type = xt;
  3437. goto matrix_success;
  3438. } else {
  3439. GB_ASSERT(!is_type_matrix(xt));
  3440. GB_ASSERT(is_type_matrix(yt));
  3441. if (op.kind == Token_Mul) {
  3442. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3443. if (xt->kind == Type_Array) {
  3444. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3445. goto matrix_error;
  3446. }
  3447. if (xt->Array.count != yt->Matrix.row_count) {
  3448. goto matrix_error;
  3449. }
  3450. // Treat arrays as row vectors
  3451. x->mode = Addressing_Value;
  3452. if (yt->Matrix.column_count == xt->Array.count) {
  3453. x->type = x->type;
  3454. } else {
  3455. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3456. }
  3457. goto matrix_success;
  3458. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3459. x->type = check_matrix_type_hint(y->type, type_hint);
  3460. return;
  3461. }
  3462. }
  3463. if (!are_types_identical(xt, yt)) {
  3464. goto matrix_error;
  3465. }
  3466. x->mode = Addressing_Value;
  3467. x->type = xt;
  3468. goto matrix_success;
  3469. }
  3470. matrix_success:
  3471. x->type = check_matrix_type_hint(x->type, type_hint);
  3472. return;
  3473. matrix_error:
  3474. gbString xts = type_to_string(x->type);
  3475. gbString yts = type_to_string(y->type);
  3476. gbString expr_str = expr_to_string(x->expr);
  3477. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3478. gb_string_free(expr_str);
  3479. gb_string_free(yts);
  3480. gb_string_free(xts);
  3481. x->type = t_invalid;
  3482. x->mode = Addressing_Invalid;
  3483. return;
  3484. }
  3485. gb_internal void check_binary_expr_dependency(CheckerContext *c, Token op, Type *bt, bool REQUIRE) {
  3486. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3487. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3488. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3489. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3490. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3491. }
  3492. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3493. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3494. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3495. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3496. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3497. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3498. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3499. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3500. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3501. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3502. }
  3503. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3504. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3505. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3506. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3507. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3508. case Basic_u128:
  3509. case Basic_i128:
  3510. if (is_arch_wasm()) {
  3511. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3512. }
  3513. break;
  3514. }
  3515. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3516. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3517. case Basic_u128:
  3518. case Basic_i128:
  3519. if (is_arch_wasm()) {
  3520. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3521. }
  3522. break;
  3523. }
  3524. } else if (op.kind == Token_Shr || op.kind == Token_ShrEq) {
  3525. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3526. case Basic_u128:
  3527. case Basic_i128:
  3528. if (is_arch_wasm()) {
  3529. add_package_dependency(c, "runtime", "__lshrti3", REQUIRE);
  3530. }
  3531. break;
  3532. }
  3533. }
  3534. }
  3535. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3536. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3537. Operand y_ = {}, *y = &y_;
  3538. ast_node(be, BinaryExpr, node);
  3539. defer({
  3540. node->viral_state_flags |= be->left->viral_state_flags;
  3541. node->viral_state_flags |= be->right->viral_state_flags;
  3542. });
  3543. Token op = be->op;
  3544. switch (op.kind) {
  3545. case Token_CmpEq:
  3546. case Token_NotEq: {
  3547. // NOTE(bill): Allow comparisons between types
  3548. if (is_ise_expr(be->left)) {
  3549. // Evalute the right before the left for an '.X' expression
  3550. check_expr_or_type(c, y, be->right, nullptr /* ignore type hint */);
  3551. check_expr_or_type(c, x, be->left, y->type);
  3552. } else {
  3553. check_expr_or_type(c, x, be->left, nullptr /* ignore type hint */);
  3554. check_expr_or_type(c, y, be->right, x->type);
  3555. }
  3556. bool xt = x->mode == Addressing_Type;
  3557. bool yt = y->mode == Addressing_Type;
  3558. // If only one is a type, this is an error
  3559. if (xt ^ yt) {
  3560. GB_ASSERT(xt != yt);
  3561. if (xt) {
  3562. if (!is_type_typeid(y->type)) {
  3563. error_operand_not_expression(x);
  3564. }
  3565. }
  3566. if (yt) {
  3567. if (!is_type_typeid(x->type)) {
  3568. error_operand_not_expression(y);
  3569. }
  3570. }
  3571. }
  3572. break;
  3573. }
  3574. case Token_in:
  3575. case Token_not_in:
  3576. {
  3577. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3578. check_expr(c, y, be->right);
  3579. Type *rhs_type = type_deref(y->type);
  3580. if (rhs_type == nullptr) {
  3581. error(y->expr, "Cannot use '%.*s' on an expression with no value", LIT(op.string));
  3582. x->mode = Addressing_Invalid;
  3583. x->expr = node;
  3584. return;
  3585. }
  3586. if (is_type_bit_set(rhs_type)) {
  3587. Type *elem = base_type(rhs_type)->BitSet.elem;
  3588. check_expr_with_type_hint(c, x, be->left, elem);
  3589. } else if (is_type_map(rhs_type)) {
  3590. Type *key = base_type(rhs_type)->Map.key;
  3591. check_expr_with_type_hint(c, x, be->left, key);
  3592. } else {
  3593. check_expr(c, x, be->left);
  3594. }
  3595. if (x->mode == Addressing_Invalid) {
  3596. return;
  3597. }
  3598. if (y->mode == Addressing_Invalid) {
  3599. x->mode = Addressing_Invalid;
  3600. x->expr = y->expr;
  3601. return;
  3602. }
  3603. if (is_type_map(rhs_type)) {
  3604. Type *yt = base_type(rhs_type);
  3605. if (op.kind == Token_in) {
  3606. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3607. } else {
  3608. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3609. }
  3610. add_map_get_dependencies(c);
  3611. } else if (is_type_bit_set(rhs_type)) {
  3612. Type *yt = base_type(rhs_type);
  3613. if (op.kind == Token_in) {
  3614. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3615. } else {
  3616. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3617. }
  3618. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3619. ExactValue k = exact_value_to_integer(x->value);
  3620. ExactValue v = exact_value_to_integer(y->value);
  3621. GB_ASSERT(k.kind == ExactValue_Integer);
  3622. GB_ASSERT(v.kind == ExactValue_Integer);
  3623. i64 key = big_int_to_i64(&k.value_integer);
  3624. i64 lower = yt->BitSet.lower;
  3625. i64 upper = yt->BitSet.upper;
  3626. if (lower <= key && key <= upper) {
  3627. i64 bit = 1ll<<key;
  3628. i64 bits = big_int_to_i64(&v.value_integer);
  3629. x->mode = Addressing_Constant;
  3630. x->type = t_untyped_bool;
  3631. if (op.kind == Token_in) {
  3632. x->value = exact_value_bool((bit & bits) != 0);
  3633. } else {
  3634. x->value = exact_value_bool((bit & bits) == 0);
  3635. }
  3636. x->expr = node;
  3637. return;
  3638. } else {
  3639. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3640. x->mode = Addressing_Invalid;
  3641. }
  3642. }
  3643. } else {
  3644. gbString t = type_to_string(y->type);
  3645. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3646. gb_string_free(t);
  3647. x->expr = node;
  3648. x->mode = Addressing_Invalid;
  3649. return;
  3650. }
  3651. if (x->mode != Addressing_Invalid) {
  3652. x->mode = Addressing_Value;
  3653. x->type = t_untyped_bool;
  3654. }
  3655. x->expr = node;
  3656. return;
  3657. }
  3658. default:
  3659. if (is_ise_expr(be->left)) {
  3660. // Evalute the right before the left for an '.X' expression
  3661. check_expr_or_type(c, y, be->right, type_hint);
  3662. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3663. check_expr_or_type(c, x, be->left, y->type);
  3664. } else {
  3665. check_expr_with_type_hint(c, x, be->left, type_hint);
  3666. }
  3667. } else {
  3668. check_expr_with_type_hint(c, x, be->left, type_hint);
  3669. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3670. check_expr_with_type_hint(c, y, be->right, x->type);
  3671. } else {
  3672. check_expr_with_type_hint(c, y, be->right, type_hint);
  3673. }
  3674. }
  3675. break;
  3676. }
  3677. if (x->mode == Addressing_Invalid) {
  3678. return;
  3679. }
  3680. if (y->mode == Addressing_Invalid) {
  3681. x->mode = Addressing_Invalid;
  3682. x->expr = y->expr;
  3683. return;
  3684. }
  3685. if (x->mode == Addressing_Builtin) {
  3686. x->mode = Addressing_Invalid;
  3687. error(x->expr, "built-in expression in binary expression");
  3688. return;
  3689. }
  3690. if (y->mode == Addressing_Builtin) {
  3691. x->mode = Addressing_Invalid;
  3692. error(y->expr, "built-in expression in binary expression");
  3693. return;
  3694. }
  3695. if (x->mode == Addressing_ProcGroup) {
  3696. x->mode = Addressing_Invalid;
  3697. if (x->proc_group != nullptr) {
  3698. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3699. } else {
  3700. error(x->expr, "procedure group used in binary expression");
  3701. }
  3702. return;
  3703. }
  3704. if (y->mode == Addressing_ProcGroup) {
  3705. x->mode = Addressing_Invalid;
  3706. if (x->proc_group != nullptr) {
  3707. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3708. } else {
  3709. error(y->expr, "procedure group used in binary expression");
  3710. }
  3711. return;
  3712. }
  3713. bool REQUIRE = true;
  3714. Type *btx = base_type(x->type);
  3715. Type *bty = base_type(y->type);
  3716. check_binary_expr_dependency(c, op, btx, REQUIRE);
  3717. check_binary_expr_dependency(c, op, bty, REQUIRE);
  3718. if (token_is_shift(op.kind)) {
  3719. check_shift(c, x, y, node, type_hint);
  3720. return;
  3721. }
  3722. switch (op.kind) {
  3723. case Token_Quo:
  3724. case Token_Mod:
  3725. case Token_ModMod:
  3726. case Token_QuoEq:
  3727. case Token_ModEq:
  3728. case Token_ModModEq:
  3729. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3730. is_type_float(x->type) && is_type_untyped(x->type)) {
  3731. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3732. gbString t = type_to_string(y->type);
  3733. if (x->value.kind != ExactValue_Invalid) {
  3734. gbString s = exact_value_to_string(x->value);
  3735. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3736. gb_string_free(s);
  3737. } else {
  3738. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3739. }
  3740. gb_string_free(t);
  3741. }
  3742. break;
  3743. }
  3744. convert_to_typed(c, x, y->type);
  3745. if (x->mode == Addressing_Invalid) {
  3746. return;
  3747. }
  3748. convert_to_typed(c, y, x->type);
  3749. if (y->mode == Addressing_Invalid) {
  3750. x->mode = Addressing_Invalid;
  3751. return;
  3752. }
  3753. if (token_is_comparison(op.kind)) {
  3754. check_comparison(c, node, x, y, op.kind);
  3755. return;
  3756. }
  3757. if (check_binary_array_expr(c, op, x, y)) {
  3758. x->mode = Addressing_Value;
  3759. x->type = x->type;
  3760. return;
  3761. }
  3762. if (check_binary_array_expr(c, op, y, x)) {
  3763. x->mode = Addressing_Value;
  3764. x->type = y->type;
  3765. return;
  3766. }
  3767. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3768. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3769. x->expr = node;
  3770. return;
  3771. }
  3772. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3773. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3774. // NOTE(bill, 2022-06-26)
  3775. // Allow any boolean types within `&&` and `||`
  3776. // This is an exception to all other binary expressions since the result
  3777. // of a comparison will always be an untyped boolean, and allowing
  3778. // any boolean between these two simplifies a lot of expressions
  3779. } else if (!are_types_identical(x->type, y->type)) {
  3780. if (x->type != t_invalid &&
  3781. y->type != t_invalid) {
  3782. gbString xt = type_to_string(x->type);
  3783. gbString yt = type_to_string(y->type);
  3784. gbString expr_str = expr_to_string(node);
  3785. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3786. gb_string_free(expr_str);
  3787. gb_string_free(yt);
  3788. gb_string_free(xt);
  3789. }
  3790. x->mode = Addressing_Invalid;
  3791. return;
  3792. }
  3793. if (!check_binary_op(c, x, op)) {
  3794. x->mode = Addressing_Invalid;
  3795. return;
  3796. }
  3797. switch (op.kind) {
  3798. case Token_Quo:
  3799. case Token_Mod:
  3800. case Token_ModMod:
  3801. case Token_QuoEq:
  3802. case Token_ModEq:
  3803. case Token_ModModEq:
  3804. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3805. y->mode == Addressing_Constant) {
  3806. bool fail = false;
  3807. switch (y->value.kind) {
  3808. case ExactValue_Integer:
  3809. if (big_int_is_zero(&y->value.value_integer)) {
  3810. fail = true;
  3811. }
  3812. break;
  3813. case ExactValue_Float:
  3814. if (y->value.value_float == 0.0) {
  3815. fail = true;
  3816. }
  3817. break;
  3818. }
  3819. if (fail) {
  3820. if (is_type_integer(x->type) || (x->mode == Addressing_Constant && x->value.kind == ExactValue_Integer)) {
  3821. if (check_for_integer_division_by_zero(c, node) != IntegerDivisionByZero_Trap) {
  3822. // Okay
  3823. break;
  3824. }
  3825. }
  3826. switch (op.kind) {
  3827. case Token_Mod:
  3828. case Token_ModMod:
  3829. case Token_ModEq:
  3830. case Token_ModModEq:
  3831. error(y->expr, "Division by zero through '%.*s' not allowed", LIT(token_strings[op.kind]));
  3832. break;
  3833. case Token_Quo:
  3834. case Token_QuoEq:
  3835. error(y->expr, "Division by zero not allowed");
  3836. break;
  3837. }
  3838. x->mode = Addressing_Invalid;
  3839. return;
  3840. }
  3841. }
  3842. break;
  3843. case Token_CmpAnd:
  3844. case Token_CmpOr:
  3845. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3846. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3847. }
  3848. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3849. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3850. }
  3851. break;
  3852. }
  3853. if (x->mode == Addressing_Constant &&
  3854. y->mode == Addressing_Constant) {
  3855. ExactValue a = x->value;
  3856. ExactValue b = y->value;
  3857. if (!is_type_constant_type(x->type)) {
  3858. x->mode = Addressing_Value;
  3859. return;
  3860. }
  3861. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3862. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3863. }
  3864. if (is_type_bit_set(x->type)) {
  3865. switch (op.kind) {
  3866. case Token_Add: op.kind = Token_Or; break;
  3867. case Token_Sub: op.kind = Token_AndNot; break;
  3868. }
  3869. }
  3870. match_exact_values(&a, &b);
  3871. IntegerDivisionByZeroKind zero_behaviour = check_for_integer_division_by_zero(c, node);
  3872. if (zero_behaviour != IntegerDivisionByZero_Trap &&
  3873. b.kind == ExactValue_Integer && big_int_is_zero(&b.value_integer) &&
  3874. (op.kind == Token_QuoEq || op.kind == Token_Mod || op.kind == Token_ModMod)) {
  3875. if (op.kind == Token_QuoEq) {
  3876. switch (zero_behaviour) {
  3877. case IntegerDivisionByZero_Zero:
  3878. // x/0 == 0
  3879. x->value = b;
  3880. break;
  3881. case IntegerDivisionByZero_Self:
  3882. // x/0 == x
  3883. x->value = a;
  3884. break;
  3885. case IntegerDivisionByZero_AllBits:
  3886. // x/0 == 0b111...111
  3887. if (is_type_untyped(x->type)) {
  3888. x->value = exact_value_i64(-1);
  3889. } else {
  3890. x->value = exact_unary_operator_value(Token_Xor, b, cast(i32)(8*type_size_of(x->type)), is_type_unsigned(x->type));
  3891. }
  3892. break;
  3893. }
  3894. } else {
  3895. /*
  3896. NOTE(bill): @integer division by zero rules
  3897. truncated: r = a - b*trunc(a/b)
  3898. floored: r = a - b*floor(a/b)
  3899. IFF a/0 == 0, then (a%0 == a) or (a%%0 == a)
  3900. IFF a/0 == a, then (a%0 == 0) or (a%%0 == 0)
  3901. IFF a/0 == 0b111..., then (a%0 == a) or (a%%0 == a)
  3902. */
  3903. switch (zero_behaviour) {
  3904. case IntegerDivisionByZero_Zero:
  3905. case IntegerDivisionByZero_AllBits:
  3906. // x%0 == x
  3907. x->value = a;
  3908. break;
  3909. case IntegerDivisionByZero_Self:
  3910. // x%0 == 0
  3911. x->value = b;
  3912. break;
  3913. }
  3914. }
  3915. } else {
  3916. x->value = exact_binary_operator_value(op.kind, a, b);
  3917. }
  3918. if (is_type_typed(x->type)) {
  3919. if (node != nullptr) {
  3920. x->expr = node;
  3921. }
  3922. check_is_expressible(c, x, x->type);
  3923. }
  3924. return;
  3925. } else if (is_type_string(x->type)) {
  3926. error(node, "String concatenation is only allowed with constant strings");
  3927. x->mode = Addressing_Invalid;
  3928. return;
  3929. }
  3930. x->mode = Addressing_Value;
  3931. }
  3932. gb_internal Operand make_operand_from_node(Ast *node) {
  3933. GB_ASSERT(node != nullptr);
  3934. Operand x = {};
  3935. x.expr = node;
  3936. x.mode = node->tav.mode;
  3937. x.type = node->tav.type;
  3938. x.value = node->tav.value;
  3939. return x;
  3940. }
  3941. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3942. GB_ASSERT(e != nullptr);
  3943. ExprInfo *old = check_get_expr_info(c, e);
  3944. if (old == nullptr) {
  3945. if (type != nullptr && type != t_invalid) {
  3946. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3947. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3948. if (e->kind == Ast_TernaryIfExpr) {
  3949. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3950. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3951. }
  3952. }
  3953. }
  3954. return;
  3955. }
  3956. switch (e->kind) {
  3957. case_ast_node(ue, UnaryExpr, e);
  3958. if (old->value.kind != ExactValue_Invalid) {
  3959. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3960. // They don't need to be updated as they will be updated later and
  3961. // checked at the end of general checking stage.
  3962. break;
  3963. }
  3964. update_untyped_expr_type(c, ue->expr, type, final);
  3965. case_end;
  3966. case_ast_node(be, BinaryExpr, e);
  3967. if (old->value.kind != ExactValue_Invalid) {
  3968. // See above note in UnaryExpr case
  3969. break;
  3970. }
  3971. if (token_is_comparison(be->op.kind)) {
  3972. // NOTE(bill): Do nothing as the types are fine
  3973. } else if (token_is_shift(be->op.kind)) {
  3974. update_untyped_expr_type(c, be->left, type, final);
  3975. } else {
  3976. update_untyped_expr_type(c, be->left, type, final);
  3977. update_untyped_expr_type(c, be->right, type, final);
  3978. }
  3979. case_end;
  3980. case_ast_node(te, TernaryIfExpr, e);
  3981. if (old->value.kind != ExactValue_Invalid) {
  3982. // See above note in UnaryExpr case
  3983. break;
  3984. }
  3985. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3986. // having an untyped value
  3987. Operand x = make_operand_from_node(te->x);
  3988. Operand y = make_operand_from_node(te->y);
  3989. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3990. update_untyped_expr_type(c, te->x, type, final);
  3991. }
  3992. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3993. update_untyped_expr_type(c, te->y, type, final);
  3994. }
  3995. case_end;
  3996. case_ast_node(te, TernaryWhenExpr, e);
  3997. if (old->value.kind != ExactValue_Invalid) {
  3998. // See above note in UnaryExpr case
  3999. break;
  4000. }
  4001. update_untyped_expr_type(c, te->x, type, final);
  4002. update_untyped_expr_type(c, te->y, type, final);
  4003. case_end;
  4004. case_ast_node(ore, OrReturnExpr, e);
  4005. if (old->value.kind != ExactValue_Invalid) {
  4006. // See above note in UnaryExpr case
  4007. break;
  4008. }
  4009. update_untyped_expr_type(c, ore->expr, type, final);
  4010. case_end;
  4011. case_ast_node(obe, OrBranchExpr, e);
  4012. if (old->value.kind != ExactValue_Invalid) {
  4013. // See above note in UnaryExpr case
  4014. break;
  4015. }
  4016. update_untyped_expr_type(c, obe->expr, type, final);
  4017. case_end;
  4018. case_ast_node(oee, OrElseExpr, e);
  4019. if (old->value.kind != ExactValue_Invalid) {
  4020. // See above note in UnaryExpr case
  4021. break;
  4022. }
  4023. update_untyped_expr_type(c, oee->x, type, final);
  4024. update_untyped_expr_type(c, oee->y, type, final);
  4025. case_end;
  4026. case_ast_node(pe, ParenExpr, e);
  4027. update_untyped_expr_type(c, pe->expr, type, final);
  4028. case_end;
  4029. }
  4030. if (!final && is_type_untyped(type)) {
  4031. old->type = base_type(type);
  4032. return;
  4033. }
  4034. // We need to remove it and then give it a new one
  4035. check_remove_expr_info(c, e);
  4036. if (old->is_lhs && !is_type_integer(type)) {
  4037. gbString expr_str = expr_to_string(e);
  4038. gbString type_str = type_to_string(type);
  4039. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  4040. gb_string_free(type_str);
  4041. gb_string_free(expr_str);
  4042. return;
  4043. }
  4044. add_type_and_value(c, e, old->mode, type, old->value);
  4045. }
  4046. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  4047. GB_ASSERT(e != nullptr);
  4048. ExprInfo *found = check_get_expr_info(c, e);
  4049. if (found) {
  4050. found->value = value;
  4051. }
  4052. }
  4053. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type, bool ignore_error_block=false) {
  4054. gbString expr_str = expr_to_string(operand->expr);
  4055. gbString type_str = type_to_string(target_type);
  4056. gbString from_type_str = type_to_string(operand->type);
  4057. char const *extra_text = "";
  4058. if (operand->mode == Addressing_Constant) {
  4059. if (big_int_is_zero(&operand->value.value_integer)) {
  4060. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  4061. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  4062. extra_text = " - Did you want 'nil'?";
  4063. }
  4064. }
  4065. }
  4066. if (!ignore_error_block) {
  4067. begin_error_block();
  4068. }
  4069. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  4070. if (operand->value.kind == ExactValue_String) {
  4071. String key = operand->value.value_string;
  4072. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  4073. Type *et = base_type(target_type);
  4074. check_did_you_mean_type(key, et->Enum.fields, ".");
  4075. }
  4076. }
  4077. gb_string_free(from_type_str);
  4078. gb_string_free(type_str);
  4079. gb_string_free(expr_str);
  4080. operand->mode = Addressing_Invalid;
  4081. if (!ignore_error_block) {
  4082. end_error_block();
  4083. }
  4084. }
  4085. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  4086. Type *t = core_type(type);
  4087. if (is_type_boolean(t)) {
  4088. // v = exact_value_to_boolean(v);
  4089. } else if (is_type_float(t)) {
  4090. v = exact_value_to_float(v);
  4091. } else if (is_type_integer(t)) {
  4092. v = exact_value_to_integer(v);
  4093. } else if (is_type_pointer(t)) {
  4094. v = exact_value_to_integer(v);
  4095. } else if (is_type_complex(t)) {
  4096. v = exact_value_to_complex(v);
  4097. } else if (is_type_quaternion(t)) {
  4098. v = exact_value_to_quaternion(v);
  4099. }
  4100. return v;
  4101. }
  4102. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  4103. if (target_type == nullptr || operand->mode == Addressing_Invalid ||
  4104. operand->mode == Addressing_Type ||
  4105. is_type_typed(operand->type) ||
  4106. target_type == t_invalid) {
  4107. return;
  4108. }
  4109. if (is_type_untyped(target_type)) {
  4110. GB_ASSERT(operand->type->kind == Type_Basic);
  4111. GB_ASSERT(target_type->kind == Type_Basic);
  4112. BasicKind x_kind = operand->type->Basic.kind;
  4113. BasicKind y_kind = target_type->Basic.kind;
  4114. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  4115. if (x_kind < y_kind) {
  4116. operand->type = target_type;
  4117. update_untyped_expr_type(c, operand->expr, target_type, false);
  4118. }
  4119. } else if (x_kind != y_kind) {
  4120. operand->mode = Addressing_Invalid;
  4121. convert_untyped_error(c, operand, target_type);
  4122. return;
  4123. }
  4124. return;
  4125. }
  4126. Type *t = base_type(target_type);
  4127. if (c->in_enum_type) {
  4128. t = core_type(target_type);
  4129. }
  4130. switch (t->kind) {
  4131. case Type_Basic:
  4132. if (operand->mode == Addressing_Constant) {
  4133. check_is_expressible(c, operand, t);
  4134. if (operand->mode == Addressing_Invalid) {
  4135. return;
  4136. }
  4137. update_untyped_expr_value(c, operand->expr, operand->value);
  4138. } else {
  4139. switch (operand->type->Basic.kind) {
  4140. case Basic_UntypedBool:
  4141. if (!is_type_boolean(target_type)) {
  4142. operand->mode = Addressing_Invalid;
  4143. convert_untyped_error(c, operand, target_type);
  4144. return;
  4145. }
  4146. break;
  4147. case Basic_UntypedInteger:
  4148. case Basic_UntypedFloat:
  4149. case Basic_UntypedComplex:
  4150. case Basic_UntypedQuaternion:
  4151. case Basic_UntypedRune:
  4152. if (!is_type_numeric(target_type)) {
  4153. operand->mode = Addressing_Invalid;
  4154. convert_untyped_error(c, operand, target_type);
  4155. return;
  4156. }
  4157. break;
  4158. case Basic_UntypedNil:
  4159. if (is_type_any(target_type)) {
  4160. // target_type = t_untyped_nil;
  4161. } else if (is_type_cstring(target_type)) {
  4162. // target_type = t_untyped_nil;
  4163. } else if (is_type_cstring16(target_type)) {
  4164. // target_type = t_untyped_nil;
  4165. } else if (!type_has_nil(target_type)) {
  4166. operand->mode = Addressing_Invalid;
  4167. convert_untyped_error(c, operand, target_type);
  4168. return;
  4169. }
  4170. break;
  4171. }
  4172. }
  4173. break;
  4174. case Type_Array: {
  4175. Type *elem = base_array_type(t);
  4176. if (check_is_assignable_to(c, operand, elem)) {
  4177. operand->mode = Addressing_Value;
  4178. } else {
  4179. if (operand->value.kind == ExactValue_String) {
  4180. String s = operand->value.value_string;
  4181. if (is_type_u8_array(t)) {
  4182. if (s.len == t->Array.count) {
  4183. break;
  4184. }
  4185. } else if (is_type_rune_array(t)) {
  4186. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  4187. if (rune_count == t->Array.count) {
  4188. break;
  4189. }
  4190. }
  4191. } else if (operand->value.kind == ExactValue_String16) {
  4192. String16 s = operand->value.value_string16;
  4193. if (is_type_u16_array(t)) {
  4194. if (s.len == t->Array.count) {
  4195. break;
  4196. }
  4197. }
  4198. }
  4199. operand->mode = Addressing_Invalid;
  4200. convert_untyped_error(c, operand, target_type);
  4201. return;
  4202. }
  4203. break;
  4204. }
  4205. case Type_SimdVector: {
  4206. Type *elem = base_array_type(t);
  4207. if (check_is_assignable_to(c, operand, elem)) {
  4208. operand->mode = Addressing_Value;
  4209. } else {
  4210. operand->mode = Addressing_Invalid;
  4211. convert_untyped_error(c, operand, target_type);
  4212. return;
  4213. }
  4214. break;
  4215. }
  4216. case Type_Matrix: {
  4217. Type *elem = base_array_type(t);
  4218. if (check_is_assignable_to(c, operand, elem)) {
  4219. if (t->Matrix.row_count != t->Matrix.column_count) {
  4220. operand->mode = Addressing_Invalid;
  4221. ERROR_BLOCK();
  4222. convert_untyped_error(c, operand, target_type, true);
  4223. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  4224. return;
  4225. } else {
  4226. operand->mode = Addressing_Value;
  4227. }
  4228. } else {
  4229. operand->mode = Addressing_Invalid;
  4230. convert_untyped_error(c, operand, target_type);
  4231. return;
  4232. }
  4233. break;
  4234. }
  4235. case Type_Union:
  4236. // IMPORTANT NOTE HACK(bill): This is just to allow for comparisons against `0` with the `os.Error` type
  4237. // as a kind of transition period
  4238. if (!build_context.strict_style &&
  4239. operand->mode == Addressing_Constant &&
  4240. target_type->kind == Type_Named &&
  4241. (c->pkg == nullptr || c->pkg->name != "os") &&
  4242. target_type->Named.name == "Error") {
  4243. Entity *e = target_type->Named.type_name;
  4244. if (e->pkg && e->pkg->name == "os") {
  4245. if (is_exact_value_zero(operand->value) &&
  4246. (operand->value.kind == ExactValue_Integer ||
  4247. operand->value.kind == ExactValue_Float)) {
  4248. operand->mode = Addressing_Value;
  4249. // target_type = t_untyped_nil;
  4250. operand->value = empty_exact_value;
  4251. update_untyped_expr_value(c, operand->expr, operand->value);
  4252. break;
  4253. }
  4254. }
  4255. }
  4256. // "fallthrough"
  4257. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  4258. TEMPORARY_ALLOCATOR_GUARD();
  4259. isize count = t->Union.variants.count;
  4260. ValidIndexAndScore *valids = temporary_alloc_array<ValidIndexAndScore>(count);
  4261. isize valid_count = 0;
  4262. isize first_success_index = -1;
  4263. for_array(i, t->Union.variants) {
  4264. Type *vt = t->Union.variants[i];
  4265. i64 score = 0;
  4266. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  4267. valids[valid_count].index = i;
  4268. valids[valid_count].score = score;
  4269. valid_count += 1;
  4270. if (first_success_index < 0) {
  4271. first_success_index = i;
  4272. }
  4273. }
  4274. }
  4275. if (valid_count > 1) {
  4276. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  4277. i64 best_score = valids[0].score;
  4278. for (isize i = 1; i < valid_count; i++) {
  4279. auto v = valids[i];
  4280. if (best_score > v.score) {
  4281. valid_count = i;
  4282. break;
  4283. }
  4284. best_score = v.score;
  4285. }
  4286. first_success_index = valids[0].index;
  4287. }
  4288. gbString type_str = type_to_string(target_type);
  4289. defer (gb_string_free(type_str));
  4290. if (valid_count == 1) {
  4291. Type *new_type = t->Union.variants[first_success_index];
  4292. target_type = new_type;
  4293. if (is_type_union(new_type)) {
  4294. convert_to_typed(c, operand, new_type);
  4295. break;
  4296. }
  4297. operand->type = new_type;
  4298. if (operand->mode != Addressing_Constant ||
  4299. !elem_type_can_be_constant(operand->type)) {
  4300. operand->mode = Addressing_Value;
  4301. }
  4302. break;
  4303. } else if (valid_count > 1) {
  4304. ERROR_BLOCK();
  4305. GB_ASSERT(first_success_index >= 0);
  4306. operand->mode = Addressing_Invalid;
  4307. convert_untyped_error(c, operand, target_type, true);
  4308. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  4309. i32 j = 0;
  4310. for (i32 i = 0; i < valid_count; i++) {
  4311. ValidIndexAndScore valid = valids[i];
  4312. if (j > 0 && valid_count > 2) error_line(", ");
  4313. if (j == valid_count-1) {
  4314. if (valid_count == 2) error_line(" ");
  4315. error_line("or ");
  4316. }
  4317. gbString str = type_to_string(t->Union.variants[valid.index]);
  4318. error_line("'%s'", str);
  4319. gb_string_free(str);
  4320. j++;
  4321. }
  4322. error_line("\n\n");
  4323. return;
  4324. } else if (is_type_untyped_uninit(operand->type)) {
  4325. target_type = t_untyped_uninit;
  4326. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  4327. ERROR_BLOCK();
  4328. operand->mode = Addressing_Invalid;
  4329. convert_untyped_error(c, operand, target_type, true);
  4330. if (count > 0) {
  4331. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  4332. error_line("\t");
  4333. for (i32 i = 0; i < count; i++) {
  4334. Type *v = t->Union.variants[i];
  4335. if (i > 0 && count > 2) error_line(", ");
  4336. if (i == count-1) {
  4337. if (count == 2) error_line(" ");
  4338. if (count > 1) {
  4339. error_line("or ");
  4340. }
  4341. }
  4342. gbString str = type_to_string(v);
  4343. error_line("'%s'", str);
  4344. gb_string_free(str);
  4345. }
  4346. error_line("\n\n");
  4347. }
  4348. return;
  4349. }
  4350. }
  4351. /* fallthrough */
  4352. default:
  4353. if (is_type_untyped_uninit(operand->type)) {
  4354. target_type = t_untyped_uninit;
  4355. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  4356. target_type = t_untyped_nil;
  4357. } else {
  4358. operand->mode = Addressing_Invalid;
  4359. convert_untyped_error(c, operand, target_type);
  4360. return;
  4361. }
  4362. break;
  4363. }
  4364. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  4365. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  4366. } else {
  4367. target_type = default_type(operand->type);
  4368. }
  4369. }
  4370. update_untyped_expr_type(c, operand->expr, target_type, true);
  4371. operand->type = target_type;
  4372. }
  4373. gb_internal bool check_index_value(CheckerContext *c, Type *main_type, bool open_range, Ast *index_value, i64 max_count, i64 *value, Type *type_hint=nullptr) {
  4374. Operand operand = {Addressing_Invalid};
  4375. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  4376. if (operand.mode == Addressing_Invalid) {
  4377. if (value) *value = 0;
  4378. // NOTE(bill): return true here to propagate the errors better
  4379. return true;
  4380. }
  4381. Type *index_type = t_int;
  4382. if (type_hint != nullptr) {
  4383. index_type = type_hint;
  4384. }
  4385. convert_to_typed(c, &operand, index_type);
  4386. if (operand.mode == Addressing_Invalid) {
  4387. if (value) *value = 0;
  4388. return false;
  4389. }
  4390. if (type_hint != nullptr) {
  4391. if (!check_is_assignable_to(c, &operand, type_hint)) {
  4392. gbString expr_str = expr_to_string(operand.expr);
  4393. gbString index_type_str = type_to_string(type_hint);
  4394. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  4395. gb_string_free(index_type_str);
  4396. gb_string_free(expr_str);
  4397. if (value) *value = 0;
  4398. return false;
  4399. }
  4400. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  4401. gbString expr_str = expr_to_string(operand.expr);
  4402. gbString type_str = type_to_string(operand.type);
  4403. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  4404. gb_string_free(type_str);
  4405. gb_string_free(expr_str);
  4406. if (value) *value = 0;
  4407. return false;
  4408. }
  4409. if (operand.mode == Addressing_Constant &&
  4410. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  4411. BigInt i = exact_value_to_integer(operand.value).value_integer;
  4412. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  4413. TEMPORARY_ALLOCATOR_GUARD();
  4414. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4415. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4416. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  4417. if (value) *value = 0;
  4418. return false;
  4419. }
  4420. if (max_count >= 0) {
  4421. if (is_type_enum(index_type)) {
  4422. Type *bt = base_type(index_type);
  4423. GB_ASSERT(bt->kind == Type_Enum);
  4424. ExactValue const &lo = *bt->Enum.min_value;
  4425. ExactValue const &hi = *bt->Enum.max_value;
  4426. String lo_str = {};
  4427. String hi_str = {};
  4428. if (bt->Enum.fields.count > 0) {
  4429. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  4430. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  4431. lo_str = bt->Enum.fields[lo_idx]->token.string;
  4432. hi_str = bt->Enum.fields[hi_idx]->token.string;
  4433. }
  4434. bool out_of_bounds = false;
  4435. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  4436. out_of_bounds = true;
  4437. }
  4438. if (out_of_bounds) {
  4439. gbString expr_str = expr_to_string(operand.expr);
  4440. if (lo_str.len > 0) {
  4441. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  4442. } else {
  4443. gbString index_type_str = type_to_string(index_type);
  4444. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  4445. gb_string_free(index_type_str);
  4446. }
  4447. gb_string_free(expr_str);
  4448. return false;
  4449. }
  4450. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  4451. return true;
  4452. } else { // NOTE(bill): Do array bound checking
  4453. i64 v = -1;
  4454. if (i.used <= 1) {
  4455. v = big_int_to_i64(&i);
  4456. }
  4457. if (value) *value = v;
  4458. bool out_of_bounds = false;
  4459. if (v < 0) {
  4460. out_of_bounds = true;
  4461. } else if (open_range) {
  4462. out_of_bounds = v > max_count;
  4463. } else {
  4464. out_of_bounds = v >= max_count;
  4465. }
  4466. if (out_of_bounds) {
  4467. TEMPORARY_ALLOCATOR_GUARD();
  4468. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4469. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4470. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  4471. return false;
  4472. }
  4473. return true;
  4474. }
  4475. } else {
  4476. if (value) *value = exact_value_to_i64(operand.value);
  4477. return true;
  4478. }
  4479. }
  4480. // NOTE(bill): It's alright :D
  4481. if (value) *value = -1;
  4482. return true;
  4483. }
  4484. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  4485. if (value.kind == ExactValue_String) {
  4486. GB_ASSERT(0 <= index && index < value.value_string.len);
  4487. u8 val = value.value_string[index];
  4488. if (success_) *success_ = true;
  4489. if (finish_) *finish_ = true;
  4490. return exact_value_u64(val);
  4491. } else if (value.kind == ExactValue_String16) {
  4492. GB_ASSERT(0 <= index && index < value.value_string.len);
  4493. u16 val = value.value_string16[index];
  4494. if (success_) *success_ = true;
  4495. if (finish_) *finish_ = true;
  4496. return exact_value_u64(val);
  4497. }
  4498. if (value.kind != ExactValue_Compound) {
  4499. if (success_) *success_ = true;
  4500. if (finish_) *finish_ = true;
  4501. return value;
  4502. }
  4503. Ast *node = value.value_compound;
  4504. switch (node->kind) {
  4505. case_ast_node(cl, CompoundLit, node);
  4506. if (cl->elems.count == 0) {
  4507. if (success_) *success_ = true;
  4508. if (finish_) *finish_ = true;
  4509. return empty_exact_value;
  4510. }
  4511. if (cl->elems[0]->kind == Ast_FieldValue) {
  4512. if (is_type_raw_union(node->tav.type)) {
  4513. if (success_) *success_ = false;
  4514. if (finish_) *finish_ = true;
  4515. return empty_exact_value;
  4516. } else if (is_type_struct(node->tav.type)) {
  4517. bool found = false;
  4518. for (Ast *elem : cl->elems) {
  4519. if (elem->kind != Ast_FieldValue) {
  4520. continue;
  4521. }
  4522. ast_node(fv, FieldValue, elem);
  4523. String name = fv->field->Ident.token.string;
  4524. Selection sub_sel = lookup_field(node->tav.type, name, false);
  4525. if (sub_sel.index.count > 0 &&
  4526. sub_sel.index[0] == index) {
  4527. value = fv->value->tav.value;
  4528. found = true;
  4529. break;
  4530. }
  4531. }
  4532. if (!found) {
  4533. // Use the zero value if it is not found
  4534. value = {};
  4535. }
  4536. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4537. for (Ast *elem : cl->elems) {
  4538. if (elem->kind != Ast_FieldValue) {
  4539. continue;
  4540. }
  4541. ast_node(fv, FieldValue, elem);
  4542. if (is_ast_range(fv->field)) {
  4543. ast_node(ie, BinaryExpr, fv->field);
  4544. TypeAndValue lo_tav = ie->left->tav;
  4545. TypeAndValue hi_tav = ie->right->tav;
  4546. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4547. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4548. TokenKind op = ie->op.kind;
  4549. i64 lo = exact_value_to_i64(lo_tav.value);
  4550. i64 hi = exact_value_to_i64(hi_tav.value);
  4551. i64 corrected_index = index;
  4552. if (is_type_enumerated_array(node->tav.type)) {
  4553. Type *bt = base_type(node->tav.type);
  4554. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4555. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4556. }
  4557. if (op != Token_RangeHalf) {
  4558. if (lo <= corrected_index && corrected_index <= hi) {
  4559. TypeAndValue tav = fv->value->tav;
  4560. if (success_) *success_ = true;
  4561. if (finish_) *finish_ = false;
  4562. return tav.value;
  4563. }
  4564. } else {
  4565. if (lo <= corrected_index && corrected_index < hi) {
  4566. TypeAndValue tav = fv->value->tav;
  4567. if (success_) *success_ = true;
  4568. if (finish_) *finish_ = false;
  4569. return tav.value;
  4570. }
  4571. }
  4572. } else {
  4573. TypeAndValue index_tav = fv->field->tav;
  4574. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4575. ExactValue index_value = index_tav.value;
  4576. if (is_type_enumerated_array(node->tav.type)) {
  4577. Type *bt = base_type(node->tav.type);
  4578. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4579. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4580. }
  4581. i64 field_index = exact_value_to_i64(index_value);
  4582. if (index == field_index) {
  4583. TypeAndValue tav = fv->value->tav;
  4584. if (success_) *success_ = true;
  4585. if (finish_) *finish_ = false;
  4586. return tav.value;
  4587. }
  4588. }
  4589. }
  4590. }
  4591. } else {
  4592. i32 count = (i32)cl->elems.count;
  4593. if (count < index) {
  4594. if (success_) *success_ = false;
  4595. if (finish_) *finish_ = true;
  4596. return empty_exact_value;
  4597. }
  4598. if (cl->elems.count <= index) {
  4599. if (success_) *success_ = false;
  4600. if (finish_) *finish_ = false;
  4601. return value;
  4602. }
  4603. TypeAndValue tav = cl->elems[index]->tav;
  4604. if (tav.mode == Addressing_Constant) {
  4605. if (success_) *success_ = true;
  4606. if (finish_) *finish_ = false;
  4607. return tav.value;
  4608. } else if (is_type_proc(tav.type)) {
  4609. if (success_) *success_ = true;
  4610. if (finish_) *finish_ = false;
  4611. return tav.value;
  4612. } else {
  4613. GB_ASSERT_MSG(is_type_untyped_nil(tav.type), "%s", type_to_string(tav.type));
  4614. if (success_) *success_ = true;
  4615. if (finish_) *finish_ = false;
  4616. return tav.value;
  4617. }
  4618. }
  4619. case_end;
  4620. default:
  4621. if (success_) *success_ = true;
  4622. if (finish_) *finish_ = true;
  4623. return empty_exact_value;
  4624. }
  4625. if (finish_) *finish_ = false;
  4626. return value;
  4627. }
  4628. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4629. if (operand->mode != Addressing_Constant) {
  4630. if (success_) *success_ = false;
  4631. return empty_exact_value;
  4632. }
  4633. if (sel.indirect) {
  4634. if (success_) *success_ = false;
  4635. return empty_exact_value;
  4636. }
  4637. if (sel.index.count == 0) {
  4638. if (success_) *success_ = false;
  4639. return empty_exact_value;
  4640. }
  4641. ExactValue value = operand->value;
  4642. if (value.kind == ExactValue_Compound) {
  4643. while (sel.index.count > 0) {
  4644. i32 index = sel.index[0];
  4645. sel = sub_selection(sel, 1);
  4646. bool finish = false;
  4647. value = get_constant_field_single(c, value, index, success_, &finish);
  4648. if (finish) {
  4649. return value;
  4650. }
  4651. }
  4652. if (success_) *success_ = true;
  4653. return value;
  4654. } else if (value.kind == ExactValue_Quaternion) {
  4655. // @QuaternionLayout
  4656. Quaternion256 q = *value.value_quaternion;
  4657. GB_ASSERT(sel.index.count == 1);
  4658. switch (sel.index[0]) {
  4659. case 3: // w
  4660. if (success_) *success_ = true;
  4661. return exact_value_float(q.real);
  4662. case 0: // x
  4663. if (success_) *success_ = true;
  4664. return exact_value_float(q.imag);
  4665. case 1: // y
  4666. if (success_) *success_ = true;
  4667. return exact_value_float(q.jmag);
  4668. case 2: // z
  4669. if (success_) *success_ = true;
  4670. return exact_value_float(q.kmag);
  4671. }
  4672. if (success_) *success_ = false;
  4673. return empty_exact_value;
  4674. } else if (value.kind == ExactValue_Complex) {
  4675. // @QuaternionLayout
  4676. Complex128 c = *value.value_complex;
  4677. GB_ASSERT(sel.index.count == 1);
  4678. switch (sel.index[0]) {
  4679. case 0: // real
  4680. if (success_) *success_ = true;
  4681. return exact_value_float(c.real);
  4682. case 1: // imag
  4683. if (success_) *success_ = true;
  4684. return exact_value_float(c.imag);
  4685. }
  4686. if (success_) *success_ = false;
  4687. return empty_exact_value;
  4688. }
  4689. if (success_) *success_ = true;
  4690. return empty_exact_value;
  4691. }
  4692. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4693. Type *array_type = base_type(type_deref(original_type));
  4694. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4695. if (array_type->kind == Type_SimdVector) {
  4696. Type *elem_type = array_type->SimdVector.elem;
  4697. return alloc_type_simd_vector(new_count, elem_type);
  4698. }
  4699. Type *elem_type = array_type->Array.elem;
  4700. Type *swizzle_array_type = nullptr;
  4701. Type *bth = base_type(type_deref(type_hint));
  4702. if (bth != nullptr && bth->kind == Type_Array &&
  4703. bth->Array.count == new_count &&
  4704. are_types_identical(bth->Array.elem, elem_type)) {
  4705. swizzle_array_type = type_hint;
  4706. } else {
  4707. i64 max_count = array_type->Array.count;
  4708. if (new_count == max_count) {
  4709. swizzle_array_type = original_type;
  4710. } else {
  4711. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4712. }
  4713. }
  4714. return swizzle_array_type;
  4715. }
  4716. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4717. bool is_declared = entity != nullptr;
  4718. if (is_declared) {
  4719. if (entity->kind == Entity_Builtin) {
  4720. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4721. // This means that we should just ignore the found result through it
  4722. *allow_builtin = entity->scope == import_scope ||
  4723. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4724. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4725. is_declared = false;
  4726. }
  4727. }
  4728. return is_declared;
  4729. }
  4730. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4731. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4732. if (node == nullptr) {
  4733. return nullptr;
  4734. }
  4735. /*if (node->kind == Ast_TernaryWhenExpr) {
  4736. ast_node(we, TernaryWhenExpr, node);
  4737. if (we->cond == nullptr) {
  4738. return nullptr;
  4739. }
  4740. if (we->cond->tav.mode != Addressing_Constant) {
  4741. return nullptr;
  4742. }
  4743. if (we->cond->tav.value.kind != ExactValue_Bool) {
  4744. return nullptr;
  4745. }
  4746. if (we->cond->tav.value.value_bool) {
  4747. return check_entity_from_ident_or_selector(c, we->x, ident_only);
  4748. } else {
  4749. Entity *e = check_entity_from_ident_or_selector(c, we->y, ident_only);
  4750. return e;
  4751. }
  4752. } else */if (node->kind == Ast_Ident) {
  4753. String name = node->Ident.token.string;
  4754. return scope_lookup(c->scope, name, node->Ident.hash);
  4755. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4756. ast_node(se, SelectorExpr, node);
  4757. if (se->token.kind == Token_ArrowRight) {
  4758. return nullptr;
  4759. }
  4760. Ast *op_expr = se->expr;
  4761. Ast *selector = unparen_expr(se->selector);
  4762. if (selector == nullptr) {
  4763. return nullptr;
  4764. }
  4765. if (selector->kind != Ast_Ident) {
  4766. return nullptr;
  4767. }
  4768. Entity *entity = nullptr;
  4769. Entity *expr_entity = nullptr;
  4770. bool check_op_expr = true;
  4771. if (op_expr->kind == Ast_Ident) {
  4772. String op_name = op_expr->Ident.token.string;
  4773. Entity *e = scope_lookup(c->scope, op_name, op_expr->Ident.hash);
  4774. if (e == nullptr) {
  4775. return nullptr;
  4776. }
  4777. add_entity_use(c, op_expr, e);
  4778. expr_entity = e;
  4779. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4780. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4781. // It pretty much needs to be in this order and this way
  4782. // If you can clean this up, please do but be really careful
  4783. String import_name = op_name;
  4784. Scope *import_scope = e->ImportName.scope;
  4785. String entity_name = selector->Ident.token.string;
  4786. check_op_expr = false;
  4787. entity = scope_lookup_current(import_scope, entity_name);
  4788. bool allow_builtin = false;
  4789. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4790. return nullptr;
  4791. }
  4792. check_entity_decl(c, entity, nullptr, nullptr);
  4793. if (entity->kind == Entity_ProcGroup) {
  4794. return entity;
  4795. }
  4796. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4797. }
  4798. }
  4799. Operand operand = {};
  4800. if (check_op_expr) {
  4801. check_expr_base(c, &operand, op_expr, nullptr);
  4802. if (operand.mode == Addressing_Invalid) {
  4803. return nullptr;
  4804. }
  4805. }
  4806. if (entity == nullptr && selector->kind == Ast_Ident) {
  4807. String field_name = selector->Ident.token.string;
  4808. if (is_type_dynamic_array(type_deref(operand.type))) {
  4809. init_mem_allocator(c->checker);
  4810. }
  4811. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4812. entity = sel.entity;
  4813. }
  4814. if (entity != nullptr) {
  4815. return entity;
  4816. }
  4817. }
  4818. return nullptr;
  4819. }
  4820. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4821. ast_node(se, SelectorExpr, node);
  4822. bool check_op_expr = true;
  4823. Entity *expr_entity = nullptr;
  4824. Entity *entity = nullptr;
  4825. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4826. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4827. ERROR_BLOCK();
  4828. error(node, "Illegal use of -> selector shorthand outside of a call");
  4829. gbString x = expr_to_string(se->expr);
  4830. gbString y = expr_to_string(se->selector);
  4831. error_line("\tSuggestion: Did you mean '%s.%s'?\n", x, y);
  4832. gb_string_free(y);
  4833. gb_string_free(x);
  4834. // TODO(bill): Should this terminate here or propagate onwards?
  4835. // operand->mode = Addressing_Invalid;
  4836. // operand->expr = node;
  4837. // return nullptr;
  4838. }
  4839. operand->expr = node;
  4840. Ast *op_expr = se->expr;
  4841. Ast *selector = unparen_expr(se->selector);
  4842. if (selector == nullptr) {
  4843. operand->mode = Addressing_Invalid;
  4844. operand->expr = node;
  4845. return nullptr;
  4846. }
  4847. if (selector->kind != Ast_Ident) {
  4848. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4849. operand->mode = Addressing_Invalid;
  4850. operand->expr = node;
  4851. return nullptr;
  4852. }
  4853. if (op_expr->kind == Ast_Ident) {
  4854. String op_name = op_expr->Ident.token.string;
  4855. Entity *e = scope_lookup(c->scope, op_name, op_expr->Ident.hash);
  4856. add_entity_use(c, op_expr, e);
  4857. expr_entity = e;
  4858. if (e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup) && selector->kind == Ast_Ident) {
  4859. gbString sel_str = expr_to_string(selector);
  4860. error(node, "'%s' is not declared by by '%.*s'", sel_str, LIT(e->token.string));
  4861. gb_string_free(sel_str);
  4862. operand->mode = Addressing_Invalid;
  4863. operand->expr = node;
  4864. return nullptr;
  4865. } else if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4866. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4867. // It pretty much needs to be in this order and this way
  4868. // If you can clean this up, please do but be really careful
  4869. String import_name = op_name;
  4870. Scope *import_scope = e->ImportName.scope;
  4871. String entity_name = selector->Ident.token.string;
  4872. if (import_scope == nullptr) {
  4873. ERROR_BLOCK();
  4874. error(node, "'%.*s' is not imported in this file, '%.*s' is unavailable", LIT(import_name), LIT(entity_name));
  4875. operand->mode = Addressing_Invalid;
  4876. operand->expr = node;
  4877. return nullptr;
  4878. }
  4879. check_op_expr = false;
  4880. entity = scope_lookup_current(import_scope, entity_name);
  4881. bool allow_builtin = false;
  4882. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4883. ERROR_BLOCK();
  4884. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4885. operand->mode = Addressing_Invalid;
  4886. operand->expr = node;
  4887. check_did_you_mean_scope(entity_name, import_scope);
  4888. return nullptr;
  4889. }
  4890. if (!is_entity_exported(entity, allow_builtin)) {
  4891. gbString sel_str = expr_to_string(selector);
  4892. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4893. gb_string_free(sel_str);
  4894. // NOTE(bill): make the state valid still, even if it's "invalid"
  4895. // operand->mode = Addressing_Invalid;
  4896. // operand->expr = node;
  4897. // return nullptr;
  4898. }
  4899. check_entity_decl(c, entity, nullptr, nullptr);
  4900. if (entity->kind == Entity_ProcGroup) {
  4901. operand->mode = Addressing_ProcGroup;
  4902. operand->proc_group = entity;
  4903. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4904. return entity;
  4905. }
  4906. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4907. }
  4908. }
  4909. if (check_op_expr) {
  4910. check_expr_base(c, operand, op_expr, nullptr);
  4911. if (operand->mode == Addressing_Invalid) {
  4912. operand->mode = Addressing_Invalid;
  4913. operand->expr = node;
  4914. return nullptr;
  4915. }
  4916. }
  4917. if (operand->type && is_type_soa_struct(type_deref(operand->type))) {
  4918. complete_soa_type(c->checker, type_deref(operand->type), false);
  4919. }
  4920. if (entity == nullptr && selector->kind == Ast_Ident) {
  4921. String field_name = selector->Ident.token.string;
  4922. Type *t = type_deref(operand->type);
  4923. if (t == nullptr) {
  4924. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4925. } else {
  4926. if (is_type_dynamic_array(t)) {
  4927. init_mem_allocator(c->checker);
  4928. }
  4929. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4930. entity = sel.entity;
  4931. // NOTE(bill): Add type info needed for fields like 'names'
  4932. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4933. add_type_info_type(c, operand->type);
  4934. }
  4935. if (is_type_enum(operand->type)) {
  4936. add_type_info_type(c, operand->type);
  4937. }
  4938. }
  4939. }
  4940. if (operand->type && is_type_simd_vector(type_deref(operand->type))) {
  4941. String field_name = selector->Ident.token.string;
  4942. if (field_name.len == 1) {
  4943. error(op_expr, "Extracting an element from a #simd array using .%.*s syntax is disallowed, prefer `simd.extract`", LIT(field_name));
  4944. } else {
  4945. error(op_expr, "Extracting elements from a #simd array using .%.*s syntax is disallowed, prefer `swizzle`", LIT(field_name));
  4946. }
  4947. return nullptr;
  4948. }
  4949. if (entity == nullptr && selector->kind == Ast_Ident && operand->type != nullptr &&
  4950. (is_type_array(type_deref(operand->type)))) {
  4951. String field_name = selector->Ident.token.string;
  4952. if (1 < field_name.len && field_name.len <= 4) {
  4953. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4954. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4955. bool found_xyzw = false;
  4956. bool found_rgba = false;
  4957. for (isize i = 0; i < field_name.len; i++) {
  4958. bool valid = false;
  4959. for (isize j = 0; j < 4; j++) {
  4960. if (field_name.text[i] == swizzles_xyzw[j]) {
  4961. found_xyzw = true;
  4962. valid = true;
  4963. break;
  4964. }
  4965. if (field_name.text[i] == swizzles_rgba[j]) {
  4966. found_rgba = true;
  4967. valid = true;
  4968. break;
  4969. }
  4970. }
  4971. if (!valid) {
  4972. goto end_of_array_selector_swizzle;
  4973. }
  4974. }
  4975. u8 *swizzles = nullptr;
  4976. u8 index_count = cast(u8)field_name.len;
  4977. if (found_xyzw && found_rgba) {
  4978. gbString op_str = expr_to_string(op_expr);
  4979. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4980. gb_string_free(op_str);
  4981. operand->mode = Addressing_Invalid;
  4982. operand->expr = node;
  4983. return nullptr;
  4984. }
  4985. u8 indices = 0;
  4986. if (found_xyzw) {
  4987. swizzles = swizzles_xyzw;
  4988. } else if (found_rgba) {
  4989. swizzles = swizzles_rgba;
  4990. }
  4991. for (isize i = 0; i < field_name.len; i++) {
  4992. for (isize j = 0; j < 4; j++) {
  4993. if (field_name.text[i] == swizzles[j]) {
  4994. indices |= cast(u8)(j)<<(i*2);
  4995. break;
  4996. }
  4997. }
  4998. }
  4999. Type *original_type = operand->type;
  5000. Type *array_type = base_type(type_deref(original_type));
  5001. GB_ASSERT(array_type->kind == Type_Array);
  5002. i64 array_count = get_array_type_count(array_type);
  5003. for (u8 i = 0; i < index_count; i++) {
  5004. u8 idx = indices>>(i*2) & 3;
  5005. if (idx >= array_count) {
  5006. char c = 0;
  5007. if (found_xyzw) {
  5008. c = swizzles_xyzw[idx];
  5009. } else if (found_rgba) {
  5010. c = swizzles_rgba[idx];
  5011. } else {
  5012. GB_PANIC("unknown swizzle kind");
  5013. }
  5014. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  5015. break;
  5016. }
  5017. }
  5018. se->swizzle_count = index_count;
  5019. se->swizzle_indices = indices;
  5020. AddressingMode prev_mode = operand->mode;
  5021. operand->mode = Addressing_SwizzleValue;
  5022. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  5023. operand->expr = node;
  5024. switch (prev_mode) {
  5025. case Addressing_Variable:
  5026. case Addressing_SoaVariable:
  5027. case Addressing_SwizzleVariable:
  5028. operand->mode = Addressing_SwizzleVariable;
  5029. break;
  5030. case Addressing_Value:
  5031. if (is_type_pointer(original_type)) {
  5032. operand->mode = Addressing_SwizzleVariable;
  5033. }
  5034. break;
  5035. }
  5036. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  5037. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5038. return swizzle_entity;
  5039. }
  5040. end_of_array_selector_swizzle:;
  5041. }
  5042. if (entity == nullptr) {
  5043. gbString op_str = expr_to_string(op_expr);
  5044. gbString type_str = type_to_string_shorthand(operand->type);
  5045. gbString sel_str = expr_to_string(selector);
  5046. if (operand->mode == Addressing_Type) {
  5047. if (is_type_polymorphic(operand->type, true)) {
  5048. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  5049. } else {
  5050. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  5051. }
  5052. } else {
  5053. ERROR_BLOCK();
  5054. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  5055. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  5056. String const &name = selector->Ident.token.string;
  5057. Type *bt = base_type(operand->type);
  5058. if (operand->type->kind == Type_Named &&
  5059. operand->type->Named.type_name &&
  5060. operand->type->Named.type_name->kind == Entity_TypeName &&
  5061. operand->type->Named.type_name->TypeName.objc_metadata) {
  5062. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  5063. } else if (bt->kind == Type_Struct) {
  5064. check_did_you_mean_type(name, bt->Struct.fields);
  5065. } else if (bt->kind == Type_Enum) {
  5066. check_did_you_mean_type(name, bt->Enum.fields);
  5067. }
  5068. }
  5069. }
  5070. gb_string_free(sel_str);
  5071. gb_string_free(type_str);
  5072. gb_string_free(op_str);
  5073. operand->mode = Addressing_Invalid;
  5074. operand->expr = node;
  5075. return nullptr;
  5076. }
  5077. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  5078. bool success = false;
  5079. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  5080. if (success) {
  5081. operand->mode = Addressing_Constant;
  5082. operand->expr = node;
  5083. operand->value = field_value;
  5084. operand->type = entity->type;
  5085. add_entity_use(c, selector, entity);
  5086. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5087. return entity;
  5088. }
  5089. gbString op_str = expr_to_string(op_expr);
  5090. gbString type_str = type_to_string_shorthand(operand->type);
  5091. gbString sel_str = expr_to_string(selector);
  5092. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  5093. gb_string_free(sel_str);
  5094. gb_string_free(type_str);
  5095. gb_string_free(op_str);
  5096. operand->mode = Addressing_Invalid;
  5097. operand->expr = node;
  5098. return nullptr;
  5099. }
  5100. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  5101. bool success = false;
  5102. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  5103. if (success) {
  5104. operand->mode = Addressing_Constant;
  5105. operand->expr = node;
  5106. operand->value = field_value;
  5107. operand->type = entity->type;
  5108. add_entity_use(c, selector, entity);
  5109. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5110. return entity;
  5111. }
  5112. gbString op_str = expr_to_string(op_expr);
  5113. gbString type_str = type_to_string_shorthand(operand->type);
  5114. gbString sel_str = expr_to_string(selector);
  5115. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  5116. gb_string_free(sel_str);
  5117. gb_string_free(type_str);
  5118. gb_string_free(op_str);
  5119. operand->mode = Addressing_Invalid;
  5120. operand->expr = node;
  5121. return nullptr;
  5122. }
  5123. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  5124. gbString op_str = expr_to_string(op_expr);
  5125. gbString type_str = type_to_string_shorthand(operand->type);
  5126. gbString sel_str = expr_to_string(selector);
  5127. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  5128. gb_string_free(sel_str);
  5129. gb_string_free(type_str);
  5130. gb_string_free(op_str);
  5131. operand->mode = Addressing_Invalid;
  5132. operand->expr = node;
  5133. return nullptr;
  5134. }
  5135. add_entity_use(c, selector, entity);
  5136. operand->type = entity->type;
  5137. operand->expr = node;
  5138. if (entity->flags & EntityFlag_BitFieldField) {
  5139. add_package_dependency(c, "runtime", "__write_bits");
  5140. add_package_dependency(c, "runtime", "__read_bits");
  5141. }
  5142. switch (entity->kind) {
  5143. case Entity_Constant:
  5144. operand->value = entity->Constant.value;
  5145. operand->mode = Addressing_Constant;
  5146. if (operand->value.kind == ExactValue_Procedure) {
  5147. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  5148. if (proc != nullptr) {
  5149. operand->mode = Addressing_Value;
  5150. operand->type = proc->type;
  5151. }
  5152. }
  5153. break;
  5154. case Entity_Variable:
  5155. if (sel.is_bit_field) {
  5156. se->is_bit_field = true;
  5157. }
  5158. if (sel.indirect) {
  5159. operand->mode = Addressing_Variable;
  5160. } else if (operand->mode == Addressing_Context) {
  5161. // Do nothing
  5162. } else if (operand->mode == Addressing_MapIndex) {
  5163. operand->mode = Addressing_Value;
  5164. } else if (entity->flags & EntityFlag_SoaPtrField) {
  5165. operand->mode = Addressing_SoaVariable;
  5166. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  5167. operand->mode = Addressing_Value;
  5168. } else if (operand->mode == Addressing_SoaVariable) {
  5169. operand->mode = Addressing_Variable;
  5170. } else if (operand->mode != Addressing_Value) {
  5171. operand->mode = Addressing_Variable;
  5172. } else {
  5173. operand->mode = Addressing_Value;
  5174. }
  5175. break;
  5176. case Entity_TypeName:
  5177. operand->mode = Addressing_Type;
  5178. break;
  5179. case Entity_Procedure:
  5180. operand->mode = Addressing_Value;
  5181. operand->value = exact_value_procedure(node);
  5182. break;
  5183. case Entity_Builtin:
  5184. operand->mode = Addressing_Builtin;
  5185. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  5186. break;
  5187. case Entity_ProcGroup:
  5188. operand->mode = Addressing_ProcGroup;
  5189. operand->proc_group = entity;
  5190. break;
  5191. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  5192. case Entity_Nil:
  5193. operand->mode = Addressing_Value;
  5194. break;
  5195. }
  5196. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5197. return entity;
  5198. }
  5199. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  5200. ptr = base_type(ptr);
  5201. if (is_type_pointer(ptr)) {
  5202. if (is_type_rawptr(ptr)) {
  5203. return false;
  5204. }
  5205. if (elem) *elem = ptr->Pointer.elem;
  5206. return true;
  5207. }
  5208. return false;
  5209. }
  5210. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  5211. elem = core_type(elem);
  5212. if (is_type_internally_pointer_like(elem)) {
  5213. return true;
  5214. }
  5215. if (elem->kind == Type_BitSet) {
  5216. elem = bit_set_to_int(elem);
  5217. }
  5218. if (elem->kind != Type_Basic) {
  5219. return false;
  5220. }
  5221. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  5222. }
  5223. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  5224. switch (node->kind) {
  5225. case_ast_node(i, Ident, node);
  5226. String name = i->token.string;
  5227. if (nested) {
  5228. Entity *e = scope_lookup_current(s, name);
  5229. if (e != nullptr) {
  5230. if (out_scope) *out_scope = e->scope;
  5231. return true;
  5232. }
  5233. } else {
  5234. Entity *e = scope_lookup(s, name, i->hash);
  5235. if (e != nullptr) {
  5236. if (out_scope) *out_scope = e->scope;
  5237. return true;
  5238. }
  5239. }
  5240. case_end;
  5241. case_ast_node(se, SelectorExpr, node);
  5242. Ast *lhs = se->expr;
  5243. Ast *rhs = se->selector;
  5244. Scope *lhs_scope = nullptr;
  5245. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  5246. return check_identifier_exists(lhs_scope, rhs, true);
  5247. }
  5248. case_end;
  5249. }
  5250. return false;
  5251. }
  5252. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  5253. bool optional_ok = false;
  5254. isize tuple_index = 0;
  5255. for (Ast *rhs_expr : rhs) {
  5256. CheckerContext c_ = *ctx;
  5257. CheckerContext *c = &c_;
  5258. Operand o = {};
  5259. Type *type_hint = nullptr;
  5260. if (tuple_index < lhs.count) {
  5261. type_hint = lhs[tuple_index].type;
  5262. }
  5263. check_expr_base(c, &o, rhs_expr, type_hint);
  5264. if (o.mode == Addressing_NoValue) {
  5265. error_operand_no_value(&o);
  5266. o.mode = Addressing_Invalid;
  5267. }
  5268. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5269. if (lhs.count == 2 && rhs.count == 1 &&
  5270. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5271. Ast *expr = unparen_expr(o.expr);
  5272. Operand val0 = o;
  5273. Operand val1 = o;
  5274. val0.mode = Addressing_Value;
  5275. val1.mode = Addressing_Value;
  5276. val1.type = t_untyped_bool;
  5277. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5278. if (expr->kind == Ast_TypeAssertion &&
  5279. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5280. // NOTE(bill): Used only for optimizations in the backend
  5281. if (is_blank_ident(lhs[0].expr)) {
  5282. expr->TypeAssertion.ignores[0] = true;
  5283. }
  5284. if (is_blank_ident(lhs[1].expr)) {
  5285. expr->TypeAssertion.ignores[1] = true;
  5286. }
  5287. }
  5288. array_add(operands, val0);
  5289. array_add(operands, val1);
  5290. optional_ok = true;
  5291. tuple_index += 2;
  5292. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  5293. Type *tuple = o.type;
  5294. GB_ASSERT(tuple->Tuple.variables.count == 2);
  5295. Ast *expr = unparen_expr(o.expr);
  5296. if (expr->kind == Ast_CallExpr) {
  5297. expr->CallExpr.optional_ok_one = true;
  5298. }
  5299. Operand val = o;
  5300. val.type = tuple->Tuple.variables[0]->type;
  5301. val.mode = Addressing_Value;
  5302. array_add(operands, val);
  5303. tuple_index += tuple->Tuple.variables.count;
  5304. } else {
  5305. array_add(operands, o);
  5306. tuple_index += 1;
  5307. }
  5308. } else {
  5309. TypeTuple *tuple = &o.type->Tuple;
  5310. for (Entity *e : tuple->variables) {
  5311. o.type = e->type;
  5312. array_add(operands, o);
  5313. }
  5314. tuple_index += tuple->variables.count;
  5315. }
  5316. }
  5317. return optional_ok;
  5318. }
  5319. typedef u32 UnpackFlags;
  5320. enum UnpackFlag : u32 {
  5321. UnpackFlag_None = 0,
  5322. UnpackFlag_AllowOk = 1<<0,
  5323. UnpackFlag_AllowUndef = 1<<1,
  5324. };
  5325. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags,
  5326. isize variadic_index = -1) {
  5327. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  5328. if (lhs == nullptr || c->decl == nullptr) {
  5329. return tuple_count;
  5330. }
  5331. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  5332. Entity *e = lhs[tuple_index + j];
  5333. if (e == nullptr) {
  5334. continue;
  5335. }
  5336. DeclInfo *decl = decl_info_of_entity(e);
  5337. if (decl == nullptr) {
  5338. continue;
  5339. }
  5340. rw_mutex_shared_lock(&decl->deps_mutex);
  5341. rw_mutex_lock(&c->decl->deps_mutex);
  5342. FOR_PTR_SET(dep, decl->deps) {
  5343. ptr_set_add(&c->decl->deps, dep);
  5344. }
  5345. rw_mutex_unlock(&c->decl->deps_mutex);
  5346. rw_mutex_shared_unlock(&decl->deps_mutex);
  5347. }
  5348. return tuple_count;
  5349. };
  5350. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  5351. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  5352. bool is_variadic = variadic_index > -1;
  5353. if (!is_variadic) {
  5354. variadic_index = lhs_count;
  5355. }
  5356. bool optional_ok = false;
  5357. isize tuple_index = 0;
  5358. for (Ast *rhs : rhs_arguments) {
  5359. if (rhs->kind == Ast_FieldValue) {
  5360. error(rhs, "Invalid use of 'field = value'");
  5361. rhs = rhs->FieldValue.value;
  5362. }
  5363. CheckerContext c_ = *ctx;
  5364. CheckerContext *c = &c_;
  5365. Operand o = {};
  5366. Type *type_hint = nullptr;
  5367. if (lhs != nullptr) {
  5368. if (tuple_index < variadic_index) {
  5369. // NOTE(bill): override DeclInfo for dependency
  5370. Entity *e = lhs[tuple_index];
  5371. if (e != nullptr) {
  5372. type_hint = e->type;
  5373. }
  5374. } else if (is_variadic) {
  5375. Entity *e = lhs[variadic_index];
  5376. if (e != nullptr) {
  5377. GB_ASSERT(e->flags & EntityFlag_Ellipsis);
  5378. GB_ASSERT(is_type_slice(e->type));
  5379. type_hint = e->type->Slice.elem;
  5380. }
  5381. }
  5382. }
  5383. Ast *rhs_expr = unparen_expr(rhs);
  5384. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  5385. // NOTE(bill): Just handle this very specific logic here
  5386. o.type = t_untyped_uninit;
  5387. o.mode = Addressing_Value;
  5388. o.expr = rhs;
  5389. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  5390. } else {
  5391. check_expr_base(c, &o, rhs, type_hint);
  5392. }
  5393. if (o.mode == Addressing_NoValue) {
  5394. error_operand_no_value(&o);
  5395. o.mode = Addressing_Invalid;
  5396. }
  5397. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5398. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  5399. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5400. Ast *expr = unparen_expr(o.expr);
  5401. Operand val0 = o;
  5402. Operand val1 = o;
  5403. val0.mode = Addressing_Value;
  5404. val1.mode = Addressing_Value;
  5405. val1.type = t_untyped_bool;
  5406. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5407. if (expr->kind == Ast_TypeAssertion &&
  5408. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5409. // NOTE(bill): Used only for optimizations in the backend
  5410. if (is_blank_ident(lhs[0]->token)) {
  5411. expr->TypeAssertion.ignores[0] = true;
  5412. }
  5413. if (is_blank_ident(lhs[1]->token)) {
  5414. expr->TypeAssertion.ignores[1] = true;
  5415. }
  5416. }
  5417. array_add(operands, val0);
  5418. array_add(operands, val1);
  5419. optional_ok = true;
  5420. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  5421. } else {
  5422. array_add(operands, o);
  5423. tuple_index += 1;
  5424. }
  5425. } else {
  5426. TypeTuple *tuple = &o.type->Tuple;
  5427. for (Entity *e : tuple->variables) {
  5428. o.type = e->type;
  5429. array_add(operands, o);
  5430. }
  5431. isize count = tuple->variables.count;
  5432. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  5433. }
  5434. }
  5435. return optional_ok;
  5436. }
  5437. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  5438. GB_ASSERT(pt != nullptr);
  5439. GB_ASSERT(pt->kind == Type_Proc);
  5440. isize param_count = 0;
  5441. isize param_count_excluding_defaults = 0;
  5442. bool variadic = pt->Proc.variadic;
  5443. TypeTuple *param_tuple = nullptr;
  5444. if (pt->Proc.params != nullptr) {
  5445. param_tuple = &pt->Proc.params->Tuple;
  5446. param_count = param_tuple->variables.count;
  5447. if (variadic) {
  5448. for (isize i = param_count-1; i >= 0; i--) {
  5449. Entity *e = param_tuple->variables[i];
  5450. if (e->kind == Entity_TypeName) {
  5451. break;
  5452. }
  5453. if (e->kind == Entity_Variable) {
  5454. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5455. param_count--;
  5456. continue;
  5457. }
  5458. }
  5459. break;
  5460. }
  5461. param_count--;
  5462. }
  5463. }
  5464. param_count_excluding_defaults = param_count;
  5465. if (param_tuple != nullptr) {
  5466. for (isize i = param_count-1; i >= 0; i--) {
  5467. Entity *e = param_tuple->variables[i];
  5468. if (e->kind == Entity_TypeName) {
  5469. break;
  5470. }
  5471. if (e->kind == Entity_Variable) {
  5472. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5473. param_count_excluding_defaults--;
  5474. continue;
  5475. }
  5476. }
  5477. break;
  5478. }
  5479. }
  5480. if (param_count_) *param_count_ = param_count;
  5481. return param_count_excluding_defaults;
  5482. }
  5483. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  5484. isize param_count = pt->param_count;
  5485. for (isize i = 0; i < param_count; i++) {
  5486. Entity *e = pt->params->Tuple.variables[i];
  5487. String name = e->token.string;
  5488. if (is_blank_ident(name)) {
  5489. continue;
  5490. }
  5491. if (name == parameter_name) {
  5492. return i;
  5493. }
  5494. }
  5495. return -1;
  5496. }
  5497. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  5498. type = base_type(type);
  5499. GB_ASSERT(type->kind == Type_Proc);
  5500. return lookup_procedure_parameter(&type->Proc, parameter_name);
  5501. }
  5502. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  5503. Entity *entity, Type *proc_type,
  5504. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  5505. CallArgumentErrorMode show_error_mode,
  5506. CallArgumentData *data,
  5507. bool checking_proc_group) {
  5508. TEMPORARY_ALLOCATOR_GUARD();
  5509. CallArgumentError err = CallArgumentError_None;
  5510. ast_node(ce, CallExpr, call);
  5511. GB_ASSERT(is_type_proc(proc_type));
  5512. proc_type = base_type(proc_type);
  5513. TypeProc *pt = &proc_type->Proc;
  5514. isize param_count = 0;
  5515. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  5516. bool variadic = pt->variadic;
  5517. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5518. i64 score = 0;
  5519. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  5520. Type *final_proc_type = proc_type;
  5521. Entity *gen_entity = nullptr;
  5522. if (vari_expand && !variadic) {
  5523. if (show_error) {
  5524. error(ce->ellipsis,
  5525. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  5526. LIT(ce->proc->Ident.token.string));
  5527. }
  5528. err = CallArgumentError_NonVariadicExpand;
  5529. } else if (vari_expand && pt->c_vararg) {
  5530. if (show_error) {
  5531. error(ce->ellipsis,
  5532. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  5533. LIT(ce->proc->Ident.token.string));
  5534. }
  5535. err = CallArgumentError_NonVariadicExpand;
  5536. }
  5537. GB_ASSERT(ce->split_args);
  5538. auto visited = temporary_slice_make<bool>(pt->param_count);
  5539. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  5540. defer ({
  5541. for (Operand const &o : ordered_operands) {
  5542. if (o.expr != nullptr) {
  5543. call->viral_state_flags |= o.expr->viral_state_flags;
  5544. }
  5545. }
  5546. });
  5547. isize positional_operand_count = positional_operands.count;
  5548. if (variadic) {
  5549. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5550. } else if (positional_operand_count > pt->param_count) {
  5551. err = CallArgumentError_TooManyArguments;
  5552. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5553. if (show_error) {
  5554. gbString proc_str = expr_to_string(ce->proc);
  5555. defer (gb_string_free(proc_str));
  5556. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5557. }
  5558. return err;
  5559. }
  5560. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5561. for (isize i = 0; i < positional_operand_count; i++) {
  5562. ordered_operands[i] = positional_operands[i];
  5563. visited[i] = true;
  5564. }
  5565. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5566. bool named_variadic_param = false;
  5567. if (named_operands.count != 0) {
  5568. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5569. for_array(i, ce->split_args->named) {
  5570. Ast *arg = ce->split_args->named[i];
  5571. Operand operand = named_operands[i];
  5572. ast_node(fv, FieldValue, arg);
  5573. if (fv->field->kind != Ast_Ident) {
  5574. if (show_error) {
  5575. gbString expr_str = expr_to_string(fv->field);
  5576. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5577. gb_string_free(expr_str);
  5578. }
  5579. err = CallArgumentError_InvalidFieldValue;
  5580. continue;
  5581. }
  5582. String name = fv->field->Ident.token.string;
  5583. isize param_index = lookup_procedure_parameter(pt, name);
  5584. if (param_index < 0) {
  5585. if (show_error) {
  5586. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5587. }
  5588. err = CallArgumentError_ParameterNotFound;
  5589. continue;
  5590. }
  5591. if (pt->variadic && param_index == pt->variadic_index) {
  5592. named_variadic_param = true;
  5593. }
  5594. if (visited[param_index]) {
  5595. if (show_error) {
  5596. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5597. }
  5598. err = CallArgumentError_DuplicateParameter;
  5599. continue;
  5600. }
  5601. visited[param_index] = true;
  5602. ordered_operands[param_index] = operand;
  5603. }
  5604. }
  5605. isize dummy_argument_count = 0;
  5606. bool actually_variadic = false;
  5607. if (variadic) {
  5608. if (visited[pt->variadic_index] &&
  5609. positional_operand_count < positional_operands.count) {
  5610. if (show_error) {
  5611. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5612. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5613. }
  5614. err = CallArgumentError_DuplicateParameter;
  5615. } else if (!visited[pt->variadic_index]) {
  5616. visited[pt->variadic_index] = true;
  5617. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5618. if (vari_expand) {
  5619. if (variadic_operands.count == 0) {
  5620. error(call, "'..' in the wrong position");
  5621. } else {
  5622. GB_ASSERT(variadic_operands.count != 0);
  5623. *variadic_operand = variadic_operands[0];
  5624. variadic_operand->type = default_type(variadic_operand->type);
  5625. actually_variadic = true;
  5626. }
  5627. } else {
  5628. AstFile *f = call->file();
  5629. // HACK(bill): this is an awful hack
  5630. Operand o = {};
  5631. o.mode = Addressing_Value;
  5632. o.expr = ast_ident(f, make_token_ident("nil"));
  5633. o.expr->Ident.token.pos = ast_token(call).pos;
  5634. if (variadic_operands.count != 0) {
  5635. actually_variadic = true;
  5636. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5637. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5638. o.type = vt->type;
  5639. } else {
  5640. dummy_argument_count += 1;
  5641. o.type = t_untyped_nil;
  5642. }
  5643. *variadic_operand = o;
  5644. }
  5645. }
  5646. }
  5647. for (isize i = 0; i < pt->param_count; i++) {
  5648. if (!visited[i]) {
  5649. Entity *e = pt->params->Tuple.variables[i];
  5650. bool context_allocator_error = false;
  5651. if (e->kind == Entity_Variable) {
  5652. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5653. if (ast_file_vet_explicit_allocators(c->file) && !checking_proc_group) {
  5654. // NOTE(lucas): check if we are trying to default to context.allocator or context.temp_allocator
  5655. if (e->Variable.param_value.original_ast_expr->kind == Ast_SelectorExpr) {
  5656. auto& expr = e->Variable.param_value.original_ast_expr->SelectorExpr.expr;
  5657. auto& selector = e->Variable.param_value.original_ast_expr->SelectorExpr.selector;
  5658. if (expr->kind == Ast_Implicit &&
  5659. expr->Implicit.string == STR_LIT("context") &&
  5660. selector->kind == Ast_Ident &&
  5661. (selector->Ident.token.string == STR_LIT("allocator") ||
  5662. selector->Ident.token.string == STR_LIT("temp_allocator"))) {
  5663. context_allocator_error = true;
  5664. }
  5665. }
  5666. }
  5667. if (!context_allocator_error) {
  5668. ordered_operands[i].mode = Addressing_Value;
  5669. ordered_operands[i].type = e->type;
  5670. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5671. dummy_argument_count += 1;
  5672. score += assign_score_function(1);
  5673. continue;
  5674. }
  5675. }
  5676. }
  5677. if (show_error) {
  5678. if (context_allocator_error) {
  5679. gbString str = type_to_string(e->type);
  5680. error(call, "Parameter '%.*s' of type '%s' must be explicitly provided in procedure call",
  5681. LIT(e->token.string), str);
  5682. gb_string_free(str);
  5683. } else if (e->kind == Entity_TypeName) {
  5684. error(call, "Type parameter '%.*s' is missing in procedure call",
  5685. LIT(e->token.string));
  5686. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5687. // Ignore
  5688. } else {
  5689. gbString str = type_to_string(e->type);
  5690. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5691. LIT(e->token.string), str);
  5692. gb_string_free(str);
  5693. }
  5694. }
  5695. err = CallArgumentError_ParameterMissing;
  5696. }
  5697. }
  5698. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5699. bool allow_array_programming = !(e && (e->flags & EntityFlag_NoBroadcast));
  5700. i64 s = 0;
  5701. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic, allow_array_programming)) {
  5702. bool ok = false;
  5703. if (e && (e->flags & EntityFlag_AnyInt)) {
  5704. if (is_type_integer(param_type)) {
  5705. ok = check_is_castable_to(c, o, param_type);
  5706. }
  5707. }
  5708. if (!allow_array_programming && check_is_assignable_to_with_score(c, o, param_type, nullptr, param_is_variadic, !allow_array_programming)) {
  5709. if (show_error) {
  5710. error(o->expr, "'#no_broadcast' disallows automatic broadcasting a value across all elements of an array-like type in a procedure argument");
  5711. }
  5712. }
  5713. if (ok) {
  5714. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5715. } else {
  5716. if (show_error) {
  5717. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5718. }
  5719. err = CallArgumentError_WrongTypes;
  5720. }
  5721. } else if (show_error) {
  5722. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5723. }
  5724. if (e && e->flags & EntityFlag_ConstInput) {
  5725. if (o->mode != Addressing_Constant) {
  5726. if (show_error) {
  5727. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5728. }
  5729. err = CallArgumentError_NoneConstantParameter;
  5730. }
  5731. }
  5732. if (e && e->kind == Entity_Constant && is_type_proc(e->type)) {
  5733. bool ok = false;
  5734. if (o->mode == Addressing_Constant) {
  5735. ok = true;
  5736. } else if (o->value.kind == ExactValue_Procedure) {
  5737. ok = true;
  5738. }
  5739. if (!ok) {
  5740. if (show_error) {
  5741. error(o->expr, "Expected a constant procedure value for the argument '%.*s'", LIT(e->token.string));
  5742. }
  5743. err = CallArgumentError_NoneConstantParameter;
  5744. }
  5745. }
  5746. if (!err && is_type_any(param_type)) {
  5747. add_type_info_type(c, o->type);
  5748. }
  5749. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5750. add_type_info_type(c, o->type);
  5751. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5752. } else if (show_error && is_type_untyped(o->type)) {
  5753. update_untyped_expr_type(c, o->expr, param_type, true);
  5754. }
  5755. return s;
  5756. };
  5757. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5758. err = CallArgumentError_None;
  5759. if (variadic) {
  5760. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5761. Type *t = pt->params->Tuple.variables[0]->type;
  5762. if (is_type_polymorphic(t)) {
  5763. if (show_error) {
  5764. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5765. }
  5766. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5767. }
  5768. }
  5769. } else {
  5770. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5771. PolyProcData poly_proc_data = {};
  5772. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5773. gen_entity = poly_proc_data.gen_entity;
  5774. Type *gept = base_type(gen_entity->type);
  5775. GB_ASSERT(is_type_proc(gept));
  5776. final_proc_type = gen_entity->type;
  5777. pt = &gept->Proc;
  5778. } else {
  5779. err = CallArgumentError_WrongTypes;
  5780. }
  5781. }
  5782. for (isize i = 0; i < pt->param_count; i++) {
  5783. Operand *o = &ordered_operands[i];
  5784. if (o->mode == Addressing_Invalid) {
  5785. continue;
  5786. }
  5787. Entity *e = pt->params->Tuple.variables[i];
  5788. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5789. if (e->kind == Entity_TypeName) {
  5790. GB_ASSERT(pt->is_polymorphic);
  5791. if (o->mode != Addressing_Type) {
  5792. if (show_error) {
  5793. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5794. }
  5795. err = CallArgumentError_WrongTypes;
  5796. }
  5797. if (are_types_identical(e->type, o->type)) {
  5798. score += assign_score_function(1);
  5799. } else {
  5800. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5801. }
  5802. continue;
  5803. }
  5804. if (param_is_variadic) {
  5805. if (!named_variadic_param) {
  5806. continue;
  5807. }
  5808. }
  5809. score += eval_param_and_score(c, o, e->type, err, false, e, show_error);
  5810. }
  5811. }
  5812. if (variadic) {
  5813. Entity *var_entity = pt->params->Tuple.variables[pt->variadic_index];
  5814. Type *slice = var_entity->type;
  5815. GB_ASSERT(is_type_slice(slice));
  5816. Type *elem = base_type(slice)->Slice.elem;
  5817. Type *t = elem;
  5818. if (is_type_polymorphic(t)) {
  5819. if (show_error) {
  5820. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5821. }
  5822. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5823. }
  5824. for_array(operand_index, variadic_operands) {
  5825. Operand *o = &variadic_operands[operand_index];
  5826. if (vari_expand) {
  5827. t = slice;
  5828. if (operand_index > 0) {
  5829. if (show_error) {
  5830. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5831. }
  5832. if (data) {
  5833. data->score = score;
  5834. data->result_type = final_proc_type->Proc.results;
  5835. data->gen_entity = gen_entity;
  5836. }
  5837. return CallArgumentError_MultipleVariadicExpand;
  5838. }
  5839. }
  5840. score += eval_param_and_score(c, o, t, err, true, var_entity, show_error);
  5841. }
  5842. if (!vari_expand && variadic_operands.count != 0) {
  5843. // NOTE(bill, 2024-07-14): minimize the stack usage for variadic parameters with the backing array
  5844. if (c->decl) {
  5845. bool found = false;
  5846. for (auto &vr : c->decl->variadic_reuses) {
  5847. if (are_types_identical(slice, vr.slice_type)) {
  5848. vr.max_count = gb_max(vr.max_count, variadic_operands.count);
  5849. found = true;
  5850. break;
  5851. }
  5852. }
  5853. if (!found) {
  5854. array_add(&c->decl->variadic_reuses, VariadicReuseData{slice, variadic_operands.count});
  5855. }
  5856. }
  5857. }
  5858. }
  5859. if (data) {
  5860. data->score = score;
  5861. data->result_type = final_proc_type->Proc.results;
  5862. data->gen_entity = gen_entity;
  5863. Ast *proc_lit = nullptr;
  5864. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5865. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5866. if (vp && vp->kind == Ast_ProcLit) {
  5867. proc_lit = vp;
  5868. }
  5869. }
  5870. if (proc_lit == nullptr) {
  5871. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5872. }
  5873. }
  5874. return err;
  5875. }
  5876. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5877. GB_ASSERT(ce != nullptr);
  5878. if (ce->args.count == 0) {
  5879. return false;
  5880. }
  5881. return ce->args[0]->kind == Ast_FieldValue;
  5882. }
  5883. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_) {
  5884. Entity **lhs = nullptr;
  5885. isize lhs_count = -1;
  5886. if (proc_type == nullptr || proc_type == t_invalid) {
  5887. return nullptr;
  5888. }
  5889. GB_ASSERT(is_type_proc(proc_type));
  5890. TypeProc *pt = &base_type(proc_type)->Proc;
  5891. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5892. if (pt->params != nullptr) {
  5893. lhs = pt->params->Tuple.variables.data;
  5894. lhs_count = pt->params->Tuple.variables.count;
  5895. }
  5896. } else {
  5897. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5898. if (pt->params == nullptr) {
  5899. lhs_count = 0;
  5900. } else {
  5901. lhs_count = pt->params->Tuple.variables.count;
  5902. }
  5903. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5904. for (isize i = 0; i < lhs_count; i++) {
  5905. Entity *e = pt->params->Tuple.variables[i];
  5906. if (!is_type_polymorphic(e->type)) {
  5907. lhs[i] = e;
  5908. }
  5909. }
  5910. }
  5911. if (lhs_count_) *lhs_count_ = lhs_count;
  5912. return lhs;
  5913. }
  5914. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5915. if (clauses != nullptr) {
  5916. for (Ast *clause : *clauses) {
  5917. Operand o = {};
  5918. check_expr(ctx, &o, clause);
  5919. if (o.mode != Addressing_Constant) {
  5920. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5921. if (print_err && call_expr) error(call_expr, "at caller location");
  5922. return false;
  5923. } else if (o.value.kind != ExactValue_Bool) {
  5924. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5925. if (print_err && call_expr) error(call_expr, "at caller location");
  5926. return false;
  5927. } else if (!o.value.value_bool) {
  5928. if (print_err) {
  5929. ERROR_BLOCK();
  5930. gbString str = expr_to_string(clause);
  5931. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5932. gb_string_free(str);
  5933. if (scope != nullptr) {
  5934. isize print_count = 0;
  5935. for (auto const &entry : scope->elements) {
  5936. Entity *e = entry.value;
  5937. switch (e->kind) {
  5938. case Entity_TypeName: {
  5939. // if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5940. gbString str = type_to_string(e->type);
  5941. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5942. gb_string_free(str);
  5943. print_count += 1;
  5944. break;
  5945. }
  5946. case Entity_Constant: {
  5947. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5948. gbString str = exact_value_to_string(e->Constant.value);
  5949. if (is_type_untyped(e->type)) {
  5950. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5951. } else {
  5952. gbString t = type_to_string(e->type);
  5953. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5954. gb_string_free(t);
  5955. }
  5956. gb_string_free(str);
  5957. print_count += 1;
  5958. break;
  5959. }
  5960. }
  5961. }
  5962. }
  5963. if (call_expr) {
  5964. TokenPos pos = ast_token(call_expr).pos;
  5965. error_line("%s at caller location\n", token_pos_to_string(pos));
  5966. }
  5967. }
  5968. return false;
  5969. }
  5970. if (ast_file_vet_style(ctx->file)) {
  5971. Ast *c = unparen_expr(clause);
  5972. if (c->kind == Ast_BinaryExpr && c->BinaryExpr.op.kind == Token_CmpAnd) {
  5973. ERROR_BLOCK();
  5974. error(c, "Prefer to separate 'where' clauses with a comma rather than '&&'");
  5975. gbString x = expr_to_string(c->BinaryExpr.left);
  5976. gbString y = expr_to_string(c->BinaryExpr.right);
  5977. error_line("\tSuggestion: '%s, %s'\n", x, y);
  5978. gb_string_free(y);
  5979. gb_string_free(x);
  5980. }
  5981. }
  5982. }
  5983. }
  5984. return true;
  5985. }
  5986. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5987. bool success = true;
  5988. type = base_type(type);
  5989. if (named_args.count > 0) {
  5990. TypeProc *pt = nullptr;
  5991. if (is_type_proc(type)) {
  5992. pt = &type->Proc;
  5993. }
  5994. for_array(i, named_args) {
  5995. Ast *arg = named_args[i];
  5996. if (arg->kind != Ast_FieldValue) {
  5997. if (show_error) {
  5998. error(arg, "Expected a 'field = value'");
  5999. }
  6000. return false;
  6001. }
  6002. ast_node(fv, FieldValue, arg);
  6003. if (fv->field->kind != Ast_Ident) {
  6004. if (show_error) {
  6005. gbString expr_str = expr_to_string(fv->field);
  6006. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6007. gb_string_free(expr_str);
  6008. }
  6009. success = false;
  6010. continue;
  6011. }
  6012. String key = fv->field->Ident.token.string;
  6013. Ast *value = fv->value;
  6014. Type *type_hint = nullptr;
  6015. if (pt) {
  6016. isize param_index = lookup_procedure_parameter(pt, key);
  6017. if (param_index < 0) {
  6018. if (show_error) {
  6019. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  6020. }
  6021. success = false;
  6022. continue;
  6023. }
  6024. Entity *e = pt->params->Tuple.variables[param_index];
  6025. if (!is_type_polymorphic(e->type)) {
  6026. type_hint = e->type;
  6027. }
  6028. }
  6029. Operand o = {};
  6030. check_expr_with_type_hint(c, &o, value, type_hint);
  6031. if (o.mode == Addressing_Invalid) {
  6032. success = false;
  6033. }
  6034. array_add(named_operands, o);
  6035. }
  6036. }
  6037. return success;
  6038. }
  6039. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  6040. Entity *e, Type *proc_type,
  6041. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  6042. CallArgumentErrorMode show_error_mode,
  6043. CallArgumentData *data,
  6044. bool checking_proc_group) {
  6045. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  6046. Ast *ident = operand->expr;
  6047. while (ident->kind == Ast_SelectorExpr) {
  6048. Ast *s = ident->SelectorExpr.selector;
  6049. ident = s;
  6050. }
  6051. if (e == nullptr) {
  6052. e = entity_of_node(ident);
  6053. if (e != nullptr) {
  6054. proc_type = e->type;
  6055. }
  6056. }
  6057. GB_ASSERT(proc_type != nullptr);
  6058. proc_type = base_type(proc_type);
  6059. if (proc_type == t_invalid) {
  6060. return false;
  6061. }
  6062. GB_ASSERT(proc_type->kind == Type_Proc);
  6063. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data, checking_proc_group);
  6064. if (return_on_failure && err != CallArgumentError_None) {
  6065. return false;
  6066. }
  6067. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  6068. if (!return_on_failure && entity_to_use != nullptr) {
  6069. add_entity_use(c, ident, entity_to_use);
  6070. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  6071. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  6072. }
  6073. if (data->gen_entity != nullptr) {
  6074. Entity *e = data->gen_entity;
  6075. DeclInfo *decl = data->gen_entity->decl_info;
  6076. CheckerContext ctx = *c;
  6077. ctx.scope = decl->scope;
  6078. ctx.decl = decl;
  6079. ctx.proc_name = e->token.string;
  6080. ctx.curr_proc_decl = decl;
  6081. ctx.curr_proc_sig = e->type;
  6082. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  6083. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  6084. if (return_on_failure) {
  6085. if (!ok) {
  6086. return false;
  6087. }
  6088. } else {
  6089. decl->where_clauses_evaluated = true;
  6090. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  6091. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  6092. }
  6093. if (is_type_proc(data->gen_entity->type)) {
  6094. Type *t = base_type(entity_to_use->type);
  6095. data->result_type = t->Proc.results;
  6096. }
  6097. }
  6098. }
  6099. return true;
  6100. }
  6101. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  6102. ast_node(ce, CallExpr, call);
  6103. GB_ASSERT(ce->split_args != nullptr);
  6104. Slice<Ast *> const &positional_args = ce->split_args->positional;
  6105. Slice<Ast *> const &named_args = ce->split_args->named;
  6106. CallArgumentData data = {};
  6107. data.result_type = t_invalid;
  6108. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  6109. auto procs = proc_group_entities_cloned(c, *operand);
  6110. if (procs.count > 1) {
  6111. isize max_arg_count = positional_args.count + named_args.count;
  6112. for (Ast *arg : positional_args) {
  6113. // NOTE(bill): The only thing that may have multiple values
  6114. // will be a call expression (assuming `or_return` and `()` will be stripped)
  6115. arg = strip_or_return_expr(arg);
  6116. if (arg && arg->kind == Ast_CallExpr) {
  6117. max_arg_count = ISIZE_MAX;
  6118. break;
  6119. }
  6120. }
  6121. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  6122. // NOTE(bill): The only thing that may have multiple values
  6123. // will be a call expression (assuming `or_return` and `()` will be stripped)
  6124. if (arg->kind == Ast_FieldValue) {
  6125. arg = strip_or_return_expr(arg->FieldValue.value);
  6126. if (arg && arg->kind == Ast_CallExpr) {
  6127. max_arg_count = ISIZE_MAX;
  6128. break;
  6129. }
  6130. }
  6131. }
  6132. // ignore named arguments first
  6133. for (Ast *arg : named_args) {
  6134. if (arg->kind != Ast_FieldValue) {
  6135. continue;
  6136. }
  6137. ast_node(fv, FieldValue, arg);
  6138. if (fv->field->kind != Ast_Ident) {
  6139. continue;
  6140. }
  6141. String key = fv->field->Ident.token.string;
  6142. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  6143. Type *t = procs[proc_index]->type;
  6144. if (is_type_proc(t)) {
  6145. isize param_index = lookup_procedure_parameter(t, key);
  6146. if (param_index < 0) {
  6147. array_unordered_remove(&procs, proc_index);
  6148. }
  6149. }
  6150. }
  6151. }
  6152. if (procs.count == 0) {
  6153. // if any of the named arguments are wrong, the `procs` will be empty
  6154. // just start from scratch
  6155. array_free(&procs);
  6156. procs = proc_group_entities_cloned(c, *operand);
  6157. }
  6158. // filter by positional argument length
  6159. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  6160. Entity *proc = procs[proc_index];
  6161. Type *pt = base_type(proc->type);
  6162. if (!(pt != nullptr && is_type_proc(pt))) {
  6163. proc_index++;
  6164. continue;
  6165. }
  6166. isize param_count = 0;
  6167. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  6168. if (param_count_excluding_defaults > max_arg_count) {
  6169. array_unordered_remove(&procs, proc_index);
  6170. continue;
  6171. }
  6172. if (!pt->Proc.variadic && max_arg_count != ISIZE_MAX && param_count < max_arg_count) {
  6173. array_unordered_remove(&procs, proc_index);
  6174. continue;
  6175. }
  6176. proc_index++;
  6177. }
  6178. }
  6179. Entity **lhs = nullptr;
  6180. isize lhs_count = -1;
  6181. i32 variadic_index = -1;
  6182. TEMPORARY_ALLOCATOR_GUARD();
  6183. auto positional_operands = array_make<Operand>(temporary_allocator(), 0, 0);
  6184. auto named_operands = array_make<Operand>(temporary_allocator(), 0, 0);
  6185. if (procs.count == 1) {
  6186. Entity *e = procs[0];
  6187. Type *pt = base_type(e->type);
  6188. if (pt != nullptr && is_type_proc(pt)) {
  6189. lhs = populate_proc_parameter_list(c, pt, &lhs_count);
  6190. if (pt->Proc.variadic) {
  6191. variadic_index = pt->Proc.variadic_index;
  6192. }
  6193. }
  6194. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6195. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  6196. check_call_arguments_single(c, call, operand,
  6197. e, e->type,
  6198. positional_operands, named_operands,
  6199. CallArgumentErrorMode::ShowErrors,
  6200. &data, false);
  6201. }
  6202. return data;
  6203. }
  6204. {
  6205. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  6206. // where the same positional parameter has the same type value (and ellipsis)
  6207. isize proc_arg_count = -1;
  6208. for (Entity *p : procs) {
  6209. Type *pt = base_type(p->type);
  6210. if (pt != nullptr && is_type_proc(pt)) {
  6211. if (proc_arg_count < 0) {
  6212. proc_arg_count = pt->Proc.param_count;
  6213. } else {
  6214. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  6215. }
  6216. }
  6217. }
  6218. if (proc_arg_count >= 0) {
  6219. lhs_count = proc_arg_count;
  6220. if (lhs_count > 0) {
  6221. lhs = gb_alloc_array(temporary_allocator(), Entity *, lhs_count);
  6222. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  6223. Entity *e = nullptr;
  6224. for (Entity *p : procs) {
  6225. Type *pt = base_type(p->type);
  6226. if (!(pt != nullptr && is_type_proc(pt))) {
  6227. continue;
  6228. }
  6229. if (e == nullptr) {
  6230. e = pt->Proc.params->Tuple.variables[param_index];
  6231. } else {
  6232. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  6233. if (e == f) {
  6234. continue;
  6235. }
  6236. if (are_types_identical(e->type, f->type)) {
  6237. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  6238. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  6239. if (ee == fe) {
  6240. continue;
  6241. }
  6242. }
  6243. // NOTE(bill): Entities are not close enough to be used
  6244. e = nullptr;
  6245. break;
  6246. }
  6247. }
  6248. lhs[param_index] = e;
  6249. }
  6250. for (Entity *p : procs) {
  6251. Type *pt = base_type(p->type);
  6252. if (!(pt != nullptr && is_type_proc(pt))) {
  6253. continue;
  6254. }
  6255. if (pt->Proc.is_polymorphic) {
  6256. if (variadic_index == -1) {
  6257. variadic_index = pt->Proc.variadic_index;
  6258. } else if (variadic_index != pt->Proc.variadic_index) {
  6259. variadic_index = -1;
  6260. break;
  6261. }
  6262. } else {
  6263. variadic_index = -1;
  6264. break;
  6265. }
  6266. }
  6267. }
  6268. }
  6269. }
  6270. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6271. for_array(i, named_args) {
  6272. Ast *arg = named_args[i];
  6273. if (arg->kind != Ast_FieldValue) {
  6274. error(arg, "Expected a 'field = value'");
  6275. return data;
  6276. }
  6277. ast_node(fv, FieldValue, arg);
  6278. if (fv->field->kind != Ast_Ident) {
  6279. gbString expr_str = expr_to_string(fv->field);
  6280. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6281. gb_string_free(expr_str);
  6282. return data;
  6283. }
  6284. String key = fv->field->Ident.token.string;
  6285. Ast *value = fv->value;
  6286. Type *type_hint = nullptr;
  6287. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  6288. Entity *e = lhs[lhs_idx];
  6289. if (e != nullptr && e->token.string == key &&
  6290. !is_type_polymorphic(e->type)) {
  6291. type_hint = e->type;
  6292. break;
  6293. }
  6294. }
  6295. Operand o = {};
  6296. check_expr_with_type_hint(c, &o, value, type_hint);
  6297. array_add(&named_operands, o);
  6298. }
  6299. auto valids = array_make<ValidIndexAndScore>(temporary_allocator(), 0, procs.count);
  6300. auto proc_entities = array_make<Entity *>(temporary_allocator(), 0, procs.count*2 + 1);
  6301. for (Entity *proc : procs) {
  6302. array_add(&proc_entities, proc);
  6303. }
  6304. int max_matched_features = 0;
  6305. gbString expr_name = expr_to_string(operand->expr);
  6306. defer (gb_string_free(expr_name));
  6307. c->in_proc_group = true;
  6308. for_array(i, procs) {
  6309. Entity *p = procs[i];
  6310. if (p->flags & EntityFlag_Disabled) {
  6311. continue;
  6312. }
  6313. Type *pt = base_type(p->type);
  6314. if (pt != nullptr && is_type_proc(pt)) {
  6315. CallArgumentData data = {};
  6316. CheckerContext ctx = *c;
  6317. ctx.no_polymorphic_errors = true;
  6318. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  6319. ctx.hide_polymorphic_errors = true;
  6320. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  6321. p, pt,
  6322. positional_operands, named_operands,
  6323. CallArgumentErrorMode::NoErrors,
  6324. &data, true);
  6325. if (!is_a_candidate) {
  6326. continue;
  6327. }
  6328. isize index = i;
  6329. ValidIndexAndScore item = {};
  6330. item.score = data.score;
  6331. if (data.gen_entity != nullptr) {
  6332. array_add(&proc_entities, data.gen_entity);
  6333. index = proc_entities.count-1;
  6334. // prefer non-polymorphic procedures over polymorphic
  6335. item.score += assign_score_function(1);
  6336. }
  6337. max_matched_features = gb_max(max_matched_features, matched_target_features(&pt->Proc));
  6338. item.index = index;
  6339. array_add(&valids, item);
  6340. }
  6341. }
  6342. c->in_proc_group = false;
  6343. if (max_matched_features > 0) {
  6344. for_array(i, valids) {
  6345. Entity *p = procs[valids[i].index];
  6346. Type *t = base_type(p->type);
  6347. GB_ASSERT(t->kind == Type_Proc);
  6348. int matched = matched_target_features(&t->Proc);
  6349. valids[i].score += assign_score_function(max_matched_features-matched);
  6350. }
  6351. }
  6352. if (valids.count > 1) {
  6353. array_sort(valids, valid_index_and_score_cmp);
  6354. i64 best_score = valids[0].score;
  6355. Entity *best_entity = proc_entities[valids[0].index];
  6356. GB_ASSERT(best_entity != nullptr);
  6357. for (isize i = 1; i < valids.count; i++) {
  6358. if (best_score > valids[i].score) {
  6359. valids.count = i;
  6360. break;
  6361. }
  6362. if (best_entity == proc_entities[valids[i].index]) {
  6363. valids.count = i;
  6364. break;
  6365. }
  6366. }
  6367. }
  6368. auto print_argument_types = [&]() {
  6369. error_line("\tGiven argument types: (");
  6370. isize i = 0;
  6371. for (Operand const &o : positional_operands) {
  6372. if (i++ > 0) error_line(", ");
  6373. gbString type = type_to_string(o.type);
  6374. defer (gb_string_free(type));
  6375. error_line("%s", type);
  6376. }
  6377. for (Operand const &o : named_operands) {
  6378. if (i++ > 0) error_line(", ");
  6379. gbString type = type_to_string(o.type);
  6380. defer (gb_string_free(type));
  6381. if (i < ce->split_args->named.count) {
  6382. Ast *named_field = ce->split_args->named[i];
  6383. ast_node(fv, FieldValue, named_field);
  6384. gbString field = expr_to_string(fv->field);
  6385. defer (gb_string_free(field));
  6386. error_line("%s = %s", field, type);
  6387. } else {
  6388. error_line("%s", type);
  6389. }
  6390. }
  6391. error_line(")\n");
  6392. };
  6393. if (valids.count == 0) {
  6394. ERROR_BLOCK();
  6395. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  6396. if (positional_operands.count == 0 && named_operands.count == 0) {
  6397. error_line("\tNo given arguments\n");
  6398. } else {
  6399. print_argument_types();
  6400. }
  6401. if (procs.count == 0) {
  6402. procs = proc_group_entities_cloned(c, *operand);
  6403. }
  6404. if (procs.count > 0) {
  6405. error_line("Did you mean to use one of the following:\n");
  6406. }
  6407. // Try to reduce the list further for `$T: typeid` like parameters
  6408. bool *possibly_ignore = temporary_alloc_array<bool>(procs.count);
  6409. isize possibly_ignore_set = 0;
  6410. if (true) {
  6411. // NOTE(bill): This currently only checks for #soa types
  6412. for_array(i, procs) {
  6413. Entity *proc = procs[i];
  6414. Type *t = base_type(proc->type);
  6415. if (t == nullptr || t->kind != Type_Proc) {
  6416. continue;
  6417. }
  6418. TypeProc *pt = &t->Proc;
  6419. if (pt->param_count == 0) {
  6420. continue;
  6421. }
  6422. for_array(j, pt->params->Tuple.variables) {
  6423. Entity *v = pt->params->Tuple.variables[j];
  6424. if (v->kind != Entity_TypeName) {
  6425. continue;
  6426. }
  6427. Type *dst_t = base_type(v->type);
  6428. while (dst_t->kind == Type_Generic && dst_t->Generic.specialized) {
  6429. dst_t = dst_t->Generic.specialized;
  6430. }
  6431. if (j >= positional_operands.count) {
  6432. continue;
  6433. }
  6434. Operand const &o = positional_operands[j];
  6435. if (o.mode != Addressing_Type) {
  6436. continue;
  6437. }
  6438. Type *t = base_type(o.type);
  6439. if (t->kind == dst_t->kind) {
  6440. continue;
  6441. }
  6442. Type *st = base_type(type_deref(o.type));
  6443. Type *dt = base_type(type_deref(dst_t));
  6444. if (st->kind == dt->kind) {
  6445. continue;
  6446. }
  6447. if (is_type_soa_struct(st)) {
  6448. possibly_ignore[i] = true;
  6449. possibly_ignore_set += 1;
  6450. continue;
  6451. }
  6452. }
  6453. }
  6454. }
  6455. if (possibly_ignore_set == procs.count) {
  6456. possibly_ignore_set = 0;
  6457. }
  6458. isize max_name_length = 0;
  6459. isize max_type_length = 0;
  6460. for_array(i, procs) {
  6461. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6462. continue;
  6463. }
  6464. Entity *proc = procs[i];
  6465. Type *t = base_type(proc->type);
  6466. if (t == t_invalid) continue;
  6467. String prefix = {};
  6468. String prefix_sep = {};
  6469. if (proc->pkg) {
  6470. prefix = proc->pkg->name;
  6471. prefix_sep = str_lit(".");
  6472. }
  6473. String name = proc->token.string;
  6474. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  6475. gbString pt;
  6476. if (t->Proc.node != nullptr) {
  6477. pt = expr_to_string(t->Proc.node);
  6478. } else {
  6479. pt = type_to_string(t);
  6480. }
  6481. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  6482. gb_string_free(pt);
  6483. }
  6484. isize max_spaces = gb_max(max_name_length, max_type_length);
  6485. char *spaces = temporary_alloc_array<char>(max_spaces+1);
  6486. for (isize i = 0; i < max_spaces; i++) {
  6487. spaces[i] = ' ';
  6488. }
  6489. spaces[max_spaces] = 0;
  6490. for_array(i, procs) {
  6491. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6492. continue;
  6493. }
  6494. Entity *proc = procs[i];
  6495. TokenPos pos = proc->token.pos;
  6496. Type *t = base_type(proc->type);
  6497. if (t == t_invalid) continue;
  6498. GB_ASSERT(t->kind == Type_Proc);
  6499. gbString pt;
  6500. defer (gb_string_free(pt));
  6501. if (t->Proc.node != nullptr) {
  6502. pt = expr_to_string(t->Proc.node);
  6503. } else {
  6504. pt = type_to_string(t);
  6505. }
  6506. String prefix = {};
  6507. String prefix_sep = {};
  6508. if (proc->pkg) {
  6509. prefix = proc->pkg->name;
  6510. prefix_sep = str_lit(".");
  6511. }
  6512. String name = proc->token.string;
  6513. isize len = prefix.len + prefix_sep.len + name.len;
  6514. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  6515. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  6516. char const *sep = "::";
  6517. if (proc->kind == Entity_Variable) {
  6518. sep = ":=";
  6519. }
  6520. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  6521. LIT(prefix), LIT(prefix_sep), LIT(name),
  6522. name_padding, spaces,
  6523. sep,
  6524. pt,
  6525. type_padding, spaces,
  6526. token_pos_to_string(pos)
  6527. );
  6528. }
  6529. if (procs.count > 0) {
  6530. error_line("\n");
  6531. }
  6532. data.result_type = t_invalid;
  6533. } else if (valids.count > 1) {
  6534. ERROR_BLOCK();
  6535. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  6536. if (positional_operands.count == 0 && named_operands.count == 0) {
  6537. error_line("\tNo given arguments\n");
  6538. } else {
  6539. print_argument_types();
  6540. }
  6541. for (auto const &valid : valids) {
  6542. Entity *proc = proc_entities[valid.index];
  6543. GB_ASSERT(proc != nullptr);
  6544. TokenPos pos = proc->token.pos;
  6545. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  6546. gbString pt = nullptr;
  6547. defer (gb_string_free(pt));
  6548. if (t->Proc.node != nullptr) {
  6549. pt = expr_to_string(t->Proc.node);
  6550. } else {
  6551. pt = type_to_string(t);
  6552. }
  6553. String name = proc->token.string;
  6554. char const *sep = "::";
  6555. if (proc->kind == Entity_Variable) {
  6556. sep = ":=";
  6557. }
  6558. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  6559. if (proc->decl_info->proc_lit != nullptr) {
  6560. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  6561. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  6562. if (pl->where_token.kind != Token_Invalid) {
  6563. error_line("\n\t\twhere ");
  6564. for_array(j, pl->where_clauses) {
  6565. Ast *clause = pl->where_clauses[j];
  6566. if (j != 0) {
  6567. error_line("\t\t ");
  6568. }
  6569. gbString str = expr_to_string(clause);
  6570. error_line("%s", str);
  6571. gb_string_free(str);
  6572. if (j != pl->where_clauses.count-1) {
  6573. error_line(",");
  6574. }
  6575. }
  6576. error_line("\n\t");
  6577. }
  6578. }
  6579. error_line("at %s\n", token_pos_to_string(pos));
  6580. }
  6581. data.result_type = t_invalid;
  6582. } else {
  6583. GB_ASSERT(valids.count == 1);
  6584. Ast *ident = operand->expr;
  6585. while (ident->kind == Ast_SelectorExpr) {
  6586. Ast *s = ident->SelectorExpr.selector;
  6587. ident = s;
  6588. }
  6589. Entity *e = proc_entities[valids[0].index];
  6590. GB_ASSERT(e != nullptr);
  6591. check_call_arguments_single(c, call, operand,
  6592. e, e->type,
  6593. positional_operands, named_operands,
  6594. CallArgumentErrorMode::ShowErrors,
  6595. &data, false);
  6596. return data;
  6597. }
  6598. return data;
  6599. }
  6600. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  6601. Type *proc_type = nullptr;
  6602. CallArgumentData data = {};
  6603. data.result_type = t_invalid;
  6604. proc_type = base_type(operand->type);
  6605. TypeProc *pt = nullptr;
  6606. if (proc_type) {
  6607. pt = &proc_type->Proc;
  6608. }
  6609. TEMPORARY_ALLOCATOR_GUARD();
  6610. ast_node(ce, CallExpr, call);
  6611. bool any_failure = false;
  6612. // Split positional and named args into separate arrays/slices
  6613. Slice<Ast *> positional_args = {};
  6614. Slice<Ast *> named_args = {};
  6615. if (ce->split_args == nullptr) {
  6616. positional_args = ce->args;
  6617. for (isize i = 0; i < ce->args.count; i++) {
  6618. Ast *arg = ce->args.data[i];
  6619. if (arg->kind == Ast_FieldValue) {
  6620. positional_args.count = i;
  6621. break;
  6622. }
  6623. }
  6624. named_args = slice(ce->args, positional_args.count, ce->args.count);
  6625. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  6626. split_args->positional = positional_args;
  6627. split_args->named = named_args;
  6628. ce->split_args = split_args;
  6629. } else {
  6630. positional_args = ce->split_args->positional;
  6631. named_args = ce->split_args->named;
  6632. }
  6633. if (operand->mode == Addressing_ProcGroup) {
  6634. return check_call_arguments_proc_group(c, operand, call);
  6635. }
  6636. TEMPORARY_ALLOCATOR_GUARD();
  6637. auto positional_operands = array_make<Operand>(temporary_allocator(), 0, positional_args.count);
  6638. auto named_operands = array_make<Operand>(temporary_allocator(), 0, 0);
  6639. if (positional_args.count > 0) {
  6640. Entity **lhs = nullptr;
  6641. isize lhs_count = -1;
  6642. i32 variadic_index = -1;
  6643. if (pt != nullptr) {
  6644. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count);
  6645. if (pt->variadic) {
  6646. variadic_index = pt->variadic_index;
  6647. }
  6648. }
  6649. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6650. }
  6651. if (named_args.count > 0) {
  6652. for_array(i, named_args) {
  6653. Ast *arg = named_args[i];
  6654. if (arg->kind != Ast_FieldValue) {
  6655. error(arg, "Expected a 'field = value'");
  6656. return data;
  6657. }
  6658. ast_node(fv, FieldValue, arg);
  6659. if (fv->field->kind != Ast_Ident) {
  6660. gbString expr_str = expr_to_string(fv->field);
  6661. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6662. any_failure = true;
  6663. gb_string_free(expr_str);
  6664. continue;
  6665. }
  6666. String key = fv->field->Ident.token.string;
  6667. Ast *value = fv->value;
  6668. isize param_index = lookup_procedure_parameter(pt, key);
  6669. Type *type_hint = nullptr;
  6670. if (param_index >= 0) {
  6671. Entity *e = pt->params->Tuple.variables[param_index];
  6672. type_hint = e->type;
  6673. }
  6674. Operand o = {};
  6675. check_expr_with_type_hint(c, &o, value, type_hint);
  6676. if (o.mode == Addressing_Invalid) {
  6677. any_failure = true;
  6678. }
  6679. array_add(&named_operands, o);
  6680. }
  6681. }
  6682. if (!any_failure) {
  6683. check_call_arguments_single(c, call, operand,
  6684. nullptr, proc_type,
  6685. positional_operands, named_operands,
  6686. CallArgumentErrorMode::ShowErrors,
  6687. &data, false);
  6688. } else if (pt) {
  6689. data.result_type = pt->results;
  6690. }
  6691. return data;
  6692. }
  6693. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6694. if (!is_type_polymorphic_record(t)) {
  6695. return -1;
  6696. }
  6697. TypeTuple *params = get_record_polymorphic_params(t);
  6698. if (params == nullptr) {
  6699. return -1;
  6700. }
  6701. for_array(i, params->variables) {
  6702. Entity *e = params->variables[i];
  6703. String name = e->token.string;
  6704. if (is_blank_ident(name)) {
  6705. continue;
  6706. }
  6707. if (name == parameter_name) {
  6708. return i;
  6709. }
  6710. }
  6711. return -1;
  6712. }
  6713. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6714. TEMPORARY_ALLOCATOR_GUARD();
  6715. ast_node(ce, CallExpr, call);
  6716. Type *original_type = operand->type;
  6717. GB_ASSERT(is_type_polymorphic_record(original_type));
  6718. bool show_error = true;
  6719. Array<Operand> operands = {};
  6720. CallArgumentError err = CallArgumentError_None;
  6721. bool named_fields = false;
  6722. {
  6723. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6724. auto prev_type_path = c->type_path;
  6725. TEMPORARY_ALLOCATOR_GUARD();
  6726. c->type_path = new_checker_type_path(temporary_allocator());
  6727. defer (c->type_path = prev_type_path);
  6728. if (is_call_expr_field_value(ce)) {
  6729. named_fields = true;
  6730. operands = array_make<Operand>(temporary_allocator(), ce->args.count);
  6731. for_array(i, ce->args) {
  6732. Ast *arg = ce->args[i];
  6733. ast_node(fv, FieldValue, arg);
  6734. if (fv->value == nullptr) {
  6735. error(fv->eq, "Expected a value");
  6736. err = CallArgumentError_InvalidFieldValue;
  6737. continue;
  6738. }
  6739. if (fv->field->kind == Ast_Ident) {
  6740. String name = fv->field->Ident.token.string;
  6741. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6742. if (index >= 0) {
  6743. TypeTuple *params = get_record_polymorphic_params(original_type);
  6744. Entity *e = params->variables[index];
  6745. if (e->kind == Entity_Constant) {
  6746. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6747. continue;
  6748. }
  6749. }
  6750. }
  6751. check_expr_or_type(c, &operands[i], fv->value);
  6752. }
  6753. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6754. if (vari_expand) {
  6755. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6756. }
  6757. } else {
  6758. operands = array_make<Operand>(temporary_allocator(), 0, 2*ce->args.count);
  6759. Entity **lhs = nullptr;
  6760. isize lhs_count = -1;
  6761. TypeTuple *params = get_record_polymorphic_params(original_type);
  6762. if (params != nullptr) {
  6763. lhs = params->variables.data;
  6764. lhs_count = params->variables.count;
  6765. }
  6766. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6767. }
  6768. }
  6769. if (err != 0) {
  6770. operand->mode = Addressing_Invalid;
  6771. return err;
  6772. }
  6773. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6774. isize param_count = tuple->variables.count;
  6775. isize minimum_param_count = param_count;
  6776. for (; minimum_param_count > 0; minimum_param_count--) {
  6777. Entity *e = tuple->variables[minimum_param_count-1];
  6778. if (e->kind != Entity_Constant) {
  6779. break;
  6780. }
  6781. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6782. break;
  6783. }
  6784. }
  6785. Array<Operand> ordered_operands = operands;
  6786. if (!named_fields) {
  6787. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6788. array_copy(&ordered_operands, operands, 0);
  6789. } else {
  6790. TEMPORARY_ALLOCATOR_GUARD();
  6791. bool *visited = temporary_alloc_array<bool>(param_count);
  6792. // LEAK(bill)
  6793. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6794. for_array(i, ce->args) {
  6795. Ast *arg = ce->args[i];
  6796. ast_node(fv, FieldValue, arg);
  6797. if (fv->field->kind != Ast_Ident) {
  6798. if (show_error) {
  6799. gbString expr_str = expr_to_string(fv->field);
  6800. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6801. gb_string_free(expr_str);
  6802. }
  6803. err = CallArgumentError_InvalidFieldValue;
  6804. continue;
  6805. }
  6806. String name = fv->field->Ident.token.string;
  6807. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6808. if (index < 0) {
  6809. if (show_error) {
  6810. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6811. }
  6812. err = CallArgumentError_ParameterNotFound;
  6813. continue;
  6814. }
  6815. if (visited[index]) {
  6816. if (show_error) {
  6817. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6818. }
  6819. err = CallArgumentError_DuplicateParameter;
  6820. continue;
  6821. }
  6822. visited[index] = true;
  6823. ordered_operands[index] = operands[i];
  6824. }
  6825. for (isize i = 0; i < param_count; i++) {
  6826. if (!visited[i]) {
  6827. Entity *e = tuple->variables[i];
  6828. if (is_blank_ident(e->token)) {
  6829. continue;
  6830. }
  6831. if (show_error) {
  6832. if (e->kind == Entity_TypeName) {
  6833. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6834. LIT(e->token.string));
  6835. } else {
  6836. gbString str = type_to_string(e->type);
  6837. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6838. LIT(e->token.string), str);
  6839. gb_string_free(str);
  6840. }
  6841. }
  6842. err = CallArgumentError_ParameterMissing;
  6843. }
  6844. }
  6845. }
  6846. if (err != 0) {
  6847. operand->mode = Addressing_Invalid;
  6848. return err;
  6849. }
  6850. while (ordered_operands.count > 0) {
  6851. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6852. break;
  6853. }
  6854. array_pop(&ordered_operands);
  6855. }
  6856. if (minimum_param_count != param_count) {
  6857. if (param_count < ordered_operands.count) {
  6858. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6859. err = CallArgumentError_TooManyArguments;
  6860. } else if (minimum_param_count > ordered_operands.count) {
  6861. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6862. err = CallArgumentError_TooFewArguments;
  6863. }
  6864. } else {
  6865. if (param_count < ordered_operands.count) {
  6866. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6867. err = CallArgumentError_TooManyArguments;
  6868. } else if (param_count > ordered_operands.count) {
  6869. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6870. err = CallArgumentError_TooFewArguments;
  6871. }
  6872. }
  6873. if (err != 0) {
  6874. return err;
  6875. }
  6876. if (minimum_param_count != param_count) {
  6877. array_resize(&ordered_operands, param_count);
  6878. isize missing_count = 0;
  6879. // NOTE(bill): Replace missing operands with the default values (if possible)
  6880. for_array(i, ordered_operands) {
  6881. Operand *o = &ordered_operands[i];
  6882. if (o->expr == nullptr) {
  6883. Entity *e = tuple->variables[i];
  6884. if (e->kind == Entity_Constant) {
  6885. missing_count += 1;
  6886. o->mode = Addressing_Constant;
  6887. o->type = default_type(e->type);
  6888. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6889. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6890. o->value = e->Constant.param_value.value;
  6891. }
  6892. } else if (e->kind == Entity_TypeName) {
  6893. missing_count += 1;
  6894. o->mode = Addressing_Type;
  6895. o->type = e->type;
  6896. o->expr = e->identifier;
  6897. }
  6898. }
  6899. }
  6900. }
  6901. isize oo_count = gb_min(param_count, ordered_operands.count);
  6902. i64 score = 0;
  6903. for (isize i = 0; i < oo_count; i++) {
  6904. Entity *e = tuple->variables[i];
  6905. Operand *o = &ordered_operands[i];
  6906. if (o->mode == Addressing_Invalid) {
  6907. continue;
  6908. }
  6909. if (e->kind == Entity_TypeName) {
  6910. if (o->mode != Addressing_Type) {
  6911. if (show_error) {
  6912. gbString expr = expr_to_string(o->expr);
  6913. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6914. gb_string_free(expr);
  6915. }
  6916. err = CallArgumentError_WrongTypes;
  6917. }
  6918. if (are_types_identical(e->type, o->type)) {
  6919. score += assign_score_function(1);
  6920. } else {
  6921. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6922. }
  6923. } else {
  6924. i64 s = 0;
  6925. if (o->type->kind == Type_Generic) {
  6926. // Polymorphic name!
  6927. score += assign_score_function(1);
  6928. continue;
  6929. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6930. if (show_error) {
  6931. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6932. }
  6933. err = CallArgumentError_WrongTypes;
  6934. }
  6935. o->type = e->type;
  6936. if (o->mode != Addressing_Constant) {
  6937. bool valid = false;
  6938. if (is_type_proc(o->type)) {
  6939. Entity *proc_entity = entity_from_expr(o->expr);
  6940. valid = proc_entity != nullptr;
  6941. }
  6942. if (!valid) {
  6943. if (show_error) {
  6944. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6945. }
  6946. err = CallArgumentError_NoneConstantParameter;
  6947. }
  6948. }
  6949. score += s;
  6950. }
  6951. // NOTE(bill): Add type info the parameters
  6952. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6953. // add_type_info_type(c, o->type);
  6954. }
  6955. if (show_error && err) {
  6956. return err;
  6957. }
  6958. {
  6959. GenTypesData *found_gen_types = ensure_polymorphic_record_entity_has_gen_types(c, original_type);
  6960. mutex_lock(&found_gen_types->mutex);
  6961. defer (mutex_unlock(&found_gen_types->mutex));
  6962. Entity *found_entity = find_polymorphic_record_entity(found_gen_types, param_count, ordered_operands);
  6963. if (found_entity) {
  6964. operand->mode = Addressing_Type;
  6965. operand->type = found_entity->type;
  6966. return err;
  6967. }
  6968. CheckerContext ctx = *c;
  6969. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6970. ctx.scope = polymorphic_record_parent_scope(original_type);
  6971. GB_ASSERT(ctx.scope != nullptr);
  6972. Type *bt = base_type(original_type);
  6973. String generated_name = make_string_c(expr_to_string(call));
  6974. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6975. if (bt->kind == Type_Struct) {
  6976. Ast *node = clone_ast(bt->Struct.node);
  6977. Type *struct_type = alloc_type_struct();
  6978. struct_type->Struct.node = node;
  6979. struct_type->Struct.polymorphic_parent = original_type;
  6980. set_base_type(named_type, struct_type);
  6981. check_open_scope(&ctx, node);
  6982. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6983. check_close_scope(&ctx);
  6984. } else if (bt->kind == Type_Union) {
  6985. Ast *node = clone_ast(bt->Union.node);
  6986. Type *union_type = alloc_type_union();
  6987. union_type->Union.node = node;
  6988. union_type->Union.polymorphic_parent = original_type;
  6989. set_base_type(named_type, union_type);
  6990. check_open_scope(&ctx, node);
  6991. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6992. check_close_scope(&ctx);
  6993. } else {
  6994. GB_PANIC("Unsupported parametric polymorphic record type");
  6995. }
  6996. bt = base_type(named_type);
  6997. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6998. GB_ASSERT(original_type->kind == Type_Named);
  6999. Entity *e = original_type->Named.type_name;
  7000. GB_ASSERT(e->kind == Entity_TypeName);
  7001. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  7002. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  7003. TypeTuple *tuple = get_record_polymorphic_params(bt);
  7004. if (tuple != nullptr) for_array(i, tuple->variables) {
  7005. Entity *v = tuple->variables[i];
  7006. String name = v->token.string;
  7007. if (i > 0) {
  7008. s = gb_string_append_fmt(s, ", ");
  7009. }
  7010. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  7011. if (v->kind == Entity_TypeName) {
  7012. if (v->type != nullptr && v->type->kind != Type_Generic) {
  7013. s = gb_string_append_fmt(s, "=");
  7014. s = write_type_to_string(s, v->type, false);
  7015. }
  7016. } else if (v->kind == Entity_Constant) {
  7017. if (v->Constant.value.kind != ExactValue_Invalid) {
  7018. s = gb_string_append_fmt(s, "=");
  7019. s = write_exact_value_to_string(s, v->Constant.value);
  7020. }
  7021. }
  7022. }
  7023. s = gb_string_append_fmt(s, ")");
  7024. String new_name = make_string_c(s);
  7025. named_type->Named.name = new_name;
  7026. if (named_type->Named.type_name) {
  7027. named_type->Named.type_name->token.string = new_name;
  7028. }
  7029. }
  7030. operand->mode = Addressing_Type;
  7031. operand->type = named_type;
  7032. }
  7033. return err;
  7034. }
  7035. // returns true on success
  7036. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  7037. bool success = true;
  7038. if (args.count > 0) {
  7039. if (allow_mixed) {
  7040. bool was_named = false;
  7041. for (Ast *arg : args) {
  7042. if (was_named && arg->kind != Ast_FieldValue) {
  7043. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  7044. success = false;
  7045. break;
  7046. }
  7047. was_named = was_named || arg->kind == Ast_FieldValue;
  7048. }
  7049. } else {
  7050. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  7051. for (Ast *arg : args) {
  7052. bool mix = false;
  7053. if (first_is_field_value) {
  7054. mix = arg->kind != Ast_FieldValue;
  7055. } else {
  7056. mix = arg->kind == Ast_FieldValue;
  7057. }
  7058. if (mix) {
  7059. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  7060. success = false;
  7061. }
  7062. }
  7063. }
  7064. }
  7065. return success;
  7066. }
  7067. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  7068. operand->mode = Addressing_Invalid; \
  7069. operand->expr = call; \
  7070. return Expr_Stmt; \
  7071. }
  7072. gb_internal ExprKind check_call_expr_as_type_cast(CheckerContext *c, Operand *operand, Ast *call, Slice<Ast *> const &args, Type *type_hint) {
  7073. GB_ASSERT(operand->mode == Addressing_Type);
  7074. Type *t = operand->type;
  7075. if (is_type_polymorphic_record(t)) {
  7076. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  7077. if (!is_type_named(t)) {
  7078. gbString s = expr_to_string(operand->expr);
  7079. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  7080. gb_string_free(s);
  7081. operand->mode = Addressing_Invalid;
  7082. operand->type = t_invalid;;
  7083. return Expr_Expr;
  7084. }
  7085. auto err = check_polymorphic_record_type(c, operand, call);
  7086. if (err == 0) {
  7087. Ast *ident = operand->expr;
  7088. while (ident->kind == Ast_SelectorExpr) {
  7089. Ast *s = ident->SelectorExpr.selector;
  7090. ident = s;
  7091. }
  7092. Type *ot = operand->type;
  7093. GB_ASSERT(ot->kind == Type_Named);
  7094. Entity *e = ot->Named.type_name;
  7095. add_entity_use(c, ident, e);
  7096. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  7097. } else {
  7098. operand->mode = Addressing_Invalid;
  7099. operand->type = t_invalid;
  7100. }
  7101. } else {
  7102. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  7103. operand->mode = Addressing_Invalid;
  7104. isize arg_count = args.count;
  7105. switch (arg_count) {
  7106. case 0:
  7107. {
  7108. gbString str = type_to_string(t);
  7109. error(call, "Missing argument in conversion to '%s'", str);
  7110. gb_string_free(str);
  7111. } break;
  7112. default:
  7113. {
  7114. gbString str = type_to_string(t);
  7115. if (t->kind == Type_Basic) {
  7116. ERROR_BLOCK();
  7117. switch (t->Basic.kind) {
  7118. case Basic_complex32:
  7119. case Basic_complex64:
  7120. case Basic_complex128:
  7121. error(call, "Too many arguments in conversion to '%s'", str);
  7122. error_line("\tSuggestion: %s(1+2i) or construct with 'complex'\n", str);
  7123. break;
  7124. case Basic_quaternion64:
  7125. case Basic_quaternion128:
  7126. case Basic_quaternion256:
  7127. error(call, "Too many arguments in conversion to '%s'", str);
  7128. error_line("\tSuggestion: %s(1+2i+3j+4k) or construct with 'quaternion'\n", str);
  7129. break;
  7130. default:
  7131. error(call, "Too many arguments in conversion to '%s'", str);
  7132. }
  7133. } else {
  7134. error(call, "Too many arguments in conversion to '%s'", str);
  7135. }
  7136. gb_string_free(str);
  7137. } break;
  7138. case 1: {
  7139. Ast *arg = args[0];
  7140. if (arg->kind == Ast_FieldValue) {
  7141. error(call, "'field = value' cannot be used in a type conversion");
  7142. arg = arg->FieldValue.value;
  7143. // NOTE(bill): Carry on the cast regardless
  7144. }
  7145. check_expr_with_type_hint(c, operand, arg, t);
  7146. if (operand->mode != Addressing_Invalid) {
  7147. if (is_type_polymorphic(t)) {
  7148. error(call, "A polymorphic type cannot be used in a type conversion");
  7149. } else {
  7150. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  7151. // as it assumes it is determining the type
  7152. check_cast(c, operand, t);
  7153. }
  7154. }
  7155. operand->type = t;
  7156. operand->expr = call;
  7157. if (operand->mode != Addressing_Invalid) {
  7158. update_untyped_expr_type(c, arg, t, false);
  7159. }
  7160. break;
  7161. }
  7162. }
  7163. }
  7164. return Expr_Expr;
  7165. }
  7166. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  7167. if (proc != nullptr &&
  7168. proc->kind == Ast_BasicDirective) {
  7169. ast_node(bd, BasicDirective, proc);
  7170. String name = bd->name.string;
  7171. if (
  7172. name == "location" ||
  7173. name == "exists" ||
  7174. name == "assert" ||
  7175. name == "panic" ||
  7176. name == "defined" ||
  7177. name == "config" ||
  7178. name == "load" ||
  7179. name == "load_directory" ||
  7180. name == "load_hash" ||
  7181. name == "hash" ||
  7182. name == "caller_expression"
  7183. ) {
  7184. operand->mode = Addressing_Builtin;
  7185. operand->builtin_id = BuiltinProc_DIRECTIVE;
  7186. operand->expr = proc;
  7187. operand->type = t_invalid;
  7188. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  7189. } else {
  7190. error(proc, "Unknown directive: #%.*s", LIT(name));
  7191. operand->expr = proc;
  7192. operand->type = t_invalid;
  7193. operand->mode = Addressing_Invalid;
  7194. return Expr_Expr;
  7195. }
  7196. if (inlining != ProcInlining_none) {
  7197. error(call, "Inlining operators are not allowed on built-in procedures");
  7198. }
  7199. } else {
  7200. if (proc != nullptr) {
  7201. check_expr_or_type(c, operand, proc);
  7202. } else {
  7203. GB_ASSERT(operand->expr != nullptr);
  7204. }
  7205. }
  7206. if (operand->mode == Addressing_Invalid) {
  7207. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  7208. for (Ast *arg : args) {
  7209. if (arg->kind == Ast_FieldValue) {
  7210. arg = arg->FieldValue.value;
  7211. }
  7212. check_expr_base(c, operand, arg, nullptr);
  7213. }
  7214. operand->mode = Addressing_Invalid;
  7215. operand->expr = call;
  7216. return Expr_Stmt;
  7217. }
  7218. if (operand->mode == Addressing_Type) {
  7219. return check_call_expr_as_type_cast(c, operand, call, args, type_hint);
  7220. }
  7221. if (operand->mode == Addressing_Builtin) {
  7222. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  7223. i32 id = operand->builtin_id;
  7224. Entity *e = entity_of_node(operand->expr);
  7225. if (e != nullptr && e->token.string == "expand_to_tuple") {
  7226. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  7227. }
  7228. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  7229. operand->mode = Addressing_Invalid;
  7230. operand->type = t_invalid;
  7231. }
  7232. operand->expr = call;
  7233. return builtin_procs[id].kind;
  7234. }
  7235. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  7236. Entity *initial_entity = entity_of_node(operand->expr);
  7237. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  7238. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  7239. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  7240. if (c->decl) {
  7241. c->decl->defer_used += 1;
  7242. }
  7243. }
  7244. add_entity_use(c, operand->expr, initial_entity);
  7245. if (initial_entity->Procedure.entry_point_only) {
  7246. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  7247. // Okay
  7248. } else {
  7249. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  7250. }
  7251. }
  7252. }
  7253. if (operand->mode != Addressing_ProcGroup) {
  7254. Type *proc_type = base_type(operand->type);
  7255. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  7256. bool valid_mode = is_operand_value(*operand);
  7257. if (!valid_type || !valid_mode) {
  7258. Ast *e = operand->expr;
  7259. gbString str = expr_to_string(e);
  7260. gbString type_str = type_to_string(operand->type);
  7261. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  7262. gb_string_free(type_str);
  7263. gb_string_free(str);
  7264. operand->mode = Addressing_Invalid;
  7265. operand->expr = call;
  7266. return Expr_Stmt;
  7267. }
  7268. }
  7269. CallArgumentData data = check_call_arguments(c, operand, call);
  7270. Type *result_type = data.result_type;
  7271. gb_zero_item(operand);
  7272. operand->expr = call;
  7273. if (result_type == t_invalid) {
  7274. operand->mode = Addressing_Invalid;
  7275. operand->type = t_invalid;
  7276. return Expr_Stmt;
  7277. }
  7278. Type *pt = base_type(operand->type);
  7279. if (pt == nullptr) {
  7280. pt = t_invalid;
  7281. }
  7282. if (pt == t_invalid) {
  7283. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7284. pt = type_of_expr(operand->expr->CallExpr.proc);
  7285. }
  7286. if (pt == t_invalid && data.gen_entity) {
  7287. pt = data.gen_entity->type;
  7288. }
  7289. }
  7290. pt = base_type(pt);
  7291. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  7292. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  7293. ERROR_BLOCK();
  7294. if (c->scope->flags & ScopeFlag_File) {
  7295. error(call, "Procedures requiring a 'context' cannot be called at the global scope");
  7296. } else {
  7297. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  7298. error_line("\tSuggestion: 'context = runtime.default_context()'");
  7299. }
  7300. }
  7301. }
  7302. if (result_type == nullptr) {
  7303. operand->mode = Addressing_NoValue;
  7304. } else {
  7305. GB_ASSERT(is_type_tuple(result_type));
  7306. isize count = result_type->Tuple.variables.count;
  7307. switch (count) {
  7308. case 0:
  7309. operand->mode = Addressing_NoValue;
  7310. break;
  7311. case 1:
  7312. operand->mode = Addressing_Value;
  7313. operand->type = result_type->Tuple.variables[0]->type;
  7314. break;
  7315. default:
  7316. operand->mode = Addressing_Value;
  7317. operand->type = result_type;
  7318. break;
  7319. }
  7320. }
  7321. bool is_call_inlined = false;
  7322. switch (inlining) {
  7323. case ProcInlining_inline:
  7324. is_call_inlined = true;
  7325. if (proc != nullptr) {
  7326. Entity *e = entity_from_expr(proc);
  7327. if (e != nullptr && e->kind == Entity_Procedure) {
  7328. DeclInfo *decl = e->decl_info;
  7329. if (decl->proc_lit) {
  7330. ast_node(pl, ProcLit, decl->proc_lit);
  7331. if (pl->inlining == ProcInlining_no_inline) {
  7332. error(call, "'#force_inline' cannot be applied to a procedure that has been marked as '#force_no_inline'");
  7333. }
  7334. }
  7335. }
  7336. }
  7337. break;
  7338. case ProcInlining_no_inline:
  7339. break;
  7340. case ProcInlining_none:
  7341. if (proc != nullptr) {
  7342. Entity *e = entity_from_expr(proc);
  7343. if (e != nullptr && e->kind == Entity_Procedure) {
  7344. DeclInfo *decl = e->decl_info;
  7345. if (decl->proc_lit) {
  7346. ast_node(pl, ProcLit, decl->proc_lit);
  7347. if (pl->inlining == ProcInlining_inline) {
  7348. is_call_inlined = true;
  7349. }
  7350. }
  7351. }
  7352. }
  7353. }
  7354. {
  7355. String invalid;
  7356. if (pt->kind == Type_Proc && pt->Proc.require_target_feature.len != 0) {
  7357. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.require_target_feature, &invalid)) {
  7358. error(call, "Called procedure requires target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7359. } else if (!check_target_feature_is_enabled(pt->Proc.require_target_feature, &invalid)) {
  7360. error(call, "Calling this procedure requires target feature '%.*s' to be enabled", LIT(invalid));
  7361. }
  7362. }
  7363. if (pt->kind == Type_Proc && pt->Proc.enable_target_feature.len != 0) {
  7364. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.enable_target_feature, &invalid)) {
  7365. error(call, "Called procedure enables target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7366. }
  7367. // NOTE: Due to restrictions in LLVM you can not inline calls with a superset of features.
  7368. if (is_call_inlined) {
  7369. if (c->curr_proc_decl == nullptr) {
  7370. error(call, "Calling a '#force_inline' procedure that enables target features is not allowed at file scope");
  7371. } else {
  7372. Entity *e = c->curr_proc_decl->entity.load();
  7373. GB_ASSERT(e);
  7374. GB_ASSERT(e->type->kind == Type_Proc);
  7375. String scope_features = e->type->Proc.enable_target_feature;
  7376. if (!check_target_feature_is_superset_of(scope_features, pt->Proc.enable_target_feature, &invalid)) {
  7377. ERROR_BLOCK();
  7378. error(call, "Inlined procedure enables target feature '%.*s', this requires the calling procedure to at least enable the same feature", LIT(invalid));
  7379. error_line("\tSuggested Example: @(enable_target_feature=\"%.*s\")\n", LIT(invalid));
  7380. }
  7381. }
  7382. }
  7383. }
  7384. }
  7385. operand->expr = call;
  7386. {
  7387. Type *type = nullptr;
  7388. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7389. type = type_of_expr(operand->expr->CallExpr.proc);
  7390. }
  7391. if (type == nullptr) {
  7392. type = pt;
  7393. }
  7394. type = base_type(type);
  7395. if (type->kind == Type_Proc && type->Proc.optional_ok && type->Proc.result_count > 0) {
  7396. operand->mode = Addressing_OptionalOk;
  7397. operand->type = type->Proc.results->Tuple.variables[0]->type;
  7398. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7399. operand->expr->CallExpr.optional_ok_one = true;
  7400. }
  7401. }
  7402. }
  7403. return Expr_Expr;
  7404. }
  7405. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  7406. check_expr_base(c, o, e, t);
  7407. check_not_tuple(c, o);
  7408. char const *err_str = nullptr;
  7409. switch (o->mode) {
  7410. case Addressing_NoValue:
  7411. err_str = "used as a value";
  7412. break;
  7413. case Addressing_Type:
  7414. if (t == nullptr || !is_type_typeid(t)) {
  7415. err_str = "is not an expression but a type, in this context it is ambiguous";
  7416. }
  7417. break;
  7418. case Addressing_Builtin:
  7419. err_str = "must be called";
  7420. break;
  7421. }
  7422. if (err_str != nullptr) {
  7423. gbString str = expr_to_string(e);
  7424. error(e, "'%s' %s", str, err_str);
  7425. gb_string_free(str);
  7426. o->mode = Addressing_Invalid;
  7427. }
  7428. }
  7429. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  7430. switch (t->kind) {
  7431. case Type_Basic:
  7432. if (t->Basic.kind == Basic_string) {
  7433. if (o->mode == Addressing_Constant) {
  7434. GB_ASSERT(o->value.kind == ExactValue_String);
  7435. *max_count = o->value.value_string.len;
  7436. }
  7437. if (o->mode != Addressing_Constant) {
  7438. o->mode = Addressing_Value;
  7439. }
  7440. o->type = t_u8;
  7441. return true;
  7442. } else if (t->Basic.kind == Basic_string16) {
  7443. if (o->mode == Addressing_Constant) {
  7444. GB_ASSERT(o->value.kind == ExactValue_String16);
  7445. *max_count = o->value.value_string16.len;
  7446. }
  7447. if (o->mode != Addressing_Constant) {
  7448. o->mode = Addressing_Value;
  7449. }
  7450. o->type = t_u16;
  7451. return true;
  7452. } else if (t->Basic.kind == Basic_UntypedString) {
  7453. if (o->mode == Addressing_Constant) {
  7454. *max_count = o->value.value_string.len;
  7455. o->type = t_u8;
  7456. return true;
  7457. }
  7458. return false;
  7459. }
  7460. break;
  7461. case Type_MultiPointer:
  7462. o->type = t->MultiPointer.elem;
  7463. if (o->mode != Addressing_Constant) {
  7464. o->mode = Addressing_Variable;
  7465. }
  7466. return true;
  7467. case Type_Array:
  7468. *max_count = t->Array.count;
  7469. if (indirection) {
  7470. o->mode = Addressing_Variable;
  7471. } else if (o->mode != Addressing_Variable &&
  7472. o->mode != Addressing_Constant) {
  7473. o->mode = Addressing_Value;
  7474. }
  7475. o->type = t->Array.elem;
  7476. return true;
  7477. case Type_EnumeratedArray:
  7478. *max_count = t->EnumeratedArray.count;
  7479. if (indirection) {
  7480. o->mode = Addressing_Variable;
  7481. } else if (o->mode != Addressing_Variable &&
  7482. o->mode != Addressing_Constant) {
  7483. o->mode = Addressing_Value;
  7484. }
  7485. o->type = t->EnumeratedArray.elem;
  7486. return true;
  7487. case Type_Matrix:
  7488. if (indirection) {
  7489. o->mode = Addressing_Variable;
  7490. } else if (o->mode != Addressing_Variable) {
  7491. o->mode = Addressing_Value;
  7492. }
  7493. if (t->Matrix.is_row_major) {
  7494. *max_count = t->Matrix.row_count;
  7495. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.column_count);
  7496. } else {
  7497. *max_count = t->Matrix.column_count;
  7498. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  7499. }
  7500. return true;
  7501. case Type_Slice:
  7502. o->type = t->Slice.elem;
  7503. if (o->mode != Addressing_Constant) {
  7504. o->mode = Addressing_Variable;
  7505. }
  7506. return true;
  7507. case Type_DynamicArray:
  7508. o->type = t->DynamicArray.elem;
  7509. if (o->mode != Addressing_Constant) {
  7510. o->mode = Addressing_Variable;
  7511. }
  7512. return true;
  7513. case Type_Struct:
  7514. if (t->Struct.soa_kind != StructSoa_None) {
  7515. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7516. *max_count = t->Struct.soa_count;
  7517. }
  7518. o->type = t->Struct.soa_elem;
  7519. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  7520. o->mode = Addressing_SoaVariable;
  7521. } else {
  7522. o->mode = Addressing_Value;
  7523. }
  7524. return true;
  7525. }
  7526. return false;
  7527. }
  7528. if (is_type_pointer(original_type) && indirection) {
  7529. Type *ptr = base_type(original_type);
  7530. if (ptr->kind == Type_MultiPointer && o->mode == Addressing_SoaVariable) {
  7531. o->type = ptr->MultiPointer.elem;
  7532. o->mode = Addressing_Value;
  7533. return true;
  7534. }
  7535. }
  7536. return false;
  7537. }
  7538. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  7539. if (is_type_untyped_uninit(x)) {
  7540. return true;
  7541. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  7542. return true;
  7543. } else if (is_type_untyped_uninit(y)) {
  7544. return true;
  7545. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  7546. return true;
  7547. }
  7548. return are_types_identical(x, y);
  7549. }
  7550. gb_internal bool check_range(CheckerContext *c, Ast *node, bool is_for_loop, Operand *x, Operand *y, ExactValue *inline_for_depth_, Type *type_hint=nullptr) {
  7551. if (!is_ast_range(node)) {
  7552. return false;
  7553. }
  7554. ast_node(ie, BinaryExpr, node);
  7555. check_expr_with_type_hint(c, x, ie->left, type_hint);
  7556. if (x->mode == Addressing_Invalid) {
  7557. return false;
  7558. }
  7559. check_expr_with_type_hint(c, y, ie->right, type_hint);
  7560. if (y->mode == Addressing_Invalid) {
  7561. return false;
  7562. }
  7563. convert_to_typed(c, x, y->type);
  7564. if (x->mode == Addressing_Invalid) {
  7565. return false;
  7566. }
  7567. convert_to_typed(c, y, x->type);
  7568. if (y->mode == Addressing_Invalid) {
  7569. return false;
  7570. }
  7571. convert_to_typed(c, x, default_type(y->type));
  7572. if (x->mode == Addressing_Invalid) {
  7573. return false;
  7574. }
  7575. convert_to_typed(c, y, default_type(x->type));
  7576. if (y->mode == Addressing_Invalid) {
  7577. return false;
  7578. }
  7579. if (!are_types_identical(x->type, y->type)) {
  7580. if (x->type != t_invalid &&
  7581. y->type != t_invalid) {
  7582. gbString xt = type_to_string(x->type);
  7583. gbString yt = type_to_string(y->type);
  7584. gbString expr_str = expr_to_string(x->expr);
  7585. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  7586. gb_string_free(expr_str);
  7587. gb_string_free(yt);
  7588. gb_string_free(xt);
  7589. }
  7590. return false;
  7591. }
  7592. Type *type = x->type;
  7593. if (is_for_loop) {
  7594. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  7595. error(ie->op, "Only numerical types are allowed within interval expressions");
  7596. return false;
  7597. }
  7598. } else {
  7599. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  7600. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  7601. return false;
  7602. }
  7603. }
  7604. if (x->mode == Addressing_Constant &&
  7605. y->mode == Addressing_Constant) {
  7606. ExactValue a = x->value;
  7607. ExactValue b = y->value;
  7608. GB_ASSERT(are_types_identical(x->type, y->type));
  7609. TokenKind op = Token_Lt;
  7610. switch (ie->op.kind) {
  7611. case Token_Ellipsis: op = Token_LtEq; break; // ..
  7612. case Token_RangeFull: op = Token_LtEq; break; // ..=
  7613. case Token_RangeHalf: op = Token_Lt; break; // ..<
  7614. default: error(ie->op, "Invalid range operator"); break;
  7615. }
  7616. bool ok = compare_exact_values(op, a, b);
  7617. if (!ok) {
  7618. // TODO(bill): Better error message
  7619. error(ie->op, "Invalid interval range");
  7620. return false;
  7621. }
  7622. ExactValue inline_for_depth = exact_value_sub(b, a);
  7623. if (ie->op.kind != Token_RangeHalf) {
  7624. inline_for_depth = exact_value_increment_one(inline_for_depth);
  7625. }
  7626. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  7627. } else if (inline_for_depth_ != nullptr) {
  7628. error(ie->op, "Interval expressions must be constant");
  7629. return false;
  7630. }
  7631. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  7632. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  7633. return true;
  7634. }
  7635. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o, Type *field_type) {
  7636. if (is_operand_nil(*o)) {
  7637. return true;
  7638. }
  7639. Ast *expr = unparen_expr(o->expr);
  7640. if (expr != nullptr) {
  7641. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  7642. if (e != nullptr && e->kind == Entity_Procedure) {
  7643. return true;
  7644. }
  7645. if (expr->kind == Ast_ProcLit) {
  7646. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  7647. return true;
  7648. }
  7649. }
  7650. if (field_type != nullptr && is_type_typeid(field_type) && o->mode == Addressing_Type) {
  7651. add_type_info_type(c, o->type);
  7652. return true;
  7653. }
  7654. if (is_type_any(field_type)) {
  7655. return false;
  7656. }
  7657. return o->mode == Addressing_Constant;
  7658. }
  7659. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  7660. if (is_type_enum(th)) {
  7661. Type *enum_type = base_type(th);
  7662. GB_ASSERT(enum_type->kind == Type_Enum);
  7663. String name = ise->selector->Ident.token.string;
  7664. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  7665. if (e == nullptr) {
  7666. return false;
  7667. }
  7668. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  7669. GB_ASSERT(e->kind == Entity_Constant);
  7670. o->value = e->Constant.value;
  7671. o->mode = Addressing_Constant;
  7672. o->type = e->type;
  7673. return true;
  7674. }
  7675. if (is_type_union(th)) {
  7676. TEMPORARY_ALLOCATOR_GUARD();
  7677. Type *union_type = base_type(th);
  7678. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  7679. for (Type *vt : union_type->Union.variants) {
  7680. Operand x = {};
  7681. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  7682. array_add(&operands, x);
  7683. }
  7684. }
  7685. if (operands.count == 1) {
  7686. *o = operands[0];
  7687. return true;
  7688. }
  7689. }
  7690. return false;
  7691. }
  7692. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7693. ast_node(ise, ImplicitSelectorExpr, node);
  7694. o->type = t_invalid;
  7695. o->expr = node;
  7696. o->mode = Addressing_Invalid;
  7697. Type *th = type_hint;
  7698. if (th == nullptr) {
  7699. gbString str = expr_to_string(node);
  7700. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  7701. gb_string_free(str);
  7702. return Expr_Expr;
  7703. }
  7704. o->type = th;
  7705. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  7706. if (!ok) {
  7707. String name = ise->selector->Ident.token.string;
  7708. if (is_type_enum(th)) {
  7709. ERROR_BLOCK();
  7710. Type *bt = base_type(th);
  7711. GB_ASSERT(bt->kind == Type_Enum);
  7712. gbString typ = type_to_string(th);
  7713. defer (gb_string_free(typ));
  7714. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  7715. check_did_you_mean_type(name, bt->Enum.fields);
  7716. } else if (is_type_bit_set(th) && is_type_enum(th->BitSet.elem)) {
  7717. ERROR_BLOCK();
  7718. gbString typ = type_to_string(th);
  7719. gbString str = expr_to_string(node);
  7720. error(node, "Cannot convert enum value to '%s'", typ);
  7721. error_line("\tSuggestion: Did you mean '{ %s }'?\n", str);
  7722. gb_string_free(typ);
  7723. gb_string_free(str);
  7724. } else {
  7725. gbString typ = type_to_string(th);
  7726. gbString str = expr_to_string(node);
  7727. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  7728. gb_string_free(str);
  7729. gb_string_free(typ);
  7730. }
  7731. }
  7732. o->expr = node;
  7733. return Expr_Expr;
  7734. }
  7735. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  7736. switch (x->mode) {
  7737. case Addressing_MapIndex:
  7738. case Addressing_OptionalOk:
  7739. case Addressing_OptionalOkPtr:
  7740. if (val_type_) *val_type_ = x->type;
  7741. break;
  7742. default:
  7743. if (ok_type_) *ok_type_ = x->type;
  7744. return;
  7745. }
  7746. Ast *expr = unparen_expr(x->expr);
  7747. if (expr->kind == Ast_CallExpr) {
  7748. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  7749. if (is_type_proc(pt)) {
  7750. Type *tuple = pt->Proc.results;
  7751. if (pt->Proc.result_count >= 2) {
  7752. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7753. }
  7754. if (change_operand) {
  7755. expr->CallExpr.optional_ok_one = false;
  7756. x->type = tuple;
  7757. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7758. }
  7759. return;
  7760. }
  7761. }
  7762. Type *tuple = make_optional_ok_type(x->type);
  7763. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7764. if (change_operand) {
  7765. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7766. x->type = tuple;
  7767. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  7768. }
  7769. }
  7770. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7771. ast_node(ie, MatrixIndexExpr, node);
  7772. check_expr(c, o, ie->expr);
  7773. node->viral_state_flags |= ie->expr->viral_state_flags;
  7774. if (o->mode == Addressing_Invalid) {
  7775. o->expr = node;
  7776. return;
  7777. }
  7778. Type *t = base_type(type_deref(o->type));
  7779. bool is_ptr = is_type_pointer(o->type);
  7780. bool is_const = o->mode == Addressing_Constant;
  7781. if (t->kind != Type_Matrix) {
  7782. gbString str = expr_to_string(o->expr);
  7783. gbString type_str = type_to_string(o->type);
  7784. defer (gb_string_free(str));
  7785. defer (gb_string_free(type_str));
  7786. if (is_const) {
  7787. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  7788. } else {
  7789. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  7790. }
  7791. o->mode = Addressing_Invalid;
  7792. o->expr = node;
  7793. return;
  7794. }
  7795. o->type = t->Matrix.elem;
  7796. if (is_ptr) {
  7797. o->mode = Addressing_Variable;
  7798. } else if (o->mode != Addressing_Variable) {
  7799. o->mode = Addressing_Value;
  7800. }
  7801. if (ie->row_index == nullptr) {
  7802. gbString str = expr_to_string(o->expr);
  7803. error(o->expr, "Missing row index for '%s'", str);
  7804. gb_string_free(str);
  7805. o->mode = Addressing_Invalid;
  7806. o->expr = node;
  7807. return;
  7808. }
  7809. if (ie->column_index == nullptr) {
  7810. gbString str = expr_to_string(o->expr);
  7811. error(o->expr, "Missing column index for '%s'", str);
  7812. gb_string_free(str);
  7813. o->mode = Addressing_Invalid;
  7814. o->expr = node;
  7815. return;
  7816. }
  7817. i64 row_count = t->Matrix.row_count;
  7818. i64 column_count = t->Matrix.column_count;
  7819. i64 row_index = 0;
  7820. i64 column_index = 0;
  7821. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7822. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7823. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7824. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7825. }
  7826. gb_unused(row_ok);
  7827. gb_unused(column_ok);
  7828. }
  7829. struct TypeAndToken {
  7830. Type *type;
  7831. Token token;
  7832. };
  7833. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7834. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7835. if (operand.mode != Addressing_Constant) {
  7836. return;
  7837. }
  7838. if (operand.value.kind == ExactValue_Invalid) {
  7839. return;
  7840. }
  7841. uintptr key = hash_exact_value(operand.value);
  7842. GB_ASSERT(key != 0);
  7843. isize count = multi_map_count(seen, key);
  7844. if (count) {
  7845. TEMPORARY_ALLOCATOR_GUARD();
  7846. TypeAndToken *taps = temporary_alloc_array<TypeAndToken>(count);
  7847. multi_map_get_all(seen, key, taps);
  7848. for (isize i = 0; i < count; i++) {
  7849. TypeAndToken tap = taps[i];
  7850. Operand to = {};
  7851. to.mode = Addressing_Value;
  7852. to.type = tap.type;
  7853. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7854. continue;
  7855. }
  7856. TokenPos pos = tap.token.pos;
  7857. if (use_expr) {
  7858. gbString expr_str = expr_to_string(operand.expr);
  7859. error(operand.expr,
  7860. "Duplicate case '%s'\n"
  7861. "\tprevious case at %s",
  7862. expr_str,
  7863. token_pos_to_string(pos));
  7864. gb_string_free(expr_str);
  7865. } else {
  7866. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7867. }
  7868. return;
  7869. }
  7870. }
  7871. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7872. multi_map_insert(seen, key, tap);
  7873. }
  7874. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7875. if (is_type_enum(x.type)) {
  7876. // TODO(bill): Fix this logic so it's fast!!!
  7877. i64 v0 = exact_value_to_i64(lhs.value);
  7878. i64 v1 = exact_value_to_i64(rhs.value);
  7879. Operand v = {};
  7880. v.mode = Addressing_Constant;
  7881. v.type = x.type;
  7882. v.expr = x.expr;
  7883. Type *bt = base_type(x.type);
  7884. GB_ASSERT(bt->kind == Type_Enum);
  7885. for (i64 vi = v0; vi <= v1; vi++) {
  7886. if (upper_op != Token_LtEq && vi == v1) {
  7887. break;
  7888. }
  7889. v.value = exact_value_i64(vi);
  7890. add_constant_switch_case(ctx, seen, v);
  7891. }
  7892. } else {
  7893. add_constant_switch_case(ctx, seen, lhs);
  7894. if (upper_op == Token_LtEq) {
  7895. add_constant_switch_case(ctx, seen, rhs);
  7896. }
  7897. }
  7898. }
  7899. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7900. add_constant_switch_case(ctx, seen, x);
  7901. }
  7902. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7903. ast_node(bd, BasicDirective, node);
  7904. ExprKind kind = Expr_Expr;
  7905. o->mode = Addressing_Constant;
  7906. String name = bd->name.string;
  7907. if (name == "file") {
  7908. String file = get_file_path_string(bd->token.pos.file_id);
  7909. switch (build_context.source_code_location_info) {
  7910. case SourceCodeLocationInfo_Normal:
  7911. break;
  7912. case SourceCodeLocationInfo_Obfuscated:
  7913. file = obfuscate_string(file, "F");
  7914. break;
  7915. case SourceCodeLocationInfo_Filename:
  7916. file = last_path_element(file);
  7917. break;
  7918. case SourceCodeLocationInfo_None:
  7919. file = str_lit("");
  7920. break;
  7921. }
  7922. o->type = t_untyped_string;
  7923. o->value = exact_value_string(file);
  7924. } else if (name == "directory") {
  7925. String file = get_file_path_string(bd->token.pos.file_id);
  7926. String path = dir_from_path(file);
  7927. switch (build_context.source_code_location_info) {
  7928. case SourceCodeLocationInfo_Normal:
  7929. break;
  7930. case SourceCodeLocationInfo_Obfuscated:
  7931. path = obfuscate_string(path, "D");
  7932. break;
  7933. case SourceCodeLocationInfo_Filename:
  7934. path = last_path_element(path);
  7935. break;
  7936. case SourceCodeLocationInfo_None:
  7937. path = str_lit("");
  7938. break;
  7939. }
  7940. o->type = t_untyped_string;
  7941. o->value = exact_value_string(path);
  7942. } else if (name == "line") {
  7943. i32 line = bd->token.pos.line;
  7944. switch (build_context.source_code_location_info) {
  7945. case SourceCodeLocationInfo_Normal:
  7946. break;
  7947. case SourceCodeLocationInfo_Obfuscated:
  7948. line = obfuscate_i32(line);
  7949. break;
  7950. case SourceCodeLocationInfo_Filename:
  7951. break;
  7952. case SourceCodeLocationInfo_None:
  7953. line = 0;
  7954. break;
  7955. }
  7956. o->type = t_untyped_integer;
  7957. o->value = exact_value_i64(line);
  7958. } else if (name == "procedure") {
  7959. if (c->curr_proc_decl == nullptr) {
  7960. error(node, "#procedure may only be used within procedures");
  7961. o->type = t_untyped_string;
  7962. o->value = exact_value_string(str_lit(""));
  7963. } else {
  7964. String p = c->proc_name;
  7965. switch (build_context.source_code_location_info) {
  7966. case SourceCodeLocationInfo_Normal:
  7967. break;
  7968. case SourceCodeLocationInfo_Obfuscated:
  7969. p = obfuscate_string(p, "P");
  7970. break;
  7971. case SourceCodeLocationInfo_Filename:
  7972. break;
  7973. case SourceCodeLocationInfo_None:
  7974. p = str_lit("");
  7975. break;
  7976. }
  7977. o->type = t_untyped_string;
  7978. o->value = exact_value_string(p);
  7979. }
  7980. } else if (name == "caller_location") {
  7981. init_core_source_code_location(c->checker);
  7982. error(node, "#caller_location may only be used as a default argument parameter");
  7983. o->type = t_source_code_location;
  7984. o->mode = Addressing_Value;
  7985. } else if (name == "caller_expression") {
  7986. error(node, "#caller_expression may only be used as a default argument parameter");
  7987. o->type = t_string;
  7988. o->mode = Addressing_Value;
  7989. } else if (name == "branch_location") {
  7990. if (!c->in_defer) {
  7991. error(node, "#branch_location may only be used within a 'defer' statement");
  7992. } else if (c->curr_proc_decl) {
  7993. Entity *e = c->curr_proc_decl->entity;
  7994. if (e != nullptr) {
  7995. GB_ASSERT(e->kind == Entity_Procedure);
  7996. e->Procedure.uses_branch_location = true;
  7997. }
  7998. }
  7999. o->type = t_source_code_location;
  8000. o->mode = Addressing_Value;
  8001. } else {
  8002. if (name == "location") {
  8003. init_core_source_code_location(c->checker);
  8004. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  8005. o->type = t_source_code_location;
  8006. o->mode = Addressing_Value;
  8007. } else if (
  8008. name == "assert" ||
  8009. name == "defined" ||
  8010. name == "config" ||
  8011. name == "exists" ||
  8012. name == "load" ||
  8013. name == "load_hash" ||
  8014. name == "load_directory" ||
  8015. name == "load_or"
  8016. ) {
  8017. error(node, "'#%.*s' must be used as a call", LIT(name));
  8018. o->type = t_invalid;
  8019. o->mode = Addressing_Invalid;
  8020. } else {
  8021. error(node, "Unknown directive: #%.*s", LIT(name));
  8022. o->type = t_invalid;
  8023. o->mode = Addressing_Invalid;
  8024. }
  8025. }
  8026. return kind;
  8027. }
  8028. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8029. ExprKind kind = Expr_Expr;
  8030. Operand cond = {Addressing_Invalid};
  8031. ast_node(te, TernaryIfExpr, node);
  8032. check_expr(c, &cond, te->cond);
  8033. node->viral_state_flags |= te->cond->viral_state_flags;
  8034. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  8035. error(te->cond, "Non-boolean condition in ternary if expression");
  8036. }
  8037. Operand x = {Addressing_Invalid};
  8038. Operand y = {Addressing_Invalid};
  8039. check_expr_or_type(c, &x, te->x, type_hint);
  8040. node->viral_state_flags |= te->x->viral_state_flags;
  8041. if (te->y != nullptr) {
  8042. Type *th = type_hint;
  8043. if (type_hint == nullptr && is_type_typed(x.type)) {
  8044. th = x.type;
  8045. }
  8046. check_expr_or_type(c, &y, te->y, th);
  8047. node->viral_state_flags |= te->y->viral_state_flags;
  8048. } else {
  8049. error(node, "A ternary expression must have an else clause");
  8050. return kind;
  8051. }
  8052. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  8053. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  8054. gbString type_string = expr_to_string(type_expr);
  8055. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  8056. gb_string_free(type_string);
  8057. return kind;
  8058. }
  8059. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  8060. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  8061. if (x.mode == Addressing_Invalid) {
  8062. return kind;
  8063. }
  8064. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  8065. if (y.mode == Addressing_Invalid) {
  8066. x.mode = Addressing_Invalid;
  8067. return kind;
  8068. }
  8069. // NOTE(bill, 2023-01-30): Allow for expression like this:
  8070. // x: union{f32} = f32(123) if cond else nil
  8071. if (type_hint && !is_type_any(type_hint)) {
  8072. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  8073. check_cast(c, &x, type_hint);
  8074. check_cast(c, &y, type_hint);
  8075. }
  8076. }
  8077. if (!ternary_compare_types(x.type, y.type)) {
  8078. gbString its = type_to_string(x.type);
  8079. gbString ets = type_to_string(y.type);
  8080. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  8081. gb_string_free(ets);
  8082. gb_string_free(its);
  8083. return kind;
  8084. }
  8085. o->type = x.type;
  8086. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  8087. o->type = y.type;
  8088. }
  8089. o->mode = Addressing_Value;
  8090. o->expr = node;
  8091. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  8092. if (check_cast_internal(c, &x, type_hint) &&
  8093. check_cast_internal(c, &y, type_hint)) {
  8094. convert_to_typed(c, o, type_hint);
  8095. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  8096. o->type = type_hint;
  8097. }
  8098. }
  8099. return kind;
  8100. }
  8101. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8102. ExprKind kind = Expr_Expr;
  8103. Operand cond = {};
  8104. ast_node(te, TernaryWhenExpr, node);
  8105. check_expr(c, &cond, te->cond);
  8106. node->viral_state_flags |= te->cond->viral_state_flags;
  8107. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  8108. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  8109. return kind;
  8110. }
  8111. if (cond.value.value_bool) {
  8112. check_expr_or_type(c, o, te->x, type_hint);
  8113. node->viral_state_flags |= te->x->viral_state_flags;
  8114. } else {
  8115. if (te->y != nullptr) {
  8116. check_expr_or_type(c, o, te->y, type_hint);
  8117. node->viral_state_flags |= te->y->viral_state_flags;
  8118. } else {
  8119. error(node, "A ternary when expression must have an else clause");
  8120. return kind;
  8121. }
  8122. }
  8123. return kind;
  8124. }
  8125. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8126. ast_node(oe, OrElseExpr, node);
  8127. String name = oe->token.string;
  8128. Ast *arg = oe->x;
  8129. Ast *default_value = oe->y;
  8130. Operand x = {};
  8131. Operand y = {};
  8132. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  8133. if (is_load_directive_call(arg)) {
  8134. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  8135. // Allow for chaining of '#load(path) or_else #load(path)'
  8136. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  8137. bool y_is_diverging = false;
  8138. check_expr_base(c, &y, default_value, x.type);
  8139. switch (y.mode) {
  8140. case Addressing_NoValue:
  8141. if (is_diverging_expr(y.expr)) {
  8142. // Allow
  8143. y.mode = Addressing_Value;
  8144. y_is_diverging = true;
  8145. } else {
  8146. error_operand_no_value(&y);
  8147. y.mode = Addressing_Invalid;
  8148. }
  8149. break;
  8150. case Addressing_Type:
  8151. error_operand_not_expression(&y);
  8152. y.mode = Addressing_Invalid;
  8153. break;
  8154. }
  8155. if (y.mode == Addressing_Invalid) {
  8156. o->mode = Addressing_Value;
  8157. o->type = t_invalid;
  8158. o->expr = node;
  8159. return Expr_Expr;
  8160. }
  8161. if (!y_is_diverging) {
  8162. check_assignment(c, &y, x.type, name);
  8163. if (y.mode != Addressing_Constant) {
  8164. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  8165. }
  8166. }
  8167. }
  8168. if (res == LoadDirective_Success) {
  8169. *o = x;
  8170. } else {
  8171. *o = y;
  8172. }
  8173. o->expr = node;
  8174. return Expr_Expr;
  8175. }
  8176. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  8177. if (x.mode == Addressing_Invalid) {
  8178. o->mode = Addressing_Value;
  8179. o->type = t_invalid;
  8180. o->expr = node;
  8181. return Expr_Expr;
  8182. }
  8183. Type *left_type = nullptr;
  8184. Type *right_type = nullptr;
  8185. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  8186. add_type_and_value(c, arg, x.mode, x.type, x.value);
  8187. bool y_is_diverging = false;
  8188. check_expr_base(c, &y, default_value, left_type);
  8189. switch (y.mode) {
  8190. case Addressing_NoValue:
  8191. if (is_diverging_expr(y.expr)) {
  8192. // Allow
  8193. y.mode = Addressing_Value;
  8194. y_is_diverging = true;
  8195. } else {
  8196. error_operand_no_value(&y);
  8197. y.mode = Addressing_Invalid;
  8198. }
  8199. break;
  8200. case Addressing_Type:
  8201. error_operand_not_expression(&y);
  8202. y.mode = Addressing_Invalid;
  8203. break;
  8204. }
  8205. if (y.mode == Addressing_Invalid) {
  8206. o->mode = Addressing_Value;
  8207. o->type = t_invalid;
  8208. o->expr = node;
  8209. return Expr_Expr;
  8210. }
  8211. if (left_type != nullptr) {
  8212. if (!y_is_diverging) {
  8213. if (is_type_tuple(left_type)) {
  8214. if (!is_type_tuple(y.type)) {
  8215. error(y.expr, "Found a single value where a %td-valued expression was expected", left_type->Tuple.variables.count);
  8216. } else if (!are_types_identical(left_type, y.type)) {
  8217. gbString xt = type_to_string(left_type);
  8218. gbString yt = type_to_string(y.type);
  8219. error(y.expr, "Mismatched types, expected (%s), got (%s)", xt, yt);
  8220. gb_string_free(yt);
  8221. gb_string_free(xt);
  8222. }
  8223. } else {
  8224. check_assignment(c, &y, left_type, name);
  8225. }
  8226. }
  8227. } else {
  8228. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8229. }
  8230. if (left_type == nullptr) {
  8231. left_type = t_invalid;
  8232. }
  8233. o->mode = Addressing_Value;
  8234. o->type = left_type;
  8235. o->expr = node;
  8236. return Expr_Expr;
  8237. }
  8238. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8239. ast_node(re, OrReturnExpr, node);
  8240. String name = re->token.string;
  8241. Operand x = {};
  8242. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  8243. if (x.mode == Addressing_Invalid) {
  8244. o->mode = Addressing_Value;
  8245. o->type = t_invalid;
  8246. o->expr = node;
  8247. return Expr_Expr;
  8248. }
  8249. Type *left_type = nullptr;
  8250. Type *right_type = nullptr;
  8251. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8252. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  8253. if (right_type == nullptr) {
  8254. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8255. } else {
  8256. Type *proc_type = base_type(c->curr_proc_sig);
  8257. GB_ASSERT(proc_type->kind == Type_Proc);
  8258. Type *result_type = proc_type->Proc.results;
  8259. if (result_type == nullptr) {
  8260. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  8261. } else {
  8262. GB_ASSERT(result_type->kind == Type_Tuple);
  8263. auto const &vars = result_type->Tuple.variables;
  8264. Type *end_type = vars[vars.count-1]->type;
  8265. if (vars.count > 1) {
  8266. if (!proc_type->Proc.has_named_results) {
  8267. error(node, "'%.*s' within a procedure with more than 1 return value requires that the return values are named, allowing for early return", LIT(name));
  8268. }
  8269. }
  8270. Operand rhs = {};
  8271. rhs.type = right_type;
  8272. rhs.mode = Addressing_Value;
  8273. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  8274. // NOTE(bill): allow implicit conversion between boolean types
  8275. // within 'or_return' to improve the experience using third-party code
  8276. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  8277. ERROR_BLOCK();
  8278. // TODO(bill): better error message
  8279. gbString a = type_to_string(right_type);
  8280. gbString b = type_to_string(end_type);
  8281. gbString ret_type = type_to_string(result_type);
  8282. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  8283. if (vars.count == 1) {
  8284. error_line("\tProcedure return value type: %s\n", ret_type);
  8285. } else {
  8286. error_line("\tProcedure return value types: (%s)\n", ret_type);
  8287. }
  8288. gb_string_free(ret_type);
  8289. gb_string_free(b);
  8290. gb_string_free(a);
  8291. }
  8292. }
  8293. }
  8294. o->expr = node;
  8295. o->type = left_type;
  8296. if (left_type != nullptr) {
  8297. o->mode = Addressing_Value;
  8298. } else {
  8299. o->mode = Addressing_NoValue;
  8300. }
  8301. if (c->curr_proc_sig == nullptr) {
  8302. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8303. }
  8304. if (c->in_defer) {
  8305. error(node, "'or_return' cannot be used within a defer statement");
  8306. }
  8307. return Expr_Expr;
  8308. }
  8309. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8310. ast_node(be, OrBranchExpr, node);
  8311. String name = be->token.string;
  8312. Operand x = {};
  8313. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  8314. if (x.mode == Addressing_Invalid) {
  8315. o->mode = Addressing_Value;
  8316. o->type = t_invalid;
  8317. o->expr = node;
  8318. return Expr_Expr;
  8319. }
  8320. Type *left_type = nullptr;
  8321. Type *right_type = nullptr;
  8322. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8323. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  8324. if (right_type == nullptr) {
  8325. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8326. } else {
  8327. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  8328. // okay
  8329. } else {
  8330. gbString s = type_to_string(right_type);
  8331. error(node, "'%.*s' requires a boolean or nil-able type, got %s", LIT(name), s);
  8332. gb_string_free(s);
  8333. }
  8334. }
  8335. o->expr = node;
  8336. o->type = left_type;
  8337. if (left_type != nullptr) {
  8338. o->mode = Addressing_Value;
  8339. } else {
  8340. o->mode = Addressing_NoValue;
  8341. }
  8342. if (c->curr_proc_sig == nullptr) {
  8343. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8344. }
  8345. Ast *label = be->label;
  8346. switch (be->token.kind) {
  8347. case Token_or_break:
  8348. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  8349. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  8350. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  8351. }
  8352. break;
  8353. case Token_or_continue:
  8354. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  8355. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  8356. }
  8357. break;
  8358. }
  8359. if (label != nullptr) {
  8360. if (c->in_defer) {
  8361. error(label, "A labelled '%.*s' cannot be used within a 'defer'", LIT(name));
  8362. return Expr_Expr;
  8363. }
  8364. if (label->kind != Ast_Ident) {
  8365. error(label, "A branch statement's label name must be an identifier");
  8366. return Expr_Expr;
  8367. }
  8368. Ast *ident = label;
  8369. String name = ident->Ident.token.string;
  8370. Operand o = {};
  8371. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  8372. if (e == nullptr) {
  8373. error(ident, "Undeclared label name: %.*s", LIT(name));
  8374. return Expr_Expr;
  8375. }
  8376. add_entity_use(c, ident, e);
  8377. if (e->kind != Entity_Label) {
  8378. error(ident, "'%.*s' is not a label", LIT(name));
  8379. return Expr_Expr;
  8380. }
  8381. Ast *parent = e->Label.parent;
  8382. GB_ASSERT(parent != nullptr);
  8383. switch (parent->kind) {
  8384. case Ast_BlockStmt:
  8385. case Ast_IfStmt:
  8386. case Ast_SwitchStmt:
  8387. if (be->token.kind != Token_or_break) {
  8388. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  8389. }
  8390. break;
  8391. case Ast_RangeStmt:
  8392. case Ast_ForStmt:
  8393. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  8394. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  8395. }
  8396. break;
  8397. }
  8398. }
  8399. return Expr_Expr;
  8400. }
  8401. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  8402. Type *bt = base_type(type);
  8403. StringSet fields_visited = {};
  8404. defer (string_set_destroy(&fields_visited));
  8405. StringMap<String> fields_visited_through_raw_union = {};
  8406. defer (string_map_destroy(&fields_visited_through_raw_union));
  8407. String assignment_str = str_lit("structure literal");
  8408. if (bt->kind == Type_BitField) {
  8409. assignment_str = str_lit("bit_field literal");
  8410. }
  8411. for (Ast *elem : elems) {
  8412. if (elem->kind != Ast_FieldValue) {
  8413. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8414. continue;
  8415. }
  8416. ast_node(fv, FieldValue, elem);
  8417. Ast *ident = fv->field;
  8418. if (ident->kind == Ast_ImplicitSelectorExpr) {
  8419. gbString expr_str = expr_to_string(ident);
  8420. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  8421. gb_string_free(expr_str);
  8422. ident = ident->ImplicitSelectorExpr.selector;
  8423. }
  8424. if (ident->kind != Ast_Ident) {
  8425. gbString expr_str = expr_to_string(ident);
  8426. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  8427. gb_string_free(expr_str);
  8428. continue;
  8429. }
  8430. String name = ident->Ident.token.string;
  8431. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8432. bool is_unknown = sel.entity == nullptr;
  8433. if (is_unknown) {
  8434. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  8435. continue;
  8436. }
  8437. Entity *field = nullptr;
  8438. if (bt->kind == Type_Struct) {
  8439. field = bt->Struct.fields[sel.index[0]];
  8440. } else if (bt->kind == Type_BitField) {
  8441. field = bt->BitField.fields[sel.index[0]];
  8442. } else {
  8443. GB_PANIC("Unknown type");
  8444. }
  8445. add_entity_use(c, ident, field);
  8446. if (string_set_update(&fields_visited, name)) {
  8447. if (sel.index.count > 1) {
  8448. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8449. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8450. } else {
  8451. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  8452. }
  8453. } else {
  8454. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  8455. }
  8456. continue;
  8457. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8458. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8459. continue;
  8460. }
  8461. if (sel.indirect) {
  8462. error(ident, "Cannot assign to the %d-nested anonymous indirect field '%.*s' in a %.*s", cast(int)sel.index.count-1, LIT(name), LIT(assignment_str));
  8463. continue;
  8464. }
  8465. if (sel.index.count > 1) {
  8466. GB_ASSERT(bt->kind == Type_Struct);
  8467. if (is_constant) {
  8468. Type *ft = type;
  8469. for (i32 index : sel.index) {
  8470. Type *bt = base_type(ft);
  8471. switch (bt->kind) {
  8472. case Type_Struct:
  8473. if (bt->Struct.is_raw_union) {
  8474. is_constant = false;
  8475. break;
  8476. }
  8477. ft = bt->Struct.fields[index]->type;
  8478. break;
  8479. case Type_Array:
  8480. ft = bt->Array.elem;
  8481. break;
  8482. case Type_BitField:
  8483. is_constant = false;
  8484. ft = bt->BitField.fields[index]->type;
  8485. break;
  8486. default:
  8487. GB_PANIC("invalid type: %s", type_to_string(ft));
  8488. break;
  8489. }
  8490. }
  8491. if (is_constant && elem_cannot_be_constant(ft)) {
  8492. is_constant = false;
  8493. }
  8494. }
  8495. Type *nested_ft = bt;
  8496. for (i32 index : sel.index) {
  8497. Type *bt = base_type(nested_ft);
  8498. switch (bt->kind) {
  8499. case Type_Struct:
  8500. if (bt->Struct.is_raw_union) {
  8501. for (Entity *re : bt->Struct.fields) {
  8502. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  8503. }
  8504. }
  8505. nested_ft = bt->Struct.fields[index]->type;
  8506. break;
  8507. case Type_Array:
  8508. nested_ft = bt->Array.elem;
  8509. break;
  8510. case Type_BitField:
  8511. nested_ft = bt->BitField.fields[index]->type;
  8512. break;
  8513. default:
  8514. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  8515. break;
  8516. }
  8517. }
  8518. field = sel.entity;
  8519. }
  8520. Operand o = {};
  8521. check_expr_or_type(c, &o, fv->value, field->type);
  8522. if (elem_cannot_be_constant(field->type)) {
  8523. is_constant = false;
  8524. }
  8525. if (is_constant) {
  8526. is_constant = check_is_operand_compound_lit_constant(c, &o, field->type);
  8527. }
  8528. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  8529. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  8530. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  8531. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  8532. }
  8533. check_assignment(c, &o, field->type, assignment_str);
  8534. c->bit_field_bit_size = prev_bit_field_bit_size;
  8535. }
  8536. }
  8537. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  8538. type_expr = unparen_expr(type_expr);
  8539. if (type_expr == nullptr) {
  8540. return false;
  8541. }
  8542. // [?]Type
  8543. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  8544. Ast *count = type_expr->ArrayType.count;
  8545. if (count->kind == Ast_UnaryExpr &&
  8546. count->UnaryExpr.op.kind == Token_Question) {
  8547. return true;
  8548. }
  8549. }
  8550. return false;
  8551. }
  8552. gb_internal bool check_for_dynamic_literals(CheckerContext *c, Ast *node, AstCompoundLit *cl) {
  8553. if (cl->elems.count == 0) {
  8554. return false;
  8555. }
  8556. if ((check_feature_flags(c, node) & OptInFeatureFlag_DynamicLiterals) == 0 && !build_context.dynamic_literals) {
  8557. ERROR_BLOCK();
  8558. error(node, "Compound literals of dynamic types are disabled by default");
  8559. error_line("\tSuggestion: If you want to enable them for this specific file, add '#+feature dynamic-literals' at the top of the file\n");
  8560. error_line("\tWarning: Please understand that dynamic literals will implicitly allocate using the current 'context.allocator' in that scope\n");
  8561. if (build_context.ODIN_DEFAULT_TO_NIL_ALLOCATOR) {
  8562. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8563. } else if (build_context.ODIN_DEFAULT_TO_PANIC_ALLOCATOR) {
  8564. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8565. }
  8566. return false;
  8567. } else if (c->curr_proc_decl != nullptr && c->curr_proc_calling_convention != ProcCC_Odin) {
  8568. if (c->scope != nullptr && (c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  8569. error(node, "Compound literals of dynamic types require a 'context' to defined");
  8570. }
  8571. }
  8572. return true;
  8573. }
  8574. gb_internal IntegerDivisionByZeroKind check_for_integer_division_by_zero(CheckerContext *c, Ast *node) {
  8575. // TODO(bill): per file `#+feature` flags
  8576. u64 flags = check_feature_flags(c, node);
  8577. if ((flags & OptInFeatureFlag_IntegerDivisionByZero_Trap) != 0) {
  8578. return IntegerDivisionByZero_Trap;
  8579. }
  8580. if ((flags & OptInFeatureFlag_IntegerDivisionByZero_Zero) != 0) {
  8581. return IntegerDivisionByZero_Zero;
  8582. }
  8583. if ((flags & OptInFeatureFlag_IntegerDivisionByZero_Self) != 0) {
  8584. return IntegerDivisionByZero_Self;
  8585. }
  8586. if ((flags & OptInFeatureFlag_IntegerDivisionByZero_AllBits) != 0) {
  8587. return IntegerDivisionByZero_AllBits;
  8588. }
  8589. return build_context.integer_division_by_zero_behaviour;
  8590. }
  8591. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8592. ExprKind kind = Expr_Expr;
  8593. ast_node(cl, CompoundLit, node);
  8594. Type *type = type_hint;
  8595. if (type != nullptr && is_type_untyped(type)) {
  8596. type = nullptr;
  8597. }
  8598. bool is_to_be_determined_array_count = false;
  8599. bool is_constant = true;
  8600. bool is_soa = false;
  8601. Ast *type_expr = cl->type;
  8602. bool used_type_hint_expr = false;
  8603. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  8604. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  8605. type_expr = clone_ast(c->type_hint_expr);
  8606. used_type_hint_expr = true;
  8607. }
  8608. }
  8609. if (type_expr != nullptr) {
  8610. type = nullptr;
  8611. // [?]Type
  8612. if (type_expr->kind == Ast_ArrayType) {
  8613. Ast *count = type_expr->ArrayType.count;
  8614. if (count != nullptr) {
  8615. if (count->kind == Ast_UnaryExpr &&
  8616. count->UnaryExpr.op.kind == Token_Question) {
  8617. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  8618. is_to_be_determined_array_count = true;
  8619. }
  8620. } else {
  8621. type = alloc_type_slice(check_type(c, type_expr->ArrayType.elem));
  8622. }
  8623. if (cl->elems.count > 0) {
  8624. if (type_expr->ArrayType.tag != nullptr) {
  8625. Ast *tag = type_expr->ArrayType.tag;
  8626. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8627. String name = tag->BasicDirective.name.string;
  8628. if (name == "soa") {
  8629. is_soa = true;
  8630. if (count == nullptr) {
  8631. error(node, "#soa slices are not supported for compound literals");
  8632. return kind;
  8633. } else if (count->kind == Ast_UnaryExpr &&
  8634. count->UnaryExpr.op.kind == Token_Question) {
  8635. error(node, "#soa fixed length arrays must specify their length and cannot use ?");
  8636. }
  8637. }
  8638. }
  8639. }
  8640. } else if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  8641. if (cl->elems.count > 0) {
  8642. Ast *tag = type_expr->DynamicArrayType.tag;
  8643. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8644. String name = tag->BasicDirective.name.string;
  8645. if (name == "soa") {
  8646. is_soa = true;
  8647. error(node, "#soa dynamic arrays are not supported for compound literals");
  8648. return kind;
  8649. }
  8650. }
  8651. }
  8652. if (type == nullptr) {
  8653. type = check_type(c, type_expr);
  8654. }
  8655. }
  8656. if (type == nullptr) {
  8657. error(node, "Missing type in compound literal");
  8658. return kind;
  8659. }
  8660. Type *t = base_type(type);
  8661. if (is_type_polymorphic(t)) {
  8662. gbString str = type_to_string(type);
  8663. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  8664. o->expr = node;
  8665. o->type = type;
  8666. gb_string_free(str);
  8667. return kind;
  8668. }
  8669. switch (t->kind) {
  8670. case Type_Struct:
  8671. if (cl->elems.count == 0) {
  8672. break; // NOTE(bill): No need to init
  8673. }
  8674. if (t->Struct.soa_kind == StructSoa_None) {
  8675. if (t->Struct.is_raw_union) {
  8676. if (cl->elems.count > 0) {
  8677. // NOTE: unions cannot be constant
  8678. is_constant = elem_type_can_be_constant(t);
  8679. if (cl->elems[0]->kind != Ast_FieldValue) {
  8680. gbString type_str = type_to_string(type);
  8681. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  8682. gb_string_free(type_str);
  8683. } else {
  8684. if (cl->elems.count != 1) {
  8685. gbString type_str = type_to_string(type);
  8686. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain up to 1 'field = value' element, got %td", type_str, cl->elems.count);
  8687. gb_string_free(type_str);
  8688. } else {
  8689. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8690. }
  8691. }
  8692. }
  8693. break;
  8694. }
  8695. wait_signal_until_available(&t->Struct.fields_wait_signal);
  8696. isize field_count = t->Struct.fields.count;
  8697. isize min_field_count = t->Struct.fields.count;
  8698. for (isize i = min_field_count-1; i >= 0; i--) {
  8699. Entity *e = t->Struct.fields[i];
  8700. GB_ASSERT(e->kind == Entity_Variable);
  8701. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  8702. min_field_count--;
  8703. } else {
  8704. break;
  8705. }
  8706. }
  8707. if (cl->elems[0]->kind == Ast_FieldValue) {
  8708. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8709. } else {
  8710. bool seen_field_value = false;
  8711. for_array(index, cl->elems) {
  8712. Entity *field = nullptr;
  8713. Ast *elem = cl->elems[index];
  8714. if (elem->kind == Ast_FieldValue) {
  8715. seen_field_value = true;
  8716. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8717. continue;
  8718. } else if (seen_field_value) {
  8719. error(elem, "Value elements cannot be used after a 'field = value'");
  8720. continue;
  8721. }
  8722. if (index >= field_count) {
  8723. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8724. break;
  8725. }
  8726. if (field == nullptr) {
  8727. field = t->Struct.fields[index];
  8728. }
  8729. Operand o = {};
  8730. check_expr_or_type(c, &o, elem, field->type);
  8731. if (elem_cannot_be_constant(field->type)) {
  8732. is_constant = false;
  8733. }
  8734. if (is_constant) {
  8735. is_constant = check_is_operand_compound_lit_constant(c, &o, field->type);
  8736. }
  8737. check_assignment(c, &o, field->type, str_lit("structure literal"));
  8738. }
  8739. if (cl->elems.count < field_count) {
  8740. if (min_field_count < field_count) {
  8741. if (cl->elems.count < min_field_count) {
  8742. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  8743. }
  8744. } else {
  8745. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8746. }
  8747. }
  8748. }
  8749. break;
  8750. } else if (t->Struct.soa_kind != StructSoa_Fixed) {
  8751. error(node, "#soa slices and dynamic arrays are not supported for compound literals");
  8752. break;
  8753. }
  8754. /*fallthrough*/
  8755. case Type_Slice:
  8756. case Type_Array:
  8757. case Type_DynamicArray:
  8758. case Type_SimdVector:
  8759. case Type_Matrix:
  8760. {
  8761. Type *elem_type = nullptr;
  8762. String context_name = {};
  8763. i64 max_type_count = -1;
  8764. if (t->kind == Type_Struct) {
  8765. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8766. elem_type = t->Struct.soa_elem;
  8767. context_name = str_lit("#soa array literal");
  8768. if (!is_to_be_determined_array_count) {
  8769. max_type_count = t->Struct.soa_count;
  8770. }
  8771. } else if (t->kind == Type_Slice) {
  8772. elem_type = t->Slice.elem;
  8773. context_name = str_lit("slice literal");
  8774. } else if (t->kind == Type_Array) {
  8775. elem_type = t->Array.elem;
  8776. context_name = str_lit("array literal");
  8777. if (!is_to_be_determined_array_count) {
  8778. max_type_count = t->Array.count;
  8779. }
  8780. } else if (t->kind == Type_Array) {
  8781. elem_type = t->Array.elem;
  8782. context_name = str_lit("array literal");
  8783. if (!is_to_be_determined_array_count) {
  8784. max_type_count = t->Array.count;
  8785. }
  8786. } else if (t->kind == Type_DynamicArray) {
  8787. elem_type = t->DynamicArray.elem;
  8788. context_name = str_lit("dynamic array literal");
  8789. is_constant = false;
  8790. } else if (t->kind == Type_SimdVector) {
  8791. elem_type = t->SimdVector.elem;
  8792. context_name = str_lit("simd vector literal");
  8793. max_type_count = t->SimdVector.count;
  8794. } else if (t->kind == Type_Matrix) {
  8795. elem_type = t->Matrix.elem;
  8796. context_name = str_lit("matrix literal");
  8797. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  8798. } else {
  8799. GB_PANIC("unreachable");
  8800. }
  8801. i64 max = 0;
  8802. Type *bet = base_type(elem_type);
  8803. if (!elem_type_can_be_constant(bet)) {
  8804. is_constant = false;
  8805. }
  8806. if (bet == t_invalid) {
  8807. break;
  8808. }
  8809. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8810. RangeCache rc = range_cache_make(heap_allocator());
  8811. defer (range_cache_destroy(&rc));
  8812. for (Ast *elem : cl->elems) {
  8813. if (elem->kind != Ast_FieldValue) {
  8814. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8815. continue;
  8816. }
  8817. ast_node(fv, FieldValue, elem);
  8818. if (is_ast_range(fv->field)) {
  8819. Token op = fv->field->BinaryExpr.op;
  8820. Operand x = {};
  8821. Operand y = {};
  8822. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  8823. if (!ok) {
  8824. continue;
  8825. }
  8826. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  8827. error(x.expr, "Expected a constant integer as an array field");
  8828. continue;
  8829. }
  8830. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  8831. error(y.expr, "Expected a constant integer as an array field");
  8832. continue;
  8833. }
  8834. i64 lo = exact_value_to_i64(x.value);
  8835. i64 hi = exact_value_to_i64(y.value);
  8836. i64 max_index = hi;
  8837. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  8838. hi -= 1;
  8839. } else { // .. (inclusive)
  8840. max_index += 1;
  8841. }
  8842. bool new_range = range_cache_add_range(&rc, lo, hi);
  8843. if (!new_range) {
  8844. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  8845. continue;
  8846. }
  8847. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  8848. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  8849. continue;
  8850. }
  8851. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  8852. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  8853. continue;
  8854. }
  8855. if (max < hi) {
  8856. max = max_index;
  8857. }
  8858. Operand operand = {};
  8859. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8860. check_assignment(c, &operand, elem_type, context_name);
  8861. if (is_constant) {
  8862. is_constant = check_is_operand_compound_lit_constant(c, &operand, elem_type);
  8863. }
  8864. } else {
  8865. Operand op_index = {};
  8866. check_expr(c, &op_index, fv->field);
  8867. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  8868. error(elem, "Expected a constant integer as an array field");
  8869. continue;
  8870. }
  8871. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  8872. i64 index = exact_value_to_i64(op_index.value);
  8873. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  8874. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  8875. continue;
  8876. }
  8877. bool new_index = range_cache_add_index(&rc, index);
  8878. if (!new_index) {
  8879. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  8880. continue;
  8881. }
  8882. if (max < index+1) {
  8883. max = index+1;
  8884. }
  8885. Operand operand = {};
  8886. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8887. check_assignment(c, &operand, elem_type, context_name);
  8888. if (is_constant) {
  8889. is_constant = check_is_operand_compound_lit_constant(c, &operand, elem_type);
  8890. }
  8891. }
  8892. }
  8893. cl->max_count = max;
  8894. } else {
  8895. isize index = 0;
  8896. for (; index < cl->elems.count; index++) {
  8897. Ast *e = cl->elems[index];
  8898. if (e == nullptr) {
  8899. error(node, "Invalid literal element");
  8900. continue;
  8901. }
  8902. if (e->kind == Ast_FieldValue) {
  8903. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8904. continue;
  8905. }
  8906. if (0 <= max_type_count && max_type_count <= index) {
  8907. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8908. }
  8909. Operand operand = {};
  8910. check_expr_with_type_hint(c, &operand, e, elem_type);
  8911. check_assignment(c, &operand, elem_type, context_name);
  8912. if (is_constant) {
  8913. is_constant = check_is_operand_compound_lit_constant(c, &operand, elem_type);
  8914. }
  8915. }
  8916. if (max < index) {
  8917. max = index;
  8918. }
  8919. }
  8920. if (t->kind == Type_Array) {
  8921. if (is_to_be_determined_array_count) {
  8922. t->Array.count = max;
  8923. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8924. if (0 < max && max < t->Array.count) {
  8925. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8926. }
  8927. }
  8928. } else if (t->kind == Type_Struct) {
  8929. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8930. if (is_to_be_determined_array_count) {
  8931. t->Struct.soa_count = cast(i32)max;
  8932. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8933. if (0 < max && max < t->Struct.soa_count) {
  8934. error(node, "Expected %lld values for this #soa array literal, got %lld", cast(long long)t->Struct.soa_count, cast(long long)max);
  8935. }
  8936. }
  8937. }
  8938. if (t->kind == Type_SimdVector) {
  8939. if (!is_constant) {
  8940. // error(node, "Expected all constant elements for a simd vector");
  8941. }
  8942. }
  8943. if (t->kind == Type_DynamicArray) {
  8944. if (check_for_dynamic_literals(c, node, cl)) {
  8945. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  8946. add_package_dependency(c, "runtime", "__dynamic_array_append");
  8947. }
  8948. }
  8949. if (t->kind == Type_Matrix) {
  8950. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8951. if (0 < max && max < max_type_count) {
  8952. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  8953. }
  8954. }
  8955. }
  8956. break;
  8957. }
  8958. case Type_EnumeratedArray:
  8959. {
  8960. Type *elem_type = t->EnumeratedArray.elem;
  8961. Type *index_type = t->EnumeratedArray.index;
  8962. String context_name = str_lit("enumerated array literal");
  8963. i64 max_type_count = t->EnumeratedArray.count;
  8964. gbString index_type_str = type_to_string(index_type);
  8965. defer (gb_string_free(index_type_str));
  8966. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  8967. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  8968. String total_lo_string = {};
  8969. String total_hi_string = {};
  8970. GB_ASSERT(is_type_enum(index_type));
  8971. {
  8972. Type *bt = base_type(index_type);
  8973. GB_ASSERT(bt->kind == Type_Enum);
  8974. for (Entity *f : bt->Enum.fields) {
  8975. if (f->kind != Entity_Constant) {
  8976. continue;
  8977. }
  8978. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  8979. total_lo_string = f->token.string;
  8980. }
  8981. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  8982. total_hi_string = f->token.string;
  8983. }
  8984. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8985. break;
  8986. }
  8987. }
  8988. }
  8989. i64 max = 0;
  8990. Type *bet = base_type(elem_type);
  8991. if (!elem_type_can_be_constant(bet)) {
  8992. is_constant = false;
  8993. }
  8994. if (bet == t_invalid) {
  8995. break;
  8996. }
  8997. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8998. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8999. defer (map_destroy(&seen));
  9000. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  9001. RangeCache rc = range_cache_make(heap_allocator());
  9002. defer (range_cache_destroy(&rc));
  9003. for (Ast *elem : cl->elems) {
  9004. if (elem->kind != Ast_FieldValue) {
  9005. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  9006. continue;
  9007. }
  9008. ast_node(fv, FieldValue, elem);
  9009. if (is_ast_range(fv->field)) {
  9010. Token op = fv->field->BinaryExpr.op;
  9011. Operand x = {};
  9012. Operand y = {};
  9013. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  9014. if (!ok) {
  9015. continue;
  9016. }
  9017. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  9018. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  9019. continue;
  9020. }
  9021. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  9022. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  9023. continue;
  9024. }
  9025. i64 lo = exact_value_to_i64(x.value);
  9026. i64 hi = exact_value_to_i64(y.value);
  9027. i64 max_index = hi;
  9028. if (op.kind == Token_RangeHalf) {
  9029. hi -= 1;
  9030. }
  9031. bool new_range = range_cache_add_range(&rc, lo, hi);
  9032. if (!new_range) {
  9033. gbString lo_str = expr_to_string(x.expr);
  9034. gbString hi_str = expr_to_string(y.expr);
  9035. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  9036. gb_string_free(hi_str);
  9037. gb_string_free(lo_str);
  9038. continue;
  9039. }
  9040. // NOTE(bill): These are sanity checks for invalid enum values
  9041. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  9042. gbString lo_str = expr_to_string(x.expr);
  9043. error(elem, "Index %s is out of bounds (%.*s .. %.*s) for %.*s", lo_str, LIT(total_lo_string), LIT(total_hi_string), LIT(context_name));
  9044. gb_string_free(lo_str);
  9045. continue;
  9046. }
  9047. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  9048. gbString hi_str = expr_to_string(y.expr);
  9049. error(elem, "Index %s is out of bounds (%.*s .. %.*s) for %.*s", hi_str, LIT(total_lo_string), LIT(total_hi_string), LIT(context_name));
  9050. gb_string_free(hi_str);
  9051. continue;
  9052. }
  9053. if (max < hi) {
  9054. max = max_index;
  9055. }
  9056. Operand operand = {};
  9057. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  9058. check_assignment(c, &operand, elem_type, context_name);
  9059. if (is_constant) {
  9060. is_constant = check_is_operand_compound_lit_constant(c, &operand, elem_type);
  9061. }
  9062. TokenKind upper_op = Token_LtEq;
  9063. if (op.kind == Token_RangeHalf) {
  9064. upper_op = Token_Lt;
  9065. }
  9066. add_to_seen_map(c, &seen, upper_op, x, x, y);
  9067. } else {
  9068. Operand op_index = {};
  9069. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  9070. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  9071. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  9072. continue;
  9073. }
  9074. i64 index = exact_value_to_i64(op_index.value);
  9075. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  9076. gbString idx_str = expr_to_string(op_index.expr);
  9077. error(elem, "Index %s is out of bounds (%.*s .. %.*s) for %.*s", idx_str, LIT(total_lo_string), LIT(total_hi_string), LIT(context_name));
  9078. gb_string_free(idx_str);
  9079. continue;
  9080. }
  9081. bool new_index = range_cache_add_index(&rc, index);
  9082. if (!new_index) {
  9083. gbString idx_str = expr_to_string(op_index.expr);
  9084. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  9085. gb_string_free(idx_str);
  9086. continue;
  9087. }
  9088. if (max < index+1) {
  9089. max = index+1;
  9090. }
  9091. Operand operand = {};
  9092. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  9093. check_assignment(c, &operand, elem_type, context_name);
  9094. if (is_constant) {
  9095. is_constant = check_is_operand_compound_lit_constant(c, &operand, elem_type);
  9096. }
  9097. add_to_seen_map(c, &seen, op_index);
  9098. }
  9099. }
  9100. cl->max_count = max;
  9101. } else {
  9102. isize index = 0;
  9103. for (; index < cl->elems.count; index++) {
  9104. Ast *e = cl->elems[index];
  9105. if (e == nullptr) {
  9106. error(node, "Invalid literal element");
  9107. continue;
  9108. }
  9109. if (e->kind == Ast_FieldValue) {
  9110. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  9111. continue;
  9112. }
  9113. if (0 <= max_type_count && max_type_count <= index) {
  9114. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  9115. }
  9116. Operand operand = {};
  9117. check_expr_with_type_hint(c, &operand, e, elem_type);
  9118. check_assignment(c, &operand, elem_type, context_name);
  9119. if (is_constant) {
  9120. is_constant = check_is_operand_compound_lit_constant(c, &operand, elem_type);
  9121. }
  9122. }
  9123. if (max < index) {
  9124. max = index;
  9125. }
  9126. }
  9127. bool was_error = false;
  9128. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  9129. if (0 < max && max < t->EnumeratedArray.count) {
  9130. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  9131. was_error = true;
  9132. } else {
  9133. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  9134. was_error = true;
  9135. }
  9136. }
  9137. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  9138. if (cl->elems.count > 0 && !was_error && !is_partial) {
  9139. TEMPORARY_ALLOCATOR_GUARD();
  9140. Type *et = base_type(index_type);
  9141. GB_ASSERT(et->kind == Type_Enum);
  9142. auto fields = et->Enum.fields;
  9143. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  9144. for (Entity *f : fields) {
  9145. if (f->kind != Entity_Constant) {
  9146. continue;
  9147. }
  9148. ExactValue v = f->Constant.value;
  9149. uintptr hash = hash_exact_value(v);
  9150. auto found = map_get(&seen, hash);
  9151. if (!found) {
  9152. array_add(&unhandled, f);
  9153. }
  9154. }
  9155. if (unhandled.count > 0) {
  9156. ERROR_BLOCK();
  9157. if (unhandled.count == 1) {
  9158. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  9159. } else {
  9160. error(node, "Unhandled enumerated array cases:");
  9161. for_array(i, unhandled) {
  9162. Entity *f = unhandled[i];
  9163. error_line("\t%.*s\n", LIT(f->token.string));
  9164. }
  9165. }
  9166. if (!build_context.terse_errors) {
  9167. error_line("\n");
  9168. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  9169. }
  9170. }
  9171. }
  9172. break;
  9173. }
  9174. case Type_Basic: {
  9175. if (!is_type_any(t)) {
  9176. if (cl->elems.count != 0) {
  9177. gbString s = type_to_string(t);
  9178. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  9179. gb_string_free(s);
  9180. is_constant = false;
  9181. }
  9182. break;
  9183. }
  9184. if (cl->elems.count == 0) {
  9185. break; // NOTE(bill): No need to init
  9186. }
  9187. { // Checker values
  9188. Type *field_types[2] = {t_rawptr, t_typeid};
  9189. isize field_count = 2;
  9190. if (cl->elems[0]->kind == Ast_FieldValue) {
  9191. bool fields_visited[2] = {};
  9192. for_array(i, cl->elems) {
  9193. Ast *elem = cl->elems[i];
  9194. if (elem->kind != Ast_FieldValue) {
  9195. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  9196. continue;
  9197. }
  9198. ast_node(fv, FieldValue, elem);
  9199. if (fv->field->kind != Ast_Ident) {
  9200. gbString expr_str = expr_to_string(fv->field);
  9201. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  9202. gb_string_free(expr_str);
  9203. continue;
  9204. }
  9205. String name = fv->field->Ident.token.string;
  9206. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  9207. if (sel.entity == nullptr) {
  9208. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  9209. continue;
  9210. }
  9211. isize index = sel.index[0];
  9212. if (fields_visited[index]) {
  9213. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  9214. continue;
  9215. }
  9216. fields_visited[index] = true;
  9217. check_expr(c, o, fv->value);
  9218. // NOTE(bill): 'any' literals can never be constant
  9219. is_constant = false;
  9220. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  9221. }
  9222. } else {
  9223. for_array(index, cl->elems) {
  9224. Ast *elem = cl->elems[index];
  9225. if (elem->kind == Ast_FieldValue) {
  9226. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  9227. continue;
  9228. }
  9229. check_expr(c, o, elem);
  9230. if (index >= field_count) {
  9231. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  9232. break;
  9233. }
  9234. // NOTE(bill): 'any' literals can never be constant
  9235. is_constant = false;
  9236. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  9237. }
  9238. if (cl->elems.count < field_count) {
  9239. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  9240. }
  9241. }
  9242. }
  9243. break;
  9244. }
  9245. case Type_Map: {
  9246. if (cl->elems.count == 0) {
  9247. break;
  9248. }
  9249. is_constant = false;
  9250. { // Checker values
  9251. bool key_is_typeid = is_type_typeid(t->Map.key);
  9252. bool value_is_typeid = is_type_typeid(t->Map.value);
  9253. for (Ast *elem : cl->elems) {
  9254. if (elem->kind != Ast_FieldValue) {
  9255. error(elem, "Only 'field = value' elements are allowed in a map literal");
  9256. continue;
  9257. }
  9258. ast_node(fv, FieldValue, elem);
  9259. if (key_is_typeid) {
  9260. check_expr_or_type(c, o, fv->field, t->Map.key);
  9261. } else {
  9262. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  9263. }
  9264. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  9265. if (o->mode == Addressing_Invalid) {
  9266. continue;
  9267. }
  9268. if (value_is_typeid) {
  9269. check_expr_or_type(c, o, fv->value, t->Map.value);
  9270. } else {
  9271. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  9272. }
  9273. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  9274. }
  9275. }
  9276. if (check_for_dynamic_literals(c, node, cl)) {
  9277. add_map_reserve_dependencies(c);
  9278. add_map_set_dependencies(c);
  9279. }
  9280. break;
  9281. }
  9282. case Type_BitSet: {
  9283. if (cl->elems.count == 0) {
  9284. break; // NOTE(bill): No need to init
  9285. }
  9286. Type *et = base_type(t->BitSet.elem);
  9287. isize field_count = 0;
  9288. if (et != nullptr && et->kind == Type_Enum) {
  9289. field_count = et->Enum.fields.count;
  9290. }
  9291. if (is_type_array(bit_set_to_int(t))) {
  9292. is_constant = false;
  9293. }
  9294. for (Ast *elem : cl->elems) {
  9295. if (elem->kind == Ast_FieldValue) {
  9296. error(elem, "'field = value' in a bit_set literal is not allowed");
  9297. is_constant = false;
  9298. continue;
  9299. }
  9300. check_expr_with_type_hint(c, o, elem, et);
  9301. if (is_constant) {
  9302. is_constant = o->mode == Addressing_Constant;
  9303. }
  9304. if (elem->kind == Ast_BinaryExpr) {
  9305. switch (elem->BinaryExpr.op.kind) {
  9306. case Token_Or:
  9307. {
  9308. gbString x = expr_to_string(elem->BinaryExpr.left);
  9309. gbString y = expr_to_string(elem->BinaryExpr.right);
  9310. gbString e = expr_to_string(elem);
  9311. error(elem, "Was the following intended? '%s, %s'; if not, surround the expression with parentheses '(%s)'", x, y, e);
  9312. gb_string_free(e);
  9313. gb_string_free(y);
  9314. gb_string_free(x);
  9315. }
  9316. break;
  9317. }
  9318. }
  9319. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  9320. if (o->mode == Addressing_Constant) {
  9321. i64 lower = t->BitSet.lower;
  9322. i64 upper = t->BitSet.upper;
  9323. i64 v = exact_value_to_i64(o->value);
  9324. if (lower <= v && v <= upper) {
  9325. // okay
  9326. } else {
  9327. gbString s = expr_to_string(o->expr);
  9328. error(elem, "Bit field value out of bounds, %s (%lld) not in the range %lld .. %lld", s, v, lower, upper);
  9329. gb_string_free(s);
  9330. continue;
  9331. }
  9332. }
  9333. }
  9334. break;
  9335. }
  9336. case Type_BitField: {
  9337. if (cl->elems.count == 0) {
  9338. break; // NOTE(bill): No need to init
  9339. }
  9340. is_constant = false;
  9341. if (cl->elems[0]->kind != Ast_FieldValue) {
  9342. gbString type_str = type_to_string(type);
  9343. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  9344. gb_string_free(type_str);
  9345. } else {
  9346. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  9347. }
  9348. break;
  9349. }
  9350. default: {
  9351. if (cl->elems.count == 0) {
  9352. break; // NOTE(bill): No need to init
  9353. }
  9354. gbString str = type_to_string(type);
  9355. error(node, "Invalid compound literal type '%s'", str);
  9356. gb_string_free(str);
  9357. return kind;
  9358. }
  9359. }
  9360. if (is_constant) {
  9361. o->mode = Addressing_Constant;
  9362. if (is_type_bit_set(type)) {
  9363. // NOTE(bill): Encode as an integer
  9364. Type *bt = base_type(type);
  9365. BigInt bits = {};
  9366. BigInt one = {};
  9367. big_int_from_u64(&one, 1);
  9368. for (Ast *e : cl->elems) {
  9369. GB_ASSERT(e->kind != Ast_FieldValue);
  9370. TypeAndValue tav = e->tav;
  9371. if (tav.mode != Addressing_Constant) {
  9372. continue;
  9373. }
  9374. if (tav.value.kind != ExactValue_Integer) {
  9375. continue;
  9376. }
  9377. i64 v = big_int_to_i64(&tav.value.value_integer);
  9378. i64 lower = bt->BitSet.lower;
  9379. u64 index = cast(u64)(v-lower);
  9380. BigInt bit = {};
  9381. big_int_from_u64(&bit, index);
  9382. big_int_shl(&bit, &one, &bit);
  9383. big_int_or(&bits, &bits, &bit);
  9384. }
  9385. o->value.kind = ExactValue_Integer;
  9386. o->value.value_integer = bits;
  9387. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  9388. ExactValue value = exact_value_compound(node);
  9389. Type *bt = core_type(type);
  9390. if (bt->kind == Type_Basic) {
  9391. if (bt->Basic.flags & BasicFlag_Boolean) {
  9392. value = exact_value_bool(false);
  9393. } else if (bt->Basic.flags & BasicFlag_Integer) {
  9394. value = exact_value_i64(0);
  9395. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  9396. value = exact_value_i64(0);
  9397. } else if (bt->Basic.flags & BasicFlag_Float) {
  9398. value = exact_value_float(0);
  9399. } else if (bt->Basic.flags & BasicFlag_Complex) {
  9400. value = exact_value_complex(0, 0);
  9401. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  9402. value = exact_value_quaternion(0, 0, 0, 0);
  9403. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  9404. value = exact_value_pointer(0);
  9405. } else if (bt->Basic.flags & BasicFlag_String) {
  9406. String empty_string = {};
  9407. value = exact_value_string(empty_string);
  9408. } else if (bt->Basic.flags & BasicFlag_Rune) {
  9409. value = exact_value_i64(0);
  9410. }
  9411. }
  9412. o->value = value;
  9413. } else {
  9414. o->value = exact_value_compound(node);
  9415. }
  9416. } else {
  9417. o->mode = Addressing_Value;
  9418. }
  9419. o->type = type;
  9420. return kind;
  9421. }
  9422. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9423. ExprKind kind = Expr_Expr;
  9424. ast_node(ta, TypeAssertion, node);
  9425. check_expr(c, o, ta->expr);
  9426. node->viral_state_flags |= ta->expr->viral_state_flags;
  9427. if (o->mode == Addressing_Invalid) {
  9428. o->expr = node;
  9429. return kind;
  9430. }
  9431. if (o->mode == Addressing_Constant) {
  9432. gbString expr_str = expr_to_string(o->expr);
  9433. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  9434. gb_string_free(expr_str);
  9435. o->mode = Addressing_Invalid;
  9436. o->expr = node;
  9437. return kind;
  9438. }
  9439. if (is_type_untyped(o->type)) {
  9440. gbString expr_str = expr_to_string(o->expr);
  9441. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  9442. gb_string_free(expr_str);
  9443. o->mode = Addressing_Invalid;
  9444. o->expr = node;
  9445. return kind;
  9446. }
  9447. Type *src = type_deref(o->type);
  9448. Type *bsrc = base_type(src);
  9449. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  9450. if (!is_type_union(src)) {
  9451. gbString str = type_to_string(o->type);
  9452. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  9453. gb_string_free(str);
  9454. o->mode = Addressing_Invalid;
  9455. o->expr = node;
  9456. return kind;
  9457. }
  9458. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  9459. bool allowed = false;
  9460. for (Type *vt : bsrc->Union.variants) {
  9461. if (are_types_identical(vt, type_hint)) {
  9462. allowed = true;
  9463. add_type_info_type(c, vt);
  9464. break;
  9465. }
  9466. }
  9467. if (allowed) {
  9468. add_type_info_type(c, o->type);
  9469. o->type = type_hint;
  9470. o->mode = Addressing_OptionalOk;
  9471. goto end;
  9472. }
  9473. }
  9474. if (bsrc->Union.variants.count != 1) {
  9475. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  9476. o->mode = Addressing_Invalid;
  9477. o->expr = node;
  9478. return kind;
  9479. }
  9480. add_type_info_type(c, o->type);
  9481. add_type_info_type(c, bsrc->Union.variants[0]);
  9482. o->type = bsrc->Union.variants[0];
  9483. o->mode = Addressing_OptionalOk;
  9484. } else {
  9485. Type *t = check_type(c, ta->type);
  9486. Type *dst = t;
  9487. if (is_type_union(src)) {
  9488. bool ok = false;
  9489. for (Type *vt : bsrc->Union.variants) {
  9490. if (are_types_identical(vt, dst)) {
  9491. ok = true;
  9492. break;
  9493. }
  9494. }
  9495. if (!ok) {
  9496. gbString expr_str = expr_to_string(o->expr);
  9497. gbString dst_type_str = type_to_string(t);
  9498. defer (gb_string_free(expr_str));
  9499. defer (gb_string_free(dst_type_str));
  9500. if (bsrc->Union.variants.count == 0) {
  9501. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  9502. } else {
  9503. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  9504. }
  9505. o->mode = Addressing_Invalid;
  9506. o->expr = node;
  9507. return kind;
  9508. }
  9509. add_type_info_type(c, o->type);
  9510. add_type_info_type(c, t);
  9511. o->type = t;
  9512. o->mode = Addressing_OptionalOk;
  9513. } else if (is_type_any(src)) {
  9514. o->type = t;
  9515. o->mode = Addressing_OptionalOk;
  9516. add_type_info_type(c, o->type);
  9517. add_type_info_type(c, t);
  9518. } else {
  9519. gbString str = type_to_string(o->type);
  9520. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  9521. gb_string_free(str);
  9522. o->mode = Addressing_Invalid;
  9523. o->expr = node;
  9524. return kind;
  9525. }
  9526. }
  9527. end:;
  9528. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  9529. add_package_dependency(c, "runtime", "type_assertion_check");
  9530. add_package_dependency(c, "runtime", "type_assertion_check2");
  9531. }
  9532. return kind;
  9533. }
  9534. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9535. ast_node(se, SelectorCallExpr, node);
  9536. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  9537. // COM APIs is a great example of where this kind of thing is extremely useful
  9538. // General idea:
  9539. //
  9540. // x->y(123) == x.y(x, 123)
  9541. //
  9542. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  9543. // Just regenerating a new AST aids things
  9544. //
  9545. // TODO(bill): Is this a good hack or not?
  9546. //
  9547. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  9548. if (se->modified_call) {
  9549. // Prevent double evaluation
  9550. o->expr = node;
  9551. o->type = node->tav.type;
  9552. o->value = node->tav.value;
  9553. o->mode = node->tav.mode;
  9554. return Expr_Expr;
  9555. }
  9556. bool allow_arrow_right_selector_expr;
  9557. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9558. c->allow_arrow_right_selector_expr = true;
  9559. Operand x = {};
  9560. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  9561. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9562. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  9563. o->mode = Addressing_Invalid;
  9564. o->type = t_invalid;
  9565. o->expr = node;
  9566. return kind;
  9567. }
  9568. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  9569. gbString type_str = type_to_string(x.type);
  9570. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  9571. gb_string_free(type_str);
  9572. o->mode = Addressing_Invalid;
  9573. o->type = t_invalid;
  9574. o->expr = node;
  9575. return Expr_Stmt;
  9576. }
  9577. ast_node(ce, CallExpr, se->call);
  9578. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  9579. Ast *first_arg = x.expr->SelectorExpr.expr;
  9580. GB_ASSERT(first_arg != nullptr);
  9581. Entity *e = entity_of_node(se->expr);
  9582. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  9583. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  9584. }
  9585. if (e->kind != Entity_ProcGroup) {
  9586. Type *pt = base_type(x.type);
  9587. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  9588. Type *first_type = nullptr;
  9589. String first_arg_name = {};
  9590. if (pt->Proc.param_count > 0) {
  9591. Entity *f = pt->Proc.params->Tuple.variables[0];
  9592. first_type = f->type;
  9593. first_arg_name = f->token.string;
  9594. }
  9595. if (first_arg_name.len == 0) {
  9596. first_arg_name = str_lit("_");
  9597. }
  9598. if (first_type == nullptr) {
  9599. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  9600. o->mode = Addressing_Invalid;
  9601. o->type = t_invalid;
  9602. o->expr = node;
  9603. return Expr_Stmt;
  9604. }
  9605. Operand y = {};
  9606. y.mode = first_arg->tav.mode;
  9607. y.type = first_arg->tav.type;
  9608. y.value = first_arg->tav.value;
  9609. if (check_is_assignable_to(c, &y, first_type)) {
  9610. // Do nothing, it's valid
  9611. } else {
  9612. Operand z = y;
  9613. z.type = type_deref(y.type);
  9614. if (check_is_assignable_to(c, &z, first_type)) {
  9615. // NOTE(bill): AST GENERATION HACK!
  9616. Token op = {Token_Pointer};
  9617. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  9618. } else if (y.mode == Addressing_Variable) {
  9619. Operand w = y;
  9620. w.type = alloc_type_pointer(y.type);
  9621. if (check_is_assignable_to(c, &w, first_type)) {
  9622. // NOTE(bill): AST GENERATION HACK!
  9623. Token op = {Token_And};
  9624. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  9625. }
  9626. }
  9627. }
  9628. if (ce->args.count > 0) {
  9629. bool fail = false;
  9630. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  9631. for (Ast *arg : ce->args) {
  9632. bool mix = false;
  9633. if (first_is_field_value) {
  9634. mix = arg->kind != Ast_FieldValue;
  9635. } else {
  9636. mix = arg->kind == Ast_FieldValue;
  9637. }
  9638. if (mix) {
  9639. fail = true;
  9640. break;
  9641. }
  9642. }
  9643. if (!fail && first_is_field_value) {
  9644. Token op = {Token_Eq};
  9645. AstFile *f = first_arg->file();
  9646. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  9647. }
  9648. }
  9649. }
  9650. auto modified_args = permanent_slice_make<Ast *>(ce->args.count+1);
  9651. modified_args[0] = first_arg;
  9652. slice_copy(&modified_args, ce->args, 1);
  9653. ce->args = modified_args;
  9654. se->modified_call = true;
  9655. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9656. c->allow_arrow_right_selector_expr = true;
  9657. check_expr_base(c, o, se->call, type_hint);
  9658. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9659. o->expr = node;
  9660. return Expr_Expr;
  9661. }
  9662. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9663. ExprKind kind = Expr_Expr;
  9664. ast_node(ie, IndexExpr, node);
  9665. check_expr(c, o, ie->expr);
  9666. node->viral_state_flags |= ie->expr->viral_state_flags;
  9667. if (o->mode == Addressing_Invalid) {
  9668. o->expr = node;
  9669. return kind;
  9670. }
  9671. Type *t = base_type(type_deref(o->type));
  9672. bool is_ptr = is_type_pointer(o->type);
  9673. bool is_const = o->mode == Addressing_Constant;
  9674. if (is_type_map(t)) {
  9675. Operand key = {};
  9676. if (is_type_typeid(t->Map.key)) {
  9677. check_expr_or_type(c, &key, ie->index, t->Map.key);
  9678. } else {
  9679. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  9680. }
  9681. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  9682. if (key.mode == Addressing_Invalid) {
  9683. o->mode = Addressing_Invalid;
  9684. o->expr = node;
  9685. return kind;
  9686. }
  9687. o->mode = Addressing_MapIndex;
  9688. o->type = t->Map.value;
  9689. o->expr = node;
  9690. add_map_get_dependencies(c);
  9691. add_map_set_dependencies(c);
  9692. return Expr_Expr;
  9693. }
  9694. i64 max_count = -1;
  9695. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  9696. if (is_const) {
  9697. if (is_type_array(t)) {
  9698. // Okay
  9699. } else if (is_type_slice(t)) {
  9700. // Okay
  9701. } else if (is_type_enumerated_array(t)) {
  9702. // Okay
  9703. } else if (is_type_string(t)) {
  9704. // Okay
  9705. } else if (is_type_matrix(t)) {
  9706. // Okay
  9707. } else {
  9708. valid = false;
  9709. }
  9710. }
  9711. if (!valid) {
  9712. gbString str = expr_to_string(o->expr);
  9713. gbString type_str = type_to_string(o->type);
  9714. defer (gb_string_free(str));
  9715. defer (gb_string_free(type_str));
  9716. if (is_const) {
  9717. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  9718. } else {
  9719. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  9720. }
  9721. o->mode = Addressing_Invalid;
  9722. o->expr = node;
  9723. return kind;
  9724. }
  9725. if (ie->index == nullptr) {
  9726. gbString str = expr_to_string(o->expr);
  9727. error(o->expr, "Missing index for '%s'", str);
  9728. gb_string_free(str);
  9729. o->mode = Addressing_Invalid;
  9730. o->expr = node;
  9731. return kind;
  9732. }
  9733. Type *index_type_hint = nullptr;
  9734. if (is_type_enumerated_array(t)) {
  9735. Type *bt = base_type(t);
  9736. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  9737. index_type_hint = bt->EnumeratedArray.index;
  9738. }
  9739. i64 index = 0;
  9740. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  9741. if (is_const) {
  9742. if (index < 0) {
  9743. ERROR_BLOCK();
  9744. gbString str = expr_to_string(o->expr);
  9745. error(o->expr, "Cannot index a constant '%s'", str);
  9746. if (!build_context.terse_errors) {
  9747. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9748. }
  9749. gb_string_free(str);
  9750. o->mode = Addressing_Invalid;
  9751. o->expr = node;
  9752. return kind;
  9753. } else if (ok && !is_type_matrix(t)) {
  9754. TypeAndValue tav = type_and_value_of_expr(ie->expr);
  9755. ExactValue value = tav.value;
  9756. o->mode = Addressing_Constant;
  9757. bool success = false;
  9758. bool finish = false;
  9759. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  9760. if (!success) {
  9761. ERROR_BLOCK();
  9762. gbString str = expr_to_string(o->expr);
  9763. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  9764. if (!build_context.terse_errors) {
  9765. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9766. }
  9767. gb_string_free(str);
  9768. o->mode = Addressing_Invalid;
  9769. o->expr = node;
  9770. return kind;
  9771. }
  9772. }
  9773. }
  9774. if (type_hint != nullptr && is_type_matrix(t)) {
  9775. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  9776. // if a type hint exists
  9777. }
  9778. return kind;
  9779. }
  9780. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9781. ExprKind kind = Expr_Stmt;
  9782. ast_node(se, SliceExpr, node);
  9783. check_expr(c, o, se->expr);
  9784. node->viral_state_flags |= se->expr->viral_state_flags;
  9785. if (o->mode == Addressing_Invalid) {
  9786. o->mode = Addressing_Invalid;
  9787. o->expr = node;
  9788. return kind;
  9789. }
  9790. bool valid = false;
  9791. i64 max_count = -1;
  9792. Type *t = base_type(type_deref(o->type));
  9793. switch (t->kind) {
  9794. case Type_Basic:
  9795. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  9796. valid = true;
  9797. if (o->mode == Addressing_Constant) {
  9798. GB_ASSERT(o->value.kind == ExactValue_String);
  9799. max_count = o->value.value_string.len;
  9800. }
  9801. o->type = type_deref(o->type);
  9802. } else if (t->Basic.kind == Basic_string16) {
  9803. valid = true;
  9804. if (o->mode == Addressing_Constant) {
  9805. GB_ASSERT(o->value.kind == ExactValue_String16);
  9806. max_count = o->value.value_string16.len;
  9807. }
  9808. o->type = type_deref(o->type);
  9809. }
  9810. break;
  9811. case Type_Array:
  9812. valid = true;
  9813. max_count = t->Array.count;
  9814. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9815. gbString str = expr_to_string(node);
  9816. error(node, "Cannot slice array '%s', value is not addressable", str);
  9817. gb_string_free(str);
  9818. o->mode = Addressing_Invalid;
  9819. o->expr = node;
  9820. return kind;
  9821. }
  9822. o->type = alloc_type_slice(t->Array.elem);
  9823. break;
  9824. case Type_MultiPointer:
  9825. valid = true;
  9826. o->type = type_deref(o->type);
  9827. break;
  9828. case Type_Slice:
  9829. valid = true;
  9830. o->type = type_deref(o->type);
  9831. break;
  9832. case Type_DynamicArray:
  9833. valid = true;
  9834. o->type = alloc_type_slice(t->DynamicArray.elem);
  9835. break;
  9836. case Type_Struct:
  9837. if (is_type_soa_struct(t)) {
  9838. valid = true;
  9839. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9840. max_count = t->Struct.soa_count;
  9841. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9842. gbString str = expr_to_string(node);
  9843. error(node, "Cannot slice #soa array '%s', value is not addressable", str);
  9844. gb_string_free(str);
  9845. o->mode = Addressing_Invalid;
  9846. o->expr = node;
  9847. return kind;
  9848. }
  9849. }
  9850. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  9851. }
  9852. break;
  9853. case Type_EnumeratedArray:
  9854. {
  9855. gbString str = expr_to_string(o->expr);
  9856. gbString type_str = type_to_string(o->type);
  9857. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  9858. gb_string_free(type_str);
  9859. gb_string_free(str);
  9860. o->mode = Addressing_Invalid;
  9861. o->expr = node;
  9862. return kind;
  9863. }
  9864. break;
  9865. }
  9866. if (!valid) {
  9867. gbString str = expr_to_string(o->expr);
  9868. gbString type_str = type_to_string(o->type);
  9869. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  9870. gb_string_free(type_str);
  9871. gb_string_free(str);
  9872. o->mode = Addressing_Invalid;
  9873. o->expr = node;
  9874. return kind;
  9875. }
  9876. if (se->low == nullptr && se->high != nullptr) {
  9877. // It is okay to continue as it will assume the 1st index is zero
  9878. }
  9879. i64 indices[2] = {};
  9880. Ast *nodes[2] = {se->low, se->high};
  9881. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9882. i64 index = max_count;
  9883. if (nodes[i] != nullptr) {
  9884. i64 capacity = -1;
  9885. if (max_count >= 0) {
  9886. capacity = max_count;
  9887. }
  9888. i64 j = 0;
  9889. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  9890. index = j;
  9891. }
  9892. node->viral_state_flags |= nodes[i]->viral_state_flags;
  9893. } else if (i == 0) {
  9894. index = 0;
  9895. }
  9896. indices[i] = index;
  9897. }
  9898. for (isize i = 0; i < gb_count_of(indices); i++) {
  9899. i64 a = indices[i];
  9900. for (isize j = i+1; j < gb_count_of(indices); j++) {
  9901. i64 b = indices[j];
  9902. if (a > b && b >= 0) {
  9903. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  9904. }
  9905. }
  9906. }
  9907. if (max_count < 0) {
  9908. if (o->mode == Addressing_Constant) {
  9909. gbString s = expr_to_string(se->expr);
  9910. error(se->expr, "Cannot slice constant value '%s'", s);
  9911. gb_string_free(s);
  9912. }
  9913. }
  9914. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  9915. /*
  9916. x[:] -> [^]T
  9917. x[i:] -> [^]T
  9918. x[:n] -> []T
  9919. x[i:n] -> []T
  9920. */
  9921. o->type = alloc_type_slice(t->MultiPointer.elem);
  9922. }
  9923. o->mode = Addressing_Value;
  9924. if (is_type_string(t) && max_count >= 0) {
  9925. bool all_constant = true;
  9926. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9927. if (nodes[i] != nullptr) {
  9928. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  9929. if (tav.mode != Addressing_Constant) {
  9930. all_constant = false;
  9931. break;
  9932. }
  9933. }
  9934. }
  9935. if (!all_constant) {
  9936. ERROR_BLOCK();
  9937. gbString str = expr_to_string(o->expr);
  9938. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  9939. if (!build_context.terse_errors) {
  9940. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9941. }
  9942. gb_string_free(str);
  9943. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  9944. o->expr = node;
  9945. return kind;
  9946. }
  9947. o->mode = Addressing_Constant;
  9948. o->type = t;
  9949. if (o->value.kind == ExactValue_String16) {
  9950. String16 s = o->value.value_string16;
  9951. o->value = exact_value_string16(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9952. } else {
  9953. String s = {};
  9954. if (o->value.kind == ExactValue_String) {
  9955. s = o->value.value_string;
  9956. }
  9957. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9958. }
  9959. }
  9960. return kind;
  9961. }
  9962. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9963. u32 prev_state_flags = c->state_flags;
  9964. defer (c->state_flags = prev_state_flags);
  9965. if (node->state_flags != 0) {
  9966. u32 in = node->state_flags;
  9967. u32 out = c->state_flags;
  9968. if (in & StateFlag_no_bounds_check) {
  9969. out |= StateFlag_no_bounds_check;
  9970. out &= ~StateFlag_bounds_check;
  9971. } else if (in & StateFlag_bounds_check) {
  9972. out |= StateFlag_bounds_check;
  9973. out &= ~StateFlag_no_bounds_check;
  9974. }
  9975. if (in & StateFlag_no_type_assert) {
  9976. out |= StateFlag_no_type_assert;
  9977. out &= ~StateFlag_type_assert;
  9978. } else if (in & StateFlag_type_assert) {
  9979. out |= StateFlag_type_assert;
  9980. out &= ~StateFlag_no_type_assert;
  9981. }
  9982. c->state_flags = out;
  9983. }
  9984. ExprKind kind = Expr_Stmt;
  9985. o->mode = Addressing_Invalid;
  9986. o->type = t_invalid;
  9987. o->value = {ExactValue_Invalid};
  9988. switch (node->kind) {
  9989. default:
  9990. return kind;
  9991. case_ast_node(be, BadExpr, node)
  9992. return kind;
  9993. case_end;
  9994. case_ast_node(i, Implicit, node);
  9995. switch (i->kind) {
  9996. case Token_context:
  9997. {
  9998. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  9999. error(node, "'context' is only allowed within procedures");
  10000. return kind;
  10001. }
  10002. if (unparen_expr(c->assignment_lhs_hint) == node) {
  10003. c->scope->flags |= ScopeFlag_ContextDefined;
  10004. }
  10005. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  10006. error(node, "'context' has not been defined within this scope");
  10007. // Continue with value
  10008. }
  10009. init_core_context(c->checker);
  10010. o->mode = Addressing_Context;
  10011. o->type = t_context;
  10012. }
  10013. break;
  10014. default:
  10015. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  10016. return kind;
  10017. }
  10018. case_end;
  10019. case_ast_node(i, Ident, node);
  10020. check_ident(c, o, node, nullptr, type_hint, false);
  10021. case_end;
  10022. case_ast_node(u, Uninit, node);
  10023. o->mode = Addressing_Value;
  10024. o->type = t_untyped_uninit;
  10025. error(node, "Global variables will always be zeroed if left unassigned, --- is disallowed");
  10026. case_end;
  10027. case_ast_node(bl, BasicLit, node);
  10028. Type *t = t_invalid;
  10029. switch (node->tav.value.kind) {
  10030. case ExactValue_String: t = t_untyped_string; break;
  10031. case ExactValue_String16: t = t_string16; break; // TODO(bill): determine this correctly
  10032. case ExactValue_Float: t = t_untyped_float; break;
  10033. case ExactValue_Complex: t = t_untyped_complex; break;
  10034. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  10035. case ExactValue_Integer:
  10036. t = t_untyped_integer;
  10037. if (bl->token.kind == Token_Rune) {
  10038. t = t_untyped_rune;
  10039. }
  10040. break;
  10041. default:
  10042. GB_PANIC("Unhandled value type for basic literal");
  10043. break;
  10044. }
  10045. o->mode = Addressing_Constant;
  10046. o->type = t;
  10047. o->value = node->tav.value;
  10048. case_end;
  10049. case_ast_node(bd, BasicDirective, node);
  10050. kind = check_basic_directive_expr(c, o, node, type_hint);
  10051. case_end;
  10052. case_ast_node(pg, ProcGroup, node);
  10053. error(node, "Illegal use of a procedure group");
  10054. o->mode = Addressing_Invalid;
  10055. case_end;
  10056. case_ast_node(pl, ProcLit, node);
  10057. CheckerContext ctx = *c;
  10058. DeclInfo *decl = nullptr;
  10059. Type *type = alloc_type(Type_Proc);
  10060. check_open_scope(&ctx, pl->type);
  10061. {
  10062. decl = make_decl_info(ctx.scope, ctx.decl);
  10063. decl->proc_lit = node;
  10064. ctx.decl = decl;
  10065. defer (ctx.decl = ctx.decl->parent);
  10066. if (pl->tags != 0) {
  10067. error(node, "A procedure literal cannot have tags");
  10068. pl->tags = 0; // TODO(bill): Should I zero this?!
  10069. }
  10070. check_procedure_type(&ctx, type, pl->type);
  10071. if (!is_type_proc(type)) {
  10072. gbString str = expr_to_string(node);
  10073. error(node, "Invalid procedure literal '%s'", str);
  10074. gb_string_free(str);
  10075. check_close_scope(&ctx);
  10076. return kind;
  10077. }
  10078. if (pl->body == nullptr) {
  10079. error(node, "A procedure literal must have a body");
  10080. return kind;
  10081. }
  10082. pl->decl = decl;
  10083. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  10084. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  10085. array_add(&ctx.checker->nested_proc_lits, decl);
  10086. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  10087. }
  10088. check_close_scope(&ctx);
  10089. o->mode = Addressing_Value;
  10090. o->type = type;
  10091. o->value = exact_value_procedure(node);
  10092. case_end;
  10093. case_ast_node(te, TernaryIfExpr, node);
  10094. kind = check_ternary_if_expr(c, o, node, type_hint);
  10095. case_end;
  10096. case_ast_node(te, TernaryWhenExpr, node);
  10097. kind = check_ternary_when_expr(c, o, node, type_hint);
  10098. case_end;
  10099. case_ast_node(oe, OrElseExpr, node);
  10100. return check_or_else_expr(c, o, node, type_hint);
  10101. case_end;
  10102. case_ast_node(re, OrReturnExpr, node);
  10103. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  10104. return check_or_return_expr(c, o, node, type_hint);
  10105. case_end;
  10106. case_ast_node(re, OrBranchExpr, node);
  10107. return check_or_branch_expr(c, o, node, type_hint);
  10108. case_end;
  10109. case_ast_node(cl, CompoundLit, node);
  10110. kind = check_compound_literal(c, o, node, type_hint);
  10111. case_end;
  10112. case_ast_node(pe, ParenExpr, node);
  10113. kind = check_expr_base(c, o, pe->expr, type_hint);
  10114. node->viral_state_flags |= pe->expr->viral_state_flags;
  10115. o->expr = node;
  10116. case_end;
  10117. case_ast_node(te, TagExpr, node);
  10118. String name = te->name.string;
  10119. error(node, "Unknown tag expression, #%.*s", LIT(name));
  10120. if (te->expr) {
  10121. kind = check_expr_base(c, o, te->expr, type_hint);
  10122. node->viral_state_flags |= te->expr->viral_state_flags;
  10123. }
  10124. o->expr = node;
  10125. case_end;
  10126. case_ast_node(ta, TypeAssertion, node);
  10127. kind = check_type_assertion(c, o, node, type_hint);
  10128. case_end;
  10129. case_ast_node(tc, TypeCast, node);
  10130. check_expr_or_type(c, o, tc->type);
  10131. if (o->mode != Addressing_Type) {
  10132. gbString str = expr_to_string(tc->type);
  10133. error(tc->type, "Expected a type, got %s", str);
  10134. gb_string_free(str);
  10135. o->mode = Addressing_Invalid;
  10136. }
  10137. if (o->mode == Addressing_Invalid) {
  10138. o->expr = node;
  10139. return kind;
  10140. }
  10141. Type *type = o->type;
  10142. check_expr_base(c, o, tc->expr, type);
  10143. node->viral_state_flags |= tc->expr->viral_state_flags;
  10144. if (o->mode != Addressing_Invalid) {
  10145. switch (tc->token.kind) {
  10146. case Token_transmute:
  10147. check_transmute(c, node, o, type, true);
  10148. break;
  10149. case Token_cast:
  10150. check_cast(c, o, type, true);
  10151. break;
  10152. default:
  10153. error(node, "Invalid AST: Invalid casting expression");
  10154. o->mode = Addressing_Invalid;
  10155. break;
  10156. }
  10157. }
  10158. return Expr_Expr;
  10159. case_end;
  10160. case_ast_node(ac, AutoCast, node);
  10161. check_expr_base(c, o, ac->expr, type_hint);
  10162. node->viral_state_flags |= ac->expr->viral_state_flags;
  10163. if (o->mode == Addressing_Invalid) {
  10164. o->expr = node;
  10165. return kind;
  10166. }
  10167. if (type_hint) {
  10168. check_cast(c, o, type_hint);
  10169. }
  10170. o->expr = node;
  10171. return Expr_Expr;
  10172. case_end;
  10173. case_ast_node(ue, UnaryExpr, node);
  10174. Type *th = type_hint;
  10175. if (ue->op.kind == Token_And) {
  10176. th = type_deref(th);
  10177. }
  10178. check_expr_base(c, o, ue->expr, th);
  10179. node->viral_state_flags |= ue->expr->viral_state_flags;
  10180. if (o->mode != Addressing_Invalid) {
  10181. check_unary_expr(c, o, ue->op, node);
  10182. }
  10183. o->expr = node;
  10184. return Expr_Expr;
  10185. case_end;
  10186. case_ast_node(be, BinaryExpr, node);
  10187. check_binary_expr(c, o, node, type_hint, true);
  10188. if (o->mode == Addressing_Invalid) {
  10189. o->expr = node;
  10190. return kind;
  10191. }
  10192. case_end;
  10193. case_ast_node(se, SelectorExpr, node);
  10194. check_selector(c, o, node, type_hint);
  10195. node->viral_state_flags |= se->expr->viral_state_flags;
  10196. case_end;
  10197. case_ast_node(se, SelectorCallExpr, node);
  10198. return check_selector_call_expr(c, o, node, type_hint);
  10199. case_end;
  10200. case_ast_node(ise, ImplicitSelectorExpr, node);
  10201. return check_implicit_selector_expr(c, o, node, type_hint);
  10202. case_end;
  10203. case_ast_node(ie, IndexExpr, node);
  10204. kind = check_index_expr(c, o, node, type_hint);
  10205. case_end;
  10206. case_ast_node(se, SliceExpr, node);
  10207. kind = check_slice_expr(c, o, node, type_hint);
  10208. case_end;
  10209. case_ast_node(mie, MatrixIndexExpr, node);
  10210. check_matrix_index_expr(c, o, node, type_hint);
  10211. o->expr = node;
  10212. return Expr_Expr;
  10213. case_end;
  10214. case_ast_node(ce, CallExpr, node);
  10215. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  10216. case_end;
  10217. case_ast_node(de, DerefExpr, node);
  10218. check_expr_or_type(c, o, de->expr);
  10219. node->viral_state_flags |= de->expr->viral_state_flags;
  10220. if (o->mode == Addressing_Invalid) {
  10221. o->mode = Addressing_Invalid;
  10222. o->expr = node;
  10223. return kind;
  10224. } else if (o->mode == Addressing_Type) {
  10225. gbString str = expr_to_string(o->expr);
  10226. error(o->expr, "Cannot dereference '%s' because it is a type", str);
  10227. o->mode = Addressing_Invalid;
  10228. o->expr = node;
  10229. return kind;
  10230. } else {
  10231. Type *t = base_type(o->type);
  10232. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  10233. o->mode = Addressing_Variable;
  10234. o->type = t->Pointer.elem;
  10235. } else if (t->kind == Type_SoaPointer) {
  10236. o->mode = Addressing_SoaVariable;
  10237. o->type = type_deref(t);
  10238. } else {
  10239. gbString str = expr_to_string(o->expr);
  10240. gbString typ = type_to_string(o->type);
  10241. ERROR_BLOCK();
  10242. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  10243. if (o->type && is_type_multi_pointer(o->type)) {
  10244. if (!build_context.terse_errors) {
  10245. error_line("\tDid you mean '%s[0]'?\n", str);
  10246. }
  10247. }
  10248. gb_string_free(typ);
  10249. gb_string_free(str);
  10250. o->mode = Addressing_Invalid;
  10251. o->expr = node;
  10252. return kind;
  10253. }
  10254. }
  10255. case_end;
  10256. case_ast_node(ia, InlineAsmExpr, node);
  10257. if (c->curr_proc_decl == nullptr) {
  10258. error(node, "Inline asm expressions are only allowed within a procedure body");
  10259. }
  10260. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  10261. Type *return_type = nullptr;
  10262. for_array(i, ia->param_types) {
  10263. param_types[i] = check_type(c, ia->param_types[i]);
  10264. }
  10265. if (ia->return_type != nullptr) {
  10266. return_type = check_type(c, ia->return_type);
  10267. }
  10268. Operand x = {};
  10269. check_expr(c, &x, ia->asm_string);
  10270. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  10271. error(x.expr, "Expected a constant string for the inline asm main parameter");
  10272. }
  10273. check_expr(c, &x, ia->constraints_string);
  10274. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  10275. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  10276. }
  10277. Scope *scope = create_scope(c->info, c->scope);
  10278. scope->flags |= ScopeFlag_Proc;
  10279. Type *params = alloc_type_tuple();
  10280. Type *results = alloc_type_tuple();
  10281. if (param_types.count != 0) {
  10282. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  10283. for_array(i, param_types) {
  10284. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  10285. }
  10286. }
  10287. if (return_type != nullptr) {
  10288. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  10289. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  10290. }
  10291. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  10292. o->type = pt;
  10293. o->mode = Addressing_Value;
  10294. o->expr = node;
  10295. return Expr_Expr;
  10296. case_end;
  10297. case Ast_DistinctType:
  10298. case Ast_TypeidType:
  10299. case Ast_PolyType:
  10300. case Ast_ProcType:
  10301. case Ast_PointerType:
  10302. case Ast_MultiPointerType:
  10303. case Ast_ArrayType:
  10304. case Ast_DynamicArrayType:
  10305. case Ast_StructType:
  10306. case Ast_UnionType:
  10307. case Ast_EnumType:
  10308. case Ast_MapType:
  10309. case Ast_BitSetType:
  10310. case Ast_MatrixType:
  10311. case Ast_RelativeType:
  10312. o->mode = Addressing_Type;
  10313. o->type = check_type(c, node);
  10314. break;
  10315. }
  10316. kind = Expr_Expr;
  10317. o->expr = node;
  10318. return kind;
  10319. }
  10320. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  10321. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  10322. if (o->type != nullptr && core_type(o->type) == nullptr) {
  10323. o->type = t_invalid;
  10324. gbString xs = expr_to_string(o->expr);
  10325. if (o->mode == Addressing_Type) {
  10326. error(o->expr, "Invalid type usage '%s'", xs);
  10327. } else {
  10328. error(o->expr, "Invalid expression '%s'", xs);
  10329. }
  10330. gb_string_free(xs);
  10331. }
  10332. if (o->type != nullptr && is_type_untyped(o->type)) {
  10333. add_untyped(c, node, o->mode, o->type, o->value);
  10334. }
  10335. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  10336. add_type_and_value(c, node, o->mode, o->type, o->value);
  10337. return kind;
  10338. }
  10339. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  10340. check_expr_base(c, o, e, nullptr);
  10341. switch (o->mode) {
  10342. default:
  10343. return; // NOTE(bill): Valid
  10344. case Addressing_NoValue:
  10345. error_operand_no_value(o);
  10346. break;
  10347. }
  10348. o->mode = Addressing_Invalid;
  10349. }
  10350. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  10351. check_expr_base(c, o, e, nullptr);
  10352. switch (o->mode) {
  10353. default:
  10354. return; // NOTE(bill): Valid
  10355. case Addressing_NoValue:
  10356. error_operand_no_value(o);
  10357. break;
  10358. case Addressing_Type:
  10359. error_operand_not_expression(o);
  10360. break;
  10361. }
  10362. o->mode = Addressing_Invalid;
  10363. }
  10364. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10365. check_expr_base(c, o, e, type_hint);
  10366. switch (o->mode) {
  10367. default:
  10368. return; // NOTE(bill): Valid
  10369. case Addressing_NoValue:
  10370. error_operand_no_value(o);
  10371. break;
  10372. case Addressing_Type:
  10373. error_operand_not_expression(o);
  10374. break;
  10375. }
  10376. o->mode = Addressing_Invalid;
  10377. }
  10378. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  10379. if (o->mode == Addressing_Value) {
  10380. // NOTE(bill): Tuples are not first class thus never named
  10381. if (o->type->kind == Type_Tuple) {
  10382. isize count = o->type->Tuple.variables.count;
  10383. error(o->expr,
  10384. "%td-valued expression found where single value expected", count);
  10385. o->mode = Addressing_Invalid;
  10386. GB_ASSERT(count != 1);
  10387. }
  10388. }
  10389. }
  10390. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  10391. check_multi_expr(c, o, e);
  10392. check_not_tuple(c, o);
  10393. }
  10394. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10395. check_expr_base(c, o, e, type_hint);
  10396. check_not_tuple(c, o);
  10397. error_operand_no_value(o);
  10398. }
  10399. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  10400. switch (v.kind) {
  10401. case ExactValue_Invalid:
  10402. return true;
  10403. case ExactValue_Bool:
  10404. return !v.value_bool;
  10405. case ExactValue_String:
  10406. return v.value_string.len == 0;
  10407. case ExactValue_String16:
  10408. return v.value_string16.len == 0;
  10409. case ExactValue_Integer:
  10410. return big_int_is_zero(&v.value_integer);
  10411. case ExactValue_Float:
  10412. return v.value_float == 0.0;
  10413. case ExactValue_Complex:
  10414. if (v.value_complex) {
  10415. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  10416. }
  10417. return true;
  10418. case ExactValue_Quaternion:
  10419. if (v.value_quaternion) {
  10420. return v.value_quaternion->real == 0.0 &&
  10421. v.value_quaternion->imag == 0.0 &&
  10422. v.value_quaternion->jmag == 0.0 &&
  10423. v.value_quaternion->kmag == 0.0;
  10424. }
  10425. return true;
  10426. case ExactValue_Pointer:
  10427. return v.value_pointer == 0;
  10428. case ExactValue_Compound:
  10429. if (v.value_compound == nullptr) {
  10430. return true;
  10431. } else {
  10432. ast_node(cl, CompoundLit, v.value_compound);
  10433. if (cl->elems.count == 0) {
  10434. return true;
  10435. } else {
  10436. for (Ast *elem : cl->elems) {
  10437. if (elem->tav.mode != Addressing_Constant) {
  10438. return false;
  10439. }
  10440. if (!is_exact_value_zero(elem->tav.value)) {
  10441. return false;
  10442. }
  10443. }
  10444. return true;
  10445. }
  10446. }
  10447. case ExactValue_Procedure:
  10448. return v.value_procedure == nullptr;
  10449. case ExactValue_Typeid:
  10450. return v.value_typeid == nullptr;
  10451. }
  10452. return true;
  10453. }
  10454. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  10455. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  10456. for_array(i, params) {
  10457. if (i > 0) {
  10458. str = gb_string_appendc(str, ", ");
  10459. }
  10460. str = write_expr_to_string(str, params[i], false);
  10461. }
  10462. return str;
  10463. }
  10464. gb_internal gbString string_append_string(gbString str, String string) {
  10465. if (string.len > 0) {
  10466. return gb_string_append_length(str, &string[0], string.len);
  10467. }
  10468. return str;
  10469. }
  10470. gb_internal gbString string_append_token(gbString str, Token token) {
  10471. str = string_append_string(str, token.string);
  10472. return str;
  10473. }
  10474. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  10475. if (node == nullptr)
  10476. return str;
  10477. if (is_ast_stmt(node)) {
  10478. GB_ASSERT("stmt passed to write_expr_to_string");
  10479. }
  10480. switch (node->kind) {
  10481. default:
  10482. str = gb_string_appendc(str, "(BadExpr)");
  10483. break;
  10484. case_ast_node(i, Ident, node);
  10485. str = string_append_token(str, i->token);
  10486. case_end;
  10487. case_ast_node(i, Implicit, node);
  10488. str = string_append_token(str, *i);
  10489. case_end;
  10490. case_ast_node(bl, BasicLit, node);
  10491. str = string_append_token(str, bl->token);
  10492. case_end;
  10493. case_ast_node(bd, BasicDirective, node);
  10494. str = gb_string_append_rune(str, '#');
  10495. str = string_append_string(str, bd->name.string);
  10496. case_end;
  10497. case_ast_node(ud, Uninit, node);
  10498. str = gb_string_appendc(str, "---");
  10499. case_end;
  10500. case_ast_node(pg, ProcGroup, node);
  10501. str = gb_string_appendc(str, "proc{");
  10502. for_array(i, pg->args) {
  10503. if (i > 0) str = gb_string_appendc(str, ", ");
  10504. str = write_expr_to_string(str, pg->args[i], shorthand);
  10505. }
  10506. str = gb_string_append_rune(str, '}');
  10507. case_end;
  10508. case_ast_node(pl, ProcLit, node);
  10509. str = write_expr_to_string(str, pl->type, shorthand);
  10510. if (pl->body) {
  10511. str = gb_string_appendc(str, " {...}");
  10512. } else {
  10513. str = gb_string_appendc(str, " ---");
  10514. }
  10515. case_end;
  10516. case_ast_node(cl, CompoundLit, node);
  10517. str = write_expr_to_string(str, cl->type, shorthand);
  10518. str = gb_string_append_rune(str, '{');
  10519. if (shorthand) {
  10520. str = gb_string_appendc(str, "...");
  10521. } else {
  10522. for_array(i, cl->elems) {
  10523. if (i > 0) str = gb_string_appendc(str, ", ");
  10524. str = write_expr_to_string(str, cl->elems[i], shorthand);
  10525. }
  10526. }
  10527. str = gb_string_append_rune(str, '}');
  10528. case_end;
  10529. case_ast_node(te, TagExpr, node);
  10530. str = gb_string_append_rune(str, '#');
  10531. str = string_append_token(str, te->name);
  10532. str = write_expr_to_string(str, te->expr, shorthand);
  10533. case_end;
  10534. case_ast_node(ue, UnaryExpr, node);
  10535. str = string_append_token(str, ue->op);
  10536. str = write_expr_to_string(str, ue->expr, shorthand);
  10537. case_end;
  10538. case_ast_node(de, DerefExpr, node);
  10539. str = write_expr_to_string(str, de->expr, shorthand);
  10540. str = gb_string_append_rune(str, '^');
  10541. case_end;
  10542. case_ast_node(be, BinaryExpr, node);
  10543. str = write_expr_to_string(str, be->left, shorthand);
  10544. str = gb_string_append_rune(str, ' ');
  10545. str = string_append_token(str, be->op);
  10546. str = gb_string_append_rune(str, ' ');
  10547. str = write_expr_to_string(str, be->right, shorthand);
  10548. case_end;
  10549. case_ast_node(te, TernaryIfExpr, node);
  10550. TokenPos x = ast_token(te->x).pos;
  10551. TokenPos cond = ast_token(te->cond).pos;
  10552. if (x < cond) {
  10553. str = write_expr_to_string(str, te->x, shorthand);
  10554. str = gb_string_appendc(str, " if ");
  10555. str = write_expr_to_string(str, te->cond, shorthand);
  10556. str = gb_string_appendc(str, " else ");
  10557. str = write_expr_to_string(str, te->y, shorthand);
  10558. } else {
  10559. str = write_expr_to_string(str, te->cond, shorthand);
  10560. str = gb_string_appendc(str, " ? ");
  10561. str = write_expr_to_string(str, te->x, shorthand);
  10562. str = gb_string_appendc(str, " : ");
  10563. str = write_expr_to_string(str, te->y, shorthand);
  10564. }
  10565. case_end;
  10566. case_ast_node(te, TernaryWhenExpr, node);
  10567. str = write_expr_to_string(str, te->x, shorthand);
  10568. str = gb_string_appendc(str, " when ");
  10569. str = write_expr_to_string(str, te->cond, shorthand);
  10570. str = gb_string_appendc(str, " else ");
  10571. str = write_expr_to_string(str, te->y, shorthand);
  10572. case_end;
  10573. case_ast_node(oe, OrElseExpr, node);
  10574. str = write_expr_to_string(str, oe->x, shorthand);
  10575. str = gb_string_appendc(str, " or_else ");
  10576. str = write_expr_to_string(str, oe->y, shorthand);
  10577. case_end;
  10578. case_ast_node(oe, OrReturnExpr, node);
  10579. str = write_expr_to_string(str, oe->expr, shorthand);
  10580. str = gb_string_appendc(str, " or_return");
  10581. case_end;
  10582. case_ast_node(oe, OrBranchExpr, node);
  10583. str = write_expr_to_string(str, oe->expr, shorthand);
  10584. str = gb_string_append_rune(str, ' ');
  10585. str = string_append_token(str, oe->token);
  10586. if (oe->label) {
  10587. str = gb_string_append_rune(str, ' ');
  10588. str = write_expr_to_string(str, oe->label, shorthand);
  10589. }
  10590. case_end;
  10591. case_ast_node(pe, ParenExpr, node);
  10592. str = gb_string_append_rune(str, '(');
  10593. str = write_expr_to_string(str, pe->expr, shorthand);
  10594. str = gb_string_append_rune(str, ')');
  10595. case_end;
  10596. case_ast_node(se, SelectorExpr, node);
  10597. str = write_expr_to_string(str, se->expr, shorthand);
  10598. str = string_append_token(str, se->token);
  10599. str = write_expr_to_string(str, se->selector, shorthand);
  10600. case_end;
  10601. case_ast_node(se, ImplicitSelectorExpr, node);
  10602. str = gb_string_append_rune(str, '.');
  10603. str = write_expr_to_string(str, se->selector, shorthand);
  10604. case_end;
  10605. case_ast_node(se, SelectorCallExpr, node);
  10606. str = write_expr_to_string(str, se->expr, shorthand);
  10607. str = gb_string_appendc(str, "(");
  10608. ast_node(ce, CallExpr, se->call);
  10609. isize start = se->modified_call ? 1 : 0;
  10610. for (isize i = start; i < ce->args.count; i++) {
  10611. Ast *arg = ce->args[i];
  10612. if (i > start) {
  10613. str = gb_string_appendc(str, ", ");
  10614. }
  10615. str = write_expr_to_string(str, arg, shorthand);
  10616. }
  10617. str = gb_string_appendc(str, ")");
  10618. case_end;
  10619. case_ast_node(ta, TypeAssertion, node);
  10620. str = write_expr_to_string(str, ta->expr, shorthand);
  10621. if (ta->type != nullptr &&
  10622. ta->type->kind == Ast_UnaryExpr &&
  10623. ta->type->UnaryExpr.op.kind == Token_Question) {
  10624. str = gb_string_appendc(str, ".?");
  10625. } else {
  10626. str = gb_string_appendc(str, ".(");
  10627. str = write_expr_to_string(str, ta->type, shorthand);
  10628. str = gb_string_append_rune(str, ')');
  10629. }
  10630. case_end;
  10631. case_ast_node(tc, TypeCast, node);
  10632. str = string_append_token(str, tc->token);
  10633. str = gb_string_append_rune(str, '(');
  10634. str = write_expr_to_string(str, tc->type, shorthand);
  10635. str = gb_string_append_rune(str, ')');
  10636. str = write_expr_to_string(str, tc->expr, shorthand);
  10637. case_end;
  10638. case_ast_node(ac, AutoCast, node);
  10639. str = string_append_token(str, ac->token);
  10640. str = gb_string_append_rune(str, ' ');
  10641. str = write_expr_to_string(str, ac->expr, shorthand);
  10642. case_end;
  10643. case_ast_node(ie, IndexExpr, node);
  10644. str = write_expr_to_string(str, ie->expr, shorthand);
  10645. str = gb_string_append_rune(str, '[');
  10646. str = write_expr_to_string(str, ie->index, shorthand);
  10647. str = gb_string_append_rune(str, ']');
  10648. case_end;
  10649. case_ast_node(se, SliceExpr, node);
  10650. str = write_expr_to_string(str, se->expr, shorthand);
  10651. str = gb_string_append_rune(str, '[');
  10652. str = write_expr_to_string(str, se->low, shorthand);
  10653. str = string_append_token(str, se->interval);
  10654. str = write_expr_to_string(str, se->high, shorthand);
  10655. str = gb_string_append_rune(str, ']');
  10656. case_end;
  10657. case_ast_node(mie, MatrixIndexExpr, node);
  10658. str = write_expr_to_string(str, mie->expr, shorthand);
  10659. str = gb_string_append_rune(str, '[');
  10660. str = write_expr_to_string(str, mie->row_index, shorthand);
  10661. str = gb_string_appendc(str, ", ");
  10662. str = write_expr_to_string(str, mie->column_index, shorthand);
  10663. str = gb_string_append_rune(str, ']');
  10664. case_end;
  10665. case_ast_node(e, Ellipsis, node);
  10666. str = gb_string_appendc(str, "..");
  10667. str = write_expr_to_string(str, e->expr, shorthand);
  10668. case_end;
  10669. case_ast_node(fv, FieldValue, node);
  10670. str = write_expr_to_string(str, fv->field, shorthand);
  10671. str = gb_string_appendc(str, " = ");
  10672. str = write_expr_to_string(str, fv->value, shorthand);
  10673. case_end;
  10674. case_ast_node(fv, EnumFieldValue, node);
  10675. str = write_expr_to_string(str, fv->name, shorthand);
  10676. if (fv->value) {
  10677. str = gb_string_appendc(str, " = ");
  10678. str = write_expr_to_string(str, fv->value, shorthand);
  10679. }
  10680. case_end;
  10681. case_ast_node(ht, HelperType, node);
  10682. str = gb_string_appendc(str, "#type ");
  10683. str = write_expr_to_string(str, ht->type, shorthand);
  10684. case_end;
  10685. case_ast_node(ht, DistinctType, node);
  10686. str = gb_string_appendc(str, "distinct ");
  10687. str = write_expr_to_string(str, ht->type, shorthand);
  10688. case_end;
  10689. case_ast_node(pt, PolyType, node);
  10690. str = gb_string_append_rune(str, '$');
  10691. str = write_expr_to_string(str, pt->type, shorthand);
  10692. if (pt->specialization != nullptr) {
  10693. str = gb_string_append_rune(str, '/');
  10694. str = write_expr_to_string(str, pt->specialization, shorthand);
  10695. }
  10696. case_end;
  10697. case_ast_node(pt, PointerType, node);
  10698. if (pt->tag) {
  10699. str = write_expr_to_string(str, pt->tag, false);
  10700. }
  10701. str = gb_string_append_rune(str, '^');
  10702. str = write_expr_to_string(str, pt->type, shorthand);
  10703. case_end;
  10704. case_ast_node(pt, MultiPointerType, node);
  10705. str = gb_string_appendc(str, "[^]");
  10706. str = write_expr_to_string(str, pt->type, shorthand);
  10707. case_end;
  10708. case_ast_node(at, ArrayType, node);
  10709. if (at->tag) {
  10710. str = write_expr_to_string(str, at->tag, false);
  10711. }
  10712. str = gb_string_append_rune(str, '[');
  10713. if (at->count != nullptr &&
  10714. at->count->kind == Ast_UnaryExpr &&
  10715. at->count->UnaryExpr.op.kind == Token_Question) {
  10716. str = gb_string_appendc(str, "?");
  10717. } else {
  10718. str = write_expr_to_string(str, at->count, shorthand);
  10719. }
  10720. str = gb_string_append_rune(str, ']');
  10721. str = write_expr_to_string(str, at->elem, shorthand);
  10722. case_end;
  10723. case_ast_node(at, DynamicArrayType, node);
  10724. if (at->tag) {
  10725. str = write_expr_to_string(str, at->tag, false);
  10726. }
  10727. str = gb_string_appendc(str, "[dynamic]");
  10728. str = write_expr_to_string(str, at->elem, shorthand);
  10729. case_end;
  10730. case_ast_node(bs, BitSetType, node);
  10731. str = gb_string_appendc(str, "bit_set[");
  10732. str = write_expr_to_string(str, bs->elem, shorthand);
  10733. str = gb_string_appendc(str, "]");
  10734. case_end;
  10735. case_ast_node(mt, MapType, node);
  10736. str = gb_string_appendc(str, "map[");
  10737. str = write_expr_to_string(str, mt->key, shorthand);
  10738. str = gb_string_append_rune(str, ']');
  10739. str = write_expr_to_string(str, mt->value, shorthand);
  10740. case_end;
  10741. case_ast_node(mt, MatrixType, node);
  10742. str = gb_string_appendc(str, "matrix[");
  10743. str = write_expr_to_string(str, mt->row_count, shorthand);
  10744. str = gb_string_appendc(str, ", ");
  10745. str = write_expr_to_string(str, mt->column_count, shorthand);
  10746. str = gb_string_append_rune(str, ']');
  10747. str = write_expr_to_string(str, mt->elem, shorthand);
  10748. case_end;
  10749. case_ast_node(f, Field, node);
  10750. if (f->flags&FieldFlag_using) {
  10751. str = gb_string_appendc(str, "using ");
  10752. }
  10753. if (f->flags&FieldFlag_no_alias) {
  10754. str = gb_string_appendc(str, "#no_alias ");
  10755. }
  10756. if (f->flags&FieldFlag_c_vararg) {
  10757. str = gb_string_appendc(str, "#c_vararg ");
  10758. }
  10759. if (f->flags&FieldFlag_any_int) {
  10760. str = gb_string_appendc(str, "#any_int ");
  10761. }
  10762. if (f->flags&FieldFlag_no_broadcast) {
  10763. str = gb_string_appendc(str, "#no_broadcast ");
  10764. }
  10765. if (f->flags&FieldFlag_const) {
  10766. str = gb_string_appendc(str, "#const ");
  10767. }
  10768. if (f->flags&FieldFlag_subtype) {
  10769. str = gb_string_appendc(str, "#subtype ");
  10770. }
  10771. for_array(i, f->names) {
  10772. Ast *name = f->names[i];
  10773. if (i > 0) str = gb_string_appendc(str, ", ");
  10774. str = write_expr_to_string(str, name, shorthand);
  10775. }
  10776. if (f->names.count > 0) {
  10777. if (f->type == nullptr && f->default_value != nullptr) {
  10778. str = gb_string_append_rune(str, ' ');
  10779. }
  10780. str = gb_string_appendc(str, ":");
  10781. }
  10782. if (f->type != nullptr) {
  10783. str = gb_string_append_rune(str, ' ');
  10784. str = write_expr_to_string(str, f->type, shorthand);
  10785. }
  10786. if (f->default_value != nullptr) {
  10787. if (f->type != nullptr) {
  10788. str = gb_string_append_rune(str, ' ');
  10789. }
  10790. str = gb_string_appendc(str, "= ");
  10791. str = write_expr_to_string(str, f->default_value, shorthand);
  10792. }
  10793. case_end;
  10794. case_ast_node(f, FieldList, node);
  10795. bool has_name = false;
  10796. for_array(i, f->list) {
  10797. ast_node(field, Field, f->list[i]);
  10798. if (field->names.count > 1) {
  10799. has_name = true;
  10800. break;
  10801. }
  10802. if (field->names.count == 0) {
  10803. continue;
  10804. }
  10805. if (!is_blank_ident(field->names[0])) {
  10806. has_name = true;
  10807. break;
  10808. }
  10809. }
  10810. for_array(i, f->list) {
  10811. if (i > 0) str = gb_string_appendc(str, ", ");
  10812. if (has_name) {
  10813. str = write_expr_to_string(str, f->list[i], shorthand);
  10814. } else {
  10815. ast_node(field, Field, f->list[i]);
  10816. if (field->flags&FieldFlag_using) {
  10817. str = gb_string_appendc(str, "using ");
  10818. }
  10819. if (field->flags&FieldFlag_no_alias) {
  10820. str = gb_string_appendc(str, "#no_alias ");
  10821. }
  10822. if (field->flags&FieldFlag_c_vararg) {
  10823. str = gb_string_appendc(str, "#c_vararg ");
  10824. }
  10825. if (field->flags&FieldFlag_any_int) {
  10826. str = gb_string_appendc(str, "#any_int ");
  10827. }
  10828. if (field->flags&FieldFlag_no_broadcast) {
  10829. str = gb_string_appendc(str, "#no_broadcast ");
  10830. }
  10831. if (field->flags&FieldFlag_const) {
  10832. str = gb_string_appendc(str, "#const ");
  10833. }
  10834. if (field->flags&FieldFlag_subtype) {
  10835. str = gb_string_appendc(str, "#subtype ");
  10836. }
  10837. str = write_expr_to_string(str, field->type, shorthand);
  10838. }
  10839. }
  10840. case_end;
  10841. case_ast_node(ce, CallExpr, node);
  10842. switch (ce->inlining) {
  10843. case ProcInlining_inline:
  10844. str = gb_string_appendc(str, "#force_inline ");
  10845. break;
  10846. case ProcInlining_no_inline:
  10847. str = gb_string_appendc(str, "#force_no_inline ");
  10848. break;
  10849. }
  10850. str = write_expr_to_string(str, ce->proc, shorthand);
  10851. str = gb_string_appendc(str, "(");
  10852. isize idx0 = cast(isize)ce->was_selector;
  10853. for (isize i = idx0; i < ce->args.count; i++) {
  10854. Ast *arg = ce->args[i];
  10855. if (i > idx0) {
  10856. str = gb_string_appendc(str, ", ");
  10857. }
  10858. str = write_expr_to_string(str, arg, shorthand);
  10859. }
  10860. str = gb_string_appendc(str, ")");
  10861. case_end;
  10862. case_ast_node(tt, TypeidType, node);
  10863. str = gb_string_appendc(str, "typeid");
  10864. if (tt->specialization) {
  10865. str = gb_string_appendc(str, "/");
  10866. str = write_expr_to_string(str, tt->specialization, shorthand);
  10867. }
  10868. case_end;
  10869. case_ast_node(pt, ProcType, node);
  10870. str = gb_string_appendc(str, "proc(");
  10871. str = write_expr_to_string(str, pt->params, shorthand);
  10872. str = gb_string_appendc(str, ")");
  10873. if (pt->results != nullptr) {
  10874. str = gb_string_appendc(str, " -> ");
  10875. bool parens_needed = false;
  10876. if (pt->results && pt->results->kind == Ast_FieldList) {
  10877. for (Ast *field : pt->results->FieldList.list) {
  10878. ast_node(f, Field, field);
  10879. if (f->names.count != 0) {
  10880. parens_needed = true;
  10881. break;
  10882. }
  10883. }
  10884. }
  10885. if (parens_needed) {
  10886. str = gb_string_append_rune(str, '(');
  10887. }
  10888. str = write_expr_to_string(str, pt->results, shorthand);
  10889. if (parens_needed) {
  10890. str = gb_string_append_rune(str, ')');
  10891. }
  10892. }
  10893. case_end;
  10894. case_ast_node(st, StructType, node);
  10895. str = gb_string_appendc(str, "struct ");
  10896. if (st->polymorphic_params) {
  10897. str = gb_string_append_rune(str, '(');
  10898. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10899. str = gb_string_appendc(str, ") ");
  10900. }
  10901. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  10902. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  10903. if (st->align) {
  10904. str = gb_string_appendc(str, "#align ");
  10905. str = write_expr_to_string(str, st->align, shorthand);
  10906. str = gb_string_append_rune(str, ' ');
  10907. }
  10908. str = gb_string_append_rune(str, '{');
  10909. if (shorthand) {
  10910. str = gb_string_appendc(str, "...");
  10911. } else {
  10912. str = write_struct_fields_to_string(str, st->fields);
  10913. }
  10914. str = gb_string_append_rune(str, '}');
  10915. case_end;
  10916. case_ast_node(st, UnionType, node);
  10917. str = gb_string_appendc(str, "union ");
  10918. if (st->polymorphic_params) {
  10919. str = gb_string_append_rune(str, '(');
  10920. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10921. str = gb_string_appendc(str, ") ");
  10922. }
  10923. switch (st->kind) {
  10924. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  10925. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  10926. }
  10927. if (st->align) {
  10928. str = gb_string_appendc(str, "#align ");
  10929. str = write_expr_to_string(str, st->align, shorthand);
  10930. str = gb_string_append_rune(str, ' ');
  10931. }
  10932. str = gb_string_append_rune(str, '{');
  10933. if (shorthand) {
  10934. str = gb_string_appendc(str, "...");
  10935. } else {
  10936. str = write_struct_fields_to_string(str, st->variants);
  10937. }
  10938. str = gb_string_append_rune(str, '}');
  10939. case_end;
  10940. case_ast_node(et, EnumType, node);
  10941. str = gb_string_appendc(str, "enum ");
  10942. if (et->base_type != nullptr) {
  10943. str = write_expr_to_string(str, et->base_type, shorthand);
  10944. str = gb_string_append_rune(str, ' ');
  10945. }
  10946. str = gb_string_append_rune(str, '{');
  10947. if (shorthand) {
  10948. str = gb_string_appendc(str, "...");
  10949. } else {
  10950. for_array(i, et->fields) {
  10951. if (i > 0) {
  10952. str = gb_string_appendc(str, ", ");
  10953. }
  10954. str = write_expr_to_string(str, et->fields[i], shorthand);
  10955. }
  10956. }
  10957. str = gb_string_append_rune(str, '}');
  10958. case_end;
  10959. case_ast_node(rt, RelativeType, node);
  10960. str = write_expr_to_string(str, rt->tag, shorthand);
  10961. str = gb_string_appendc(str, "" );
  10962. str = write_expr_to_string(str, rt->type, shorthand);
  10963. case_end;
  10964. case_ast_node(f, BitFieldField, node);
  10965. str = write_expr_to_string(str, f->name, shorthand);
  10966. str = gb_string_appendc(str, ": ");
  10967. str = write_expr_to_string(str, f->type, shorthand);
  10968. str = gb_string_appendc(str, " | ");
  10969. str = write_expr_to_string(str, f->bit_size, shorthand);
  10970. case_end;
  10971. case_ast_node(bf, BitFieldType, node);
  10972. str = gb_string_appendc(str, "bit_field ");
  10973. if (!shorthand) {
  10974. str = write_expr_to_string(str, bf->backing_type, shorthand);
  10975. }
  10976. str = gb_string_appendc(str, " {");
  10977. if (shorthand) {
  10978. str = gb_string_appendc(str, "...");
  10979. } else {
  10980. for_array(i, bf->fields) {
  10981. if (i > 0) {
  10982. str = gb_string_appendc(str, ", ");
  10983. }
  10984. str = write_expr_to_string(str, bf->fields[i], false);
  10985. }
  10986. }
  10987. str = gb_string_appendc(str, "}");
  10988. case_end;
  10989. case_ast_node(ia, InlineAsmExpr, node);
  10990. str = gb_string_appendc(str, "asm(");
  10991. for_array(i, ia->param_types) {
  10992. if (i > 0) {
  10993. str = gb_string_appendc(str, ", ");
  10994. }
  10995. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  10996. }
  10997. str = gb_string_appendc(str, ")");
  10998. if (ia->return_type != nullptr) {
  10999. str = gb_string_appendc(str, " -> ");
  11000. str = write_expr_to_string(str, ia->return_type, shorthand);
  11001. }
  11002. if (ia->has_side_effects) {
  11003. str = gb_string_appendc(str, " #side_effects");
  11004. }
  11005. if (ia->is_align_stack) {
  11006. str = gb_string_appendc(str, " #stack_align");
  11007. }
  11008. if (ia->dialect) {
  11009. str = gb_string_appendc(str, " #");
  11010. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  11011. }
  11012. str = gb_string_appendc(str, " {");
  11013. if (shorthand) {
  11014. str = gb_string_appendc(str, "...");
  11015. } else {
  11016. str = write_expr_to_string(str, ia->asm_string, shorthand);
  11017. str = gb_string_appendc(str, ", ");
  11018. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  11019. }
  11020. str = gb_string_appendc(str, "}");
  11021. case_end;
  11022. }
  11023. return str;
  11024. }
  11025. gb_internal gbString expr_to_string(Ast *expression) {
  11026. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  11027. }
  11028. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  11029. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  11030. }
  11031. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  11032. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  11033. }