check_expr.cpp 358 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284
  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. enum LoadDirectiveResult {
  108. LoadDirective_Success = 0,
  109. LoadDirective_Error = 1,
  110. LoadDirective_NotFound = 2,
  111. };
  112. gb_internal bool is_load_directive_call(Ast *call) {
  113. call = unparen_expr(call);
  114. if (call->kind != Ast_CallExpr) {
  115. return false;
  116. }
  117. ast_node(ce, CallExpr, call);
  118. if (ce->proc->kind != Ast_BasicDirective) {
  119. return false;
  120. }
  121. ast_node(bd, BasicDirective, ce->proc);
  122. String name = bd->name.string;
  123. return name == "load";
  124. }
  125. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  126. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  127. auto results = did_you_mean_results(d);
  128. if (results.count != 0) {
  129. error_line("\tSuggestion: Did you mean?\n");
  130. for (auto const &result : results) {
  131. String const &target = result.target;
  132. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  133. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  134. }
  135. }
  136. }
  137. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  138. if (e->kind != Entity_TypeName) {
  139. return;
  140. }
  141. if (e->TypeName.objc_metadata == nullptr) {
  142. return;
  143. }
  144. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  145. Type *t = base_type(e->type);
  146. GB_ASSERT(t->kind == Type_Struct);
  147. if (is_type) {
  148. for (auto const &entry : objc_metadata->type_entries) {
  149. string_set_add(set, entry.name);
  150. }
  151. } else {
  152. for (auto const &entry : objc_metadata->value_entries) {
  153. string_set_add(set, entry.name);
  154. }
  155. }
  156. for (Entity *f : t->Struct.fields) {
  157. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  158. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  159. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  160. }
  161. }
  162. }
  163. }
  164. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  165. if (build_context.terse_errors) { return; }
  166. ERROR_BLOCK();
  167. GB_ASSERT(e->kind == Entity_TypeName);
  168. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  169. auto *objc_metadata = e->TypeName.objc_metadata;
  170. MUTEX_GUARD(objc_metadata->mutex);
  171. StringSet set = {};
  172. defer (string_set_destroy(&set));
  173. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  174. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  175. defer (did_you_mean_destroy(&d));
  176. for (String const &target : set) {
  177. did_you_mean_append(&d, target);
  178. }
  179. check_did_you_mean_print(&d, prefix);
  180. }
  181. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  182. if (build_context.terse_errors) { return; }
  183. ERROR_BLOCK();
  184. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  185. defer (did_you_mean_destroy(&d));
  186. for (Entity *e : fields) {
  187. did_you_mean_append(&d, e->token.string);
  188. }
  189. check_did_you_mean_print(&d, prefix);
  190. }
  191. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  192. if (build_context.terse_errors) { return; }
  193. ERROR_BLOCK();
  194. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  195. defer (did_you_mean_destroy(&d));
  196. for (Entity *e : fields) {
  197. did_you_mean_append(&d, e->token.string);
  198. }
  199. check_did_you_mean_print(&d, prefix);
  200. }
  201. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  202. if (build_context.terse_errors) { return; }
  203. ERROR_BLOCK();
  204. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  205. defer (did_you_mean_destroy(&d));
  206. rw_mutex_shared_lock(&scope->mutex);
  207. for (auto const &entry : scope->elements) {
  208. Entity *e = entry.value;
  209. did_you_mean_append(&d, e->token.string);
  210. }
  211. rw_mutex_shared_unlock(&scope->mutex);
  212. check_did_you_mean_print(&d, prefix);
  213. }
  214. gb_internal Entity *entity_from_expr(Ast *expr) {
  215. expr = unparen_expr(expr);
  216. if (expr == nullptr) {
  217. return nullptr;
  218. }
  219. switch (expr->kind) {
  220. case Ast_Ident:
  221. return expr->Ident.entity;
  222. case Ast_SelectorExpr:
  223. return entity_from_expr(expr->SelectorExpr.selector);
  224. }
  225. return nullptr;
  226. }
  227. gb_internal void error_operand_not_expression(Operand *o) {
  228. if (o->mode == Addressing_Type) {
  229. gbString err = expr_to_string(o->expr);
  230. error(o->expr, "'%s' is not an expression but a type", err);
  231. gb_string_free(err);
  232. o->mode = Addressing_Invalid;
  233. }
  234. }
  235. gb_internal void error_operand_no_value(Operand *o) {
  236. if (o->mode == Addressing_NoValue) {
  237. Ast *x = unparen_expr(o->expr);
  238. if (x != nullptr && x->kind == Ast_CallExpr) {
  239. Ast *p = unparen_expr(x->CallExpr.proc);
  240. if (p->kind == Ast_BasicDirective) {
  241. String tag = p->BasicDirective.name.string;
  242. if (tag == "panic" ||
  243. tag == "assert") {
  244. return;
  245. }
  246. }
  247. }
  248. gbString err = expr_to_string(o->expr);
  249. if (x != nullptr && x->kind == Ast_CallExpr) {
  250. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  251. } else {
  252. error(o->expr, "'%s' used as a value", err);
  253. }
  254. gb_string_free(err);
  255. o->mode = Addressing_Invalid;
  256. }
  257. }
  258. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  259. if (build_context.dynamic_map_calls) {
  260. add_package_dependency(c, "runtime", "__dynamic_map_get");
  261. } else {
  262. add_package_dependency(c, "runtime", "map_desired_position");
  263. add_package_dependency(c, "runtime", "map_probe_distance");
  264. }
  265. }
  266. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  267. init_core_source_code_location(c->checker);
  268. if (t_map_set_proc == nullptr) {
  269. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  270. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  271. }
  272. if (build_context.dynamic_map_calls) {
  273. add_package_dependency(c, "runtime", "__dynamic_map_set");
  274. } else {
  275. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  276. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  277. }
  278. }
  279. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  280. init_core_source_code_location(c->checker);
  281. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  282. }
  283. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  284. Scope *s = c->scope;
  285. check_collect_entities(c, nodes);
  286. for (auto const &entry : s->elements) {
  287. Entity *e = entry.value;\
  288. switch (e->kind) {
  289. case Entity_Constant:
  290. case Entity_TypeName:
  291. case Entity_Procedure:
  292. break;
  293. default:
  294. continue;
  295. }
  296. DeclInfo *d = decl_info_of_entity(e);
  297. if (d != nullptr) {
  298. check_entity_decl(c, e, d, nullptr);
  299. }
  300. }
  301. }
  302. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  303. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  304. ///////////////////////////////////////////////////////////////////////////////
  305. // //
  306. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  307. // //
  308. ///////////////////////////////////////////////////////////////////////////////
  309. CheckerInfo *info = old_c->info;
  310. if (base_entity == nullptr) {
  311. return false;
  312. }
  313. if (!is_type_proc(base_entity->type)) {
  314. return false;
  315. }
  316. if (base_entity->flags & EntityFlag_Disabled) {
  317. return false;
  318. }
  319. String name = base_entity->token.string;
  320. Type *src = base_type(base_entity->type);
  321. Type *dst = nullptr;
  322. if (type != nullptr) {
  323. dst = base_type(type);
  324. }
  325. if (param_operands == nullptr) {
  326. GB_ASSERT(dst != nullptr);
  327. }
  328. if (param_operands != nullptr) {
  329. GB_ASSERT(dst == nullptr);
  330. }
  331. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  332. return false;
  333. }
  334. if (dst != nullptr) {
  335. if (dst->Proc.is_polymorphic) {
  336. return false;
  337. }
  338. if (dst->Proc.param_count != src->Proc.param_count ||
  339. dst->Proc.result_count != src->Proc.result_count) {
  340. return false;
  341. }
  342. }
  343. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  344. if (old_decl == nullptr) {
  345. return false;
  346. }
  347. gbAllocator a = heap_allocator();
  348. Array<Operand> operands = {};
  349. if (param_operands) {
  350. operands = *param_operands;
  351. } else {
  352. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  353. for (isize i = 0; i < dst->Proc.param_count; i++) {
  354. Entity *param = dst->Proc.params->Tuple.variables[i];
  355. Operand o = {Addressing_Value};
  356. o.type = param->type;
  357. array_add(&operands, o);
  358. }
  359. }
  360. defer (if (param_operands == nullptr) {
  361. array_free(&operands);
  362. });
  363. CheckerContext nctx = *old_c;
  364. Scope *scope = create_scope(info, base_entity->scope);
  365. scope->flags |= ScopeFlag_Proc;
  366. nctx.scope = scope;
  367. nctx.allow_polymorphic_types = true;
  368. if (nctx.polymorphic_scope == nullptr) {
  369. nctx.polymorphic_scope = scope;
  370. }
  371. auto *pt = &src->Proc;
  372. // NOTE(bill): This is slightly memory leaking if the type already exists
  373. // Maybe it's better to check with the previous types first?
  374. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  375. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  376. if (!success) {
  377. return false;
  378. }
  379. GenProcsData *gen_procs = nullptr;
  380. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  381. GB_ASSERT(base_entity->kind == Entity_Procedure);
  382. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  383. gen_procs = base_entity->Procedure.gen_procs;
  384. if (gen_procs) {
  385. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  386. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  387. for (Entity *other : gen_procs->procs) {
  388. Type *pt = base_type(other->type);
  389. if (are_types_identical(pt, final_proc_type)) {
  390. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  391. if (poly_proc_data) {
  392. poly_proc_data->gen_entity = other;
  393. }
  394. return true;
  395. }
  396. }
  397. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  398. } else {
  399. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  400. gen_procs->procs.allocator = heap_allocator();
  401. base_entity->Procedure.gen_procs = gen_procs;
  402. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  403. }
  404. {
  405. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  406. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  407. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  408. nctx.no_polymorphic_errors = false;
  409. // NOTE(bill): Reset scope from the failed procedure type
  410. scope->head_child.store(nullptr, std::memory_order_relaxed);
  411. string_map_clear(&scope->elements);
  412. ptr_set_clear(&scope->imported);
  413. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  414. Ast *cloned_proc_type_node = clone_ast(pt->node);
  415. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  416. if (!success) {
  417. return false;
  418. }
  419. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  420. for (Entity *other : gen_procs->procs) {
  421. Type *pt = base_type(other->type);
  422. if (are_types_identical(pt, final_proc_type)) {
  423. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  424. if (poly_proc_data) {
  425. poly_proc_data->gen_entity = other;
  426. }
  427. DeclInfo *decl = other->decl_info;
  428. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  429. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  430. proc_info->file = other->file;
  431. proc_info->token = other->token;
  432. proc_info->decl = decl;
  433. proc_info->type = other->type;
  434. proc_info->body = decl->proc_lit->ProcLit.body;
  435. proc_info->tags = other->Procedure.tags;;
  436. proc_info->generated_from_polymorphic = true;
  437. proc_info->poly_def_node = poly_def_node;
  438. check_procedure_later(nctx.checker, proc_info);
  439. }
  440. return true;
  441. }
  442. }
  443. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  444. }
  445. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  446. ast_node(pl, ProcLit, proc_lit);
  447. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  448. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  449. final_proc_type->Proc.is_poly_specialized = true;
  450. final_proc_type->Proc.is_polymorphic = true;
  451. final_proc_type->Proc.variadic = src->Proc.variadic;
  452. final_proc_type->Proc.require_results = src->Proc.require_results;
  453. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  454. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  455. final_proc_type->Proc.diverging = src->Proc.diverging;
  456. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  457. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  458. final_proc_type->Proc.enable_target_feature = src->Proc.enable_target_feature;
  459. final_proc_type->Proc.require_target_feature = src->Proc.require_target_feature;
  460. for (isize i = 0; i < operands.count; i++) {
  461. Operand o = operands[i];
  462. if (final_proc_type == o.type ||
  463. base_entity->type == o.type) {
  464. // NOTE(bill): Cycle
  465. final_proc_type->Proc.is_poly_specialized = false;
  466. break;
  467. }
  468. }
  469. u64 tags = base_entity->Procedure.tags;
  470. Ast *ident = clone_ast(base_entity->identifier);
  471. Token token = ident->Ident.token;
  472. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  473. d->gen_proc_type = final_proc_type;
  474. d->type_expr = pl->type;
  475. d->proc_lit = proc_lit;
  476. d->proc_checked_state = ProcCheckedState_Unchecked;
  477. d->defer_use_checked = false;
  478. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  479. entity->state.store(EntityState_Resolved);
  480. entity->identifier = ident;
  481. add_entity_and_decl_info(&nctx, ident, entity, d);
  482. // NOTE(bill): Set the scope afterwards as this is not real overloading
  483. entity->scope = scope->parent;
  484. entity->file = base_entity->file;
  485. entity->pkg = base_entity->pkg;
  486. entity->flags = 0;
  487. entity->Procedure.optimization_mode = base_entity->Procedure.optimization_mode;
  488. if (base_entity->flags & EntityFlag_Cold) {
  489. entity->flags |= EntityFlag_Cold;
  490. }
  491. if (base_entity->flags & EntityFlag_Disabled) {
  492. entity->flags |= EntityFlag_Disabled;
  493. }
  494. d->entity = entity;
  495. AstFile *file = nullptr;
  496. {
  497. Scope *s = entity->scope;
  498. while (s != nullptr && s->file == nullptr) {
  499. file = s->file;
  500. s = s->parent;
  501. }
  502. }
  503. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  504. array_add(&gen_procs->procs, entity);
  505. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  506. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  507. proc_info->file = file;
  508. proc_info->token = token;
  509. proc_info->decl = d;
  510. proc_info->type = final_proc_type;
  511. proc_info->body = pl->body;
  512. proc_info->tags = tags;
  513. proc_info->generated_from_polymorphic = true;
  514. proc_info->poly_def_node = poly_def_node;
  515. if (poly_proc_data) {
  516. poly_proc_data->gen_entity = entity;
  517. poly_proc_data->proc_info = proc_info;
  518. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  519. }
  520. // NOTE(bill): Check the newly generated procedure body
  521. check_procedure_later(nctx.checker, proc_info);
  522. return true;
  523. }
  524. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  525. if (operand->expr == nullptr) return false;
  526. Entity *base_entity = entity_from_expr(operand->expr);
  527. if (base_entity == nullptr) return false;
  528. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  529. }
  530. 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) {
  531. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  532. }
  533. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  534. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  535. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  536. #define MAXIMUM_TYPE_DISTANCE 10
  537. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming) {
  538. if (c == nullptr) {
  539. GB_ASSERT(operand->mode == Addressing_Value);
  540. GB_ASSERT(is_type_typed(operand->type));
  541. }
  542. if (operand->mode == Addressing_Invalid ||
  543. type == t_invalid) {
  544. return -1;
  545. }
  546. if (operand->mode == Addressing_Builtin) {
  547. return -1;
  548. }
  549. if (operand->mode == Addressing_Type) {
  550. if (is_type_typeid(type)) {
  551. if (is_type_polymorphic(operand->type)) {
  552. return -1;
  553. }
  554. add_type_info_type(c, operand->type);
  555. return 4;
  556. }
  557. return -1;
  558. }
  559. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  560. return -1;
  561. }
  562. Type *s = operand->type;
  563. if (are_types_identical(s, type)) {
  564. return 0;
  565. }
  566. Type *src = base_type(s);
  567. Type *dst = base_type(type);
  568. if (is_type_untyped_uninit(src)) {
  569. return 1;
  570. }
  571. if (is_type_untyped_nil(src)) {
  572. if (type_has_nil(dst)) {
  573. return 1;
  574. }
  575. return -1;
  576. }
  577. if (is_type_untyped(src)) {
  578. if (is_type_any(dst)) {
  579. // NOTE(bill): Anything can cast to 'Any'
  580. add_type_info_type(c, s);
  581. return MAXIMUM_TYPE_DISTANCE;
  582. }
  583. if (dst->kind == Type_Basic) {
  584. if (operand->mode == Addressing_Constant) {
  585. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  586. if (is_type_typed(dst) && src->kind == Type_Basic) {
  587. switch (src->Basic.kind) {
  588. case Basic_UntypedBool:
  589. if (is_type_boolean(dst)) {
  590. return 1;
  591. }
  592. break;
  593. case Basic_UntypedRune:
  594. if (is_type_integer(dst) || is_type_rune(dst)) {
  595. return 1;
  596. }
  597. break;
  598. case Basic_UntypedInteger:
  599. if (is_type_integer(dst) || is_type_rune(dst)) {
  600. return 1;
  601. }
  602. break;
  603. case Basic_UntypedString:
  604. if (is_type_string(dst)) {
  605. return 1;
  606. }
  607. break;
  608. case Basic_UntypedFloat:
  609. if (is_type_float(dst)) {
  610. return 1;
  611. }
  612. break;
  613. case Basic_UntypedComplex:
  614. if (is_type_complex(dst)) {
  615. return 1;
  616. }
  617. if (is_type_quaternion(dst)) {
  618. return 2;
  619. }
  620. break;
  621. case Basic_UntypedQuaternion:
  622. if (is_type_quaternion(dst)) {
  623. return 1;
  624. }
  625. break;
  626. }
  627. }
  628. return 2;
  629. }
  630. return -1;
  631. }
  632. if (src->kind == Type_Basic) {
  633. Type *d = base_array_type(dst);
  634. i64 score = -1;
  635. switch (src->Basic.kind) {
  636. case Basic_UntypedBool:
  637. if (is_type_boolean(d)) {
  638. score = 1;
  639. }
  640. break;
  641. case Basic_UntypedRune:
  642. if (is_type_integer(d) || is_type_rune(d)) {
  643. score = 1;
  644. }
  645. break;
  646. case Basic_UntypedInteger:
  647. if (is_type_integer(d) || is_type_rune(d)) {
  648. score = 1;
  649. }
  650. break;
  651. case Basic_UntypedString:
  652. if (is_type_string(d)) {
  653. score = 1;
  654. }
  655. break;
  656. case Basic_UntypedFloat:
  657. if (is_type_float(d)) {
  658. score = 1;
  659. }
  660. break;
  661. case Basic_UntypedComplex:
  662. if (is_type_complex(d)) {
  663. score = 1;
  664. }
  665. if (is_type_quaternion(d)) {
  666. score = 2;
  667. }
  668. break;
  669. case Basic_UntypedQuaternion:
  670. if (is_type_quaternion(d)) {
  671. score = 1;
  672. }
  673. break;
  674. }
  675. if (score > 0) {
  676. if (is_type_typed(d)) {
  677. score += 1;
  678. }
  679. if (d != dst) {
  680. score += 6;
  681. }
  682. }
  683. return score;
  684. }
  685. }
  686. }
  687. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  688. if (c->in_enum_type) {
  689. return 3;
  690. }
  691. }
  692. {
  693. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  694. if (subtype_level > 0) {
  695. return 4 + subtype_level;
  696. }
  697. }
  698. // rawptr <- ^T
  699. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  700. return 5;
  701. }
  702. // rawptr <- [^]T
  703. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  704. return 5;
  705. }
  706. // ^T <- [^]T
  707. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  708. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  709. return 4;
  710. }
  711. }
  712. // [^]T <- ^T
  713. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  714. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  715. return 4;
  716. }
  717. }
  718. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  719. bool modify_type = !c->no_polymorphic_errors;
  720. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  721. return 2;
  722. }
  723. }
  724. if (is_type_union(dst)) {
  725. for (Type *vt : dst->Union.variants) {
  726. if (are_types_identical(vt, s)) {
  727. return 1;
  728. }
  729. if (is_type_proc(vt)) {
  730. if (are_types_identical(base_type(vt), src)) {
  731. return 1;
  732. }
  733. }
  734. }
  735. if (dst->Union.variants.count == 1) {
  736. Type *vt = dst->Union.variants[0];
  737. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  738. if (score >= 0) {
  739. return score+2;
  740. }
  741. } else if (is_type_untyped(src)) {
  742. i64 prev_lowest_score = -1;
  743. i64 lowest_score = -1;
  744. for (Type *vt : dst->Union.variants) {
  745. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  746. if (score >= 0) {
  747. if (lowest_score < 0) {
  748. lowest_score = score;
  749. } else {
  750. if (prev_lowest_score < 0) {
  751. prev_lowest_score = lowest_score;
  752. } else {
  753. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  754. }
  755. lowest_score = gb_min(lowest_score, score);
  756. }
  757. }
  758. }
  759. if (lowest_score >= 0) {
  760. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  761. return lowest_score+2;
  762. }
  763. }
  764. }
  765. }
  766. if (is_type_proc(dst)) {
  767. if (are_types_identical(src, dst)) {
  768. return 3;
  769. }
  770. PolyProcData poly_proc_data = {};
  771. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  772. Entity *e = poly_proc_data.gen_entity;
  773. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  774. add_entity_use(c, operand->expr, e);
  775. return 4;
  776. }
  777. }
  778. if (is_type_complex_or_quaternion(dst)) {
  779. Type *elem = base_complex_elem_type(dst);
  780. if (are_types_identical(elem, base_type(src))) {
  781. return 5;
  782. }
  783. }
  784. if (allow_array_programming) {
  785. if (is_type_array(dst)) {
  786. Type *elem = base_array_type(dst);
  787. i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
  788. if (distance >= 0) {
  789. return distance + 6;
  790. }
  791. }
  792. if (is_type_simd_vector(dst)) {
  793. Type *dst_elem = base_array_type(dst);
  794. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  795. if (distance >= 0) {
  796. return distance + 6;
  797. }
  798. }
  799. }
  800. if (is_type_matrix(dst)) {
  801. if (are_types_identical(src, dst)) {
  802. return 5;
  803. }
  804. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  805. Type *dst_elem = base_array_type(dst);
  806. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  807. if (distance >= 0) {
  808. return distance + 7;
  809. }
  810. }
  811. }
  812. if (is_type_any(dst)) {
  813. if (!is_type_polymorphic(src)) {
  814. if (operand->mode == Addressing_Context && operand->type == t_context) {
  815. return -1;
  816. } else {
  817. // NOTE(bill): Anything can cast to 'Any'
  818. add_type_info_type(c, s);
  819. return MAXIMUM_TYPE_DISTANCE;
  820. }
  821. }
  822. }
  823. Ast *expr = unparen_expr(operand->expr);
  824. if (expr != nullptr) {
  825. if (expr->kind == Ast_AutoCast) {
  826. Operand x = *operand;
  827. x.expr = expr->AutoCast.expr;
  828. if (check_cast_internal(c, &x, type)) {
  829. return MAXIMUM_TYPE_DISTANCE;
  830. }
  831. }
  832. }
  833. return -1;
  834. }
  835. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  836. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  837. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  838. // TODO(bill): A decent score function
  839. i64 d = distance*distance; // x^2
  840. if (is_variadic && d >= 0) {
  841. d += distance + 1; // x^2 + x + 1
  842. }
  843. return gb_max(c - d, 0);
  844. }
  845. 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) {
  846. if (c == nullptr) {
  847. GB_ASSERT(operand->mode == Addressing_Value);
  848. GB_ASSERT(is_type_typed(operand->type));
  849. }
  850. if (operand->mode == Addressing_Invalid || type == t_invalid) {
  851. if (score_) *score_ = 0;
  852. return false;
  853. }
  854. // Handle polymorphic procedure used as default parameter
  855. if (operand->mode == Addressing_Value && is_type_proc(type) && is_type_proc(operand->type)) {
  856. Entity *e = entity_from_expr(operand->expr);
  857. if (e != nullptr && e->kind == Entity_Procedure && is_type_polymorphic(e->type) && !is_type_polymorphic(type)) {
  858. // Special case: Allow a polymorphic procedure to be used as default value for concrete proc type
  859. // during the initial check. It will be properly instantiated when actually used.
  860. if (score_) *score_ = assign_score_function(1);
  861. return true;
  862. }
  863. }
  864. i64 score = check_distance_between_types(c, operand, type, allow_array_programming);
  865. if (score >= 0) {
  866. if (score_) *score_ = assign_score_function(score, is_variadic);
  867. return true;
  868. }
  869. if (score_) *score_ = 0;
  870. return false;
  871. }
  872. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming=true) {
  873. i64 score = 0;
  874. return check_is_assignable_to_with_score(c, operand, type, &score, /*is_variadic*/false, allow_array_programming);
  875. }
  876. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  877. Operand x = {};
  878. x.type = src;
  879. x.mode = Addressing_Value;
  880. return check_is_assignable_to(nullptr, &x, dst);
  881. }
  882. gb_internal AstPackage *get_package_of_type(Type *type) {
  883. for (;;) {
  884. if (type == nullptr) {
  885. return nullptr;
  886. }
  887. switch (type->kind) {
  888. case Type_Basic:
  889. return builtin_pkg;
  890. case Type_Named:
  891. if (type->Named.type_name != nullptr) {
  892. return type->Named.type_name->pkg;
  893. }
  894. return nullptr;
  895. case Type_Pointer:
  896. type = type->Pointer.elem;
  897. continue;
  898. case Type_Array:
  899. type = type->Array.elem;
  900. continue;
  901. case Type_Slice:
  902. type = type->Slice.elem;
  903. continue;
  904. case Type_DynamicArray:
  905. type = type->DynamicArray.elem;
  906. continue;
  907. }
  908. return nullptr;
  909. }
  910. }
  911. // NOTE(bill): 'context_name' is for debugging and error messages
  912. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  913. check_not_tuple(c, operand);
  914. if (operand->mode == Addressing_Invalid) {
  915. return;
  916. }
  917. // Grab definite or indefinite article matching `context_name`, or "" if not found.
  918. String article = error_article(context_name);
  919. if (is_type_untyped(operand->type)) {
  920. Type *target_type = type;
  921. if (type == nullptr || is_type_any(type)) {
  922. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  923. error(operand->expr, "Use of --- in %.*s%.*s", LIT(article), LIT(context_name));
  924. operand->mode = Addressing_Invalid;
  925. return;
  926. }
  927. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  928. error(operand->expr, "Use of untyped nil in %.*s%.*s", LIT(article), LIT(context_name));
  929. operand->mode = Addressing_Invalid;
  930. return;
  931. }
  932. target_type = default_type(operand->type);
  933. if (type != nullptr && !is_type_any(type)) {
  934. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  935. }
  936. add_type_info_type(c, type);
  937. add_type_info_type(c, target_type);
  938. }
  939. convert_to_typed(c, operand, target_type);
  940. if (operand->mode == Addressing_Invalid) {
  941. return;
  942. }
  943. }
  944. if (type == nullptr) {
  945. return;
  946. }
  947. if (operand->mode == Addressing_ProcGroup) {
  948. bool good = false;
  949. if (type != nullptr && is_type_proc(type)) {
  950. Array<Entity *> procs = proc_group_entities(c, *operand);
  951. // NOTE(bill): These should be done
  952. for (Entity *e : procs) {
  953. Type *t = base_type(e->type);
  954. if (t == t_invalid) {
  955. continue;
  956. }
  957. Operand x = {};
  958. x.mode = Addressing_Value;
  959. x.type = t;
  960. if (check_is_assignable_to(c, &x, type)) {
  961. add_entity_use(c, operand->expr, e);
  962. good = true;
  963. break;
  964. }
  965. }
  966. }
  967. if (!good) {
  968. gbString expr_str = expr_to_string(operand->expr);
  969. gbString op_type_str = type_to_string(operand->type);
  970. gbString type_str = type_to_string(type);
  971. defer (gb_string_free(type_str));
  972. defer (gb_string_free(op_type_str));
  973. defer (gb_string_free(expr_str));
  974. // TODO(bill): is this a good enough error message?
  975. error(operand->expr,
  976. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s%.*s",
  977. expr_str,
  978. op_type_str,
  979. LIT(article),
  980. LIT(context_name));
  981. operand->mode = Addressing_Invalid;
  982. }
  983. convert_to_typed(c, operand, type);
  984. return;
  985. }
  986. if (check_is_assignable_to(c, operand, type)) {
  987. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  988. add_type_info_type(c, operand->type);
  989. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  990. }
  991. } else {
  992. gbString expr_str = expr_to_string(operand->expr);
  993. gbString op_type_str = type_to_string(operand->type);
  994. gbString type_str = type_to_string(type);
  995. defer (gb_string_free(type_str));
  996. defer (gb_string_free(op_type_str));
  997. defer (gb_string_free(expr_str));
  998. switch (operand->mode) {
  999. case Addressing_Builtin:
  1000. error(operand->expr,
  1001. "Cannot assign built-in procedure '%s' to %.*s%.*s",
  1002. expr_str,
  1003. LIT(article),
  1004. LIT(context_name));
  1005. break;
  1006. case Addressing_Type:
  1007. if (is_type_polymorphic(operand->type)) {
  1008. error(operand->expr,
  1009. "Cannot assign '%s', a polymorphic type, to %.*s%.*s",
  1010. op_type_str,
  1011. LIT(article),
  1012. LIT(context_name));
  1013. } else {
  1014. ERROR_BLOCK();
  1015. error(operand->expr,
  1016. "Cannot assign '%s', a type, to %.*s%.*s",
  1017. op_type_str,
  1018. LIT(article),
  1019. LIT(context_name));
  1020. if (type && are_types_identical(type, t_any)) {
  1021. error_line("\tSuggestion: 'typeid_of(%s)'", expr_str);
  1022. }
  1023. }
  1024. break;
  1025. default:
  1026. // TODO(bill): is this a good enough error message?
  1027. {
  1028. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  1029. gbString type_extra = gb_string_make(heap_allocator(), "");
  1030. defer (gb_string_free(op_type_extra));
  1031. defer (gb_string_free(type_extra));
  1032. isize on = gb_string_length(op_type_str);
  1033. isize tn = gb_string_length(type_str);
  1034. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  1035. AstPackage *op_pkg = get_package_of_type(operand->type);
  1036. AstPackage *type_pkg = get_package_of_type(type);
  1037. if (op_pkg != nullptr) {
  1038. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  1039. }
  1040. if (type_pkg != nullptr) {
  1041. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  1042. }
  1043. }
  1044. ERROR_BLOCK();
  1045. error(operand->expr,
  1046. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s%.*s",
  1047. expr_str,
  1048. op_type_str, op_type_extra,
  1049. type_str, type_extra,
  1050. LIT(article),
  1051. LIT(context_name));
  1052. check_assignment_error_suggestion(c, operand, type);
  1053. Type *src = base_type(operand->type);
  1054. Type *dst = base_type(type);
  1055. if (context_name == "procedure argument") {
  1056. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  1057. gbString a = expr_to_string(operand->expr);
  1058. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  1059. gb_string_free(a);
  1060. }
  1061. }
  1062. if (src->kind == dst->kind && src->kind == Type_Proc) {
  1063. Type *x = src;
  1064. Type *y = dst;
  1065. bool same_inputs = are_types_identical_internal(x->Proc.params, y->Proc.params, false);
  1066. bool same_outputs = are_types_identical_internal(x->Proc.results, y->Proc.results, false);
  1067. if (same_inputs && same_outputs &&
  1068. x->Proc.calling_convention != y->Proc.calling_convention) {
  1069. gbString s_expected = type_to_string(y);
  1070. gbString s_got = type_to_string(x);
  1071. error_line("\tNote: The calling conventions differ between the procedure signature types\n");
  1072. error_line("\t Expected \"%s\", got \"%s\"\n",
  1073. proc_calling_convention_strings[y->Proc.calling_convention],
  1074. proc_calling_convention_strings[x->Proc.calling_convention]);
  1075. error_line("\t Expected: %s\n", s_expected);
  1076. error_line("\t Got: %s\n", s_got);
  1077. gb_string_free(s_got);
  1078. gb_string_free(s_expected);
  1079. } else if (same_inputs && same_outputs &&
  1080. x->Proc.diverging != y->Proc.diverging) {
  1081. gbString s_expected = type_to_string(y);
  1082. if (y->Proc.diverging) {
  1083. s_expected = gb_string_appendc(s_expected, " -> !");
  1084. }
  1085. gbString s_got = type_to_string(x);
  1086. if (x->Proc.diverging) {
  1087. s_got = gb_string_appendc(s_got, " -> !");
  1088. }
  1089. error_line("\tNote: One of the procedures is diverging while the other isn't\n");
  1090. error_line("\t Expected: %s\n", s_expected);
  1091. error_line("\t Got: %s\n", s_got);
  1092. gb_string_free(s_got);
  1093. gb_string_free(s_expected);
  1094. } else if (same_inputs && !same_outputs) {
  1095. gbString s_expected = type_to_string(y->Proc.results);
  1096. gbString s_got = type_to_string(x->Proc.results);
  1097. error_line("\tNote: The return types differ between the procedure signature types\n");
  1098. error_line("\t Expected: %s\n", s_expected);
  1099. error_line("\t Got: %s\n", s_got);
  1100. gb_string_free(s_got);
  1101. gb_string_free(s_expected);
  1102. } else if (!same_inputs && same_outputs) {
  1103. gbString s_expected = type_to_string(y->Proc.params);
  1104. gbString s_got = type_to_string(x->Proc.params);
  1105. error_line("\tNote: The input parameter types differ between the procedure signature types\n");
  1106. error_line("\t Expected: %s\n", s_expected);
  1107. error_line("\t Got: %s\n", s_got);
  1108. gb_string_free(s_got);
  1109. gb_string_free(s_expected);
  1110. } else {
  1111. gbString s_expected = type_to_string(y);
  1112. gbString s_got = type_to_string(x);
  1113. error_line("\tNote: The signature type do not match whatsoever\n");
  1114. error_line("\t Expected: %s\n", s_expected);
  1115. error_line("\t Got: %s\n", s_got);
  1116. gb_string_free(s_got);
  1117. gb_string_free(s_expected);
  1118. }
  1119. }
  1120. }
  1121. break;
  1122. }
  1123. operand->mode = Addressing_Invalid;
  1124. return;
  1125. }
  1126. }
  1127. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1128. Type *gt = *gt_;
  1129. GB_ASSERT(gt->kind == Type_Generic);
  1130. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1131. GB_ASSERT(e != nullptr);
  1132. if (e->kind == Entity_TypeName) {
  1133. *gt_ = nullptr;
  1134. *dst_count = source_count;
  1135. e->kind = Entity_Constant;
  1136. e->Constant.value = exact_value_i64(source_count);
  1137. e->type = t_untyped_integer;
  1138. return true;
  1139. } else if (e->kind == Entity_Constant) {
  1140. *gt_ = nullptr;
  1141. if (e->Constant.value.kind != ExactValue_Integer) {
  1142. return false;
  1143. }
  1144. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1145. if (count != source_count) {
  1146. return false;
  1147. }
  1148. *dst_count = source_count;
  1149. return true;
  1150. }
  1151. return false;
  1152. }
  1153. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1154. Operand o = {Addressing_Value};
  1155. o.type = source;
  1156. switch (poly->kind) {
  1157. case Type_Basic:
  1158. if (compound) return are_types_identical(poly, source);
  1159. return check_is_assignable_to(c, &o, poly);
  1160. case Type_Named: {
  1161. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1162. return true;
  1163. }
  1164. if (compound || !is_type_generic(poly)) {
  1165. return are_types_identical(poly, source);
  1166. }
  1167. return check_is_assignable_to(c, &o, poly);
  1168. }
  1169. case Type_Generic: {
  1170. if (poly->Generic.specialized != nullptr) {
  1171. Type *s = poly->Generic.specialized;
  1172. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1173. return false;
  1174. }
  1175. }
  1176. if (modify_type) {
  1177. Type *ds = default_type(source);
  1178. gb_memmove(poly, ds, gb_size_of(Type));
  1179. }
  1180. return true;
  1181. }
  1182. case Type_Pointer:
  1183. if (source->kind == Type_Pointer) {
  1184. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1185. if (level > 0) {
  1186. return true;
  1187. }
  1188. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1189. } else if (source->kind == Type_MultiPointer) {
  1190. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1191. if (level > 0) {
  1192. return true;
  1193. }
  1194. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1195. }
  1196. return false;
  1197. case Type_MultiPointer:
  1198. if (source->kind == Type_MultiPointer) {
  1199. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1200. if (level > 0) {
  1201. return true;
  1202. }
  1203. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1204. } else if (source->kind == Type_Pointer) {
  1205. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1206. if (level > 0) {
  1207. return true;
  1208. }
  1209. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1210. }
  1211. return false;
  1212. case Type_Array:
  1213. if (source->kind == Type_Array) {
  1214. if (poly->Array.generic_count != nullptr) {
  1215. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1216. return false;
  1217. }
  1218. }
  1219. if (poly->Array.count == source->Array.count) {
  1220. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1221. }
  1222. } else if (source->kind == Type_EnumeratedArray) {
  1223. if (poly->Array.generic_count != nullptr) {
  1224. Type *gt = poly->Array.generic_count;
  1225. GB_ASSERT(gt->kind == Type_Generic);
  1226. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1227. GB_ASSERT(e != nullptr);
  1228. if (e->kind == Entity_TypeName) {
  1229. Type *index = source->EnumeratedArray.index;
  1230. Type *it = base_type(index);
  1231. if (it->kind != Type_Enum) {
  1232. return false;
  1233. }
  1234. poly->kind = Type_EnumeratedArray;
  1235. poly->cached_size = -1;
  1236. poly->cached_align = -1;
  1237. poly->flags.exchange(source->flags);
  1238. poly->failure = false;
  1239. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1240. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1241. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1242. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1243. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1244. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1245. e->kind = Entity_TypeName;
  1246. e->TypeName.is_type_alias = true;
  1247. e->type = index;
  1248. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1249. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1250. }
  1251. }
  1252. }
  1253. }
  1254. return false;
  1255. case Type_EnumeratedArray:
  1256. if (source->kind == Type_EnumeratedArray) {
  1257. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1258. return false;
  1259. }
  1260. if (poly->EnumeratedArray.op) {
  1261. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1262. return false;
  1263. }
  1264. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1265. return false;
  1266. }
  1267. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1268. return false;
  1269. }
  1270. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1271. }
  1272. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1273. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1274. return index || elem;
  1275. }
  1276. return false;
  1277. case Type_DynamicArray:
  1278. if (source->kind == Type_DynamicArray) {
  1279. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1280. }
  1281. return false;
  1282. case Type_Slice:
  1283. if (source->kind == Type_Slice) {
  1284. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1285. }
  1286. return false;
  1287. case Type_Enum:
  1288. return false;
  1289. case Type_BitSet:
  1290. if (source->kind == Type_BitSet) {
  1291. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1292. return false;
  1293. }
  1294. // For generic types like bit_set[$T] the upper and lower of the poly type will be zeroes since
  1295. // it could not figure that stuff out when the poly type was created.
  1296. if (poly->BitSet.upper == 0 && modify_type) {
  1297. poly->BitSet.upper = source->BitSet.upper;
  1298. }
  1299. if (poly->BitSet.lower == 0 && modify_type) {
  1300. poly->BitSet.lower = source->BitSet.lower;
  1301. }
  1302. if (poly->BitSet.underlying == nullptr) {
  1303. if (modify_type) {
  1304. poly->BitSet.underlying = source->BitSet.underlying;
  1305. }
  1306. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1307. return false;
  1308. }
  1309. return true;
  1310. }
  1311. return false;
  1312. case Type_Union:
  1313. if (source->kind == Type_Union) {
  1314. TypeUnion *x = &poly->Union;
  1315. TypeUnion *y = &source->Union;
  1316. if (x->variants.count != y->variants.count) {
  1317. return false;
  1318. }
  1319. for_array(i, x->variants) {
  1320. Type *a = x->variants[i];
  1321. Type *b = y->variants[i];
  1322. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1323. if (!ok) return false;
  1324. }
  1325. return true;
  1326. }
  1327. return false;
  1328. case Type_Struct:
  1329. if (source->kind == Type_Struct) {
  1330. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1331. poly->Struct.soa_kind != StructSoa_None) {
  1332. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1333. if (ok) switch (source->Struct.soa_kind) {
  1334. case StructSoa_None:
  1335. default:
  1336. GB_PANIC("Unhandled SOA Kind");
  1337. break;
  1338. case StructSoa_Fixed:
  1339. if (modify_type) {
  1340. Type *type = make_soa_struct_fixed(c, nullptr, poly->Struct.node, poly->Struct.soa_elem, poly->Struct.soa_count, nullptr);
  1341. gb_memmove(poly, type, gb_size_of(*type));
  1342. }
  1343. break;
  1344. case StructSoa_Slice:
  1345. if (modify_type) {
  1346. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1347. gb_memmove(poly, type, gb_size_of(*type));
  1348. }
  1349. break;
  1350. case StructSoa_Dynamic:
  1351. if (modify_type) {
  1352. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1353. gb_memmove(poly, type, gb_size_of(*type));
  1354. }
  1355. break;
  1356. }
  1357. return ok;
  1358. }
  1359. // NOTE(bill): Check for subtypes of
  1360. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1361. }
  1362. return false;
  1363. case Type_BitField:
  1364. if (source->kind == Type_BitField) {
  1365. return is_polymorphic_type_assignable(c, poly->BitField.backing_type, source->BitField.backing_type, true, modify_type);
  1366. }
  1367. return false;
  1368. case Type_Tuple:
  1369. GB_PANIC("This should never happen");
  1370. return false;
  1371. case Type_Proc:
  1372. if (source->kind == Type_Proc) {
  1373. TypeProc *x = &poly->Proc;
  1374. TypeProc *y = &source->Proc;
  1375. if (x->calling_convention != y->calling_convention) {
  1376. return false;
  1377. }
  1378. if (x->c_vararg != y->c_vararg) {
  1379. return false;
  1380. }
  1381. if (x->variadic != y->variadic) {
  1382. return false;
  1383. }
  1384. if (x->param_count != y->param_count) {
  1385. return false;
  1386. }
  1387. if (x->result_count != y->result_count) {
  1388. return false;
  1389. }
  1390. for (isize i = 0; i < x->param_count; i++) {
  1391. Entity *a = x->params->Tuple.variables[i];
  1392. Entity *b = y->params->Tuple.variables[i];
  1393. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1394. if (!ok) return false;
  1395. }
  1396. for (isize i = 0; i < x->result_count; i++) {
  1397. Entity *a = x->results->Tuple.variables[i];
  1398. Entity *b = y->results->Tuple.variables[i];
  1399. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1400. if (!ok) return false;
  1401. }
  1402. return true;
  1403. }
  1404. return false;
  1405. case Type_Map:
  1406. if (source->kind == Type_Map) {
  1407. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1408. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1409. if (key || value) {
  1410. poly->Map.lookup_result_type = nullptr;
  1411. init_map_internal_types(poly);
  1412. return true;
  1413. }
  1414. }
  1415. return false;
  1416. case Type_Matrix:
  1417. if (source->kind == Type_Matrix) {
  1418. if (poly->Matrix.generic_row_count != nullptr) {
  1419. poly->Matrix.stride_in_bytes = 0;
  1420. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1421. return false;
  1422. }
  1423. }
  1424. if (poly->Matrix.generic_column_count != nullptr) {
  1425. poly->Matrix.stride_in_bytes = 0;
  1426. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1427. return false;
  1428. }
  1429. }
  1430. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1431. poly->Matrix.column_count == source->Matrix.column_count) {
  1432. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1433. }
  1434. }
  1435. return false;
  1436. case Type_SimdVector:
  1437. if (source->kind == Type_SimdVector) {
  1438. if (poly->SimdVector.generic_count != nullptr) {
  1439. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1440. return false;
  1441. }
  1442. }
  1443. if (poly->SimdVector.count == source->SimdVector.count) {
  1444. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1445. }
  1446. }
  1447. return false;
  1448. }
  1449. return false;
  1450. }
  1451. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1452. if (curr->state != EntityState_InProgress) {
  1453. return false;
  1454. }
  1455. for_array(i, *c->type_path) {
  1456. Entity *prev = c->type_path->data[i];
  1457. if (prev == curr) {
  1458. if (report) {
  1459. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1460. for (isize j = i; j < c->type_path->count; j++) {
  1461. Entity *curr = (*c->type_path)[j];
  1462. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1463. }
  1464. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1465. curr->type = t_invalid;
  1466. }
  1467. return true;
  1468. }
  1469. }
  1470. return false;
  1471. }
  1472. struct CIdentSuggestion {
  1473. String name;
  1474. String msg;
  1475. };
  1476. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1477. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1478. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1479. {str_lit("sizeof"), str_lit("'size_of'?")},
  1480. {str_lit("alignof"), str_lit("'align_of'?")},
  1481. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1482. {str_lit("_Bool"), str_lit("'bool'?")},
  1483. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1484. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1485. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1486. {str_lit("float"), str_lit("'f32'?")},
  1487. {str_lit("double"), str_lit("'f64'?")},
  1488. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1489. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1490. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1491. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1492. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1493. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1494. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1495. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1496. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1497. {str_lit("uint8_t"), str_lit("'u8'?")},
  1498. {str_lit("int8_t"), str_lit("'i8'?")},
  1499. {str_lit("uint16_t"), str_lit("'u16'?")},
  1500. {str_lit("int16_t"), str_lit("'i16'?")},
  1501. {str_lit("uint32_t"), str_lit("'u32'?")},
  1502. {str_lit("int32_t"), str_lit("'i32'?")},
  1503. {str_lit("uint64_t"), str_lit("'u64'?")},
  1504. {str_lit("int64_t"), str_lit("'i64'?")},
  1505. {str_lit("uint128_t"), str_lit("'u128'?")},
  1506. {str_lit("int128_t"), str_lit("'i128'?")},
  1507. {str_lit("float32"), str_lit("'f32'?")},
  1508. {str_lit("float64"), str_lit("'f64'?")},
  1509. {str_lit("float32_t"), str_lit("'f32'?")},
  1510. {str_lit("float64_t"), str_lit("'f64'?")},
  1511. };
  1512. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1513. GB_ASSERT(n->kind == Ast_Ident);
  1514. o->mode = Addressing_Invalid;
  1515. o->expr = n;
  1516. String name = n->Ident.token.string;
  1517. Entity *e = scope_lookup(c->scope, name);
  1518. if (e == nullptr) {
  1519. if (is_blank_ident(name)) {
  1520. error(n, "'_' cannot be used as a value");
  1521. } else {
  1522. ERROR_BLOCK();
  1523. error(n, "Undeclared name: %.*s", LIT(name));
  1524. // NOTE(bill): Loads of checks for C programmers
  1525. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1526. if (name == suggestion.name) {
  1527. error_line("\tSuggestion: Did you mean %.*s\n", LIT(suggestion.msg));
  1528. }
  1529. }
  1530. }
  1531. o->type = t_invalid;
  1532. o->mode = Addressing_Invalid;
  1533. if (named_type != nullptr) {
  1534. set_base_type(named_type, t_invalid);
  1535. }
  1536. return nullptr;
  1537. }
  1538. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1539. if (e->parent_proc_decl != nullptr &&
  1540. e->parent_proc_decl != c->curr_proc_decl) {
  1541. if (e->kind == Entity_Variable) {
  1542. if ((e->flags & EntityFlag_Static) == 0) {
  1543. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1544. return nullptr;
  1545. }
  1546. } else if (e->kind == Entity_Label) {
  1547. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1548. return nullptr;
  1549. }
  1550. }
  1551. if (e->kind == Entity_ProcGroup) {
  1552. auto *pge = &e->ProcGroup;
  1553. DeclInfo *d = decl_info_of_entity(e);
  1554. check_entity_decl(c, e, d, nullptr);
  1555. Array<Entity *> procs = pge->entities;
  1556. bool skip = false;
  1557. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1558. // NOTE(bill): These should be done
  1559. for (Entity *proc : procs) {
  1560. Type *t = base_type(proc->type);
  1561. if (t == t_invalid) {
  1562. continue;
  1563. }
  1564. Operand x = {};
  1565. x.mode = Addressing_Value;
  1566. x.type = t;
  1567. if (check_is_assignable_to(c, &x, type_hint)) {
  1568. e = proc;
  1569. add_entity_use(c, n, e);
  1570. skip = true;
  1571. break;
  1572. }
  1573. }
  1574. }
  1575. if (!skip) {
  1576. o->mode = Addressing_ProcGroup;
  1577. o->type = t_invalid;
  1578. o->proc_group = e;
  1579. return nullptr;
  1580. }
  1581. }
  1582. add_entity_use(c, n, e);
  1583. if (e->state == EntityState_Unresolved) {
  1584. check_entity_decl(c, e, nullptr, named_type);
  1585. }
  1586. if (e->type == nullptr) {
  1587. // TODO(bill): Which is correct? return or compiler_error?
  1588. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1589. return nullptr;
  1590. }
  1591. e->flags |= EntityFlag_Used;
  1592. Type *type = e->type;
  1593. o->type = type;
  1594. switch (e->kind) {
  1595. case Entity_Constant:
  1596. if (type == t_invalid) {
  1597. o->type = t_invalid;
  1598. return e;
  1599. }
  1600. o->value = e->Constant.value;
  1601. if (o->value.kind == ExactValue_Invalid) {
  1602. return e;
  1603. }
  1604. if (o->value.kind == ExactValue_Procedure) {
  1605. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1606. if (proc != nullptr) {
  1607. o->mode = Addressing_Value;
  1608. o->type = proc->type;
  1609. return proc;
  1610. }
  1611. }
  1612. o->mode = Addressing_Constant;
  1613. break;
  1614. case Entity_Variable:
  1615. e->flags |= EntityFlag_Used;
  1616. if (type == t_invalid) {
  1617. o->type = t_invalid;
  1618. return e;
  1619. }
  1620. o->mode = Addressing_Variable;
  1621. if (e->flags & EntityFlag_Value) {
  1622. o->mode = Addressing_Value;
  1623. }
  1624. break;
  1625. case Entity_Procedure:
  1626. o->mode = Addressing_Value;
  1627. o->value = exact_value_procedure(n);
  1628. break;
  1629. case Entity_Builtin:
  1630. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1631. o->mode = Addressing_Builtin;
  1632. break;
  1633. case Entity_TypeName:
  1634. o->mode = Addressing_Type;
  1635. if (check_cycle(c, e, true)) {
  1636. o->type = t_invalid;
  1637. }
  1638. if (o->type != nullptr && o->type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1639. Type *bt = base_type(o->type);
  1640. if (bt != nullptr) {
  1641. o->type = bt;
  1642. }
  1643. }
  1644. break;
  1645. case Entity_ImportName:
  1646. if (!allow_import_name) {
  1647. error(n, "Use of import name '%.*s' not in the form of 'x.y'", LIT(name));
  1648. }
  1649. return e;
  1650. case Entity_LibraryName:
  1651. if (!allow_import_name) {
  1652. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1653. }
  1654. return e;
  1655. case Entity_Label:
  1656. o->mode = Addressing_NoValue;
  1657. break;
  1658. case Entity_Nil:
  1659. o->mode = Addressing_Value;
  1660. break;
  1661. default:
  1662. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1663. break;
  1664. }
  1665. return e;
  1666. }
  1667. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1668. if (o->type == nullptr) {
  1669. gbString str = expr_to_string(o->expr);
  1670. error(o->expr, "Expression has no value '%s'", str);
  1671. gb_string_free(str);
  1672. return false;
  1673. }
  1674. if (o->mode == Addressing_Type) {
  1675. gbString str = type_to_string(o->type);
  1676. error(o->expr, "Expected an expression for operator '%.*s', got type '%s'", LIT(op.string), str);
  1677. gb_string_free(str);
  1678. return false;
  1679. }
  1680. Type *type = base_type(core_array_type(o->type));
  1681. gbString str = nullptr;
  1682. switch (op.kind) {
  1683. case Token_Add:
  1684. case Token_Sub:
  1685. if (!is_type_numeric(type)) {
  1686. str = expr_to_string(o->expr);
  1687. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1688. gb_string_free(str);
  1689. }
  1690. break;
  1691. case Token_Xor:
  1692. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1693. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1694. }
  1695. break;
  1696. case Token_Not:
  1697. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1698. ERROR_BLOCK();
  1699. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1700. if (is_type_integer(type)) {
  1701. str = expr_to_string(o->expr);
  1702. error_line("\tSuggestion: Did you mean to do one of the following?\n");
  1703. error_line("\t\t'%s == 0'?\n", str);
  1704. error_line("\t\tUse of the bitwise not operator '~'?\n");
  1705. gb_string_free(str);
  1706. }
  1707. } else {
  1708. o->type = t_untyped_bool;
  1709. }
  1710. break;
  1711. case Token_Mul:
  1712. {
  1713. ERROR_BLOCK();
  1714. error(op, "Operator '%.*s' is not a valid unary operator in Odin", LIT(op.string));
  1715. if (is_type_pointer(o->type)) {
  1716. str = expr_to_string(o->expr);
  1717. error_line("\tSuggestion: Did you mean '%s^'?\n", str);
  1718. o->type = type_deref(o->type);
  1719. } else if (is_type_multi_pointer(o->type)) {
  1720. str = expr_to_string(o->expr);
  1721. error_line("\tSuggestion: The value is a multi-pointer, did you mean '%s[0]'?\n", str);
  1722. o->type = type_deref(o->type, true);
  1723. }
  1724. }
  1725. break;
  1726. default:
  1727. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1728. return false;
  1729. }
  1730. return true;
  1731. }
  1732. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1733. Type *main_type = o->type;
  1734. Type *type = base_type(core_array_type(main_type));
  1735. Type *ct = core_type(type);
  1736. switch (op.kind) {
  1737. case Token_Sub:
  1738. case Token_SubEq:
  1739. if (is_type_bit_set(type)) {
  1740. return true;
  1741. } else if (!is_type_numeric(type)) {
  1742. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1743. return false;
  1744. }
  1745. break;
  1746. case Token_Quo:
  1747. case Token_QuoEq:
  1748. if (is_type_matrix(main_type)) {
  1749. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1750. return false;
  1751. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1752. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1753. return false;
  1754. }
  1755. /*fallthrough*/
  1756. case Token_Mul:
  1757. case Token_MulEq:
  1758. case Token_AddEq:
  1759. if (is_type_bit_set(type)) {
  1760. return true;
  1761. } else if (!is_type_numeric(type)) {
  1762. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1763. return false;
  1764. }
  1765. break;
  1766. case Token_Add:
  1767. if (is_type_string(type)) {
  1768. if (o->mode == Addressing_Constant) {
  1769. return true;
  1770. }
  1771. error(op, "String concatenation is only allowed with constant strings");
  1772. return false;
  1773. } else if (is_type_bit_set(type)) {
  1774. return true;
  1775. } else if (!is_type_numeric(type)) {
  1776. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1777. return false;
  1778. }
  1779. break;
  1780. case Token_And:
  1781. case Token_Or:
  1782. case Token_AndEq:
  1783. case Token_OrEq:
  1784. case Token_Xor:
  1785. case Token_XorEq:
  1786. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1787. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1788. return false;
  1789. }
  1790. break;
  1791. case Token_Mod:
  1792. case Token_ModMod:
  1793. case Token_ModEq:
  1794. case Token_ModModEq:
  1795. if (is_type_matrix(main_type)) {
  1796. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1797. return false;
  1798. }
  1799. if (!is_type_integer(type)) {
  1800. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1801. return false;
  1802. } else if (is_type_simd_vector(main_type)) {
  1803. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1804. return false;
  1805. }
  1806. break;
  1807. case Token_AndNot:
  1808. case Token_AndNotEq:
  1809. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1810. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1811. return false;
  1812. }
  1813. break;
  1814. case Token_CmpAnd:
  1815. case Token_CmpOr:
  1816. case Token_CmpAndEq:
  1817. case Token_CmpOrEq:
  1818. if (!is_type_boolean(type)) {
  1819. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1820. return false;
  1821. }
  1822. break;
  1823. default:
  1824. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1825. return false;
  1826. }
  1827. return true;
  1828. }
  1829. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1830. if (in_value.kind == ExactValue_Invalid) {
  1831. // NOTE(bill): There's already been an error
  1832. return true;
  1833. }
  1834. type = core_type(type);
  1835. if (type == t_invalid) {
  1836. return false;
  1837. } else if (is_type_boolean(type)) {
  1838. return in_value.kind == ExactValue_Bool;
  1839. } else if (is_type_string(type)) {
  1840. return in_value.kind == ExactValue_String;
  1841. } else if (is_type_integer(type) || is_type_rune(type)) {
  1842. if (in_value.kind == ExactValue_Bool) {
  1843. return false;
  1844. }
  1845. ExactValue v = exact_value_to_integer(in_value);
  1846. if (v.kind != ExactValue_Integer) {
  1847. return false;
  1848. }
  1849. if (out_value) *out_value = v;
  1850. if (is_type_untyped(type)) {
  1851. return true;
  1852. }
  1853. BigInt i = v.value_integer;
  1854. i64 byte_size = type_size_of(type);
  1855. BigInt umax = {};
  1856. BigInt imin = {};
  1857. BigInt imax = {};
  1858. if (c->bit_field_bit_size > 0) {
  1859. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1860. big_int_from_u64(&umax, 1);
  1861. big_int_from_i64(&imin, 1);
  1862. big_int_from_i64(&imax, 1);
  1863. BigInt bu = {};
  1864. BigInt bi = {};
  1865. big_int_from_i64(&bu, bit_size);
  1866. big_int_from_i64(&bi, bit_size-1);
  1867. big_int_shl_eq(&umax, &bu);
  1868. mp_decr(&umax);
  1869. big_int_shl_eq(&imin, &bi);
  1870. big_int_neg(&imin, &imin);
  1871. big_int_shl_eq(&imax, &bi);
  1872. mp_decr(&imax);
  1873. } else {
  1874. if (byte_size < 16) {
  1875. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1876. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1877. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1878. } else {
  1879. big_int_from_u64(&umax, 1);
  1880. big_int_from_i64(&imin, 1);
  1881. big_int_from_i64(&imax, 1);
  1882. BigInt bi128 = {};
  1883. BigInt bi127 = {};
  1884. big_int_from_i64(&bi128, 128);
  1885. big_int_from_i64(&bi127, 127);
  1886. big_int_shl_eq(&umax, &bi128);
  1887. mp_decr(&umax);
  1888. big_int_shl_eq(&imin, &bi127);
  1889. big_int_neg(&imin, &imin);
  1890. big_int_shl_eq(&imax, &bi127);
  1891. mp_decr(&imax);
  1892. }
  1893. }
  1894. switch (type->Basic.kind) {
  1895. case Basic_rune:
  1896. case Basic_i8:
  1897. case Basic_i16:
  1898. case Basic_i32:
  1899. case Basic_i64:
  1900. case Basic_i128:
  1901. case Basic_int:
  1902. case Basic_i16le:
  1903. case Basic_i32le:
  1904. case Basic_i64le:
  1905. case Basic_i128le:
  1906. case Basic_i16be:
  1907. case Basic_i32be:
  1908. case Basic_i64be:
  1909. case Basic_i128be:
  1910. {
  1911. // return imin <= i && i <= imax;
  1912. int a = big_int_cmp(&imin, &i);
  1913. int b = big_int_cmp(&i, &imax);
  1914. return (a <= 0) && (b <= 0);
  1915. }
  1916. case Basic_u8:
  1917. case Basic_u16:
  1918. case Basic_u32:
  1919. case Basic_u64:
  1920. case Basic_u128:
  1921. case Basic_uint:
  1922. case Basic_uintptr:
  1923. case Basic_u16le:
  1924. case Basic_u32le:
  1925. case Basic_u64le:
  1926. case Basic_u128le:
  1927. case Basic_u16be:
  1928. case Basic_u32be:
  1929. case Basic_u64be:
  1930. case Basic_u128be:
  1931. {
  1932. // return 0ull <= i && i <= umax;
  1933. int b = big_int_cmp(&i, &umax);
  1934. return !i.sign && (b <= 0);
  1935. }
  1936. case Basic_UntypedInteger:
  1937. return true;
  1938. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1939. }
  1940. } else if (is_type_float(type)) {
  1941. ExactValue v = exact_value_to_float(in_value);
  1942. if (v.kind != ExactValue_Float) {
  1943. return false;
  1944. }
  1945. if (out_value) *out_value = v;
  1946. switch (type->Basic.kind) {
  1947. case Basic_f16:
  1948. case Basic_f32:
  1949. case Basic_f64:
  1950. return true;
  1951. case Basic_f16le:
  1952. case Basic_f16be:
  1953. case Basic_f32le:
  1954. case Basic_f32be:
  1955. case Basic_f64le:
  1956. case Basic_f64be:
  1957. return true;
  1958. case Basic_UntypedFloat:
  1959. return true;
  1960. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1961. }
  1962. } else if (is_type_complex(type)) {
  1963. ExactValue v = exact_value_to_complex(in_value);
  1964. if (v.kind != ExactValue_Complex) {
  1965. return false;
  1966. }
  1967. switch (type->Basic.kind) {
  1968. case Basic_complex32:
  1969. case Basic_complex64:
  1970. case Basic_complex128: {
  1971. ExactValue real = exact_value_real(v);
  1972. ExactValue imag = exact_value_imag(v);
  1973. if (real.kind != ExactValue_Invalid &&
  1974. imag.kind != ExactValue_Invalid) {
  1975. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1976. return true;
  1977. }
  1978. break;
  1979. }
  1980. case Basic_UntypedComplex:
  1981. return true;
  1982. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1983. }
  1984. return false;
  1985. } else if (is_type_quaternion(type)) {
  1986. ExactValue v = exact_value_to_quaternion(in_value);
  1987. if (v.kind != ExactValue_Quaternion) {
  1988. return false;
  1989. }
  1990. switch (type->Basic.kind) {
  1991. case Basic_quaternion64:
  1992. case Basic_quaternion128:
  1993. case Basic_quaternion256: {
  1994. ExactValue real = exact_value_real(v);
  1995. ExactValue imag = exact_value_imag(v);
  1996. ExactValue jmag = exact_value_jmag(v);
  1997. ExactValue kmag = exact_value_kmag(v);
  1998. if (real.kind != ExactValue_Invalid &&
  1999. imag.kind != ExactValue_Invalid) {
  2000. 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));
  2001. return true;
  2002. }
  2003. break;
  2004. }
  2005. case Basic_UntypedComplex:
  2006. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  2007. return true;
  2008. case Basic_UntypedQuaternion:
  2009. return true;
  2010. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  2011. }
  2012. return false;
  2013. } else if (is_type_pointer(type)) {
  2014. if (in_value.kind == ExactValue_Pointer) {
  2015. return true;
  2016. }
  2017. if (in_value.kind == ExactValue_Integer) {
  2018. return false;
  2019. // return true;
  2020. }
  2021. if (in_value.kind == ExactValue_String) {
  2022. return false;
  2023. }
  2024. if (out_value) *out_value = in_value;
  2025. } else if (is_type_bit_set(type)) {
  2026. if (in_value.kind == ExactValue_Integer) {
  2027. return true;
  2028. }
  2029. }
  2030. return false;
  2031. }
  2032. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  2033. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  2034. gbString b = type_to_string(type);
  2035. defer (gb_string_free(b));
  2036. if (is_type_enum(o->type)) {
  2037. if (check_is_castable_to(c, o, type)) {
  2038. gbString ot = type_to_string(o->type);
  2039. error_line("\tSuggestion: Try casting the '%s' expression to '%s'", ot, b);
  2040. gb_string_free(ot);
  2041. }
  2042. return true;
  2043. }
  2044. i64 sz = type_size_of(type);
  2045. i64 bit_size = 8*sz;
  2046. bool size_changed = false;
  2047. if (max_bit_size > 0) {
  2048. size_changed = (bit_size != max_bit_size);
  2049. bit_size = gb_min(bit_size, max_bit_size);
  2050. }
  2051. BigInt *bi = &o->value.value_integer;
  2052. if (is_type_unsigned(type)) {
  2053. BigInt one = big_int_make_u64(1);
  2054. BigInt max_size = big_int_make_u64(1);
  2055. BigInt bits = big_int_make_i64(bit_size);
  2056. big_int_shl_eq(&max_size, &bits);
  2057. big_int_sub_eq(&max_size, &one);
  2058. if (big_int_is_neg(bi)) {
  2059. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  2060. BigInt dst = {};
  2061. big_int_neg(&dst, bi);
  2062. if (big_int_cmp(&dst, &max_size) < 0) {
  2063. big_int_sub_eq(&dst, &one);
  2064. String dst_str = big_int_to_string(temporary_allocator(), &dst);
  2065. gbString t = type_to_string(type);
  2066. error_line("\tSuggestion: ~%s(%.*s)\n", t, LIT(dst_str));
  2067. gb_string_free(t);
  2068. }
  2069. } else {
  2070. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2071. if (size_changed) {
  2072. 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));
  2073. } else {
  2074. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2075. }
  2076. }
  2077. } else {
  2078. BigInt zero = big_int_make_u64(0);
  2079. BigInt one = big_int_make_u64(1);
  2080. BigInt max_size = big_int_make_u64(1);
  2081. BigInt bits = big_int_make_i64(bit_size - 1);
  2082. big_int_shl_eq(&max_size, &bits);
  2083. String max_size_str = {};
  2084. if (big_int_is_neg(bi)) {
  2085. big_int_neg(&max_size, &max_size);
  2086. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2087. } else {
  2088. big_int_sub_eq(&max_size, &one);
  2089. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2090. }
  2091. if (size_changed) {
  2092. 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));
  2093. } else {
  2094. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2095. }
  2096. }
  2097. return true;
  2098. }
  2099. return false;
  2100. }
  2101. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  2102. gbString a = expr_to_string(o->expr);
  2103. gbString b = type_to_string(type);
  2104. defer(
  2105. gb_string_free(b);
  2106. gb_string_free(a);
  2107. );
  2108. Type *src = base_type(o->type);
  2109. Type *dst = base_type(type);
  2110. if (is_type_array(src) && is_type_slice(dst)) {
  2111. Type *s = src->Array.elem;
  2112. Type *d = dst->Slice.elem;
  2113. if (are_types_identical(s, d)) {
  2114. error_line("\tSuggestion: The array expression may be sliced with %s[:]\n", a);
  2115. }
  2116. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  2117. Type *s = src->DynamicArray.elem;
  2118. Type *d = dst->Slice.elem;
  2119. if (are_types_identical(s, d)) {
  2120. error_line("\tSuggestion: The dynamic array expression may be sliced with %s[:]\n", a);
  2121. }
  2122. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  2123. error_line("\tSuggestion: The expression may be directly casted to type %s\n", b);
  2124. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2125. error_line("\tSuggestion: A string may be transmuted to %s\n", b);
  2126. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable,\n");
  2127. error_line("\t whereas slices in general are assumed to be mutable.\n");
  2128. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  2129. error_line("\tSuggestion: The expression may be casted to %s\n", b);
  2130. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  2131. return;
  2132. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  2133. gbString s = expr_to_string(c->type_hint_expr);
  2134. error_line("\tSuggestion: Make sure that `%s` is attached to the compound literal directly\n", s);
  2135. gb_string_free(s);
  2136. } else if (is_type_pointer(type) &&
  2137. o->mode == Addressing_Variable &&
  2138. are_types_identical(type_deref(type), o->type)) {
  2139. gbString s = expr_to_string(o->expr);
  2140. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  2141. gb_string_free(s);
  2142. } else if (is_type_pointer(o->type) &&
  2143. are_types_identical(type_deref(o->type), type)) {
  2144. gbString s = expr_to_string(o->expr);
  2145. error_line("\tSuggestion: Did you mean `%s^`\n", s);
  2146. gb_string_free(s);
  2147. }
  2148. }
  2149. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  2150. gbString a = expr_to_string(o->expr);
  2151. gbString b = type_to_string(type);
  2152. defer(
  2153. gb_string_free(b);
  2154. gb_string_free(a);
  2155. );
  2156. Type *src = base_type(o->type);
  2157. Type *dst = base_type(type);
  2158. if (is_type_array(src) && is_type_slice(dst)) {
  2159. Type *s = src->Array.elem;
  2160. Type *d = dst->Slice.elem;
  2161. if (are_types_identical(s, d)) {
  2162. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2163. }
  2164. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  2165. if (is_type_uintptr(type)) {
  2166. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  2167. } else {
  2168. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  2169. i64 x = type_size_of(o->type);
  2170. i64 y = type_size_of(type);
  2171. if (x != y) {
  2172. 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);
  2173. }
  2174. }
  2175. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2176. if (is_type_uintptr(o->type)) {
  2177. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2178. } else {
  2179. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2180. }
  2181. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2182. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2183. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2184. return;
  2185. }
  2186. }
  2187. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2188. GB_ASSERT(o->mode == Addressing_Constant);
  2189. ExactValue out_value = o->value;
  2190. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2191. o->value = out_value;
  2192. return true;
  2193. } else {
  2194. o->value = out_value;
  2195. gbString a = expr_to_string(o->expr);
  2196. gbString b = type_to_string(type);
  2197. gbString c = type_to_string(o->type);
  2198. gbString s = exact_value_to_string(o->value);
  2199. defer(
  2200. gb_string_free(s);
  2201. gb_string_free(c);
  2202. gb_string_free(b);
  2203. gb_string_free(a);
  2204. o->mode = Addressing_Invalid;
  2205. );
  2206. ERROR_BLOCK();
  2207. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2208. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2209. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2210. } else {
  2211. i64 max_bit_size = 0;
  2212. if (ctx->bit_field_bit_size) {
  2213. max_bit_size = ctx->bit_field_bit_size;
  2214. }
  2215. if (are_types_identical(o->type, type)) {
  2216. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2217. } else {
  2218. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2219. }
  2220. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2221. }
  2222. } else {
  2223. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2224. check_assignment_error_suggestion(ctx, o, type);
  2225. }
  2226. return false;
  2227. }
  2228. }
  2229. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2230. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2231. if (o->expr->SelectorExpr.is_bit_field) {
  2232. return true;
  2233. }
  2234. }
  2235. if (o->mode == Addressing_OptionalOk) {
  2236. Ast *expr = unselector_expr(o->expr);
  2237. if (expr->kind != Ast_TypeAssertion) {
  2238. return true;
  2239. }
  2240. ast_node(ta, TypeAssertion, expr);
  2241. TypeAndValue tv = ta->expr->tav;
  2242. if (is_type_pointer(tv.type)) {
  2243. return false;
  2244. }
  2245. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2246. return false;
  2247. }
  2248. if (is_type_any(tv.type)) {
  2249. return false;
  2250. }
  2251. return true;
  2252. }
  2253. if (o->mode == Addressing_MapIndex) {
  2254. return false;
  2255. }
  2256. Ast *expr = unparen_expr(o->expr);
  2257. if (expr->kind == Ast_CompoundLit) {
  2258. return false;
  2259. }
  2260. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2261. }
  2262. gb_internal ExactValue exact_bit_set_all_set_mask(Type *type) {
  2263. type = base_type(type);
  2264. GB_ASSERT(type->kind == Type_BitSet);
  2265. i64 lower = type->BitSet.lower;
  2266. i64 upper = type->BitSet.upper;
  2267. Type *elem = type->BitSet.elem;
  2268. Type *underlying = type->BitSet.underlying;
  2269. bool is_backed = underlying != nullptr;
  2270. gb_unused(is_backed);
  2271. BigInt b_lower = {};
  2272. BigInt b_upper = {};
  2273. big_int_from_i64(&b_lower, lower);
  2274. big_int_from_i64(&b_upper, upper);
  2275. BigInt one = {};
  2276. big_int_from_u64(&one, 1);
  2277. BigInt mask = {};
  2278. if (elem == nullptr) {
  2279. big_int_from_i64(&mask, -1);
  2280. } else if (is_type_enum(elem)) {
  2281. Type *e = base_type(elem);
  2282. GB_ASSERT(e->kind == Type_Enum);
  2283. gb_unused(e);
  2284. if ((big_int_cmp(&e->Enum.min_value->value_integer, &b_lower) == 0 || is_backed) &&
  2285. big_int_cmp(&e->Enum.max_value->value_integer, &b_upper) == 0) {
  2286. i64 lower_base = is_backed ? gb_min(0, lower) : lower;
  2287. BigInt b_lower_base = {};
  2288. big_int_from_i64(&b_lower_base, lower_base);
  2289. for (Entity *f : e->Enum.fields) {
  2290. if (f->kind != Entity_Constant) {
  2291. continue;
  2292. }
  2293. if (f->Constant.value.kind != ExactValue_Integer) {
  2294. continue;
  2295. }
  2296. BigInt shift_amount = {};
  2297. big_int_sub(&shift_amount, &f->Constant.value.value_integer, &b_lower_base);
  2298. BigInt value = {};
  2299. big_int_shl(&value, &one, &shift_amount);
  2300. big_int_or(&mask, &mask, &value);
  2301. }
  2302. } else {
  2303. // TODO(bill): enum range based");
  2304. big_int_from_i64(&mask, -1);
  2305. }
  2306. } else {
  2307. i64 lower_base = lower;
  2308. for (i64 x = lower; x <= upper; x++) {
  2309. BigInt shift_amount = {};
  2310. big_int_from_i64(&shift_amount, x - lower_base);
  2311. BigInt value = {};
  2312. big_int_shl(&value, &one, &shift_amount);
  2313. big_int_or(&mask, &mask, &value);
  2314. }
  2315. }
  2316. ExactValue res = {};
  2317. res.kind = ExactValue_Integer;
  2318. res.value_integer = mask;
  2319. return res;
  2320. }
  2321. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2322. switch (op.kind) {
  2323. case Token_And: { // Pointer address
  2324. if (check_is_not_addressable(c, o)) {
  2325. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2326. ast_node(ue, UnaryExpr, node);
  2327. gbString str = expr_to_string(ue->expr);
  2328. defer (gb_string_free(str));
  2329. Entity *e = entity_of_node(ue->expr);
  2330. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2331. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2332. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2333. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2334. } else {
  2335. switch (o->mode) {
  2336. case Addressing_Constant:
  2337. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2338. break;
  2339. case Addressing_SwizzleValue:
  2340. case Addressing_SwizzleVariable:
  2341. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2342. break;
  2343. default:
  2344. {
  2345. ERROR_BLOCK();
  2346. error(op, "Cannot take the pointer address of '%s'", str);
  2347. if (e == nullptr) {
  2348. break;
  2349. }
  2350. if ((e->flags & EntityFlag_ForValue) != 0) {
  2351. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2352. if (parent_type != nullptr && is_type_string(parent_type)) {
  2353. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2354. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2355. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2356. } else {
  2357. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2358. }
  2359. if (parent_type != nullptr && is_type_map(parent_type)) {
  2360. error_line("\t Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2361. } else {
  2362. error_line("\t Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2363. }
  2364. }
  2365. if ((e->flags & EntityFlag_SwitchValue) != 0) {
  2366. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2367. error_line("\t Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2368. }
  2369. }
  2370. break;
  2371. }
  2372. }
  2373. }
  2374. o->mode = Addressing_Invalid;
  2375. return;
  2376. }
  2377. if (o->mode == Addressing_SoaVariable) {
  2378. ast_node(ue, UnaryExpr, node);
  2379. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2380. ast_node(ie, IndexExpr, ue->expr);
  2381. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2382. GB_ASSERT(is_type_soa_struct(soa_type));
  2383. o->type = alloc_type_soa_pointer(soa_type);
  2384. } else {
  2385. o->type = alloc_type_pointer(o->type);
  2386. }
  2387. } else {
  2388. o->type = alloc_type_pointer(o->type);
  2389. }
  2390. switch (o->mode) {
  2391. case Addressing_OptionalOk:
  2392. case Addressing_MapIndex:
  2393. o->mode = Addressing_OptionalOkPtr;
  2394. break;
  2395. default:
  2396. o->mode = Addressing_Value;
  2397. break;
  2398. }
  2399. return;
  2400. }
  2401. }
  2402. if (!check_unary_op(c, o, op)) {
  2403. o->mode = Addressing_Invalid;
  2404. return;
  2405. }
  2406. if (o->mode == Addressing_Constant) {
  2407. Type *type = base_type(o->type);
  2408. if (!is_type_constant_type(o->type)) {
  2409. if (is_type_array_like(o->type)) {
  2410. o->mode = Addressing_Value;
  2411. return;
  2412. }
  2413. gbString xt = type_to_string(o->type);
  2414. gbString err_str = expr_to_string(node);
  2415. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2416. gb_string_free(err_str);
  2417. gb_string_free(xt);
  2418. o->mode = Addressing_Invalid;
  2419. return;
  2420. }
  2421. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2422. gbString err_str = expr_to_string(node);
  2423. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2424. gb_string_free(err_str);
  2425. o->mode = Addressing_Invalid;
  2426. return;
  2427. }
  2428. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2429. gbString err_str = expr_to_string(node);
  2430. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2431. gb_string_free(err_str);
  2432. o->mode = Addressing_Invalid;
  2433. return;
  2434. }
  2435. i32 precision = 0;
  2436. if (is_type_typed(type)) {
  2437. precision = cast(i32)(8 * type_size_of(type));
  2438. }
  2439. bool is_unsigned = is_type_unsigned(type);
  2440. if (is_type_rune(type)) {
  2441. GB_ASSERT(!is_unsigned);
  2442. }
  2443. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2444. if (op.kind == Token_Xor && is_type_bit_set(type)) {
  2445. ExactValue mask = exact_bit_set_all_set_mask(type);
  2446. o->value = exact_binary_operator_value(Token_And, o->value, mask);
  2447. }
  2448. if (is_type_typed(type)) {
  2449. if (node != nullptr) {
  2450. o->expr = node;
  2451. }
  2452. check_is_expressible(c, o, type);
  2453. }
  2454. return;
  2455. }
  2456. o->mode = Addressing_Value;
  2457. }
  2458. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2459. if (t == nullptr) {
  2460. return;
  2461. }
  2462. t = base_type(t);
  2463. if (!is_type_comparable(t)) {
  2464. return;
  2465. }
  2466. switch (t->kind) {
  2467. case Type_Basic:
  2468. switch (t->Basic.kind) {
  2469. case Basic_complex32:
  2470. add_package_dependency(c, "runtime", "complex32_eq");
  2471. add_package_dependency(c, "runtime", "complex32_ne");
  2472. break;
  2473. case Basic_complex64:
  2474. add_package_dependency(c, "runtime", "complex64_eq");
  2475. add_package_dependency(c, "runtime", "complex64_ne");
  2476. break;
  2477. case Basic_complex128:
  2478. add_package_dependency(c, "runtime", "complex128_eq");
  2479. add_package_dependency(c, "runtime", "complex128_ne");
  2480. break;
  2481. case Basic_quaternion64:
  2482. add_package_dependency(c, "runtime", "quaternion64_eq");
  2483. add_package_dependency(c, "runtime", "quaternion64_ne");
  2484. break;
  2485. case Basic_quaternion128:
  2486. add_package_dependency(c, "runtime", "quaternion128_eq");
  2487. add_package_dependency(c, "runtime", "quaternion128_ne");
  2488. break;
  2489. case Basic_quaternion256:
  2490. add_package_dependency(c, "runtime", "quaternion256_eq");
  2491. add_package_dependency(c, "runtime", "quaternion256_ne");
  2492. break;
  2493. case Basic_cstring:
  2494. add_package_dependency(c, "runtime", "cstring_eq");
  2495. add_package_dependency(c, "runtime", "cstring_ne");
  2496. break;
  2497. case Basic_string:
  2498. add_package_dependency(c, "runtime", "string_eq");
  2499. add_package_dependency(c, "runtime", "string_ne");
  2500. break;
  2501. }
  2502. break;
  2503. case Type_Struct:
  2504. for (Entity *field : t->Struct.fields) {
  2505. add_comparison_procedures_for_fields(c, field->type);
  2506. }
  2507. break;
  2508. }
  2509. }
  2510. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2511. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2512. bool comp = are_types_identical(x->type, y->type);
  2513. switch (op) {
  2514. case Token_CmpEq: /* comp = comp; */ break;
  2515. case Token_NotEq: comp = !comp; break;
  2516. }
  2517. x->mode = Addressing_Constant;
  2518. x->type = t_untyped_bool;
  2519. x->value = exact_value_bool(comp);
  2520. return;
  2521. }
  2522. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2523. add_type_info_type(c, x->type);
  2524. add_type_info_type(c, y->type);
  2525. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2526. x->mode = Addressing_Value;
  2527. x->type = t_untyped_bool;
  2528. return;
  2529. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2530. add_type_info_type(c, x->type);
  2531. add_type_info_type(c, y->type);
  2532. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2533. x->mode = Addressing_Value;
  2534. x->type = t_untyped_bool;
  2535. return;
  2536. }
  2537. TEMPORARY_ALLOCATOR_GUARD();
  2538. gbString err_str = nullptr;
  2539. if (check_is_assignable_to(c, x, y->type) ||
  2540. check_is_assignable_to(c, y, x->type)) {
  2541. Type *err_type = x->type;
  2542. bool defined = false;
  2543. switch (op) {
  2544. case Token_CmpEq:
  2545. case Token_NotEq:
  2546. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2547. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2548. (is_operand_nil(*y) && type_has_nil(x->type));
  2549. break;
  2550. case Token_Lt:
  2551. case Token_Gt:
  2552. case Token_LtEq:
  2553. case Token_GtEq:
  2554. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2555. defined = true;
  2556. } else {
  2557. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2558. }
  2559. break;
  2560. }
  2561. if (!defined) {
  2562. gbString xs = type_to_string(x->type, temporary_allocator());
  2563. gbString ys = type_to_string(y->type, temporary_allocator());
  2564. if (!is_type_comparable(x->type)) {
  2565. err_str = gb_string_make(temporary_allocator(),
  2566. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", xs, LIT(token_strings[op]))
  2567. );
  2568. } else if (!is_type_comparable(y->type)) {
  2569. err_str = gb_string_make(temporary_allocator(),
  2570. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", ys, LIT(token_strings[op]))
  2571. );
  2572. } else {
  2573. err_str = gb_string_make(temporary_allocator(),
  2574. gb_bprintf("Operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2575. );
  2576. }
  2577. } else {
  2578. Type *comparison_type = x->type;
  2579. if (x->type == err_type && is_operand_nil(*x)) {
  2580. comparison_type = y->type;
  2581. }
  2582. add_comparison_procedures_for_fields(c, comparison_type);
  2583. }
  2584. } else {
  2585. gbString xt, yt;
  2586. if (x->mode == Addressing_ProcGroup) {
  2587. xt = gb_string_make(temporary_allocator(), "procedure group");
  2588. } else {
  2589. xt = type_to_string(x->type);
  2590. }
  2591. if (y->mode == Addressing_ProcGroup) {
  2592. yt = gb_string_make(temporary_allocator(), "procedure group");
  2593. } else {
  2594. yt = type_to_string(y->type);
  2595. }
  2596. err_str = gb_string_make(temporary_allocator(), gb_bprintf("Mismatched types '%s' and '%s'", xt, yt));
  2597. }
  2598. if (err_str != nullptr) {
  2599. error(node, "Cannot compare expression. %s.", err_str);
  2600. x->type = t_untyped_bool;
  2601. } else {
  2602. if (x->mode == Addressing_Constant &&
  2603. y->mode == Addressing_Constant) {
  2604. if (is_type_constant_type(x->type)) {
  2605. if (is_type_bit_set(x->type)) {
  2606. switch (op) {
  2607. case Token_CmpEq:
  2608. case Token_NotEq:
  2609. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2610. break;
  2611. case Token_Lt:
  2612. case Token_LtEq:
  2613. {
  2614. ExactValue lhs = x->value;
  2615. ExactValue rhs = y->value;
  2616. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2617. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2618. if (op == Token_Lt) {
  2619. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2620. }
  2621. x->value = res;
  2622. break;
  2623. }
  2624. case Token_Gt:
  2625. case Token_GtEq:
  2626. {
  2627. ExactValue lhs = x->value;
  2628. ExactValue rhs = y->value;
  2629. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2630. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2631. if (op == Token_Gt) {
  2632. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2633. }
  2634. x->value = res;
  2635. break;
  2636. }
  2637. }
  2638. } else {
  2639. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2640. }
  2641. } else {
  2642. x->mode = Addressing_Value;
  2643. }
  2644. } else {
  2645. x->mode = Addressing_Value;
  2646. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2647. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2648. i64 size = 0;
  2649. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2650. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2651. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2652. switch (op) {
  2653. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2654. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2655. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2656. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2657. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2658. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2659. }
  2660. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2661. switch (op) {
  2662. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2663. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2664. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2665. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2666. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2667. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2668. }
  2669. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2670. switch (op) {
  2671. case Token_CmpEq:
  2672. switch (8*size) {
  2673. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2674. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2675. }
  2676. break;
  2677. case Token_NotEq:
  2678. switch (8*size) {
  2679. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2680. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2681. }
  2682. break;
  2683. }
  2684. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2685. switch (op) {
  2686. case Token_CmpEq:
  2687. switch (8*size) {
  2688. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2689. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2690. }
  2691. break;
  2692. case Token_NotEq:
  2693. switch (8*size) {
  2694. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2695. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2696. }
  2697. break;
  2698. }
  2699. }
  2700. }
  2701. x->type = t_untyped_bool;
  2702. }
  2703. }
  2704. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2705. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2706. ast_node(be, BinaryExpr, node);
  2707. bool y_is_untyped = is_type_untyped(y->type);
  2708. if (y_is_untyped) {
  2709. convert_to_typed(c, y, t_untyped_integer);
  2710. if (y->mode == Addressing_Invalid) {
  2711. x->mode = Addressing_Invalid;
  2712. return;
  2713. }
  2714. } else if (!is_type_unsigned(y->type)) {
  2715. gbString y_str = expr_to_string(y->expr);
  2716. error(y->expr, "Shift amount '%s' must be an unsigned integer", y_str);
  2717. gb_string_free(y_str);
  2718. x->mode = Addressing_Invalid;
  2719. return;
  2720. }
  2721. bool x_is_untyped = is_type_untyped(x->type);
  2722. if (!(x_is_untyped || is_type_integer(x->type))) {
  2723. gbString x_str = expr_to_string(x->expr);
  2724. error(x->expr, "Shifted operand '%s' must be an integer", x_str);
  2725. gb_string_free(x_str);
  2726. x->mode = Addressing_Invalid;
  2727. return;
  2728. }
  2729. if (y->mode == Addressing_Constant) {
  2730. if (big_int_is_neg(&y->value.value_integer)) {
  2731. gbString y_str = expr_to_string(y->expr);
  2732. error(y->expr, "Shift amount '%s' cannot be negative", y_str);
  2733. gb_string_free(y_str);
  2734. x->mode = Addressing_Invalid;
  2735. return;
  2736. }
  2737. BigInt max_shift = {};
  2738. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2739. if (big_int_cmp(&y->value.value_integer, &max_shift) > 0) {
  2740. gbString y_str = expr_to_string(y->expr);
  2741. error(y->expr, "Shift amount '%s' must be <= %u", y_str, MAX_BIG_INT_SHIFT);
  2742. gb_string_free(y_str);
  2743. x->mode = Addressing_Invalid;
  2744. return;
  2745. }
  2746. if (x->mode == Addressing_Constant) {
  2747. if (x_is_untyped) {
  2748. convert_to_typed(c, x, t_untyped_integer);
  2749. if (x->mode == Addressing_Invalid) {
  2750. return;
  2751. }
  2752. x->expr = node;
  2753. x->value = exact_value_shift(be->op.kind, exact_value_to_integer(x->value), exact_value_to_integer(y->value));
  2754. return;
  2755. }
  2756. x->expr = node;
  2757. x->value = exact_value_shift(be->op.kind, x->value, y->value);
  2758. check_is_expressible(c, x, x->type);
  2759. return;
  2760. }
  2761. if (y_is_untyped) {
  2762. convert_to_typed(c, y, t_uint);
  2763. }
  2764. return;
  2765. }
  2766. if (x->mode == Addressing_Constant) {
  2767. if (x_is_untyped) {
  2768. if (type_hint) {
  2769. if (is_type_integer(type_hint)) {
  2770. convert_to_typed(c, x, type_hint);
  2771. } else if (is_type_any(type_hint)) {
  2772. convert_to_typed(c, x, default_type(t_untyped_integer));
  2773. } else {
  2774. gbString x_str = expr_to_string(x->expr);
  2775. gbString type_str = type_to_string(type_hint);
  2776. error(x->expr, "Shifted operand '%s' cannot convert to non-integer type '%s'", x_str, type_str);
  2777. gb_string_free(x_str);
  2778. gb_string_free(type_str);
  2779. x->mode = Addressing_Invalid;
  2780. return;
  2781. }
  2782. } else {
  2783. check_is_expressible(c, x, default_type(t_untyped_integer));
  2784. }
  2785. if (x->mode == Addressing_Invalid) {
  2786. return;
  2787. }
  2788. }
  2789. x->mode = Addressing_Value;
  2790. }
  2791. }
  2792. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2793. if (check_is_assignable_to(c, operand, y)) {
  2794. return true;
  2795. }
  2796. bool is_constant = operand->mode == Addressing_Constant;
  2797. Type *x = operand->type;
  2798. Type *src = core_type(x);
  2799. Type *dst = core_type(y);
  2800. if (are_types_identical(src, dst)) {
  2801. return true;
  2802. }
  2803. // if (is_type_tuple(src)) {
  2804. // Ast *expr = unparen_expr(operand->expr);
  2805. // if (expr && expr->kind == Ast_CallExpr) {
  2806. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2807. // ast_node(ce, CallExpr, expr);
  2808. // Type *pt = base_type(type_of_expr(ce->proc));
  2809. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2810. // if (pt->Proc.result_count > 0) {
  2811. // Operand op = *operand;
  2812. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2813. // bool ok = check_is_castable_to(c, &op, y);
  2814. // if (ok) {
  2815. // ce->optional_ok_one = true;
  2816. // }
  2817. // return ok;
  2818. // }
  2819. // }
  2820. // }
  2821. // }
  2822. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2823. if (is_type_u8_array(dst)) {
  2824. String s = operand->value.value_string;
  2825. return s.len == dst->Array.count;
  2826. }
  2827. if (is_type_rune_array(dst)) {
  2828. String s = operand->value.value_string;
  2829. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2830. }
  2831. }
  2832. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2833. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2834. return dst->Array.count == src->Array.count;
  2835. }
  2836. }
  2837. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2838. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2839. }
  2840. // Cast between booleans and integers
  2841. if (is_type_boolean(src) || is_type_integer(src)) {
  2842. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2843. return true;
  2844. }
  2845. }
  2846. // Cast between numbers
  2847. if (is_type_integer(src) || is_type_float(src)) {
  2848. if (is_type_integer(dst) || is_type_float(dst)) {
  2849. return true;
  2850. }
  2851. }
  2852. if (is_type_bit_field(src)) {
  2853. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2854. }
  2855. if (is_type_bit_field(dst)) {
  2856. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2857. }
  2858. if (is_type_integer(src) && is_type_rune(dst)) {
  2859. return true;
  2860. }
  2861. if (is_type_rune(src) && is_type_integer(dst)) {
  2862. return true;
  2863. }
  2864. if (is_type_complex(src) && is_type_complex(dst)) {
  2865. return true;
  2866. }
  2867. if (is_type_float(src) && is_type_complex(dst)) {
  2868. return true;
  2869. }
  2870. if (is_type_float(src) && is_type_quaternion(dst)) {
  2871. return true;
  2872. }
  2873. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2874. return true;
  2875. }
  2876. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2877. return true;
  2878. }
  2879. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2880. GB_ASSERT(src->kind == Type_Matrix);
  2881. GB_ASSERT(dst->kind == Type_Matrix);
  2882. Operand op = *operand;
  2883. op.type = src->Matrix.elem;
  2884. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2885. return false;
  2886. }
  2887. if (src->Matrix.row_count != src->Matrix.column_count) {
  2888. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2889. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2890. return src_count == dst_count;
  2891. }
  2892. return is_matrix_square(dst) && is_matrix_square(src);
  2893. }
  2894. // Cast between pointers
  2895. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2896. return true;
  2897. }
  2898. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2899. return true;
  2900. }
  2901. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2902. return true;
  2903. }
  2904. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2905. return true;
  2906. }
  2907. // uintptr <-> pointer
  2908. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2909. return true;
  2910. }
  2911. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2912. return true;
  2913. }
  2914. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2915. return true;
  2916. }
  2917. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2918. return true;
  2919. }
  2920. // []byte/[]u8 <-> string (not cstring)
  2921. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2922. return true;
  2923. }
  2924. // cstring -> string
  2925. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2926. if (operand->mode != Addressing_Constant) {
  2927. add_package_dependency(c, "runtime", "cstring_to_string");
  2928. }
  2929. return true;
  2930. }
  2931. // cstring -> ^u8
  2932. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2933. return !is_constant;
  2934. }
  2935. // cstring -> [^]u8
  2936. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2937. return !is_constant;
  2938. }
  2939. // cstring -> rawptr
  2940. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2941. return !is_constant;
  2942. }
  2943. // ^u8 -> cstring
  2944. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2945. return !is_constant;
  2946. }
  2947. // [^]u8 -> cstring
  2948. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2949. return !is_constant;
  2950. }
  2951. // rawptr -> cstring
  2952. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2953. return !is_constant;
  2954. }
  2955. // proc <-> proc
  2956. if (is_type_proc(src) && is_type_proc(dst)) {
  2957. if (is_type_polymorphic(dst)) {
  2958. if (is_type_polymorphic(src) &&
  2959. operand->mode == Addressing_Variable) {
  2960. return true;
  2961. }
  2962. return false;
  2963. }
  2964. return true;
  2965. }
  2966. // proc -> rawptr
  2967. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2968. return true;
  2969. }
  2970. // rawptr -> proc
  2971. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2972. return true;
  2973. }
  2974. if (is_type_array(dst)) {
  2975. Type *elem = base_array_type(dst);
  2976. if (check_is_castable_to(c, operand, elem)) {
  2977. return true;
  2978. }
  2979. }
  2980. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2981. if (src->SimdVector.count != dst->SimdVector.count) {
  2982. return false;
  2983. }
  2984. Type *elem_src = base_array_type(src);
  2985. Type *elem_dst = base_array_type(dst);
  2986. Operand x = {};
  2987. x.type = elem_src;
  2988. x.mode = Addressing_Value;
  2989. return check_is_castable_to(c, &x, elem_dst);
  2990. }
  2991. if (is_type_simd_vector(dst)) {
  2992. Type *elem = base_array_type(dst);
  2993. if (check_is_castable_to(c, operand, elem)) {
  2994. return true;
  2995. }
  2996. }
  2997. return false;
  2998. }
  2999. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  3000. bool is_const_expr = x->mode == Addressing_Constant;
  3001. Type *bt = base_type(type);
  3002. if (is_const_expr && is_type_constant_type(bt)) {
  3003. if (core_type(bt)->kind == Type_Basic) {
  3004. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  3005. return true;
  3006. } else if (check_is_castable_to(c, x, type)) {
  3007. if (is_type_pointer(type)) {
  3008. return true;
  3009. }
  3010. }
  3011. } else if (check_is_castable_to(c, x, type)) {
  3012. x->value = {};
  3013. x->mode = Addressing_Value;
  3014. return true;
  3015. }
  3016. } else if (check_is_castable_to(c, x, type)) {
  3017. if (x->mode != Addressing_Constant) {
  3018. x->mode = Addressing_Value;
  3019. } else if (is_type_slice(type) && is_type_string(x->type)) {
  3020. x->mode = Addressing_Value;
  3021. } else if (is_type_union(type)) {
  3022. x->mode = Addressing_Value;
  3023. }
  3024. if (x->mode == Addressing_Value) {
  3025. x->value = {};
  3026. }
  3027. return true;
  3028. }
  3029. return false;
  3030. }
  3031. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type, bool forbid_identical = false) {
  3032. if (!is_operand_value(*x)) {
  3033. error(x->expr, "Only values can be casted");
  3034. x->mode = Addressing_Invalid;
  3035. return;
  3036. }
  3037. bool is_const_expr = x->mode == Addressing_Constant;
  3038. bool can_convert = check_cast_internal(c, x, type);
  3039. if (!can_convert) {
  3040. TEMPORARY_ALLOCATOR_GUARD();
  3041. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  3042. gbString to_type = type_to_string(type, temporary_allocator());
  3043. gbString from_type = type_to_string(x->type, temporary_allocator());
  3044. x->mode = Addressing_Invalid;
  3045. ERROR_BLOCK();
  3046. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  3047. if (is_const_expr) {
  3048. gbString val_str = exact_value_to_string(x->value);
  3049. if (is_type_float(x->type) && is_type_integer(type)) {
  3050. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  3051. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3052. x->mode = Addressing_Constant;
  3053. x->type = type;
  3054. } else {
  3055. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  3056. if (is_type_numeric(type)) {
  3057. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3058. x->mode = Addressing_Constant;
  3059. x->type = type;
  3060. }
  3061. }
  3062. gb_string_free(val_str);
  3063. }
  3064. check_cast_error_suggestion(c, x, type);
  3065. return;
  3066. }
  3067. if (is_type_untyped(x->type)) {
  3068. Type *final_type = type;
  3069. if (is_const_expr && !is_type_constant_type(type)) {
  3070. if (is_type_union(type)) {
  3071. convert_to_typed(c, x, type);
  3072. }
  3073. final_type = default_type(x->type);
  3074. }
  3075. update_untyped_expr_type(c, x->expr, final_type, true);
  3076. } else {
  3077. Type *src = core_type(x->type);
  3078. Type *dst = core_type(type);
  3079. if (src != dst) {
  3080. bool const REQUIRE = true;
  3081. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  3082. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  3083. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  3084. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  3085. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  3086. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  3087. } else if (src == t_f16 && is_type_float(dst)) {
  3088. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  3089. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  3090. } else if (is_type_float(dst) && dst == t_f16) {
  3091. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  3092. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  3093. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  3094. }
  3095. }
  3096. // If we check polymorphic procedures, we risk erring on
  3097. // identical casts that cannot be foreseen or otherwise
  3098. // forbidden, so just skip them.
  3099. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3100. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig))) {
  3101. Type *src_exact = x->type;
  3102. Type *dst_exact = type;
  3103. if (src_exact != nullptr &&
  3104. dst_exact != nullptr &&
  3105. are_types_identical(src_exact, dst_exact)
  3106. ) {
  3107. gbString oper_str = expr_to_string(x->expr);
  3108. gbString to_type = type_to_string(dst_exact);
  3109. error(x->expr, "Unneeded cast of '%s' to identical type '%s'", oper_str, to_type);
  3110. gb_string_free(oper_str);
  3111. gb_string_free(to_type);
  3112. }
  3113. }
  3114. }
  3115. x->type = type;
  3116. }
  3117. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t, bool forbid_identical = false) {
  3118. if (!is_operand_value(*o)) {
  3119. error(o->expr, "'transmute' can only be applied to values");
  3120. o->mode = Addressing_Invalid;
  3121. return false;
  3122. }
  3123. Operand src = *o;
  3124. Type *src_t = o->type;
  3125. Type *dst_t = t;
  3126. Type *src_bt = base_type(src_t);
  3127. Type *dst_bt = base_type(dst_t);
  3128. if (is_type_untyped(src_t)) {
  3129. gbString expr_str = expr_to_string(o->expr);
  3130. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  3131. gb_string_free(expr_str);
  3132. o->mode = Addressing_Invalid;
  3133. o->expr = node;
  3134. return false;
  3135. }
  3136. if (dst_bt == nullptr || dst_bt == t_invalid) {
  3137. GB_ASSERT(global_error_collector.count != 0);
  3138. o->mode = Addressing_Invalid;
  3139. o->expr = node;
  3140. return false;
  3141. }
  3142. if (src_bt == nullptr || src_bt == t_invalid) {
  3143. // NOTE(bill): this should be an error
  3144. GB_ASSERT(global_error_collector.count != 0);
  3145. o->mode = Addressing_Value;
  3146. o->expr = node;
  3147. o->type = dst_t;
  3148. return true;
  3149. }
  3150. i64 srcz = type_size_of(src_t);
  3151. i64 dstz = type_size_of(dst_t);
  3152. if (srcz != dstz) {
  3153. gbString expr_str = expr_to_string(o->expr);
  3154. gbString type_str = type_to_string(dst_t);
  3155. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  3156. gb_string_free(type_str);
  3157. gb_string_free(expr_str);
  3158. o->mode = Addressing_Invalid;
  3159. o->expr = node;
  3160. return false;
  3161. }
  3162. o->expr = node;
  3163. o->type = dst_t;
  3164. if (o->mode == Addressing_Constant) {
  3165. if (are_types_identical(src_bt, dst_bt)) {
  3166. return true;
  3167. }
  3168. if ((is_type_integer(src_t) && is_type_integer(dst_t)) ||
  3169. is_type_integer(src_t) && is_type_bit_set(dst_t)) {
  3170. if (types_have_same_internal_endian(src_t, dst_t)) {
  3171. ExactValue src_v = exact_value_to_integer(o->value);
  3172. GB_ASSERT(src_v.kind == ExactValue_Integer || src_v.kind == ExactValue_Invalid);
  3173. BigInt v = src_v.value_integer;
  3174. BigInt smax = {};
  3175. BigInt umax = {};
  3176. big_int_from_u64(&smax, 0);
  3177. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  3178. big_int_from_u64(&umax, 1);
  3179. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  3180. big_int_shl_eq(&umax, &sz_in_bits);
  3181. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  3182. if (big_int_cmp(&v, &smax) >= 0) {
  3183. big_int_sub_eq(&v, &umax);
  3184. }
  3185. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  3186. if (big_int_is_neg(&v)) {
  3187. big_int_add_eq(&v, &umax);
  3188. }
  3189. }
  3190. o->value.kind = ExactValue_Integer;
  3191. o->value.value_integer = v;
  3192. return true;
  3193. }
  3194. }
  3195. } else {
  3196. // If we check polymorphic procedures, we risk erring on
  3197. // identical casts that cannot be foreseen or otherwise
  3198. // forbidden, so just skip them.
  3199. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3200. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig)) &&
  3201. check_is_castable_to(c, &src, dst_t)) {
  3202. if (are_types_identical(src_t, dst_t)) {
  3203. gbString oper_str = expr_to_string(o->expr);
  3204. gbString to_type = type_to_string(dst_t);
  3205. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3206. gb_string_free(oper_str);
  3207. gb_string_free(to_type);
  3208. } else if (is_type_internally_pointer_like(src_t) &&
  3209. is_type_internally_pointer_like(dst_t)) {
  3210. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since the types are pointer-like");
  3211. } else if (are_types_identical(src_bt, dst_bt)) {
  3212. gbString oper_str = expr_to_string(o->expr);
  3213. gbString to_type = type_to_string(dst_t);
  3214. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3215. gb_string_free(oper_str);
  3216. gb_string_free(to_type);
  3217. } else if (is_type_integer(src_t) && is_type_integer(dst_t) &&
  3218. types_have_same_internal_endian(src_t, dst_t) &&
  3219. type_endian_kind_of(src_t) == type_endian_kind_of(dst_t)) {
  3220. gbString oper_type = type_to_string(src_t);
  3221. gbString to_type = type_to_string(dst_t);
  3222. 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);
  3223. gb_string_free(to_type);
  3224. gb_string_free(oper_type);
  3225. }
  3226. }
  3227. }
  3228. o->mode = Addressing_Value;
  3229. o->value = {};
  3230. return true;
  3231. }
  3232. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  3233. if (is_type_array_like(x->type) || is_type_array_like(y->type)) {
  3234. if (op.kind == Token_CmpAnd || op.kind == Token_CmpOr) {
  3235. error(op, "Array programming is not allowed with the operator '%.*s'", LIT(op.string));
  3236. }
  3237. }
  3238. if (is_type_array(x->type) && !is_type_array(y->type)) {
  3239. if (check_is_assignable_to(c, y, x->type)) {
  3240. if (check_binary_op(c, x, op)) {
  3241. return true;
  3242. }
  3243. }
  3244. }
  3245. if (is_type_simd_vector(x->type) && !is_type_simd_vector(y->type)) {
  3246. if (check_is_assignable_to(c, y, x->type)) {
  3247. if (check_binary_op(c, x, op)) {
  3248. return true;
  3249. }
  3250. }
  3251. }
  3252. return false;
  3253. }
  3254. gb_internal bool is_ise_expr(Ast *node) {
  3255. node = unparen_expr(node);
  3256. return node->kind == Ast_ImplicitSelectorExpr;
  3257. }
  3258. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  3259. if (use_lhs_as_type_hint) { // RHS in this case
  3260. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  3261. }
  3262. return false;
  3263. }
  3264. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  3265. Type *xt = base_type(matrix);
  3266. if (type_hint != nullptr) {
  3267. Type *th = base_type(type_hint);
  3268. if (are_types_identical(th, xt)) {
  3269. return type_hint;
  3270. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  3271. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  3272. // ignore
  3273. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  3274. xt->Matrix.column_count == th->Matrix.column_count) {
  3275. return type_hint;
  3276. }
  3277. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  3278. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  3279. // ignore
  3280. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  3281. return type_hint;
  3282. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3283. return type_hint;
  3284. }
  3285. }
  3286. }
  3287. return matrix;
  3288. }
  3289. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3290. if (!check_binary_op(c, x, op)) {
  3291. x->mode = Addressing_Invalid;
  3292. return;
  3293. }
  3294. Type *xt = base_type(x->type);
  3295. Type *yt = base_type(y->type);
  3296. if (is_type_matrix(x->type)) {
  3297. GB_ASSERT(xt->kind == Type_Matrix);
  3298. if (op.kind == Token_Mul) {
  3299. if (yt->kind == Type_Matrix) {
  3300. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3301. goto matrix_error;
  3302. }
  3303. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3304. goto matrix_error;
  3305. }
  3306. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3307. goto matrix_error;
  3308. }
  3309. x->mode = Addressing_Value;
  3310. if (are_types_identical(xt, yt)) {
  3311. if (are_types_identical(x->type, y->type)) {
  3312. return;
  3313. }
  3314. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3315. // prefer the named type
  3316. x->type = y->type;
  3317. }
  3318. } else {
  3319. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3320. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3321. }
  3322. goto matrix_success;
  3323. } else if (yt->kind == Type_Array) {
  3324. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3325. goto matrix_error;
  3326. }
  3327. if (xt->Matrix.column_count != yt->Array.count) {
  3328. goto matrix_error;
  3329. }
  3330. // Treat arrays as column vectors
  3331. x->mode = Addressing_Value;
  3332. if (xt->Matrix.row_count == yt->Array.count) {
  3333. x->type = y->type;
  3334. } else {
  3335. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3336. }
  3337. goto matrix_success;
  3338. }
  3339. }
  3340. if (!are_types_identical(xt, yt)) {
  3341. goto matrix_error;
  3342. }
  3343. x->mode = Addressing_Value;
  3344. x->type = xt;
  3345. goto matrix_success;
  3346. } else {
  3347. GB_ASSERT(!is_type_matrix(xt));
  3348. GB_ASSERT(is_type_matrix(yt));
  3349. if (op.kind == Token_Mul) {
  3350. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3351. if (xt->kind == Type_Array) {
  3352. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3353. goto matrix_error;
  3354. }
  3355. if (xt->Array.count != yt->Matrix.row_count) {
  3356. goto matrix_error;
  3357. }
  3358. // Treat arrays as row vectors
  3359. x->mode = Addressing_Value;
  3360. if (yt->Matrix.column_count == xt->Array.count) {
  3361. x->type = x->type;
  3362. } else {
  3363. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3364. }
  3365. goto matrix_success;
  3366. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3367. x->type = check_matrix_type_hint(y->type, type_hint);
  3368. return;
  3369. }
  3370. }
  3371. if (!are_types_identical(xt, yt)) {
  3372. goto matrix_error;
  3373. }
  3374. x->mode = Addressing_Value;
  3375. x->type = xt;
  3376. goto matrix_success;
  3377. }
  3378. matrix_success:
  3379. x->type = check_matrix_type_hint(x->type, type_hint);
  3380. return;
  3381. matrix_error:
  3382. gbString xts = type_to_string(x->type);
  3383. gbString yts = type_to_string(y->type);
  3384. gbString expr_str = expr_to_string(x->expr);
  3385. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3386. gb_string_free(expr_str);
  3387. gb_string_free(yts);
  3388. gb_string_free(xts);
  3389. x->type = t_invalid;
  3390. x->mode = Addressing_Invalid;
  3391. return;
  3392. }
  3393. gb_internal void check_binary_expr_dependency(CheckerContext *c, Token op, Type *bt, bool REQUIRE) {
  3394. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3395. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3396. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3397. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3398. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3399. }
  3400. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3401. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3402. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3403. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3404. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3405. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3406. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3407. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3408. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3409. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3410. }
  3411. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3412. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3413. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3414. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3415. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3416. case Basic_u128:
  3417. case Basic_i128:
  3418. if (is_arch_wasm()) {
  3419. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3420. }
  3421. break;
  3422. }
  3423. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3424. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3425. case Basic_u128:
  3426. case Basic_i128:
  3427. if (is_arch_wasm()) {
  3428. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3429. }
  3430. break;
  3431. }
  3432. } else if (op.kind == Token_Shr || op.kind == Token_ShrEq) {
  3433. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3434. case Basic_u128:
  3435. case Basic_i128:
  3436. if (is_arch_wasm()) {
  3437. add_package_dependency(c, "runtime", "__lshrti3", REQUIRE);
  3438. }
  3439. break;
  3440. }
  3441. }
  3442. }
  3443. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3444. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3445. Operand y_ = {}, *y = &y_;
  3446. ast_node(be, BinaryExpr, node);
  3447. defer({
  3448. node->viral_state_flags |= be->left->viral_state_flags;
  3449. node->viral_state_flags |= be->right->viral_state_flags;
  3450. });
  3451. Token op = be->op;
  3452. switch (op.kind) {
  3453. case Token_CmpEq:
  3454. case Token_NotEq: {
  3455. // NOTE(bill): Allow comparisons between types
  3456. if (is_ise_expr(be->left)) {
  3457. // Evalute the right before the left for an '.X' expression
  3458. check_expr_or_type(c, y, be->right, nullptr /* ignore type hint */);
  3459. check_expr_or_type(c, x, be->left, y->type);
  3460. } else {
  3461. check_expr_or_type(c, x, be->left, nullptr /* ignore type hint */);
  3462. check_expr_or_type(c, y, be->right, x->type);
  3463. }
  3464. bool xt = x->mode == Addressing_Type;
  3465. bool yt = y->mode == Addressing_Type;
  3466. // If only one is a type, this is an error
  3467. if (xt ^ yt) {
  3468. GB_ASSERT(xt != yt);
  3469. if (xt) {
  3470. if (!is_type_typeid(y->type)) {
  3471. error_operand_not_expression(x);
  3472. }
  3473. }
  3474. if (yt) {
  3475. if (!is_type_typeid(x->type)) {
  3476. error_operand_not_expression(y);
  3477. }
  3478. }
  3479. }
  3480. break;
  3481. }
  3482. case Token_in:
  3483. case Token_not_in:
  3484. {
  3485. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3486. check_expr(c, y, be->right);
  3487. Type *rhs_type = type_deref(y->type);
  3488. if (rhs_type == nullptr) {
  3489. error(y->expr, "Cannot use '%.*s' on an expression with no value", LIT(op.string));
  3490. x->mode = Addressing_Invalid;
  3491. x->expr = node;
  3492. return;
  3493. }
  3494. if (is_type_bit_set(rhs_type)) {
  3495. Type *elem = base_type(rhs_type)->BitSet.elem;
  3496. check_expr_with_type_hint(c, x, be->left, elem);
  3497. } else if (is_type_map(rhs_type)) {
  3498. Type *key = base_type(rhs_type)->Map.key;
  3499. check_expr_with_type_hint(c, x, be->left, key);
  3500. } else {
  3501. check_expr(c, x, be->left);
  3502. }
  3503. if (x->mode == Addressing_Invalid) {
  3504. return;
  3505. }
  3506. if (y->mode == Addressing_Invalid) {
  3507. x->mode = Addressing_Invalid;
  3508. x->expr = y->expr;
  3509. return;
  3510. }
  3511. if (is_type_map(rhs_type)) {
  3512. Type *yt = base_type(rhs_type);
  3513. if (op.kind == Token_in) {
  3514. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3515. } else {
  3516. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3517. }
  3518. add_map_get_dependencies(c);
  3519. } else if (is_type_bit_set(rhs_type)) {
  3520. Type *yt = base_type(rhs_type);
  3521. if (op.kind == Token_in) {
  3522. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3523. } else {
  3524. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3525. }
  3526. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3527. ExactValue k = exact_value_to_integer(x->value);
  3528. ExactValue v = exact_value_to_integer(y->value);
  3529. GB_ASSERT(k.kind == ExactValue_Integer);
  3530. GB_ASSERT(v.kind == ExactValue_Integer);
  3531. i64 key = big_int_to_i64(&k.value_integer);
  3532. i64 lower = yt->BitSet.lower;
  3533. i64 upper = yt->BitSet.upper;
  3534. if (lower <= key && key <= upper) {
  3535. i64 bit = 1ll<<key;
  3536. i64 bits = big_int_to_i64(&v.value_integer);
  3537. x->mode = Addressing_Constant;
  3538. x->type = t_untyped_bool;
  3539. if (op.kind == Token_in) {
  3540. x->value = exact_value_bool((bit & bits) != 0);
  3541. } else {
  3542. x->value = exact_value_bool((bit & bits) == 0);
  3543. }
  3544. x->expr = node;
  3545. return;
  3546. } else {
  3547. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3548. x->mode = Addressing_Invalid;
  3549. }
  3550. }
  3551. } else {
  3552. gbString t = type_to_string(y->type);
  3553. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3554. gb_string_free(t);
  3555. x->expr = node;
  3556. x->mode = Addressing_Invalid;
  3557. return;
  3558. }
  3559. if (x->mode != Addressing_Invalid) {
  3560. x->mode = Addressing_Value;
  3561. x->type = t_untyped_bool;
  3562. }
  3563. x->expr = node;
  3564. return;
  3565. }
  3566. default:
  3567. if (is_ise_expr(be->left)) {
  3568. // Evalute the right before the left for an '.X' expression
  3569. check_expr_or_type(c, y, be->right, type_hint);
  3570. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3571. check_expr_or_type(c, x, be->left, y->type);
  3572. } else {
  3573. check_expr_with_type_hint(c, x, be->left, type_hint);
  3574. }
  3575. } else {
  3576. check_expr_with_type_hint(c, x, be->left, type_hint);
  3577. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3578. check_expr_with_type_hint(c, y, be->right, x->type);
  3579. } else {
  3580. check_expr_with_type_hint(c, y, be->right, type_hint);
  3581. }
  3582. }
  3583. break;
  3584. }
  3585. if (x->mode == Addressing_Invalid) {
  3586. return;
  3587. }
  3588. if (y->mode == Addressing_Invalid) {
  3589. x->mode = Addressing_Invalid;
  3590. x->expr = y->expr;
  3591. return;
  3592. }
  3593. if (x->mode == Addressing_Builtin) {
  3594. x->mode = Addressing_Invalid;
  3595. error(x->expr, "built-in expression in binary expression");
  3596. return;
  3597. }
  3598. if (y->mode == Addressing_Builtin) {
  3599. x->mode = Addressing_Invalid;
  3600. error(y->expr, "built-in expression in binary expression");
  3601. return;
  3602. }
  3603. if (x->mode == Addressing_ProcGroup) {
  3604. x->mode = Addressing_Invalid;
  3605. if (x->proc_group != nullptr) {
  3606. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3607. } else {
  3608. error(x->expr, "procedure group used in binary expression");
  3609. }
  3610. return;
  3611. }
  3612. if (y->mode == Addressing_ProcGroup) {
  3613. x->mode = Addressing_Invalid;
  3614. if (x->proc_group != nullptr) {
  3615. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3616. } else {
  3617. error(y->expr, "procedure group used in binary expression");
  3618. }
  3619. return;
  3620. }
  3621. bool REQUIRE = true;
  3622. Type *btx = base_type(x->type);
  3623. Type *bty = base_type(y->type);
  3624. check_binary_expr_dependency(c, op, btx, REQUIRE);
  3625. check_binary_expr_dependency(c, op, bty, REQUIRE);
  3626. if (token_is_shift(op.kind)) {
  3627. check_shift(c, x, y, node, type_hint);
  3628. return;
  3629. }
  3630. switch (op.kind) {
  3631. case Token_Quo:
  3632. case Token_Mod:
  3633. case Token_ModMod:
  3634. case Token_QuoEq:
  3635. case Token_ModEq:
  3636. case Token_ModModEq:
  3637. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3638. is_type_float(x->type) && is_type_untyped(x->type)) {
  3639. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3640. gbString t = type_to_string(y->type);
  3641. if (x->value.kind != ExactValue_Invalid) {
  3642. gbString s = exact_value_to_string(x->value);
  3643. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3644. gb_string_free(s);
  3645. } else {
  3646. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3647. }
  3648. gb_string_free(t);
  3649. }
  3650. break;
  3651. }
  3652. convert_to_typed(c, x, y->type);
  3653. if (x->mode == Addressing_Invalid) {
  3654. return;
  3655. }
  3656. convert_to_typed(c, y, x->type);
  3657. if (y->mode == Addressing_Invalid) {
  3658. x->mode = Addressing_Invalid;
  3659. return;
  3660. }
  3661. if (token_is_comparison(op.kind)) {
  3662. check_comparison(c, node, x, y, op.kind);
  3663. return;
  3664. }
  3665. if (check_binary_array_expr(c, op, x, y)) {
  3666. x->mode = Addressing_Value;
  3667. x->type = x->type;
  3668. return;
  3669. }
  3670. if (check_binary_array_expr(c, op, y, x)) {
  3671. x->mode = Addressing_Value;
  3672. x->type = y->type;
  3673. return;
  3674. }
  3675. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3676. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3677. x->expr = node;
  3678. return;
  3679. }
  3680. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3681. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3682. // NOTE(bill, 2022-06-26)
  3683. // Allow any boolean types within `&&` and `||`
  3684. // This is an exception to all other binary expressions since the result
  3685. // of a comparison will always be an untyped boolean, and allowing
  3686. // any boolean between these two simplifies a lot of expressions
  3687. } else if (!are_types_identical(x->type, y->type)) {
  3688. if (x->type != t_invalid &&
  3689. y->type != t_invalid) {
  3690. gbString xt = type_to_string(x->type);
  3691. gbString yt = type_to_string(y->type);
  3692. gbString expr_str = expr_to_string(node);
  3693. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3694. gb_string_free(expr_str);
  3695. gb_string_free(yt);
  3696. gb_string_free(xt);
  3697. }
  3698. x->mode = Addressing_Invalid;
  3699. return;
  3700. }
  3701. if (!check_binary_op(c, x, op)) {
  3702. x->mode = Addressing_Invalid;
  3703. return;
  3704. }
  3705. switch (op.kind) {
  3706. case Token_Quo:
  3707. case Token_Mod:
  3708. case Token_ModMod:
  3709. case Token_QuoEq:
  3710. case Token_ModEq:
  3711. case Token_ModModEq:
  3712. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3713. y->mode == Addressing_Constant) {
  3714. bool fail = false;
  3715. switch (y->value.kind) {
  3716. case ExactValue_Integer:
  3717. if (big_int_is_zero(&y->value.value_integer)) {
  3718. fail = true;
  3719. }
  3720. break;
  3721. case ExactValue_Float:
  3722. if (y->value.value_float == 0.0) {
  3723. fail = true;
  3724. }
  3725. break;
  3726. }
  3727. if (fail) {
  3728. error(y->expr, "Division by zero not allowed");
  3729. x->mode = Addressing_Invalid;
  3730. return;
  3731. }
  3732. }
  3733. break;
  3734. case Token_CmpAnd:
  3735. case Token_CmpOr:
  3736. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3737. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3738. }
  3739. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3740. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3741. }
  3742. break;
  3743. }
  3744. if (x->mode == Addressing_Constant &&
  3745. y->mode == Addressing_Constant) {
  3746. ExactValue a = x->value;
  3747. ExactValue b = y->value;
  3748. if (!is_type_constant_type(x->type)) {
  3749. x->mode = Addressing_Value;
  3750. return;
  3751. }
  3752. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3753. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3754. }
  3755. if (is_type_bit_set(x->type)) {
  3756. switch (op.kind) {
  3757. case Token_Add: op.kind = Token_Or; break;
  3758. case Token_Sub: op.kind = Token_AndNot; break;
  3759. }
  3760. }
  3761. x->value = exact_binary_operator_value(op.kind, a, b);
  3762. if (is_type_typed(x->type)) {
  3763. if (node != nullptr) {
  3764. x->expr = node;
  3765. }
  3766. check_is_expressible(c, x, x->type);
  3767. }
  3768. return;
  3769. } else if (is_type_string(x->type)) {
  3770. error(node, "String concatenation is only allowed with constant strings");
  3771. x->mode = Addressing_Invalid;
  3772. return;
  3773. }
  3774. x->mode = Addressing_Value;
  3775. }
  3776. gb_internal Operand make_operand_from_node(Ast *node) {
  3777. GB_ASSERT(node != nullptr);
  3778. Operand x = {};
  3779. x.expr = node;
  3780. x.mode = node->tav.mode;
  3781. x.type = node->tav.type;
  3782. x.value = node->tav.value;
  3783. return x;
  3784. }
  3785. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3786. GB_ASSERT(e != nullptr);
  3787. ExprInfo *old = check_get_expr_info(c, e);
  3788. if (old == nullptr) {
  3789. if (type != nullptr && type != t_invalid) {
  3790. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3791. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3792. if (e->kind == Ast_TernaryIfExpr) {
  3793. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3794. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3795. }
  3796. }
  3797. }
  3798. return;
  3799. }
  3800. switch (e->kind) {
  3801. case_ast_node(ue, UnaryExpr, e);
  3802. if (old->value.kind != ExactValue_Invalid) {
  3803. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3804. // They don't need to be updated as they will be updated later and
  3805. // checked at the end of general checking stage.
  3806. break;
  3807. }
  3808. update_untyped_expr_type(c, ue->expr, type, final);
  3809. case_end;
  3810. case_ast_node(be, BinaryExpr, e);
  3811. if (old->value.kind != ExactValue_Invalid) {
  3812. // See above note in UnaryExpr case
  3813. break;
  3814. }
  3815. if (token_is_comparison(be->op.kind)) {
  3816. // NOTE(bill): Do nothing as the types are fine
  3817. } else if (token_is_shift(be->op.kind)) {
  3818. update_untyped_expr_type(c, be->left, type, final);
  3819. } else {
  3820. update_untyped_expr_type(c, be->left, type, final);
  3821. update_untyped_expr_type(c, be->right, type, final);
  3822. }
  3823. case_end;
  3824. case_ast_node(te, TernaryIfExpr, e);
  3825. if (old->value.kind != ExactValue_Invalid) {
  3826. // See above note in UnaryExpr case
  3827. break;
  3828. }
  3829. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3830. // having an untyped value
  3831. Operand x = make_operand_from_node(te->x);
  3832. Operand y = make_operand_from_node(te->y);
  3833. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3834. update_untyped_expr_type(c, te->x, type, final);
  3835. }
  3836. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3837. update_untyped_expr_type(c, te->y, type, final);
  3838. }
  3839. case_end;
  3840. case_ast_node(te, TernaryWhenExpr, e);
  3841. if (old->value.kind != ExactValue_Invalid) {
  3842. // See above note in UnaryExpr case
  3843. break;
  3844. }
  3845. update_untyped_expr_type(c, te->x, type, final);
  3846. update_untyped_expr_type(c, te->y, type, final);
  3847. case_end;
  3848. case_ast_node(ore, OrReturnExpr, e);
  3849. if (old->value.kind != ExactValue_Invalid) {
  3850. // See above note in UnaryExpr case
  3851. break;
  3852. }
  3853. update_untyped_expr_type(c, ore->expr, type, final);
  3854. case_end;
  3855. case_ast_node(obe, OrBranchExpr, e);
  3856. if (old->value.kind != ExactValue_Invalid) {
  3857. // See above note in UnaryExpr case
  3858. break;
  3859. }
  3860. update_untyped_expr_type(c, obe->expr, type, final);
  3861. case_end;
  3862. case_ast_node(oee, OrElseExpr, e);
  3863. if (old->value.kind != ExactValue_Invalid) {
  3864. // See above note in UnaryExpr case
  3865. break;
  3866. }
  3867. update_untyped_expr_type(c, oee->x, type, final);
  3868. update_untyped_expr_type(c, oee->y, type, final);
  3869. case_end;
  3870. case_ast_node(pe, ParenExpr, e);
  3871. update_untyped_expr_type(c, pe->expr, type, final);
  3872. case_end;
  3873. }
  3874. if (!final && is_type_untyped(type)) {
  3875. old->type = base_type(type);
  3876. return;
  3877. }
  3878. // We need to remove it and then give it a new one
  3879. check_remove_expr_info(c, e);
  3880. if (old->is_lhs && !is_type_integer(type)) {
  3881. gbString expr_str = expr_to_string(e);
  3882. gbString type_str = type_to_string(type);
  3883. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3884. gb_string_free(type_str);
  3885. gb_string_free(expr_str);
  3886. return;
  3887. }
  3888. add_type_and_value(c, e, old->mode, type, old->value);
  3889. }
  3890. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3891. GB_ASSERT(e != nullptr);
  3892. ExprInfo *found = check_get_expr_info(c, e);
  3893. if (found) {
  3894. found->value = value;
  3895. }
  3896. }
  3897. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type, bool ignore_error_block=false) {
  3898. gbString expr_str = expr_to_string(operand->expr);
  3899. gbString type_str = type_to_string(target_type);
  3900. gbString from_type_str = type_to_string(operand->type);
  3901. char const *extra_text = "";
  3902. if (operand->mode == Addressing_Constant) {
  3903. if (big_int_is_zero(&operand->value.value_integer)) {
  3904. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3905. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3906. extra_text = " - Did you want 'nil'?";
  3907. }
  3908. }
  3909. }
  3910. if (!ignore_error_block) {
  3911. begin_error_block();
  3912. }
  3913. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3914. if (operand->value.kind == ExactValue_String) {
  3915. String key = operand->value.value_string;
  3916. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3917. Type *et = base_type(target_type);
  3918. check_did_you_mean_type(key, et->Enum.fields, ".");
  3919. }
  3920. }
  3921. gb_string_free(from_type_str);
  3922. gb_string_free(type_str);
  3923. gb_string_free(expr_str);
  3924. operand->mode = Addressing_Invalid;
  3925. if (!ignore_error_block) {
  3926. end_error_block();
  3927. }
  3928. }
  3929. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3930. Type *t = core_type(type);
  3931. if (is_type_boolean(t)) {
  3932. // v = exact_value_to_boolean(v);
  3933. } else if (is_type_float(t)) {
  3934. v = exact_value_to_float(v);
  3935. } else if (is_type_integer(t)) {
  3936. v = exact_value_to_integer(v);
  3937. } else if (is_type_pointer(t)) {
  3938. v = exact_value_to_integer(v);
  3939. } else if (is_type_complex(t)) {
  3940. v = exact_value_to_complex(v);
  3941. } else if (is_type_quaternion(t)) {
  3942. v = exact_value_to_quaternion(v);
  3943. }
  3944. return v;
  3945. }
  3946. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3947. // GB_ASSERT_NOT_NULL(target_type);
  3948. if (target_type == nullptr || operand->mode == Addressing_Invalid ||
  3949. operand->mode == Addressing_Type ||
  3950. is_type_typed(operand->type) ||
  3951. target_type == t_invalid) {
  3952. return;
  3953. }
  3954. if (is_type_untyped(target_type)) {
  3955. GB_ASSERT(operand->type->kind == Type_Basic);
  3956. GB_ASSERT(target_type->kind == Type_Basic);
  3957. BasicKind x_kind = operand->type->Basic.kind;
  3958. BasicKind y_kind = target_type->Basic.kind;
  3959. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3960. if (x_kind < y_kind) {
  3961. operand->type = target_type;
  3962. update_untyped_expr_type(c, operand->expr, target_type, false);
  3963. }
  3964. } else if (x_kind != y_kind) {
  3965. operand->mode = Addressing_Invalid;
  3966. convert_untyped_error(c, operand, target_type);
  3967. return;
  3968. }
  3969. return;
  3970. }
  3971. Type *t = base_type(target_type);
  3972. if (c->in_enum_type) {
  3973. t = core_type(target_type);
  3974. }
  3975. switch (t->kind) {
  3976. case Type_Basic:
  3977. if (operand->mode == Addressing_Constant) {
  3978. check_is_expressible(c, operand, t);
  3979. if (operand->mode == Addressing_Invalid) {
  3980. return;
  3981. }
  3982. update_untyped_expr_value(c, operand->expr, operand->value);
  3983. } else {
  3984. switch (operand->type->Basic.kind) {
  3985. case Basic_UntypedBool:
  3986. if (!is_type_boolean(target_type)) {
  3987. operand->mode = Addressing_Invalid;
  3988. convert_untyped_error(c, operand, target_type);
  3989. return;
  3990. }
  3991. break;
  3992. case Basic_UntypedInteger:
  3993. case Basic_UntypedFloat:
  3994. case Basic_UntypedComplex:
  3995. case Basic_UntypedQuaternion:
  3996. case Basic_UntypedRune:
  3997. if (!is_type_numeric(target_type)) {
  3998. operand->mode = Addressing_Invalid;
  3999. convert_untyped_error(c, operand, target_type);
  4000. return;
  4001. }
  4002. break;
  4003. case Basic_UntypedNil:
  4004. if (is_type_any(target_type)) {
  4005. // target_type = t_untyped_nil;
  4006. } else if (is_type_cstring(target_type)) {
  4007. // target_type = t_untyped_nil;
  4008. } else if (!type_has_nil(target_type)) {
  4009. operand->mode = Addressing_Invalid;
  4010. convert_untyped_error(c, operand, target_type);
  4011. return;
  4012. }
  4013. break;
  4014. }
  4015. }
  4016. break;
  4017. case Type_Array: {
  4018. Type *elem = base_array_type(t);
  4019. if (check_is_assignable_to(c, operand, elem)) {
  4020. operand->mode = Addressing_Value;
  4021. } else {
  4022. if (operand->value.kind == ExactValue_String) {
  4023. String s = operand->value.value_string;
  4024. if (is_type_u8_array(t)) {
  4025. if (s.len == t->Array.count) {
  4026. break;
  4027. }
  4028. } else if (is_type_rune_array(t)) {
  4029. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  4030. if (rune_count == t->Array.count) {
  4031. break;
  4032. }
  4033. }
  4034. }
  4035. operand->mode = Addressing_Invalid;
  4036. convert_untyped_error(c, operand, target_type);
  4037. return;
  4038. }
  4039. break;
  4040. }
  4041. case Type_SimdVector: {
  4042. Type *elem = base_array_type(t);
  4043. if (check_is_assignable_to(c, operand, elem)) {
  4044. operand->mode = Addressing_Value;
  4045. } else {
  4046. operand->mode = Addressing_Invalid;
  4047. convert_untyped_error(c, operand, target_type);
  4048. return;
  4049. }
  4050. break;
  4051. }
  4052. case Type_Matrix: {
  4053. Type *elem = base_array_type(t);
  4054. if (check_is_assignable_to(c, operand, elem)) {
  4055. if (t->Matrix.row_count != t->Matrix.column_count) {
  4056. operand->mode = Addressing_Invalid;
  4057. ERROR_BLOCK();
  4058. convert_untyped_error(c, operand, target_type, true);
  4059. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  4060. return;
  4061. } else {
  4062. operand->mode = Addressing_Value;
  4063. }
  4064. } else {
  4065. operand->mode = Addressing_Invalid;
  4066. convert_untyped_error(c, operand, target_type);
  4067. return;
  4068. }
  4069. break;
  4070. }
  4071. case Type_Union:
  4072. // IMPORTANT NOTE HACK(bill): This is just to allow for comparisons against `0` with the `os.Error` type
  4073. // as a kind of transition period
  4074. if (!build_context.strict_style &&
  4075. operand->mode == Addressing_Constant &&
  4076. target_type->kind == Type_Named &&
  4077. (c->pkg == nullptr || c->pkg->name != "os") &&
  4078. target_type->Named.name == "Error") {
  4079. Entity *e = target_type->Named.type_name;
  4080. if (e->pkg && e->pkg->name == "os") {
  4081. if (is_exact_value_zero(operand->value) &&
  4082. (operand->value.kind == ExactValue_Integer ||
  4083. operand->value.kind == ExactValue_Float)) {
  4084. operand->mode = Addressing_Value;
  4085. // target_type = t_untyped_nil;
  4086. operand->value = empty_exact_value;
  4087. update_untyped_expr_value(c, operand->expr, operand->value);
  4088. break;
  4089. }
  4090. }
  4091. }
  4092. // "fallthrough"
  4093. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  4094. TEMPORARY_ALLOCATOR_GUARD();
  4095. isize count = t->Union.variants.count;
  4096. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  4097. isize valid_count = 0;
  4098. isize first_success_index = -1;
  4099. for_array(i, t->Union.variants) {
  4100. Type *vt = t->Union.variants[i];
  4101. i64 score = 0;
  4102. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  4103. valids[valid_count].index = i;
  4104. valids[valid_count].score = score;
  4105. valid_count += 1;
  4106. if (first_success_index < 0) {
  4107. first_success_index = i;
  4108. }
  4109. }
  4110. }
  4111. if (valid_count > 1) {
  4112. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  4113. i64 best_score = valids[0].score;
  4114. for (isize i = 1; i < valid_count; i++) {
  4115. auto v = valids[i];
  4116. if (best_score > v.score) {
  4117. valid_count = i;
  4118. break;
  4119. }
  4120. best_score = v.score;
  4121. }
  4122. first_success_index = valids[0].index;
  4123. }
  4124. gbString type_str = type_to_string(target_type);
  4125. defer (gb_string_free(type_str));
  4126. if (valid_count == 1) {
  4127. Type *new_type = t->Union.variants[first_success_index];
  4128. target_type = new_type;
  4129. if (is_type_union(new_type)) {
  4130. convert_to_typed(c, operand, new_type);
  4131. break;
  4132. }
  4133. operand->type = new_type;
  4134. operand->mode = Addressing_Value;
  4135. break;
  4136. } else if (valid_count > 1) {
  4137. ERROR_BLOCK();
  4138. GB_ASSERT(first_success_index >= 0);
  4139. operand->mode = Addressing_Invalid;
  4140. convert_untyped_error(c, operand, target_type, true);
  4141. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  4142. i32 j = 0;
  4143. for (i32 i = 0; i < valid_count; i++) {
  4144. ValidIndexAndScore valid = valids[i];
  4145. if (j > 0 && valid_count > 2) error_line(", ");
  4146. if (j == valid_count-1) {
  4147. if (valid_count == 2) error_line(" ");
  4148. error_line("or ");
  4149. }
  4150. gbString str = type_to_string(t->Union.variants[valid.index]);
  4151. error_line("'%s'", str);
  4152. gb_string_free(str);
  4153. j++;
  4154. }
  4155. error_line("\n\n");
  4156. return;
  4157. } else if (is_type_untyped_uninit(operand->type)) {
  4158. target_type = t_untyped_uninit;
  4159. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  4160. ERROR_BLOCK();
  4161. operand->mode = Addressing_Invalid;
  4162. convert_untyped_error(c, operand, target_type, true);
  4163. if (count > 0) {
  4164. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  4165. error_line("\t");
  4166. for (i32 i = 0; i < count; i++) {
  4167. Type *v = t->Union.variants[i];
  4168. if (i > 0 && count > 2) error_line(", ");
  4169. if (i == count-1) {
  4170. if (count == 2) error_line(" ");
  4171. if (count > 1) {
  4172. error_line("or ");
  4173. }
  4174. }
  4175. gbString str = type_to_string(v);
  4176. error_line("'%s'", str);
  4177. gb_string_free(str);
  4178. }
  4179. error_line("\n\n");
  4180. }
  4181. return;
  4182. }
  4183. }
  4184. /* fallthrough */
  4185. default:
  4186. if (is_type_untyped_uninit(operand->type)) {
  4187. target_type = t_untyped_uninit;
  4188. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  4189. target_type = t_untyped_nil;
  4190. } else {
  4191. operand->mode = Addressing_Invalid;
  4192. convert_untyped_error(c, operand, target_type);
  4193. return;
  4194. }
  4195. break;
  4196. }
  4197. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  4198. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  4199. } else {
  4200. target_type = default_type(operand->type);
  4201. }
  4202. }
  4203. update_untyped_expr_type(c, operand->expr, target_type, true);
  4204. operand->type = target_type;
  4205. }
  4206. 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) {
  4207. Operand operand = {Addressing_Invalid};
  4208. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  4209. if (operand.mode == Addressing_Invalid) {
  4210. if (value) *value = 0;
  4211. // NOTE(bill): return true here to propagate the errors better
  4212. return true;
  4213. }
  4214. Type *index_type = t_int;
  4215. if (type_hint != nullptr) {
  4216. index_type = type_hint;
  4217. }
  4218. convert_to_typed(c, &operand, index_type);
  4219. if (operand.mode == Addressing_Invalid) {
  4220. if (value) *value = 0;
  4221. return false;
  4222. }
  4223. if (type_hint != nullptr) {
  4224. if (!check_is_assignable_to(c, &operand, type_hint)) {
  4225. gbString expr_str = expr_to_string(operand.expr);
  4226. gbString index_type_str = type_to_string(type_hint);
  4227. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  4228. gb_string_free(index_type_str);
  4229. gb_string_free(expr_str);
  4230. if (value) *value = 0;
  4231. return false;
  4232. }
  4233. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  4234. gbString expr_str = expr_to_string(operand.expr);
  4235. gbString type_str = type_to_string(operand.type);
  4236. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  4237. gb_string_free(type_str);
  4238. gb_string_free(expr_str);
  4239. if (value) *value = 0;
  4240. return false;
  4241. }
  4242. if (operand.mode == Addressing_Constant &&
  4243. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  4244. BigInt i = exact_value_to_integer(operand.value).value_integer;
  4245. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  4246. TEMPORARY_ALLOCATOR_GUARD();
  4247. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4248. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4249. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  4250. if (value) *value = 0;
  4251. return false;
  4252. }
  4253. if (max_count >= 0) {
  4254. if (is_type_enum(index_type)) {
  4255. Type *bt = base_type(index_type);
  4256. GB_ASSERT(bt->kind == Type_Enum);
  4257. ExactValue const &lo = *bt->Enum.min_value;
  4258. ExactValue const &hi = *bt->Enum.max_value;
  4259. String lo_str = {};
  4260. String hi_str = {};
  4261. if (bt->Enum.fields.count > 0) {
  4262. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  4263. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  4264. lo_str = bt->Enum.fields[lo_idx]->token.string;
  4265. hi_str = bt->Enum.fields[hi_idx]->token.string;
  4266. }
  4267. bool out_of_bounds = false;
  4268. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  4269. out_of_bounds = true;
  4270. }
  4271. if (out_of_bounds) {
  4272. gbString expr_str = expr_to_string(operand.expr);
  4273. if (lo_str.len > 0) {
  4274. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  4275. } else {
  4276. gbString index_type_str = type_to_string(index_type);
  4277. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  4278. gb_string_free(index_type_str);
  4279. }
  4280. gb_string_free(expr_str);
  4281. return false;
  4282. }
  4283. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  4284. return true;
  4285. } else { // NOTE(bill): Do array bound checking
  4286. i64 v = -1;
  4287. if (i.used <= 1) {
  4288. v = big_int_to_i64(&i);
  4289. }
  4290. if (value) *value = v;
  4291. bool out_of_bounds = false;
  4292. if (v < 0) {
  4293. out_of_bounds = true;
  4294. } else if (open_range) {
  4295. out_of_bounds = v > max_count;
  4296. } else {
  4297. out_of_bounds = v >= max_count;
  4298. }
  4299. if (out_of_bounds) {
  4300. TEMPORARY_ALLOCATOR_GUARD();
  4301. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4302. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4303. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  4304. return false;
  4305. }
  4306. return true;
  4307. }
  4308. } else {
  4309. if (value) *value = exact_value_to_i64(operand.value);
  4310. return true;
  4311. }
  4312. }
  4313. // NOTE(bill): It's alright :D
  4314. if (value) *value = -1;
  4315. return true;
  4316. }
  4317. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  4318. if (value.kind == ExactValue_String) {
  4319. GB_ASSERT(0 <= index && index < value.value_string.len);
  4320. u8 val = value.value_string[index];
  4321. if (success_) *success_ = true;
  4322. if (finish_) *finish_ = true;
  4323. return exact_value_u64(val);
  4324. }
  4325. if (value.kind != ExactValue_Compound) {
  4326. if (success_) *success_ = true;
  4327. if (finish_) *finish_ = true;
  4328. return value;
  4329. }
  4330. Ast *node = value.value_compound;
  4331. switch (node->kind) {
  4332. case_ast_node(cl, CompoundLit, node);
  4333. if (cl->elems.count == 0) {
  4334. if (success_) *success_ = true;
  4335. if (finish_) *finish_ = true;
  4336. return empty_exact_value;
  4337. }
  4338. if (cl->elems[0]->kind == Ast_FieldValue) {
  4339. if (is_type_struct(node->tav.type)) {
  4340. bool found = false;
  4341. for (Ast *elem : cl->elems) {
  4342. if (elem->kind != Ast_FieldValue) {
  4343. continue;
  4344. }
  4345. ast_node(fv, FieldValue, elem);
  4346. String name = fv->field->Ident.token.string;
  4347. Selection sub_sel = lookup_field(node->tav.type, name, false);
  4348. defer (array_free(&sub_sel.index));
  4349. if (sub_sel.index.count > 0 &&
  4350. sub_sel.index[0] == index) {
  4351. value = fv->value->tav.value;
  4352. found = true;
  4353. break;
  4354. }
  4355. }
  4356. if (!found) {
  4357. // Use the zero value if it is not found
  4358. value = {};
  4359. }
  4360. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4361. for (Ast *elem : cl->elems) {
  4362. if (elem->kind != Ast_FieldValue) {
  4363. continue;
  4364. }
  4365. ast_node(fv, FieldValue, elem);
  4366. if (is_ast_range(fv->field)) {
  4367. ast_node(ie, BinaryExpr, fv->field);
  4368. TypeAndValue lo_tav = ie->left->tav;
  4369. TypeAndValue hi_tav = ie->right->tav;
  4370. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4371. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4372. TokenKind op = ie->op.kind;
  4373. i64 lo = exact_value_to_i64(lo_tav.value);
  4374. i64 hi = exact_value_to_i64(hi_tav.value);
  4375. i64 corrected_index = index;
  4376. if (is_type_enumerated_array(node->tav.type)) {
  4377. Type *bt = base_type(node->tav.type);
  4378. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4379. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4380. }
  4381. if (op != Token_RangeHalf) {
  4382. if (lo <= corrected_index && corrected_index <= hi) {
  4383. TypeAndValue tav = fv->value->tav;
  4384. if (success_) *success_ = true;
  4385. if (finish_) *finish_ = false;
  4386. return tav.value;
  4387. }
  4388. } else {
  4389. if (lo <= corrected_index && corrected_index < hi) {
  4390. TypeAndValue tav = fv->value->tav;
  4391. if (success_) *success_ = true;
  4392. if (finish_) *finish_ = false;
  4393. return tav.value;
  4394. }
  4395. }
  4396. } else {
  4397. TypeAndValue index_tav = fv->field->tav;
  4398. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4399. ExactValue index_value = index_tav.value;
  4400. if (is_type_enumerated_array(node->tav.type)) {
  4401. Type *bt = base_type(node->tav.type);
  4402. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4403. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4404. }
  4405. i64 field_index = exact_value_to_i64(index_value);
  4406. if (index == field_index) {
  4407. TypeAndValue tav = fv->value->tav;
  4408. if (success_) *success_ = true;
  4409. if (finish_) *finish_ = false;
  4410. return tav.value;
  4411. }
  4412. }
  4413. }
  4414. }
  4415. } else {
  4416. i32 count = (i32)cl->elems.count;
  4417. if (count < index) {
  4418. if (success_) *success_ = false;
  4419. if (finish_) *finish_ = true;
  4420. return empty_exact_value;
  4421. }
  4422. if (cl->elems.count <= index) {
  4423. if (success_) *success_ = false;
  4424. if (finish_) *finish_ = false;
  4425. return value;
  4426. }
  4427. TypeAndValue tav = cl->elems[index]->tav;
  4428. if (tav.mode == Addressing_Constant) {
  4429. if (success_) *success_ = true;
  4430. if (finish_) *finish_ = false;
  4431. return tav.value;
  4432. } else if (is_type_proc(tav.type)) {
  4433. if (success_) *success_ = true;
  4434. if (finish_) *finish_ = false;
  4435. return tav.value;
  4436. } else {
  4437. GB_ASSERT_MSG(is_type_untyped_nil(tav.type), "%s", type_to_string(tav.type));
  4438. if (success_) *success_ = true;
  4439. if (finish_) *finish_ = false;
  4440. return tav.value;
  4441. }
  4442. }
  4443. case_end;
  4444. default:
  4445. if (success_) *success_ = true;
  4446. if (finish_) *finish_ = true;
  4447. return empty_exact_value;
  4448. }
  4449. if (finish_) *finish_ = false;
  4450. return value;
  4451. }
  4452. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4453. if (operand->mode != Addressing_Constant) {
  4454. if (success_) *success_ = false;
  4455. return empty_exact_value;
  4456. }
  4457. if (sel.indirect) {
  4458. if (success_) *success_ = false;
  4459. return empty_exact_value;
  4460. }
  4461. if (sel.index.count == 0) {
  4462. if (success_) *success_ = false;
  4463. return empty_exact_value;
  4464. }
  4465. ExactValue value = operand->value;
  4466. if (value.kind == ExactValue_Compound) {
  4467. while (sel.index.count > 0) {
  4468. i32 index = sel.index[0];
  4469. sel = sub_selection(sel, 1);
  4470. bool finish = false;
  4471. value = get_constant_field_single(c, value, index, success_, &finish);
  4472. if (finish) {
  4473. return value;
  4474. }
  4475. }
  4476. if (success_) *success_ = true;
  4477. return value;
  4478. } else if (value.kind == ExactValue_Quaternion) {
  4479. // @QuaternionLayout
  4480. Quaternion256 q = *value.value_quaternion;
  4481. GB_ASSERT(sel.index.count == 1);
  4482. switch (sel.index[0]) {
  4483. case 3: // w
  4484. if (success_) *success_ = true;
  4485. return exact_value_float(q.real);
  4486. case 0: // x
  4487. if (success_) *success_ = true;
  4488. return exact_value_float(q.imag);
  4489. case 1: // y
  4490. if (success_) *success_ = true;
  4491. return exact_value_float(q.jmag);
  4492. case 2: // z
  4493. if (success_) *success_ = true;
  4494. return exact_value_float(q.kmag);
  4495. }
  4496. if (success_) *success_ = false;
  4497. return empty_exact_value;
  4498. } else if (value.kind == ExactValue_Complex) {
  4499. // @QuaternionLayout
  4500. Complex128 c = *value.value_complex;
  4501. GB_ASSERT(sel.index.count == 1);
  4502. switch (sel.index[0]) {
  4503. case 0: // real
  4504. if (success_) *success_ = true;
  4505. return exact_value_float(c.real);
  4506. case 1: // imag
  4507. if (success_) *success_ = true;
  4508. return exact_value_float(c.imag);
  4509. }
  4510. if (success_) *success_ = false;
  4511. return empty_exact_value;
  4512. }
  4513. if (success_) *success_ = true;
  4514. return empty_exact_value;
  4515. }
  4516. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4517. Type *array_type = base_type(type_deref(original_type));
  4518. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4519. if (array_type->kind == Type_SimdVector) {
  4520. Type *elem_type = array_type->SimdVector.elem;
  4521. return alloc_type_simd_vector(new_count, elem_type);
  4522. }
  4523. Type *elem_type = array_type->Array.elem;
  4524. Type *swizzle_array_type = nullptr;
  4525. Type *bth = base_type(type_deref(type_hint));
  4526. if (bth != nullptr && bth->kind == Type_Array &&
  4527. bth->Array.count == new_count &&
  4528. are_types_identical(bth->Array.elem, elem_type)) {
  4529. swizzle_array_type = type_hint;
  4530. } else {
  4531. i64 max_count = array_type->Array.count;
  4532. if (new_count == max_count) {
  4533. swizzle_array_type = original_type;
  4534. } else {
  4535. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4536. }
  4537. }
  4538. return swizzle_array_type;
  4539. }
  4540. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4541. bool is_declared = entity != nullptr;
  4542. if (is_declared) {
  4543. if (entity->kind == Entity_Builtin) {
  4544. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4545. // This means that we should just ignore the found result through it
  4546. *allow_builtin = entity->scope == import_scope ||
  4547. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4548. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4549. is_declared = false;
  4550. }
  4551. }
  4552. return is_declared;
  4553. }
  4554. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4555. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4556. if (node == nullptr) {
  4557. return nullptr;
  4558. }
  4559. /*if (node->kind == Ast_TernaryWhenExpr) {
  4560. ast_node(we, TernaryWhenExpr, node);
  4561. if (we->cond == nullptr) {
  4562. return nullptr;
  4563. }
  4564. if (we->cond->tav.mode != Addressing_Constant) {
  4565. return nullptr;
  4566. }
  4567. if (we->cond->tav.value.kind != ExactValue_Bool) {
  4568. return nullptr;
  4569. }
  4570. if (we->cond->tav.value.value_bool) {
  4571. return check_entity_from_ident_or_selector(c, we->x, ident_only);
  4572. } else {
  4573. Entity *e = check_entity_from_ident_or_selector(c, we->y, ident_only);
  4574. return e;
  4575. }
  4576. } else */if (node->kind == Ast_Ident) {
  4577. String name = node->Ident.token.string;
  4578. return scope_lookup(c->scope, name);
  4579. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4580. ast_node(se, SelectorExpr, node);
  4581. if (se->token.kind == Token_ArrowRight) {
  4582. return nullptr;
  4583. }
  4584. Ast *op_expr = se->expr;
  4585. Ast *selector = unparen_expr(se->selector);
  4586. if (selector == nullptr) {
  4587. return nullptr;
  4588. }
  4589. if (selector->kind != Ast_Ident) {
  4590. return nullptr;
  4591. }
  4592. Entity *entity = nullptr;
  4593. Entity *expr_entity = nullptr;
  4594. bool check_op_expr = true;
  4595. if (op_expr->kind == Ast_Ident) {
  4596. String op_name = op_expr->Ident.token.string;
  4597. Entity *e = scope_lookup(c->scope, op_name);
  4598. if (e == nullptr) {
  4599. return nullptr;
  4600. }
  4601. add_entity_use(c, op_expr, e);
  4602. expr_entity = e;
  4603. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4604. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4605. // It pretty much needs to be in this order and this way
  4606. // If you can clean this up, please do but be really careful
  4607. String import_name = op_name;
  4608. Scope *import_scope = e->ImportName.scope;
  4609. String entity_name = selector->Ident.token.string;
  4610. check_op_expr = false;
  4611. entity = scope_lookup_current(import_scope, entity_name);
  4612. bool allow_builtin = false;
  4613. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4614. return nullptr;
  4615. }
  4616. check_entity_decl(c, entity, nullptr, nullptr);
  4617. if (entity->kind == Entity_ProcGroup) {
  4618. return entity;
  4619. }
  4620. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4621. }
  4622. }
  4623. Operand operand = {};
  4624. if (check_op_expr) {
  4625. check_expr_base(c, &operand, op_expr, nullptr);
  4626. if (operand.mode == Addressing_Invalid) {
  4627. return nullptr;
  4628. }
  4629. }
  4630. if (entity == nullptr && selector->kind == Ast_Ident) {
  4631. String field_name = selector->Ident.token.string;
  4632. if (is_type_dynamic_array(type_deref(operand.type))) {
  4633. init_mem_allocator(c->checker);
  4634. }
  4635. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4636. entity = sel.entity;
  4637. }
  4638. if (entity != nullptr) {
  4639. return entity;
  4640. }
  4641. }
  4642. return nullptr;
  4643. }
  4644. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4645. ast_node(se, SelectorExpr, node);
  4646. bool check_op_expr = true;
  4647. Entity *expr_entity = nullptr;
  4648. Entity *entity = nullptr;
  4649. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4650. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4651. ERROR_BLOCK();
  4652. error(node, "Illegal use of -> selector shorthand outside of a call");
  4653. gbString x = expr_to_string(se->expr);
  4654. gbString y = expr_to_string(se->selector);
  4655. error_line("\tSuggestion: Did you mean '%s.%s'?\n", x, y);
  4656. gb_string_free(y);
  4657. gb_string_free(x);
  4658. // TODO(bill): Should this terminate here or propagate onwards?
  4659. // operand->mode = Addressing_Invalid;
  4660. // operand->expr = node;
  4661. // return nullptr;
  4662. }
  4663. operand->expr = node;
  4664. Ast *op_expr = se->expr;
  4665. Ast *selector = unparen_expr(se->selector);
  4666. if (selector == nullptr) {
  4667. operand->mode = Addressing_Invalid;
  4668. operand->expr = node;
  4669. return nullptr;
  4670. }
  4671. if (selector->kind != Ast_Ident) {
  4672. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4673. operand->mode = Addressing_Invalid;
  4674. operand->expr = node;
  4675. return nullptr;
  4676. }
  4677. if (op_expr->kind == Ast_Ident) {
  4678. String op_name = op_expr->Ident.token.string;
  4679. Entity *e = scope_lookup(c->scope, op_name);
  4680. add_entity_use(c, op_expr, e);
  4681. expr_entity = e;
  4682. if (e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup) && selector->kind == Ast_Ident) {
  4683. gbString sel_str = expr_to_string(selector);
  4684. error(node, "'%s' is not declared by by '%.*s'", sel_str, LIT(e->token.string));
  4685. gb_string_free(sel_str);
  4686. operand->mode = Addressing_Invalid;
  4687. operand->expr = node;
  4688. return nullptr;
  4689. } else if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4690. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4691. // It pretty much needs to be in this order and this way
  4692. // If you can clean this up, please do but be really careful
  4693. String import_name = op_name;
  4694. Scope *import_scope = e->ImportName.scope;
  4695. String entity_name = selector->Ident.token.string;
  4696. if (import_scope == nullptr) {
  4697. ERROR_BLOCK();
  4698. error(node, "'%.*s' is not imported in this file, '%.*s' is unavailable", LIT(import_name), LIT(entity_name));
  4699. operand->mode = Addressing_Invalid;
  4700. operand->expr = node;
  4701. return nullptr;
  4702. }
  4703. check_op_expr = false;
  4704. entity = scope_lookup_current(import_scope, entity_name);
  4705. bool allow_builtin = false;
  4706. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4707. ERROR_BLOCK();
  4708. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4709. operand->mode = Addressing_Invalid;
  4710. operand->expr = node;
  4711. check_did_you_mean_scope(entity_name, import_scope);
  4712. return nullptr;
  4713. }
  4714. if (!is_entity_exported(entity, allow_builtin)) {
  4715. gbString sel_str = expr_to_string(selector);
  4716. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4717. gb_string_free(sel_str);
  4718. // NOTE(bill): make the state valid still, even if it's "invalid"
  4719. // operand->mode = Addressing_Invalid;
  4720. // operand->expr = node;
  4721. // return nullptr;
  4722. }
  4723. check_entity_decl(c, entity, nullptr, nullptr);
  4724. if (entity->kind == Entity_ProcGroup) {
  4725. operand->mode = Addressing_ProcGroup;
  4726. operand->proc_group = entity;
  4727. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4728. return entity;
  4729. }
  4730. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4731. }
  4732. }
  4733. if (check_op_expr) {
  4734. check_expr_base(c, operand, op_expr, nullptr);
  4735. if (operand->mode == Addressing_Invalid) {
  4736. operand->mode = Addressing_Invalid;
  4737. operand->expr = node;
  4738. return nullptr;
  4739. }
  4740. }
  4741. if (operand->type && is_type_soa_struct(type_deref(operand->type))) {
  4742. complete_soa_type(c->checker, type_deref(operand->type), false);
  4743. }
  4744. if (entity == nullptr && selector->kind == Ast_Ident) {
  4745. String field_name = selector->Ident.token.string;
  4746. Type *t = type_deref(operand->type);
  4747. if (t == nullptr) {
  4748. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4749. } else {
  4750. if (is_type_dynamic_array(t)) {
  4751. init_mem_allocator(c->checker);
  4752. }
  4753. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4754. entity = sel.entity;
  4755. // NOTE(bill): Add type info needed for fields like 'names'
  4756. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4757. add_type_info_type(c, operand->type);
  4758. }
  4759. if (is_type_enum(operand->type)) {
  4760. add_type_info_type(c, operand->type);
  4761. }
  4762. }
  4763. }
  4764. if (operand->type && is_type_simd_vector(type_deref(operand->type))) {
  4765. String field_name = selector->Ident.token.string;
  4766. if (field_name.len == 1) {
  4767. error(op_expr, "Extracting an element from a #simd array using .%.*s syntax is disallowed, prefer `simd.extract`", LIT(field_name));
  4768. } else {
  4769. error(op_expr, "Extracting elements from a #simd array using .%.*s syntax is disallowed, prefer `swizzle`", LIT(field_name));
  4770. }
  4771. return nullptr;
  4772. }
  4773. if (entity == nullptr && selector->kind == Ast_Ident && operand->type != nullptr &&
  4774. (is_type_array(type_deref(operand->type)))) {
  4775. String field_name = selector->Ident.token.string;
  4776. if (1 < field_name.len && field_name.len <= 4) {
  4777. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4778. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4779. bool found_xyzw = false;
  4780. bool found_rgba = false;
  4781. for (isize i = 0; i < field_name.len; i++) {
  4782. bool valid = false;
  4783. for (isize j = 0; j < 4; j++) {
  4784. if (field_name.text[i] == swizzles_xyzw[j]) {
  4785. found_xyzw = true;
  4786. valid = true;
  4787. break;
  4788. }
  4789. if (field_name.text[i] == swizzles_rgba[j]) {
  4790. found_rgba = true;
  4791. valid = true;
  4792. break;
  4793. }
  4794. }
  4795. if (!valid) {
  4796. goto end_of_array_selector_swizzle;
  4797. }
  4798. }
  4799. u8 *swizzles = nullptr;
  4800. u8 index_count = cast(u8)field_name.len;
  4801. if (found_xyzw && found_rgba) {
  4802. gbString op_str = expr_to_string(op_expr);
  4803. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4804. gb_string_free(op_str);
  4805. operand->mode = Addressing_Invalid;
  4806. operand->expr = node;
  4807. return nullptr;
  4808. }
  4809. u8 indices = 0;
  4810. if (found_xyzw) {
  4811. swizzles = swizzles_xyzw;
  4812. } else if (found_rgba) {
  4813. swizzles = swizzles_rgba;
  4814. }
  4815. for (isize i = 0; i < field_name.len; i++) {
  4816. for (isize j = 0; j < 4; j++) {
  4817. if (field_name.text[i] == swizzles[j]) {
  4818. indices |= cast(u8)(j)<<(i*2);
  4819. break;
  4820. }
  4821. }
  4822. }
  4823. Type *original_type = operand->type;
  4824. Type *array_type = base_type(type_deref(original_type));
  4825. GB_ASSERT(array_type->kind == Type_Array);
  4826. i64 array_count = get_array_type_count(array_type);
  4827. for (u8 i = 0; i < index_count; i++) {
  4828. u8 idx = indices>>(i*2) & 3;
  4829. if (idx >= array_count) {
  4830. char c = 0;
  4831. if (found_xyzw) {
  4832. c = swizzles_xyzw[idx];
  4833. } else if (found_rgba) {
  4834. c = swizzles_rgba[idx];
  4835. } else {
  4836. GB_PANIC("unknown swizzle kind");
  4837. }
  4838. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4839. break;
  4840. }
  4841. }
  4842. se->swizzle_count = index_count;
  4843. se->swizzle_indices = indices;
  4844. AddressingMode prev_mode = operand->mode;
  4845. operand->mode = Addressing_SwizzleValue;
  4846. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4847. operand->expr = node;
  4848. switch (prev_mode) {
  4849. case Addressing_Variable:
  4850. case Addressing_SoaVariable:
  4851. case Addressing_SwizzleVariable:
  4852. operand->mode = Addressing_SwizzleVariable;
  4853. break;
  4854. case Addressing_Value:
  4855. if (is_type_pointer(original_type)) {
  4856. operand->mode = Addressing_SwizzleVariable;
  4857. }
  4858. break;
  4859. }
  4860. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4861. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4862. return swizzle_entity;
  4863. }
  4864. end_of_array_selector_swizzle:;
  4865. }
  4866. if (entity == nullptr) {
  4867. gbString op_str = expr_to_string(op_expr);
  4868. gbString type_str = type_to_string_shorthand(operand->type);
  4869. gbString sel_str = expr_to_string(selector);
  4870. if (operand->mode == Addressing_Type) {
  4871. if (is_type_polymorphic(operand->type, true)) {
  4872. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4873. } else {
  4874. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4875. }
  4876. } else {
  4877. ERROR_BLOCK();
  4878. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4879. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4880. String const &name = selector->Ident.token.string;
  4881. Type *bt = base_type(operand->type);
  4882. if (operand->type->kind == Type_Named &&
  4883. operand->type->Named.type_name &&
  4884. operand->type->Named.type_name->kind == Entity_TypeName &&
  4885. operand->type->Named.type_name->TypeName.objc_metadata) {
  4886. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4887. } else if (bt->kind == Type_Struct) {
  4888. check_did_you_mean_type(name, bt->Struct.fields);
  4889. } else if (bt->kind == Type_Enum) {
  4890. check_did_you_mean_type(name, bt->Enum.fields);
  4891. }
  4892. }
  4893. }
  4894. gb_string_free(sel_str);
  4895. gb_string_free(type_str);
  4896. gb_string_free(op_str);
  4897. operand->mode = Addressing_Invalid;
  4898. operand->expr = node;
  4899. return nullptr;
  4900. }
  4901. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4902. bool success = false;
  4903. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4904. if (success) {
  4905. operand->mode = Addressing_Constant;
  4906. operand->expr = node;
  4907. operand->value = field_value;
  4908. operand->type = entity->type;
  4909. add_entity_use(c, selector, entity);
  4910. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4911. return entity;
  4912. }
  4913. gbString op_str = expr_to_string(op_expr);
  4914. gbString type_str = type_to_string_shorthand(operand->type);
  4915. gbString sel_str = expr_to_string(selector);
  4916. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4917. gb_string_free(sel_str);
  4918. gb_string_free(type_str);
  4919. gb_string_free(op_str);
  4920. operand->mode = Addressing_Invalid;
  4921. operand->expr = node;
  4922. return nullptr;
  4923. }
  4924. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4925. bool success = false;
  4926. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4927. if (success) {
  4928. operand->mode = Addressing_Constant;
  4929. operand->expr = node;
  4930. operand->value = field_value;
  4931. operand->type = entity->type;
  4932. add_entity_use(c, selector, entity);
  4933. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4934. return entity;
  4935. }
  4936. gbString op_str = expr_to_string(op_expr);
  4937. gbString type_str = type_to_string_shorthand(operand->type);
  4938. gbString sel_str = expr_to_string(selector);
  4939. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4940. gb_string_free(sel_str);
  4941. gb_string_free(type_str);
  4942. gb_string_free(op_str);
  4943. operand->mode = Addressing_Invalid;
  4944. operand->expr = node;
  4945. return nullptr;
  4946. }
  4947. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4948. gbString op_str = expr_to_string(op_expr);
  4949. gbString type_str = type_to_string_shorthand(operand->type);
  4950. gbString sel_str = expr_to_string(selector);
  4951. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4952. gb_string_free(sel_str);
  4953. gb_string_free(type_str);
  4954. gb_string_free(op_str);
  4955. operand->mode = Addressing_Invalid;
  4956. operand->expr = node;
  4957. return nullptr;
  4958. }
  4959. add_entity_use(c, selector, entity);
  4960. operand->type = entity->type;
  4961. operand->expr = node;
  4962. if (entity->flags & EntityFlag_BitFieldField) {
  4963. add_package_dependency(c, "runtime", "__write_bits");
  4964. add_package_dependency(c, "runtime", "__read_bits");
  4965. }
  4966. switch (entity->kind) {
  4967. case Entity_Constant:
  4968. operand->value = entity->Constant.value;
  4969. operand->mode = Addressing_Constant;
  4970. if (operand->value.kind == ExactValue_Procedure) {
  4971. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4972. if (proc != nullptr) {
  4973. operand->mode = Addressing_Value;
  4974. operand->type = proc->type;
  4975. }
  4976. }
  4977. break;
  4978. case Entity_Variable:
  4979. if (sel.is_bit_field) {
  4980. se->is_bit_field = true;
  4981. }
  4982. if (sel.indirect) {
  4983. operand->mode = Addressing_Variable;
  4984. } else if (operand->mode == Addressing_Context) {
  4985. // Do nothing
  4986. } else if (operand->mode == Addressing_MapIndex) {
  4987. operand->mode = Addressing_Value;
  4988. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4989. operand->mode = Addressing_SoaVariable;
  4990. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4991. operand->mode = Addressing_Value;
  4992. } else if (operand->mode == Addressing_SoaVariable) {
  4993. operand->mode = Addressing_Variable;
  4994. } else if (operand->mode != Addressing_Value) {
  4995. operand->mode = Addressing_Variable;
  4996. } else {
  4997. operand->mode = Addressing_Value;
  4998. }
  4999. break;
  5000. case Entity_TypeName:
  5001. operand->mode = Addressing_Type;
  5002. break;
  5003. case Entity_Procedure:
  5004. operand->mode = Addressing_Value;
  5005. operand->value = exact_value_procedure(node);
  5006. break;
  5007. case Entity_Builtin:
  5008. operand->mode = Addressing_Builtin;
  5009. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  5010. break;
  5011. case Entity_ProcGroup:
  5012. operand->mode = Addressing_ProcGroup;
  5013. operand->proc_group = entity;
  5014. break;
  5015. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  5016. case Entity_Nil:
  5017. operand->mode = Addressing_Value;
  5018. break;
  5019. }
  5020. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5021. return entity;
  5022. }
  5023. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  5024. ptr = base_type(ptr);
  5025. if (is_type_pointer(ptr)) {
  5026. if (is_type_rawptr(ptr)) {
  5027. return false;
  5028. }
  5029. if (elem) *elem = ptr->Pointer.elem;
  5030. return true;
  5031. }
  5032. return false;
  5033. }
  5034. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  5035. elem = core_type(elem);
  5036. if (is_type_internally_pointer_like(elem)) {
  5037. return true;
  5038. }
  5039. if (elem->kind == Type_BitSet) {
  5040. elem = bit_set_to_int(elem);
  5041. }
  5042. if (elem->kind != Type_Basic) {
  5043. return false;
  5044. }
  5045. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  5046. }
  5047. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  5048. switch (node->kind) {
  5049. case_ast_node(i, Ident, node);
  5050. String name = i->token.string;
  5051. if (nested) {
  5052. Entity *e = scope_lookup_current(s, name);
  5053. if (e != nullptr) {
  5054. if (out_scope) *out_scope = e->scope;
  5055. return true;
  5056. }
  5057. } else {
  5058. Entity *e = scope_lookup(s, name);
  5059. if (e != nullptr) {
  5060. if (out_scope) *out_scope = e->scope;
  5061. return true;
  5062. }
  5063. }
  5064. case_end;
  5065. case_ast_node(se, SelectorExpr, node);
  5066. Ast *lhs = se->expr;
  5067. Ast *rhs = se->selector;
  5068. Scope *lhs_scope = nullptr;
  5069. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  5070. return check_identifier_exists(lhs_scope, rhs, true);
  5071. }
  5072. case_end;
  5073. }
  5074. return false;
  5075. }
  5076. gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) {
  5077. if (o.type && is_type_no_copy(o.type)) {
  5078. Ast *expr = unparen_expr(o.expr);
  5079. if (expr && o.mode != Addressing_Constant && o.mode != Addressing_Type) {
  5080. if (expr->kind == Ast_CallExpr) {
  5081. // Okay
  5082. } else {
  5083. error(o.expr, "Invalid use of #no_copy value in %.*s", LIT(context));
  5084. return true;
  5085. }
  5086. }
  5087. }
  5088. return false;
  5089. }
  5090. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  5091. bool optional_ok = false;
  5092. isize tuple_index = 0;
  5093. for (Ast *rhs_expr : rhs) {
  5094. CheckerContext c_ = *ctx;
  5095. CheckerContext *c = &c_;
  5096. Operand o = {};
  5097. Type *type_hint = nullptr;
  5098. if (tuple_index < lhs.count) {
  5099. type_hint = lhs[tuple_index].type;
  5100. }
  5101. check_expr_base(c, &o, rhs_expr, type_hint);
  5102. if (o.mode == Addressing_NoValue) {
  5103. error_operand_no_value(&o);
  5104. o.mode = Addressing_Invalid;
  5105. }
  5106. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5107. if (lhs.count == 2 && rhs.count == 1 &&
  5108. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5109. Ast *expr = unparen_expr(o.expr);
  5110. Operand val0 = o;
  5111. Operand val1 = o;
  5112. val0.mode = Addressing_Value;
  5113. val1.mode = Addressing_Value;
  5114. val1.type = t_untyped_bool;
  5115. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5116. if (expr->kind == Ast_TypeAssertion &&
  5117. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5118. // NOTE(bill): Used only for optimizations in the backend
  5119. if (is_blank_ident(lhs[0].expr)) {
  5120. expr->TypeAssertion.ignores[0] = true;
  5121. }
  5122. if (is_blank_ident(lhs[1].expr)) {
  5123. expr->TypeAssertion.ignores[1] = true;
  5124. }
  5125. }
  5126. array_add(operands, val0);
  5127. array_add(operands, val1);
  5128. optional_ok = true;
  5129. tuple_index += 2;
  5130. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  5131. Type *tuple = o.type;
  5132. GB_ASSERT(tuple->Tuple.variables.count == 2);
  5133. Ast *expr = unparen_expr(o.expr);
  5134. if (expr->kind == Ast_CallExpr) {
  5135. expr->CallExpr.optional_ok_one = true;
  5136. }
  5137. Operand val = o;
  5138. val.type = tuple->Tuple.variables[0]->type;
  5139. val.mode = Addressing_Value;
  5140. array_add(operands, val);
  5141. tuple_index += tuple->Tuple.variables.count;
  5142. } else {
  5143. array_add(operands, o);
  5144. tuple_index += 1;
  5145. }
  5146. } else {
  5147. TypeTuple *tuple = &o.type->Tuple;
  5148. for (Entity *e : tuple->variables) {
  5149. o.type = e->type;
  5150. array_add(operands, o);
  5151. check_no_copy_assignment(o, str_lit("assignment"));
  5152. }
  5153. tuple_index += tuple->variables.count;
  5154. }
  5155. }
  5156. return optional_ok;
  5157. }
  5158. typedef u32 UnpackFlags;
  5159. enum UnpackFlag : u32 {
  5160. UnpackFlag_None = 0,
  5161. UnpackFlag_AllowOk = 1<<0,
  5162. UnpackFlag_AllowUndef = 1<<1,
  5163. };
  5164. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags,
  5165. isize variadic_index = -1) {
  5166. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  5167. if (lhs == nullptr || c->decl == nullptr) {
  5168. return tuple_count;
  5169. }
  5170. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  5171. Entity *e = lhs[tuple_index + j];
  5172. if (e == nullptr) {
  5173. continue;
  5174. }
  5175. DeclInfo *decl = decl_info_of_entity(e);
  5176. if (decl == nullptr) {
  5177. continue;
  5178. }
  5179. rw_mutex_shared_lock(&decl->deps_mutex);
  5180. rw_mutex_lock(&c->decl->deps_mutex);
  5181. for (Entity *dep : decl->deps) {
  5182. ptr_set_add(&c->decl->deps, dep);
  5183. }
  5184. rw_mutex_unlock(&c->decl->deps_mutex);
  5185. rw_mutex_shared_unlock(&decl->deps_mutex);
  5186. }
  5187. return tuple_count;
  5188. };
  5189. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  5190. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  5191. bool is_variadic = variadic_index > -1;
  5192. if (!is_variadic) {
  5193. variadic_index = lhs_count;
  5194. }
  5195. bool optional_ok = false;
  5196. isize tuple_index = 0;
  5197. for (Ast *rhs : rhs_arguments) {
  5198. if (rhs->kind == Ast_FieldValue) {
  5199. error(rhs, "Invalid use of 'field = value'");
  5200. rhs = rhs->FieldValue.value;
  5201. }
  5202. CheckerContext c_ = *ctx;
  5203. CheckerContext *c = &c_;
  5204. Operand o = {};
  5205. Type *type_hint = nullptr;
  5206. if (lhs != nullptr) {
  5207. if (tuple_index < variadic_index) {
  5208. // NOTE(bill): override DeclInfo for dependency
  5209. Entity *e = lhs[tuple_index];
  5210. if (e != nullptr) {
  5211. type_hint = e->type;
  5212. }
  5213. } else if (is_variadic) {
  5214. Entity *e = lhs[variadic_index];
  5215. if (e != nullptr) {
  5216. GB_ASSERT(e->flags & EntityFlag_Ellipsis);
  5217. GB_ASSERT(is_type_slice(e->type));
  5218. type_hint = e->type->Slice.elem;
  5219. }
  5220. }
  5221. }
  5222. Ast *rhs_expr = unparen_expr(rhs);
  5223. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  5224. // NOTE(bill): Just handle this very specific logic here
  5225. o.type = t_untyped_uninit;
  5226. o.mode = Addressing_Value;
  5227. o.expr = rhs;
  5228. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  5229. } else {
  5230. check_expr_base(c, &o, rhs, type_hint);
  5231. }
  5232. if (o.mode == Addressing_NoValue) {
  5233. error_operand_no_value(&o);
  5234. o.mode = Addressing_Invalid;
  5235. }
  5236. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5237. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  5238. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5239. Ast *expr = unparen_expr(o.expr);
  5240. Operand val0 = o;
  5241. Operand val1 = o;
  5242. val0.mode = Addressing_Value;
  5243. val1.mode = Addressing_Value;
  5244. val1.type = t_untyped_bool;
  5245. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5246. if (expr->kind == Ast_TypeAssertion &&
  5247. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5248. // NOTE(bill): Used only for optimizations in the backend
  5249. if (is_blank_ident(lhs[0]->token)) {
  5250. expr->TypeAssertion.ignores[0] = true;
  5251. }
  5252. if (is_blank_ident(lhs[1]->token)) {
  5253. expr->TypeAssertion.ignores[1] = true;
  5254. }
  5255. }
  5256. array_add(operands, val0);
  5257. array_add(operands, val1);
  5258. optional_ok = true;
  5259. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  5260. } else {
  5261. array_add(operands, o);
  5262. tuple_index += 1;
  5263. }
  5264. } else {
  5265. TypeTuple *tuple = &o.type->Tuple;
  5266. for (Entity *e : tuple->variables) {
  5267. o.type = e->type;
  5268. array_add(operands, o);
  5269. }
  5270. isize count = tuple->variables.count;
  5271. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  5272. }
  5273. }
  5274. return optional_ok;
  5275. }
  5276. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  5277. GB_ASSERT(pt != nullptr);
  5278. GB_ASSERT(pt->kind == Type_Proc);
  5279. isize param_count = 0;
  5280. isize param_count_excluding_defaults = 0;
  5281. bool variadic = pt->Proc.variadic;
  5282. TypeTuple *param_tuple = nullptr;
  5283. if (pt->Proc.params != nullptr) {
  5284. param_tuple = &pt->Proc.params->Tuple;
  5285. param_count = param_tuple->variables.count;
  5286. if (variadic) {
  5287. for (isize i = param_count-1; i >= 0; i--) {
  5288. Entity *e = param_tuple->variables[i];
  5289. if (e->kind == Entity_TypeName) {
  5290. break;
  5291. }
  5292. if (e->kind == Entity_Variable) {
  5293. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5294. param_count--;
  5295. continue;
  5296. }
  5297. }
  5298. break;
  5299. }
  5300. param_count--;
  5301. }
  5302. }
  5303. param_count_excluding_defaults = param_count;
  5304. if (param_tuple != nullptr) {
  5305. for (isize i = param_count-1; i >= 0; i--) {
  5306. Entity *e = param_tuple->variables[i];
  5307. if (e->kind == Entity_TypeName) {
  5308. break;
  5309. }
  5310. if (e->kind == Entity_Variable) {
  5311. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5312. param_count_excluding_defaults--;
  5313. continue;
  5314. }
  5315. }
  5316. break;
  5317. }
  5318. }
  5319. if (param_count_) *param_count_ = param_count;
  5320. return param_count_excluding_defaults;
  5321. }
  5322. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  5323. isize param_count = pt->param_count;
  5324. for (isize i = 0; i < param_count; i++) {
  5325. Entity *e = pt->params->Tuple.variables[i];
  5326. String name = e->token.string;
  5327. if (is_blank_ident(name)) {
  5328. continue;
  5329. }
  5330. if (name == parameter_name) {
  5331. return i;
  5332. }
  5333. }
  5334. return -1;
  5335. }
  5336. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  5337. type = base_type(type);
  5338. GB_ASSERT(type->kind == Type_Proc);
  5339. return lookup_procedure_parameter(&type->Proc, parameter_name);
  5340. }
  5341. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  5342. Entity *entity, Type *proc_type,
  5343. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  5344. CallArgumentErrorMode show_error_mode,
  5345. CallArgumentData *data) {
  5346. TEMPORARY_ALLOCATOR_GUARD();
  5347. CallArgumentError err = CallArgumentError_None;
  5348. ast_node(ce, CallExpr, call);
  5349. GB_ASSERT(is_type_proc(proc_type));
  5350. proc_type = base_type(proc_type);
  5351. TypeProc *pt = &proc_type->Proc;
  5352. isize param_count = 0;
  5353. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  5354. bool variadic = pt->variadic;
  5355. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5356. i64 score = 0;
  5357. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  5358. Type *final_proc_type = proc_type;
  5359. Entity *gen_entity = nullptr;
  5360. if (vari_expand && !variadic) {
  5361. if (show_error) {
  5362. error(ce->ellipsis,
  5363. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  5364. LIT(ce->proc->Ident.token.string));
  5365. }
  5366. err = CallArgumentError_NonVariadicExpand;
  5367. } else if (vari_expand && pt->c_vararg) {
  5368. if (show_error) {
  5369. error(ce->ellipsis,
  5370. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  5371. LIT(ce->proc->Ident.token.string));
  5372. }
  5373. err = CallArgumentError_NonVariadicExpand;
  5374. }
  5375. GB_ASSERT(ce->split_args);
  5376. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  5377. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  5378. defer ({
  5379. for (Operand const &o : ordered_operands) {
  5380. if (o.expr != nullptr) {
  5381. call->viral_state_flags |= o.expr->viral_state_flags;
  5382. }
  5383. }
  5384. });
  5385. isize positional_operand_count = positional_operands.count;
  5386. if (variadic) {
  5387. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5388. } else if (positional_operand_count > pt->param_count) {
  5389. err = CallArgumentError_TooManyArguments;
  5390. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5391. if (show_error) {
  5392. gbString proc_str = expr_to_string(ce->proc);
  5393. defer (gb_string_free(proc_str));
  5394. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5395. }
  5396. return err;
  5397. }
  5398. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5399. for (isize i = 0; i < positional_operand_count; i++) {
  5400. ordered_operands[i] = positional_operands[i];
  5401. visited[i] = true;
  5402. }
  5403. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5404. bool named_variadic_param = false;
  5405. if (named_operands.count != 0) {
  5406. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5407. for_array(i, ce->split_args->named) {
  5408. Ast *arg = ce->split_args->named[i];
  5409. Operand operand = named_operands[i];
  5410. ast_node(fv, FieldValue, arg);
  5411. if (fv->field->kind != Ast_Ident) {
  5412. if (show_error) {
  5413. gbString expr_str = expr_to_string(fv->field);
  5414. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5415. gb_string_free(expr_str);
  5416. }
  5417. err = CallArgumentError_InvalidFieldValue;
  5418. continue;
  5419. }
  5420. String name = fv->field->Ident.token.string;
  5421. isize param_index = lookup_procedure_parameter(pt, name);
  5422. if (param_index < 0) {
  5423. if (show_error) {
  5424. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5425. }
  5426. err = CallArgumentError_ParameterNotFound;
  5427. continue;
  5428. }
  5429. if (pt->variadic && param_index == pt->variadic_index) {
  5430. named_variadic_param = true;
  5431. }
  5432. if (visited[param_index]) {
  5433. if (show_error) {
  5434. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5435. }
  5436. err = CallArgumentError_DuplicateParameter;
  5437. continue;
  5438. }
  5439. visited[param_index] = true;
  5440. ordered_operands[param_index] = operand;
  5441. }
  5442. }
  5443. isize dummy_argument_count = 0;
  5444. bool actually_variadic = false;
  5445. if (variadic) {
  5446. if (visited[pt->variadic_index] &&
  5447. positional_operand_count < positional_operands.count) {
  5448. if (show_error) {
  5449. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5450. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5451. }
  5452. err = CallArgumentError_DuplicateParameter;
  5453. } else if (!visited[pt->variadic_index]) {
  5454. visited[pt->variadic_index] = true;
  5455. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5456. if (vari_expand) {
  5457. if (variadic_operands.count == 0) {
  5458. error(call, "'..' in the wrong position");
  5459. } else {
  5460. GB_ASSERT(variadic_operands.count != 0);
  5461. *variadic_operand = variadic_operands[0];
  5462. variadic_operand->type = default_type(variadic_operand->type);
  5463. actually_variadic = true;
  5464. }
  5465. } else {
  5466. AstFile *f = call->file();
  5467. // HACK(bill): this is an awful hack
  5468. Operand o = {};
  5469. o.mode = Addressing_Value;
  5470. o.expr = ast_ident(f, make_token_ident("nil"));
  5471. o.expr->Ident.token.pos = ast_token(call).pos;
  5472. if (variadic_operands.count != 0) {
  5473. actually_variadic = true;
  5474. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5475. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5476. o.type = vt->type;
  5477. } else {
  5478. dummy_argument_count += 1;
  5479. o.type = t_untyped_nil;
  5480. }
  5481. *variadic_operand = o;
  5482. }
  5483. }
  5484. }
  5485. for (Operand const &o : ordered_operands) {
  5486. if (o.mode != Addressing_Invalid) {
  5487. check_no_copy_assignment(o, str_lit("procedure call expression"));
  5488. }
  5489. }
  5490. for (isize i = 0; i < pt->param_count; i++) {
  5491. if (!visited[i]) {
  5492. Entity *e = pt->params->Tuple.variables[i];
  5493. if (e->kind == Entity_Variable) {
  5494. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5495. ordered_operands[i].mode = Addressing_Value;
  5496. ordered_operands[i].type = e->type;
  5497. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5498. dummy_argument_count += 1;
  5499. score += assign_score_function(1);
  5500. continue;
  5501. }
  5502. }
  5503. if (show_error) {
  5504. if (e->kind == Entity_TypeName) {
  5505. error(call, "Type parameter '%.*s' is missing in procedure call",
  5506. LIT(e->token.string));
  5507. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5508. // Ignore
  5509. } else {
  5510. gbString str = type_to_string(e->type);
  5511. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5512. LIT(e->token.string), str);
  5513. gb_string_free(str);
  5514. }
  5515. }
  5516. err = CallArgumentError_ParameterMissing;
  5517. }
  5518. }
  5519. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5520. bool allow_array_programming = !(e && (e->flags & EntityFlag_NoBroadcast));
  5521. i64 s = 0;
  5522. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic, allow_array_programming)) {
  5523. bool ok = false;
  5524. if (e && (e->flags & EntityFlag_AnyInt)) {
  5525. if (is_type_integer(param_type)) {
  5526. ok = check_is_castable_to(c, o, param_type);
  5527. }
  5528. }
  5529. if (!allow_array_programming && check_is_assignable_to_with_score(c, o, param_type, nullptr, param_is_variadic, !allow_array_programming)) {
  5530. if (show_error) {
  5531. error(o->expr, "'#no_broadcast' disallows automatic broadcasting a value across all elements of an array-like type in a procedure argument");
  5532. }
  5533. }
  5534. if (ok) {
  5535. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5536. } else {
  5537. if (show_error) {
  5538. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5539. }
  5540. err = CallArgumentError_WrongTypes;
  5541. }
  5542. } else if (show_error) {
  5543. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5544. }
  5545. if (e && e->flags & EntityFlag_ConstInput) {
  5546. if (o->mode != Addressing_Constant) {
  5547. if (show_error) {
  5548. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5549. }
  5550. err = CallArgumentError_NoneConstantParameter;
  5551. }
  5552. }
  5553. if (!err && is_type_any(param_type)) {
  5554. add_type_info_type(c, o->type);
  5555. }
  5556. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5557. add_type_info_type(c, o->type);
  5558. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5559. } else if (show_error && is_type_untyped(o->type)) {
  5560. update_untyped_expr_type(c, o->expr, param_type, true);
  5561. }
  5562. return s;
  5563. };
  5564. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5565. err = CallArgumentError_None;
  5566. if (variadic) {
  5567. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5568. Type *t = pt->params->Tuple.variables[0]->type;
  5569. if (is_type_polymorphic(t)) {
  5570. if (show_error) {
  5571. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5572. }
  5573. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5574. }
  5575. }
  5576. } else {
  5577. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5578. PolyProcData poly_proc_data = {};
  5579. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5580. gen_entity = poly_proc_data.gen_entity;
  5581. Type *gept = base_type(gen_entity->type);
  5582. GB_ASSERT(is_type_proc(gept));
  5583. final_proc_type = gen_entity->type;
  5584. pt = &gept->Proc;
  5585. } else {
  5586. err = CallArgumentError_WrongTypes;
  5587. }
  5588. }
  5589. for (isize i = 0; i < pt->param_count; i++) {
  5590. Operand *o = &ordered_operands[i];
  5591. if (o->mode == Addressing_Invalid) {
  5592. continue;
  5593. }
  5594. Entity *e = pt->params->Tuple.variables[i];
  5595. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5596. if (e->kind == Entity_TypeName) {
  5597. GB_ASSERT(pt->is_polymorphic);
  5598. if (o->mode != Addressing_Type) {
  5599. if (show_error) {
  5600. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5601. }
  5602. err = CallArgumentError_WrongTypes;
  5603. }
  5604. if (are_types_identical(e->type, o->type)) {
  5605. score += assign_score_function(1);
  5606. } else {
  5607. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5608. }
  5609. continue;
  5610. }
  5611. if (param_is_variadic) {
  5612. if (!named_variadic_param) {
  5613. continue;
  5614. }
  5615. }
  5616. score += eval_param_and_score(c, o, e->type, err, false, e, show_error);
  5617. }
  5618. }
  5619. if (variadic) {
  5620. Entity *var_entity = pt->params->Tuple.variables[pt->variadic_index];
  5621. Type *slice = var_entity->type;
  5622. GB_ASSERT(is_type_slice(slice));
  5623. Type *elem = base_type(slice)->Slice.elem;
  5624. Type *t = elem;
  5625. if (is_type_polymorphic(t)) {
  5626. if (show_error) {
  5627. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5628. }
  5629. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5630. }
  5631. for_array(operand_index, variadic_operands) {
  5632. Operand *o = &variadic_operands[operand_index];
  5633. if (vari_expand) {
  5634. t = slice;
  5635. if (operand_index > 0) {
  5636. if (show_error) {
  5637. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5638. }
  5639. if (data) {
  5640. data->score = score;
  5641. data->result_type = final_proc_type->Proc.results;
  5642. data->gen_entity = gen_entity;
  5643. }
  5644. return CallArgumentError_MultipleVariadicExpand;
  5645. }
  5646. }
  5647. score += eval_param_and_score(c, o, t, err, true, var_entity, show_error);
  5648. }
  5649. if (!vari_expand && variadic_operands.count != 0) {
  5650. // NOTE(bill, 2024-07-14): minimize the stack usage for variadic parameters with the backing array
  5651. if (c->decl) {
  5652. bool found = false;
  5653. for (auto &vr : c->decl->variadic_reuses) {
  5654. if (are_types_identical(slice, vr.slice_type)) {
  5655. vr.max_count = gb_max(vr.max_count, variadic_operands.count);
  5656. found = true;
  5657. break;
  5658. }
  5659. }
  5660. if (!found) {
  5661. array_add(&c->decl->variadic_reuses, VariadicReuseData{slice, variadic_operands.count});
  5662. }
  5663. }
  5664. }
  5665. }
  5666. if (data) {
  5667. data->score = score;
  5668. data->result_type = final_proc_type->Proc.results;
  5669. data->gen_entity = gen_entity;
  5670. Ast *proc_lit = nullptr;
  5671. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5672. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5673. if (vp && vp->kind == Ast_ProcLit) {
  5674. proc_lit = vp;
  5675. }
  5676. }
  5677. if (proc_lit == nullptr) {
  5678. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5679. }
  5680. }
  5681. return err;
  5682. }
  5683. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5684. GB_ASSERT(ce != nullptr);
  5685. if (ce->args.count == 0) {
  5686. return false;
  5687. }
  5688. return ce->args[0]->kind == Ast_FieldValue;
  5689. }
  5690. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_) {
  5691. Entity **lhs = nullptr;
  5692. isize lhs_count = -1;
  5693. if (proc_type == nullptr || proc_type == t_invalid) {
  5694. return nullptr;
  5695. }
  5696. GB_ASSERT(is_type_proc(proc_type));
  5697. TypeProc *pt = &base_type(proc_type)->Proc;
  5698. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5699. if (pt->params != nullptr) {
  5700. lhs = pt->params->Tuple.variables.data;
  5701. lhs_count = pt->params->Tuple.variables.count;
  5702. }
  5703. } else {
  5704. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5705. if (pt->params == nullptr) {
  5706. lhs_count = 0;
  5707. } else {
  5708. lhs_count = pt->params->Tuple.variables.count;
  5709. }
  5710. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5711. for (isize i = 0; i < lhs_count; i++) {
  5712. Entity *e = pt->params->Tuple.variables[i];
  5713. if (!is_type_polymorphic(e->type)) {
  5714. lhs[i] = e;
  5715. }
  5716. }
  5717. }
  5718. if (lhs_count_) *lhs_count_ = lhs_count;
  5719. return lhs;
  5720. }
  5721. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5722. if (clauses != nullptr) {
  5723. for (Ast *clause : *clauses) {
  5724. Operand o = {};
  5725. check_expr(ctx, &o, clause);
  5726. if (o.mode != Addressing_Constant) {
  5727. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5728. if (print_err && call_expr) error(call_expr, "at caller location");
  5729. return false;
  5730. } else if (o.value.kind != ExactValue_Bool) {
  5731. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5732. if (print_err && call_expr) error(call_expr, "at caller location");
  5733. return false;
  5734. } else if (!o.value.value_bool) {
  5735. if (print_err) {
  5736. ERROR_BLOCK();
  5737. gbString str = expr_to_string(clause);
  5738. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5739. gb_string_free(str);
  5740. if (scope != nullptr) {
  5741. isize print_count = 0;
  5742. for (auto const &entry : scope->elements) {
  5743. Entity *e = entry.value;
  5744. switch (e->kind) {
  5745. case Entity_TypeName: {
  5746. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5747. gbString str = type_to_string(e->type);
  5748. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5749. gb_string_free(str);
  5750. print_count += 1;
  5751. break;
  5752. }
  5753. case Entity_Constant: {
  5754. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5755. gbString str = exact_value_to_string(e->Constant.value);
  5756. if (is_type_untyped(e->type)) {
  5757. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5758. } else {
  5759. gbString t = type_to_string(e->type);
  5760. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5761. gb_string_free(t);
  5762. }
  5763. gb_string_free(str);
  5764. print_count += 1;
  5765. break;
  5766. }
  5767. }
  5768. }
  5769. }
  5770. if (call_expr) {
  5771. TokenPos pos = ast_token(call_expr).pos;
  5772. error_line("%s at caller location\n", token_pos_to_string(pos));
  5773. }
  5774. }
  5775. return false;
  5776. }
  5777. if (ast_file_vet_style(ctx->file)) {
  5778. Ast *c = unparen_expr(clause);
  5779. if (c->kind == Ast_BinaryExpr && c->BinaryExpr.op.kind == Token_CmpAnd) {
  5780. ERROR_BLOCK();
  5781. error(c, "Prefer to separate 'where' clauses with a comma rather than '&&'");
  5782. gbString x = expr_to_string(c->BinaryExpr.left);
  5783. gbString y = expr_to_string(c->BinaryExpr.right);
  5784. error_line("\tSuggestion: '%s, %s'\n", x, y);
  5785. gb_string_free(y);
  5786. gb_string_free(x);
  5787. }
  5788. }
  5789. }
  5790. }
  5791. return true;
  5792. }
  5793. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5794. bool success = true;
  5795. type = base_type(type);
  5796. if (named_args.count > 0) {
  5797. TypeProc *pt = nullptr;
  5798. if (is_type_proc(type)) {
  5799. pt = &type->Proc;
  5800. }
  5801. for_array(i, named_args) {
  5802. Ast *arg = named_args[i];
  5803. if (arg->kind != Ast_FieldValue) {
  5804. if (show_error) {
  5805. error(arg, "Expected a 'field = value'");
  5806. }
  5807. return false;
  5808. }
  5809. ast_node(fv, FieldValue, arg);
  5810. if (fv->field->kind != Ast_Ident) {
  5811. if (show_error) {
  5812. gbString expr_str = expr_to_string(fv->field);
  5813. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5814. gb_string_free(expr_str);
  5815. }
  5816. success = false;
  5817. continue;
  5818. }
  5819. String key = fv->field->Ident.token.string;
  5820. Ast *value = fv->value;
  5821. Type *type_hint = nullptr;
  5822. if (pt) {
  5823. isize param_index = lookup_procedure_parameter(pt, key);
  5824. if (param_index < 0) {
  5825. if (show_error) {
  5826. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5827. }
  5828. success = false;
  5829. continue;
  5830. }
  5831. Entity *e = pt->params->Tuple.variables[param_index];
  5832. if (!is_type_polymorphic(e->type)) {
  5833. type_hint = e->type;
  5834. }
  5835. }
  5836. Operand o = {};
  5837. check_expr_with_type_hint(c, &o, value, type_hint);
  5838. if (o.mode == Addressing_Invalid) {
  5839. success = false;
  5840. }
  5841. array_add(named_operands, o);
  5842. }
  5843. }
  5844. return success;
  5845. }
  5846. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5847. Entity *e, Type *proc_type,
  5848. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5849. CallArgumentErrorMode show_error_mode,
  5850. CallArgumentData *data) {
  5851. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5852. Ast *ident = operand->expr;
  5853. while (ident->kind == Ast_SelectorExpr) {
  5854. Ast *s = ident->SelectorExpr.selector;
  5855. ident = s;
  5856. }
  5857. if (e == nullptr) {
  5858. e = entity_of_node(ident);
  5859. if (e != nullptr) {
  5860. proc_type = e->type;
  5861. }
  5862. }
  5863. GB_ASSERT(proc_type != nullptr);
  5864. proc_type = base_type(proc_type);
  5865. if (proc_type == t_invalid) {
  5866. return false;
  5867. }
  5868. GB_ASSERT(proc_type->kind == Type_Proc);
  5869. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5870. if (return_on_failure && err != CallArgumentError_None) {
  5871. return false;
  5872. }
  5873. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5874. if (!return_on_failure && entity_to_use != nullptr) {
  5875. add_entity_use(c, ident, entity_to_use);
  5876. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5877. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5878. }
  5879. if (data->gen_entity != nullptr) {
  5880. Entity *e = data->gen_entity;
  5881. DeclInfo *decl = data->gen_entity->decl_info;
  5882. CheckerContext ctx = *c;
  5883. ctx.scope = decl->scope;
  5884. ctx.decl = decl;
  5885. ctx.proc_name = e->token.string;
  5886. ctx.curr_proc_decl = decl;
  5887. ctx.curr_proc_sig = e->type;
  5888. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5889. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5890. if (return_on_failure) {
  5891. if (!ok) {
  5892. return false;
  5893. }
  5894. } else {
  5895. decl->where_clauses_evaluated = true;
  5896. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5897. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5898. }
  5899. if (is_type_proc(data->gen_entity->type)) {
  5900. Type *t = base_type(entity_to_use->type);
  5901. data->result_type = t->Proc.results;
  5902. }
  5903. }
  5904. }
  5905. return true;
  5906. }
  5907. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5908. ast_node(ce, CallExpr, call);
  5909. GB_ASSERT(ce->split_args != nullptr);
  5910. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5911. Slice<Ast *> const &named_args = ce->split_args->named;
  5912. CallArgumentData data = {};
  5913. data.result_type = t_invalid;
  5914. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5915. auto procs = proc_group_entities_cloned(c, *operand);
  5916. if (procs.count > 1) {
  5917. isize max_arg_count = positional_args.count + named_args.count;
  5918. for (Ast *arg : positional_args) {
  5919. // NOTE(bill): The only thing that may have multiple values
  5920. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5921. arg = strip_or_return_expr(arg);
  5922. if (arg && arg->kind == Ast_CallExpr) {
  5923. max_arg_count = ISIZE_MAX;
  5924. break;
  5925. }
  5926. }
  5927. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5928. // NOTE(bill): The only thing that may have multiple values
  5929. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5930. if (arg->kind == Ast_FieldValue) {
  5931. arg = strip_or_return_expr(arg->FieldValue.value);
  5932. if (arg && arg->kind == Ast_CallExpr) {
  5933. max_arg_count = ISIZE_MAX;
  5934. break;
  5935. }
  5936. }
  5937. }
  5938. // ignore named arguments first
  5939. for (Ast *arg : named_args) {
  5940. if (arg->kind != Ast_FieldValue) {
  5941. continue;
  5942. }
  5943. ast_node(fv, FieldValue, arg);
  5944. if (fv->field->kind != Ast_Ident) {
  5945. continue;
  5946. }
  5947. String key = fv->field->Ident.token.string;
  5948. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5949. Type *t = procs[proc_index]->type;
  5950. if (is_type_proc(t)) {
  5951. isize param_index = lookup_procedure_parameter(t, key);
  5952. if (param_index < 0) {
  5953. array_unordered_remove(&procs, proc_index);
  5954. }
  5955. }
  5956. }
  5957. }
  5958. if (procs.count == 0) {
  5959. // if any of the named arguments are wrong, the `procs` will be empty
  5960. // just start from scratch
  5961. array_free(&procs);
  5962. procs = proc_group_entities_cloned(c, *operand);
  5963. }
  5964. // filter by positional argument length
  5965. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5966. Entity *proc = procs[proc_index];
  5967. Type *pt = base_type(proc->type);
  5968. if (!(pt != nullptr && is_type_proc(pt))) {
  5969. proc_index++;
  5970. continue;
  5971. }
  5972. isize param_count = 0;
  5973. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5974. if (param_count_excluding_defaults > max_arg_count) {
  5975. array_unordered_remove(&procs, proc_index);
  5976. continue;
  5977. }
  5978. proc_index++;
  5979. }
  5980. }
  5981. Entity **lhs = nullptr;
  5982. isize lhs_count = -1;
  5983. i32 variadic_index = -1;
  5984. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5985. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5986. defer (array_free(&positional_operands));
  5987. defer (array_free(&named_operands));
  5988. if (procs.count == 1) {
  5989. Entity *e = procs[0];
  5990. Type *pt = base_type(e->type);
  5991. if (pt != nullptr && is_type_proc(pt)) {
  5992. lhs = populate_proc_parameter_list(c, pt, &lhs_count);
  5993. if (pt->Proc.variadic) {
  5994. variadic_index = pt->Proc.variadic_index;
  5995. }
  5996. }
  5997. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  5998. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5999. check_call_arguments_single(c, call, operand,
  6000. e, e->type,
  6001. positional_operands, named_operands,
  6002. CallArgumentErrorMode::ShowErrors,
  6003. &data);
  6004. }
  6005. return data;
  6006. }
  6007. {
  6008. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  6009. // where the same positional parameter has the same type value (and ellipsis)
  6010. isize proc_arg_count = -1;
  6011. for (Entity *p : procs) {
  6012. Type *pt = base_type(p->type);
  6013. if (pt != nullptr && is_type_proc(pt)) {
  6014. if (proc_arg_count < 0) {
  6015. proc_arg_count = pt->Proc.param_count;
  6016. } else {
  6017. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  6018. }
  6019. }
  6020. }
  6021. if (proc_arg_count >= 0) {
  6022. lhs_count = proc_arg_count;
  6023. if (lhs_count > 0) {
  6024. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  6025. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  6026. Entity *e = nullptr;
  6027. for (Entity *p : procs) {
  6028. Type *pt = base_type(p->type);
  6029. if (!(pt != nullptr && is_type_proc(pt))) {
  6030. continue;
  6031. }
  6032. if (e == nullptr) {
  6033. e = pt->Proc.params->Tuple.variables[param_index];
  6034. } else {
  6035. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  6036. if (e == f) {
  6037. continue;
  6038. }
  6039. if (are_types_identical(e->type, f->type)) {
  6040. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  6041. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  6042. if (ee == fe) {
  6043. continue;
  6044. }
  6045. }
  6046. // NOTE(bill): Entities are not close enough to be used
  6047. e = nullptr;
  6048. break;
  6049. }
  6050. }
  6051. lhs[param_index] = e;
  6052. }
  6053. for (Entity *p : procs) {
  6054. Type *pt = base_type(p->type);
  6055. if (!(pt != nullptr && is_type_proc(pt))) {
  6056. continue;
  6057. }
  6058. if (pt->Proc.is_polymorphic) {
  6059. if (variadic_index == -1) {
  6060. variadic_index = pt->Proc.variadic_index;
  6061. } else if (variadic_index != pt->Proc.variadic_index) {
  6062. variadic_index = -1;
  6063. break;
  6064. }
  6065. } else {
  6066. variadic_index = -1;
  6067. break;
  6068. }
  6069. }
  6070. }
  6071. }
  6072. }
  6073. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6074. for_array(i, named_args) {
  6075. Ast *arg = named_args[i];
  6076. if (arg->kind != Ast_FieldValue) {
  6077. error(arg, "Expected a 'field = value'");
  6078. return data;
  6079. }
  6080. ast_node(fv, FieldValue, arg);
  6081. if (fv->field->kind != Ast_Ident) {
  6082. gbString expr_str = expr_to_string(fv->field);
  6083. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6084. gb_string_free(expr_str);
  6085. return data;
  6086. }
  6087. String key = fv->field->Ident.token.string;
  6088. Ast *value = fv->value;
  6089. Type *type_hint = nullptr;
  6090. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  6091. Entity *e = lhs[lhs_idx];
  6092. if (e != nullptr && e->token.string == key &&
  6093. !is_type_polymorphic(e->type)) {
  6094. type_hint = e->type;
  6095. break;
  6096. }
  6097. }
  6098. Operand o = {};
  6099. check_expr_with_type_hint(c, &o, value, type_hint);
  6100. array_add(&named_operands, o);
  6101. }
  6102. gb_free(heap_allocator(), lhs);
  6103. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  6104. defer (array_free(&valids));
  6105. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  6106. defer (array_free(&proc_entities));
  6107. for (Entity *proc : procs) {
  6108. array_add(&proc_entities, proc);
  6109. }
  6110. int max_matched_features = 0;
  6111. gbString expr_name = expr_to_string(operand->expr);
  6112. defer (gb_string_free(expr_name));
  6113. for_array(i, procs) {
  6114. Entity *p = procs[i];
  6115. if (p->flags & EntityFlag_Disabled) {
  6116. continue;
  6117. }
  6118. Type *pt = base_type(p->type);
  6119. if (pt != nullptr && is_type_proc(pt)) {
  6120. CallArgumentData data = {};
  6121. CheckerContext ctx = *c;
  6122. ctx.no_polymorphic_errors = true;
  6123. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  6124. ctx.hide_polymorphic_errors = true;
  6125. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  6126. p, pt,
  6127. positional_operands, named_operands,
  6128. CallArgumentErrorMode::NoErrors,
  6129. &data);
  6130. if (!is_a_candidate) {
  6131. continue;
  6132. }
  6133. isize index = i;
  6134. ValidIndexAndScore item = {};
  6135. item.score = data.score;
  6136. if (data.gen_entity != nullptr) {
  6137. array_add(&proc_entities, data.gen_entity);
  6138. index = proc_entities.count-1;
  6139. // prefer non-polymorphic procedures over polymorphic
  6140. item.score += assign_score_function(1);
  6141. }
  6142. max_matched_features = gb_max(max_matched_features, matched_target_features(&pt->Proc));
  6143. item.index = index;
  6144. array_add(&valids, item);
  6145. }
  6146. }
  6147. if (max_matched_features > 0) {
  6148. for_array(i, valids) {
  6149. Entity *p = procs[valids[i].index];
  6150. Type *t = base_type(p->type);
  6151. GB_ASSERT(t->kind == Type_Proc);
  6152. int matched = matched_target_features(&t->Proc);
  6153. valids[i].score += assign_score_function(max_matched_features-matched);
  6154. }
  6155. }
  6156. if (valids.count > 1) {
  6157. array_sort(valids, valid_index_and_score_cmp);
  6158. i64 best_score = valids[0].score;
  6159. Entity *best_entity = proc_entities[valids[0].index];
  6160. GB_ASSERT(best_entity != nullptr);
  6161. for (isize i = 1; i < valids.count; i++) {
  6162. if (best_score > valids[i].score) {
  6163. valids.count = i;
  6164. break;
  6165. }
  6166. if (best_entity == proc_entities[valids[i].index]) {
  6167. valids.count = i;
  6168. break;
  6169. }
  6170. }
  6171. }
  6172. auto print_argument_types = [&]() {
  6173. error_line("\tGiven argument types: (");
  6174. isize i = 0;
  6175. for (Operand const &o : positional_operands) {
  6176. if (i++ > 0) error_line(", ");
  6177. gbString type = type_to_string(o.type);
  6178. defer (gb_string_free(type));
  6179. error_line("%s", type);
  6180. }
  6181. for (Operand const &o : named_operands) {
  6182. if (i++ > 0) error_line(", ");
  6183. gbString type = type_to_string(o.type);
  6184. defer (gb_string_free(type));
  6185. if (i < ce->split_args->named.count) {
  6186. Ast *named_field = ce->split_args->named[i];
  6187. ast_node(fv, FieldValue, named_field);
  6188. gbString field = expr_to_string(fv->field);
  6189. defer (gb_string_free(field));
  6190. error_line("%s = %s", field, type);
  6191. } else {
  6192. error_line("%s", type);
  6193. }
  6194. }
  6195. error_line(")\n");
  6196. };
  6197. if (valids.count == 0) {
  6198. ERROR_BLOCK();
  6199. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  6200. if (positional_operands.count == 0 && named_operands.count == 0) {
  6201. error_line("\tNo given arguments\n");
  6202. } else {
  6203. print_argument_types();
  6204. }
  6205. if (procs.count == 0) {
  6206. procs = proc_group_entities_cloned(c, *operand);
  6207. }
  6208. if (procs.count > 0) {
  6209. error_line("Did you mean to use one of the following:\n");
  6210. }
  6211. // Try to reduce the list further for `$T: typeid` like parameters
  6212. bool *possibly_ignore = gb_alloc_array(temporary_allocator(), bool, procs.count);
  6213. isize possibly_ignore_set = 0;
  6214. if (true) {
  6215. // NOTE(bill): This currently only checks for #soa types
  6216. for_array(i, procs) {
  6217. Entity *proc = procs[i];
  6218. Type *t = base_type(proc->type);
  6219. if (t == nullptr || t->kind != Type_Proc) {
  6220. continue;
  6221. }
  6222. TypeProc *pt = &t->Proc;
  6223. if (pt->param_count == 0) {
  6224. continue;
  6225. }
  6226. for_array(j, pt->params->Tuple.variables) {
  6227. Entity *v = pt->params->Tuple.variables[j];
  6228. if (v->kind != Entity_TypeName) {
  6229. continue;
  6230. }
  6231. Type *dst_t = base_type(v->type);
  6232. while (dst_t->kind == Type_Generic && dst_t->Generic.specialized) {
  6233. dst_t = dst_t->Generic.specialized;
  6234. }
  6235. if (j >= positional_operands.count) {
  6236. continue;
  6237. }
  6238. Operand const &o = positional_operands[j];
  6239. if (o.mode != Addressing_Type) {
  6240. continue;
  6241. }
  6242. Type *t = base_type(o.type);
  6243. if (t->kind == dst_t->kind) {
  6244. continue;
  6245. }
  6246. Type *st = base_type(type_deref(o.type));
  6247. Type *dt = base_type(type_deref(dst_t));
  6248. if (st->kind == dt->kind) {
  6249. continue;
  6250. }
  6251. if (is_type_soa_struct(st)) {
  6252. possibly_ignore[i] = true;
  6253. possibly_ignore_set += 1;
  6254. continue;
  6255. }
  6256. }
  6257. }
  6258. }
  6259. if (possibly_ignore_set == procs.count) {
  6260. possibly_ignore_set = 0;
  6261. }
  6262. isize max_name_length = 0;
  6263. isize max_type_length = 0;
  6264. for_array(i, procs) {
  6265. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6266. continue;
  6267. }
  6268. Entity *proc = procs[i];
  6269. Type *t = base_type(proc->type);
  6270. if (t == t_invalid) continue;
  6271. String prefix = {};
  6272. String prefix_sep = {};
  6273. if (proc->pkg) {
  6274. prefix = proc->pkg->name;
  6275. prefix_sep = str_lit(".");
  6276. }
  6277. String name = proc->token.string;
  6278. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  6279. gbString pt;
  6280. if (t->Proc.node != nullptr) {
  6281. pt = expr_to_string(t->Proc.node);
  6282. } else {
  6283. pt = type_to_string(t);
  6284. }
  6285. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  6286. gb_string_free(pt);
  6287. }
  6288. isize max_spaces = gb_max(max_name_length, max_type_length);
  6289. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  6290. for (isize i = 0; i < max_spaces; i++) {
  6291. spaces[i] = ' ';
  6292. }
  6293. spaces[max_spaces] = 0;
  6294. for_array(i, procs) {
  6295. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6296. continue;
  6297. }
  6298. Entity *proc = procs[i];
  6299. TokenPos pos = proc->token.pos;
  6300. Type *t = base_type(proc->type);
  6301. if (t == t_invalid) continue;
  6302. GB_ASSERT(t->kind == Type_Proc);
  6303. gbString pt;
  6304. defer (gb_string_free(pt));
  6305. if (t->Proc.node != nullptr) {
  6306. pt = expr_to_string(t->Proc.node);
  6307. } else {
  6308. pt = type_to_string(t);
  6309. }
  6310. String prefix = {};
  6311. String prefix_sep = {};
  6312. if (proc->pkg) {
  6313. prefix = proc->pkg->name;
  6314. prefix_sep = str_lit(".");
  6315. }
  6316. String name = proc->token.string;
  6317. isize len = prefix.len + prefix_sep.len + name.len;
  6318. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  6319. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  6320. char const *sep = "::";
  6321. if (proc->kind == Entity_Variable) {
  6322. sep = ":=";
  6323. }
  6324. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  6325. LIT(prefix), LIT(prefix_sep), LIT(name),
  6326. name_padding, spaces,
  6327. sep,
  6328. pt,
  6329. type_padding, spaces,
  6330. token_pos_to_string(pos)
  6331. );
  6332. }
  6333. if (procs.count > 0) {
  6334. error_line("\n");
  6335. }
  6336. data.result_type = t_invalid;
  6337. } else if (valids.count > 1) {
  6338. ERROR_BLOCK();
  6339. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  6340. if (positional_operands.count == 0 && named_operands.count == 0) {
  6341. error_line("\tNo given arguments\n");
  6342. } else {
  6343. print_argument_types();
  6344. }
  6345. for (auto const &valid : valids) {
  6346. Entity *proc = proc_entities[valid.index];
  6347. GB_ASSERT(proc != nullptr);
  6348. TokenPos pos = proc->token.pos;
  6349. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  6350. gbString pt = nullptr;
  6351. defer (gb_string_free(pt));
  6352. if (t->Proc.node != nullptr) {
  6353. pt = expr_to_string(t->Proc.node);
  6354. } else {
  6355. pt = type_to_string(t);
  6356. }
  6357. String name = proc->token.string;
  6358. char const *sep = "::";
  6359. if (proc->kind == Entity_Variable) {
  6360. sep = ":=";
  6361. }
  6362. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  6363. if (proc->decl_info->proc_lit != nullptr) {
  6364. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  6365. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  6366. if (pl->where_token.kind != Token_Invalid) {
  6367. error_line("\n\t\twhere ");
  6368. for_array(j, pl->where_clauses) {
  6369. Ast *clause = pl->where_clauses[j];
  6370. if (j != 0) {
  6371. error_line("\t\t ");
  6372. }
  6373. gbString str = expr_to_string(clause);
  6374. error_line("%s", str);
  6375. gb_string_free(str);
  6376. if (j != pl->where_clauses.count-1) {
  6377. error_line(",");
  6378. }
  6379. }
  6380. error_line("\n\t");
  6381. }
  6382. }
  6383. error_line("at %s\n", token_pos_to_string(pos));
  6384. }
  6385. data.result_type = t_invalid;
  6386. } else {
  6387. GB_ASSERT(valids.count == 1);
  6388. Ast *ident = operand->expr;
  6389. while (ident->kind == Ast_SelectorExpr) {
  6390. Ast *s = ident->SelectorExpr.selector;
  6391. ident = s;
  6392. }
  6393. Entity *e = proc_entities[valids[0].index];
  6394. GB_ASSERT(e != nullptr);
  6395. Array<Operand> named_operands = {};
  6396. check_call_arguments_single(c, call, operand,
  6397. e, e->type,
  6398. positional_operands, named_operands,
  6399. CallArgumentErrorMode::ShowErrors,
  6400. &data);
  6401. return data;
  6402. }
  6403. return data;
  6404. }
  6405. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  6406. Type *proc_type = nullptr;
  6407. CallArgumentData data = {};
  6408. data.result_type = t_invalid;
  6409. proc_type = base_type(operand->type);
  6410. TypeProc *pt = nullptr;
  6411. if (proc_type) {
  6412. pt = &proc_type->Proc;
  6413. }
  6414. TEMPORARY_ALLOCATOR_GUARD();
  6415. ast_node(ce, CallExpr, call);
  6416. bool any_failure = false;
  6417. // Split positional and named args into separate arrays/slices
  6418. Slice<Ast *> positional_args = {};
  6419. Slice<Ast *> named_args = {};
  6420. if (ce->split_args == nullptr) {
  6421. positional_args = ce->args;
  6422. for (isize i = 0; i < ce->args.count; i++) {
  6423. Ast *arg = ce->args.data[i];
  6424. if (arg->kind == Ast_FieldValue) {
  6425. positional_args.count = i;
  6426. break;
  6427. }
  6428. }
  6429. named_args = slice(ce->args, positional_args.count, ce->args.count);
  6430. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  6431. split_args->positional = positional_args;
  6432. split_args->named = named_args;
  6433. ce->split_args = split_args;
  6434. } else {
  6435. positional_args = ce->split_args->positional;
  6436. named_args = ce->split_args->named;
  6437. }
  6438. if (operand->mode == Addressing_ProcGroup) {
  6439. return check_call_arguments_proc_group(c, operand, call);
  6440. }
  6441. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  6442. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6443. defer (array_free(&positional_operands));
  6444. defer (array_free(&named_operands));
  6445. if (positional_args.count > 0) {
  6446. Entity **lhs = nullptr;
  6447. isize lhs_count = -1;
  6448. i32 variadic_index = -1;
  6449. if (pt != nullptr) {
  6450. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count);
  6451. if (pt->variadic) {
  6452. variadic_index = pt->variadic_index;
  6453. }
  6454. }
  6455. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6456. }
  6457. if (named_args.count > 0) {
  6458. for_array(i, named_args) {
  6459. Ast *arg = named_args[i];
  6460. if (arg->kind != Ast_FieldValue) {
  6461. error(arg, "Expected a 'field = value'");
  6462. return data;
  6463. }
  6464. ast_node(fv, FieldValue, arg);
  6465. if (fv->field->kind != Ast_Ident) {
  6466. gbString expr_str = expr_to_string(fv->field);
  6467. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6468. any_failure = true;
  6469. gb_string_free(expr_str);
  6470. continue;
  6471. }
  6472. String key = fv->field->Ident.token.string;
  6473. Ast *value = fv->value;
  6474. isize param_index = lookup_procedure_parameter(pt, key);
  6475. Type *type_hint = nullptr;
  6476. if (param_index >= 0) {
  6477. Entity *e = pt->params->Tuple.variables[param_index];
  6478. type_hint = e->type;
  6479. }
  6480. Operand o = {};
  6481. check_expr_with_type_hint(c, &o, value, type_hint);
  6482. if (o.mode == Addressing_Invalid) {
  6483. any_failure = true;
  6484. }
  6485. array_add(&named_operands, o);
  6486. }
  6487. }
  6488. if (!any_failure) {
  6489. check_call_arguments_single(c, call, operand,
  6490. nullptr, proc_type,
  6491. positional_operands, named_operands,
  6492. CallArgumentErrorMode::ShowErrors,
  6493. &data);
  6494. } else if (pt) {
  6495. data.result_type = pt->results;
  6496. }
  6497. return data;
  6498. }
  6499. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6500. if (!is_type_polymorphic_record(t)) {
  6501. return -1;
  6502. }
  6503. TypeTuple *params = get_record_polymorphic_params(t);
  6504. if (params == nullptr) {
  6505. return -1;
  6506. }
  6507. for_array(i, params->variables) {
  6508. Entity *e = params->variables[i];
  6509. String name = e->token.string;
  6510. if (is_blank_ident(name)) {
  6511. continue;
  6512. }
  6513. if (name == parameter_name) {
  6514. return i;
  6515. }
  6516. }
  6517. return -1;
  6518. }
  6519. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6520. ast_node(ce, CallExpr, call);
  6521. Type *original_type = operand->type;
  6522. GB_ASSERT(is_type_polymorphic_record(original_type));
  6523. bool show_error = true;
  6524. Array<Operand> operands = {};
  6525. defer (array_free(&operands));
  6526. CallArgumentError err = CallArgumentError_None;
  6527. bool named_fields = false;
  6528. {
  6529. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6530. auto prev_type_path = c->type_path;
  6531. c->type_path = new_checker_type_path();
  6532. defer ({
  6533. destroy_checker_type_path(c->type_path);
  6534. c->type_path = prev_type_path;
  6535. });
  6536. if (is_call_expr_field_value(ce)) {
  6537. named_fields = true;
  6538. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6539. for_array(i, ce->args) {
  6540. Ast *arg = ce->args[i];
  6541. ast_node(fv, FieldValue, arg);
  6542. if (fv->value == nullptr) {
  6543. error(fv->eq, "Expected a value");
  6544. err = CallArgumentError_InvalidFieldValue;
  6545. continue;
  6546. }
  6547. if (fv->field->kind == Ast_Ident) {
  6548. String name = fv->field->Ident.token.string;
  6549. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6550. if (index >= 0) {
  6551. TypeTuple *params = get_record_polymorphic_params(original_type);
  6552. Entity *e = params->variables[index];
  6553. if (e->kind == Entity_Constant) {
  6554. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6555. continue;
  6556. }
  6557. }
  6558. }
  6559. check_expr_or_type(c, &operands[i], fv->value);
  6560. }
  6561. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6562. if (vari_expand) {
  6563. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6564. }
  6565. } else {
  6566. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6567. Entity **lhs = nullptr;
  6568. isize lhs_count = -1;
  6569. TypeTuple *params = get_record_polymorphic_params(original_type);
  6570. if (params != nullptr) {
  6571. lhs = params->variables.data;
  6572. lhs_count = params->variables.count;
  6573. }
  6574. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6575. }
  6576. }
  6577. if (err != 0) {
  6578. operand->mode = Addressing_Invalid;
  6579. return err;
  6580. }
  6581. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6582. isize param_count = tuple->variables.count;
  6583. isize minimum_param_count = param_count;
  6584. for (; minimum_param_count > 0; minimum_param_count--) {
  6585. Entity *e = tuple->variables[minimum_param_count-1];
  6586. if (e->kind != Entity_Constant) {
  6587. break;
  6588. }
  6589. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6590. break;
  6591. }
  6592. }
  6593. Array<Operand> ordered_operands = operands;
  6594. if (!named_fields) {
  6595. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6596. array_copy(&ordered_operands, operands, 0);
  6597. } else {
  6598. TEMPORARY_ALLOCATOR_GUARD();
  6599. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6600. // LEAK(bill)
  6601. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6602. for_array(i, ce->args) {
  6603. Ast *arg = ce->args[i];
  6604. ast_node(fv, FieldValue, arg);
  6605. if (fv->field->kind != Ast_Ident) {
  6606. if (show_error) {
  6607. gbString expr_str = expr_to_string(fv->field);
  6608. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6609. gb_string_free(expr_str);
  6610. }
  6611. err = CallArgumentError_InvalidFieldValue;
  6612. continue;
  6613. }
  6614. String name = fv->field->Ident.token.string;
  6615. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6616. if (index < 0) {
  6617. if (show_error) {
  6618. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6619. }
  6620. err = CallArgumentError_ParameterNotFound;
  6621. continue;
  6622. }
  6623. if (visited[index]) {
  6624. if (show_error) {
  6625. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6626. }
  6627. err = CallArgumentError_DuplicateParameter;
  6628. continue;
  6629. }
  6630. visited[index] = true;
  6631. ordered_operands[index] = operands[i];
  6632. }
  6633. for (isize i = 0; i < param_count; i++) {
  6634. if (!visited[i]) {
  6635. Entity *e = tuple->variables[i];
  6636. if (is_blank_ident(e->token)) {
  6637. continue;
  6638. }
  6639. if (show_error) {
  6640. if (e->kind == Entity_TypeName) {
  6641. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6642. LIT(e->token.string));
  6643. } else {
  6644. gbString str = type_to_string(e->type);
  6645. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6646. LIT(e->token.string), str);
  6647. gb_string_free(str);
  6648. }
  6649. }
  6650. err = CallArgumentError_ParameterMissing;
  6651. }
  6652. }
  6653. }
  6654. if (err != 0) {
  6655. operand->mode = Addressing_Invalid;
  6656. return err;
  6657. }
  6658. while (ordered_operands.count > 0) {
  6659. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6660. break;
  6661. }
  6662. array_pop(&ordered_operands);
  6663. }
  6664. if (minimum_param_count != param_count) {
  6665. if (param_count < ordered_operands.count) {
  6666. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6667. err = CallArgumentError_TooManyArguments;
  6668. } else if (minimum_param_count > ordered_operands.count) {
  6669. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6670. err = CallArgumentError_TooFewArguments;
  6671. }
  6672. } else {
  6673. if (param_count < ordered_operands.count) {
  6674. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6675. err = CallArgumentError_TooManyArguments;
  6676. } else if (param_count > ordered_operands.count) {
  6677. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6678. err = CallArgumentError_TooFewArguments;
  6679. }
  6680. }
  6681. if (err != 0) {
  6682. return err;
  6683. }
  6684. if (minimum_param_count != param_count) {
  6685. array_resize(&ordered_operands, param_count);
  6686. isize missing_count = 0;
  6687. // NOTE(bill): Replace missing operands with the default values (if possible)
  6688. for_array(i, ordered_operands) {
  6689. Operand *o = &ordered_operands[i];
  6690. if (o->expr == nullptr) {
  6691. Entity *e = tuple->variables[i];
  6692. if (e->kind == Entity_Constant) {
  6693. missing_count += 1;
  6694. o->mode = Addressing_Constant;
  6695. o->type = default_type(e->type);
  6696. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6697. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6698. o->value = e->Constant.param_value.value;
  6699. }
  6700. } else if (e->kind == Entity_TypeName) {
  6701. missing_count += 1;
  6702. o->mode = Addressing_Type;
  6703. o->type = e->type;
  6704. o->expr = e->identifier;
  6705. }
  6706. }
  6707. }
  6708. }
  6709. isize oo_count = gb_min(param_count, ordered_operands.count);
  6710. i64 score = 0;
  6711. for (isize i = 0; i < oo_count; i++) {
  6712. Entity *e = tuple->variables[i];
  6713. Operand *o = &ordered_operands[i];
  6714. if (o->mode == Addressing_Invalid) {
  6715. continue;
  6716. }
  6717. if (e->kind == Entity_TypeName) {
  6718. if (o->mode != Addressing_Type) {
  6719. if (show_error) {
  6720. gbString expr = expr_to_string(o->expr);
  6721. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6722. gb_string_free(expr);
  6723. }
  6724. err = CallArgumentError_WrongTypes;
  6725. }
  6726. if (are_types_identical(e->type, o->type)) {
  6727. score += assign_score_function(1);
  6728. } else {
  6729. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6730. }
  6731. } else {
  6732. i64 s = 0;
  6733. if (o->type->kind == Type_Generic) {
  6734. // Polymorphic name!
  6735. score += assign_score_function(1);
  6736. continue;
  6737. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6738. if (show_error) {
  6739. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6740. }
  6741. err = CallArgumentError_WrongTypes;
  6742. }
  6743. o->type = e->type;
  6744. if (o->mode != Addressing_Constant) {
  6745. bool valid = false;
  6746. if (is_type_proc(o->type)) {
  6747. Entity *proc_entity = entity_from_expr(o->expr);
  6748. valid = proc_entity != nullptr;
  6749. }
  6750. if (!valid) {
  6751. if (show_error) {
  6752. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6753. }
  6754. err = CallArgumentError_NoneConstantParameter;
  6755. }
  6756. }
  6757. score += s;
  6758. }
  6759. // NOTE(bill): Add type info the parameters
  6760. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6761. // add_type_info_type(c, o->type);
  6762. }
  6763. if (show_error && err) {
  6764. return err;
  6765. }
  6766. {
  6767. GenTypesData *found_gen_types = ensure_polymorphic_record_entity_has_gen_types(c, original_type);
  6768. mutex_lock(&found_gen_types->mutex);
  6769. defer (mutex_unlock(&found_gen_types->mutex));
  6770. Entity *found_entity = find_polymorphic_record_entity(found_gen_types, param_count, ordered_operands);
  6771. if (found_entity) {
  6772. operand->mode = Addressing_Type;
  6773. operand->type = found_entity->type;
  6774. return err;
  6775. }
  6776. CheckerContext ctx = *c;
  6777. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6778. ctx.scope = polymorphic_record_parent_scope(original_type);
  6779. GB_ASSERT(ctx.scope != nullptr);
  6780. Type *bt = base_type(original_type);
  6781. String generated_name = make_string_c(expr_to_string(call));
  6782. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6783. if (bt->kind == Type_Struct) {
  6784. Ast *node = clone_ast(bt->Struct.node);
  6785. Type *struct_type = alloc_type_struct();
  6786. struct_type->Struct.node = node;
  6787. struct_type->Struct.polymorphic_parent = original_type;
  6788. set_base_type(named_type, struct_type);
  6789. check_open_scope(&ctx, node);
  6790. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6791. check_close_scope(&ctx);
  6792. } else if (bt->kind == Type_Union) {
  6793. Ast *node = clone_ast(bt->Union.node);
  6794. Type *union_type = alloc_type_union();
  6795. union_type->Union.node = node;
  6796. union_type->Union.polymorphic_parent = original_type;
  6797. set_base_type(named_type, union_type);
  6798. check_open_scope(&ctx, node);
  6799. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6800. check_close_scope(&ctx);
  6801. } else {
  6802. GB_PANIC("Unsupported parametric polymorphic record type");
  6803. }
  6804. bt = base_type(named_type);
  6805. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6806. GB_ASSERT(original_type->kind == Type_Named);
  6807. Entity *e = original_type->Named.type_name;
  6808. GB_ASSERT(e->kind == Entity_TypeName);
  6809. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6810. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6811. TypeTuple *tuple = get_record_polymorphic_params(bt);
  6812. if (tuple != nullptr) for_array(i, tuple->variables) {
  6813. Entity *v = tuple->variables[i];
  6814. String name = v->token.string;
  6815. if (i > 0) {
  6816. s = gb_string_append_fmt(s, ", ");
  6817. }
  6818. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6819. if (v->kind == Entity_TypeName) {
  6820. if (v->type->kind != Type_Generic) {
  6821. s = gb_string_append_fmt(s, "=");
  6822. s = write_type_to_string(s, v->type, false);
  6823. }
  6824. } else if (v->kind == Entity_Constant) {
  6825. if (v->Constant.value.kind != ExactValue_Invalid) {
  6826. s = gb_string_append_fmt(s, "=");
  6827. s = write_exact_value_to_string(s, v->Constant.value);
  6828. }
  6829. }
  6830. }
  6831. s = gb_string_append_fmt(s, ")");
  6832. String new_name = make_string_c(s);
  6833. named_type->Named.name = new_name;
  6834. if (named_type->Named.type_name) {
  6835. named_type->Named.type_name->token.string = new_name;
  6836. }
  6837. }
  6838. operand->mode = Addressing_Type;
  6839. operand->type = named_type;
  6840. }
  6841. return err;
  6842. }
  6843. // returns true on success
  6844. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6845. bool success = true;
  6846. if (args.count > 0) {
  6847. if (allow_mixed) {
  6848. bool was_named = false;
  6849. for (Ast *arg : args) {
  6850. if (was_named && arg->kind != Ast_FieldValue) {
  6851. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6852. success = false;
  6853. break;
  6854. }
  6855. was_named = was_named || arg->kind == Ast_FieldValue;
  6856. }
  6857. } else {
  6858. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6859. for (Ast *arg : args) {
  6860. bool mix = false;
  6861. if (first_is_field_value) {
  6862. mix = arg->kind != Ast_FieldValue;
  6863. } else {
  6864. mix = arg->kind == Ast_FieldValue;
  6865. }
  6866. if (mix) {
  6867. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6868. success = false;
  6869. }
  6870. }
  6871. }
  6872. }
  6873. return success;
  6874. }
  6875. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6876. operand->mode = Addressing_Invalid; \
  6877. operand->expr = call; \
  6878. return Expr_Stmt; \
  6879. }
  6880. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6881. if (proc != nullptr &&
  6882. proc->kind == Ast_BasicDirective) {
  6883. ast_node(bd, BasicDirective, proc);
  6884. String name = bd->name.string;
  6885. if (
  6886. name == "location" ||
  6887. name == "exists" ||
  6888. name == "assert" ||
  6889. name == "panic" ||
  6890. name == "defined" ||
  6891. name == "config" ||
  6892. name == "load" ||
  6893. name == "load_directory" ||
  6894. name == "load_hash" ||
  6895. name == "hash" ||
  6896. name == "caller_expression"
  6897. ) {
  6898. operand->mode = Addressing_Builtin;
  6899. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6900. operand->expr = proc;
  6901. operand->type = t_invalid;
  6902. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6903. } else {
  6904. error(proc, "Unknown directive: #%.*s", LIT(name));
  6905. operand->expr = proc;
  6906. operand->type = t_invalid;
  6907. operand->mode = Addressing_Invalid;
  6908. return Expr_Expr;
  6909. }
  6910. if (inlining != ProcInlining_none) {
  6911. error(call, "Inlining operators are not allowed on built-in procedures");
  6912. }
  6913. } else {
  6914. if (proc != nullptr) {
  6915. check_expr_or_type(c, operand, proc);
  6916. } else {
  6917. GB_ASSERT(operand->expr != nullptr);
  6918. }
  6919. }
  6920. if (operand->mode == Addressing_Invalid) {
  6921. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6922. for (Ast *arg : args) {
  6923. if (arg->kind == Ast_FieldValue) {
  6924. arg = arg->FieldValue.value;
  6925. }
  6926. check_expr_base(c, operand, arg, nullptr);
  6927. }
  6928. operand->mode = Addressing_Invalid;
  6929. operand->expr = call;
  6930. return Expr_Stmt;
  6931. }
  6932. if (operand->mode == Addressing_Type) {
  6933. Type *t = operand->type;
  6934. if (is_type_polymorphic_record(t)) {
  6935. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6936. if (!is_type_named(t)) {
  6937. gbString s = expr_to_string(operand->expr);
  6938. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6939. gb_string_free(s);
  6940. operand->mode = Addressing_Invalid;
  6941. operand->type = t_invalid;;
  6942. return Expr_Expr;
  6943. }
  6944. auto err = check_polymorphic_record_type(c, operand, call);
  6945. if (err == 0) {
  6946. Ast *ident = operand->expr;
  6947. while (ident->kind == Ast_SelectorExpr) {
  6948. Ast *s = ident->SelectorExpr.selector;
  6949. ident = s;
  6950. }
  6951. Type *ot = operand->type;
  6952. GB_ASSERT(ot->kind == Type_Named);
  6953. Entity *e = ot->Named.type_name;
  6954. add_entity_use(c, ident, e);
  6955. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6956. } else {
  6957. operand->mode = Addressing_Invalid;
  6958. operand->type = t_invalid;
  6959. }
  6960. } else {
  6961. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6962. operand->mode = Addressing_Invalid;
  6963. isize arg_count = args.count;
  6964. switch (arg_count) {
  6965. case 0:
  6966. {
  6967. gbString str = type_to_string(t);
  6968. error(call, "Missing argument in conversion to '%s'", str);
  6969. gb_string_free(str);
  6970. } break;
  6971. default:
  6972. {
  6973. gbString str = type_to_string(t);
  6974. if (t->kind == Type_Basic) {
  6975. ERROR_BLOCK();
  6976. switch (t->Basic.kind) {
  6977. case Basic_complex32:
  6978. case Basic_complex64:
  6979. case Basic_complex128:
  6980. error(call, "Too many arguments in conversion to '%s'", str);
  6981. error_line("\tSuggestion: %s(1+2i) or construct with 'complex'\n", str);
  6982. break;
  6983. case Basic_quaternion64:
  6984. case Basic_quaternion128:
  6985. case Basic_quaternion256:
  6986. error(call, "Too many arguments in conversion to '%s'", str);
  6987. error_line("\tSuggestion: %s(1+2i+3j+4k) or construct with 'quaternion'\n", str);
  6988. break;
  6989. default:
  6990. error(call, "Too many arguments in conversion to '%s'", str);
  6991. }
  6992. } else {
  6993. error(call, "Too many arguments in conversion to '%s'", str);
  6994. }
  6995. gb_string_free(str);
  6996. } break;
  6997. case 1: {
  6998. Ast *arg = args[0];
  6999. if (arg->kind == Ast_FieldValue) {
  7000. error(call, "'field = value' cannot be used in a type conversion");
  7001. arg = arg->FieldValue.value;
  7002. // NOTE(bill): Carry on the cast regardless
  7003. }
  7004. check_expr_with_type_hint(c, operand, arg, t);
  7005. if (operand->mode != Addressing_Invalid) {
  7006. if (is_type_polymorphic(t)) {
  7007. error(call, "A polymorphic type cannot be used in a type conversion");
  7008. } else {
  7009. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  7010. // as it assumes it is determining the type
  7011. check_cast(c, operand, t);
  7012. }
  7013. }
  7014. operand->type = t;
  7015. operand->expr = call;
  7016. if (operand->mode != Addressing_Invalid) {
  7017. update_untyped_expr_type(c, arg, t, false);
  7018. }
  7019. break;
  7020. }
  7021. }
  7022. }
  7023. return Expr_Expr;
  7024. }
  7025. if (operand->mode == Addressing_Builtin) {
  7026. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  7027. i32 id = operand->builtin_id;
  7028. Entity *e = entity_of_node(operand->expr);
  7029. if (e != nullptr && e->token.string == "expand_to_tuple") {
  7030. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  7031. }
  7032. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  7033. operand->mode = Addressing_Invalid;
  7034. operand->type = t_invalid;
  7035. }
  7036. operand->expr = call;
  7037. return builtin_procs[id].kind;
  7038. }
  7039. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  7040. Entity *initial_entity = entity_of_node(operand->expr);
  7041. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  7042. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  7043. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  7044. if (c->decl) {
  7045. c->decl->defer_used += 1;
  7046. }
  7047. }
  7048. add_entity_use(c, operand->expr, initial_entity);
  7049. if (initial_entity->Procedure.entry_point_only) {
  7050. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  7051. // Okay
  7052. } else {
  7053. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  7054. }
  7055. }
  7056. }
  7057. if (operand->mode != Addressing_ProcGroup) {
  7058. Type *proc_type = base_type(operand->type);
  7059. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  7060. bool valid_mode = is_operand_value(*operand);
  7061. if (!valid_type || !valid_mode) {
  7062. Ast *e = operand->expr;
  7063. gbString str = expr_to_string(e);
  7064. gbString type_str = type_to_string(operand->type);
  7065. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  7066. gb_string_free(type_str);
  7067. gb_string_free(str);
  7068. operand->mode = Addressing_Invalid;
  7069. operand->expr = call;
  7070. return Expr_Stmt;
  7071. }
  7072. }
  7073. CallArgumentData data = check_call_arguments(c, operand, call);
  7074. Type *result_type = data.result_type;
  7075. gb_zero_item(operand);
  7076. operand->expr = call;
  7077. if (result_type == t_invalid) {
  7078. operand->mode = Addressing_Invalid;
  7079. operand->type = t_invalid;
  7080. return Expr_Stmt;
  7081. }
  7082. Type *pt = base_type(operand->type);
  7083. if (pt == nullptr) {
  7084. pt = t_invalid;
  7085. }
  7086. if (pt == t_invalid) {
  7087. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7088. pt = type_of_expr(operand->expr->CallExpr.proc);
  7089. }
  7090. if (pt == t_invalid && data.gen_entity) {
  7091. pt = data.gen_entity->type;
  7092. }
  7093. }
  7094. pt = base_type(pt);
  7095. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  7096. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  7097. ERROR_BLOCK();
  7098. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  7099. error_line("\tSuggestion: 'context = runtime.default_context()'");
  7100. }
  7101. }
  7102. if (result_type == nullptr) {
  7103. operand->mode = Addressing_NoValue;
  7104. } else {
  7105. GB_ASSERT(is_type_tuple(result_type));
  7106. isize count = result_type->Tuple.variables.count;
  7107. switch (count) {
  7108. case 0:
  7109. operand->mode = Addressing_NoValue;
  7110. break;
  7111. case 1:
  7112. operand->mode = Addressing_Value;
  7113. operand->type = result_type->Tuple.variables[0]->type;
  7114. break;
  7115. default:
  7116. operand->mode = Addressing_Value;
  7117. operand->type = result_type;
  7118. break;
  7119. }
  7120. }
  7121. bool is_call_inlined = false;
  7122. switch (inlining) {
  7123. case ProcInlining_inline:
  7124. is_call_inlined = true;
  7125. if (proc != nullptr) {
  7126. Entity *e = entity_from_expr(proc);
  7127. if (e != nullptr && e->kind == Entity_Procedure) {
  7128. DeclInfo *decl = e->decl_info;
  7129. if (decl->proc_lit) {
  7130. ast_node(pl, ProcLit, decl->proc_lit);
  7131. if (pl->inlining == ProcInlining_no_inline) {
  7132. error(call, "'#force_inline' cannot be applied to a procedure that has been marked as '#force_no_inline'");
  7133. }
  7134. }
  7135. }
  7136. }
  7137. break;
  7138. case ProcInlining_no_inline:
  7139. break;
  7140. case ProcInlining_none:
  7141. if (proc != nullptr) {
  7142. Entity *e = entity_from_expr(proc);
  7143. if (e != nullptr && e->kind == Entity_Procedure) {
  7144. DeclInfo *decl = e->decl_info;
  7145. if (decl->proc_lit) {
  7146. ast_node(pl, ProcLit, decl->proc_lit);
  7147. if (pl->inlining == ProcInlining_inline) {
  7148. is_call_inlined = true;
  7149. }
  7150. }
  7151. }
  7152. }
  7153. }
  7154. {
  7155. String invalid;
  7156. if (pt->kind == Type_Proc && pt->Proc.require_target_feature.len != 0) {
  7157. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.require_target_feature, &invalid)) {
  7158. error(call, "Called procedure requires target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7159. } else if (!check_target_feature_is_enabled(pt->Proc.require_target_feature, &invalid)) {
  7160. error(call, "Calling this procedure requires target feature '%.*s' to be enabled", LIT(invalid));
  7161. }
  7162. }
  7163. if (pt->kind == Type_Proc && pt->Proc.enable_target_feature.len != 0) {
  7164. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.enable_target_feature, &invalid)) {
  7165. error(call, "Called procedure enables target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7166. }
  7167. // NOTE: Due to restrictions in LLVM you can not inline calls with a superset of features.
  7168. if (is_call_inlined) {
  7169. if (c->curr_proc_decl == nullptr) {
  7170. error(call, "Calling a '#force_inline' procedure that enables target features is not allowed at file scope");
  7171. } else {
  7172. GB_ASSERT(c->curr_proc_decl->entity);
  7173. GB_ASSERT(c->curr_proc_decl->entity->type->kind == Type_Proc);
  7174. String scope_features = c->curr_proc_decl->entity->type->Proc.enable_target_feature;
  7175. if (!check_target_feature_is_superset_of(scope_features, pt->Proc.enable_target_feature, &invalid)) {
  7176. ERROR_BLOCK();
  7177. error(call, "Inlined procedure enables target feature '%.*s', this requires the calling procedure to at least enable the same feature", LIT(invalid));
  7178. error_line("\tSuggested Example: @(enable_target_feature=\"%.*s\")\n", LIT(invalid));
  7179. }
  7180. }
  7181. }
  7182. }
  7183. }
  7184. operand->expr = call;
  7185. {
  7186. Type *type = nullptr;
  7187. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7188. type = type_of_expr(operand->expr->CallExpr.proc);
  7189. }
  7190. if (type == nullptr) {
  7191. type = pt;
  7192. }
  7193. type = base_type(type);
  7194. if (type->kind == Type_Proc && type->Proc.optional_ok && type->Proc.result_count > 0) {
  7195. operand->mode = Addressing_OptionalOk;
  7196. operand->type = type->Proc.results->Tuple.variables[0]->type;
  7197. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7198. operand->expr->CallExpr.optional_ok_one = true;
  7199. }
  7200. }
  7201. }
  7202. return Expr_Expr;
  7203. }
  7204. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  7205. check_expr_base(c, o, e, t);
  7206. check_not_tuple(c, o);
  7207. char const *err_str = nullptr;
  7208. switch (o->mode) {
  7209. case Addressing_NoValue:
  7210. err_str = "used as a value";
  7211. break;
  7212. case Addressing_Type:
  7213. if (t == nullptr || !is_type_typeid(t)) {
  7214. err_str = "is not an expression but a type, in this context it is ambiguous";
  7215. }
  7216. break;
  7217. case Addressing_Builtin:
  7218. err_str = "must be called";
  7219. break;
  7220. }
  7221. if (err_str != nullptr) {
  7222. gbString str = expr_to_string(e);
  7223. error(e, "'%s' %s", str, err_str);
  7224. gb_string_free(str);
  7225. o->mode = Addressing_Invalid;
  7226. }
  7227. }
  7228. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  7229. switch (t->kind) {
  7230. case Type_Basic:
  7231. if (t->Basic.kind == Basic_string) {
  7232. if (o->mode == Addressing_Constant) {
  7233. *max_count = o->value.value_string.len;
  7234. }
  7235. if (o->mode != Addressing_Constant) {
  7236. o->mode = Addressing_Value;
  7237. }
  7238. o->type = t_u8;
  7239. return true;
  7240. } else if (t->Basic.kind == Basic_UntypedString) {
  7241. if (o->mode == Addressing_Constant) {
  7242. *max_count = o->value.value_string.len;
  7243. o->type = t_u8;
  7244. return true;
  7245. }
  7246. return false;
  7247. }
  7248. break;
  7249. case Type_MultiPointer:
  7250. o->type = t->MultiPointer.elem;
  7251. if (o->mode != Addressing_Constant) {
  7252. o->mode = Addressing_Variable;
  7253. }
  7254. return true;
  7255. case Type_Array:
  7256. *max_count = t->Array.count;
  7257. if (indirection) {
  7258. o->mode = Addressing_Variable;
  7259. } else if (o->mode != Addressing_Variable &&
  7260. o->mode != Addressing_Constant) {
  7261. o->mode = Addressing_Value;
  7262. }
  7263. o->type = t->Array.elem;
  7264. return true;
  7265. case Type_EnumeratedArray:
  7266. *max_count = t->EnumeratedArray.count;
  7267. if (indirection) {
  7268. o->mode = Addressing_Variable;
  7269. } else if (o->mode != Addressing_Variable &&
  7270. o->mode != Addressing_Constant) {
  7271. o->mode = Addressing_Value;
  7272. }
  7273. o->type = t->EnumeratedArray.elem;
  7274. return true;
  7275. case Type_Matrix:
  7276. if (indirection) {
  7277. o->mode = Addressing_Variable;
  7278. } else if (o->mode != Addressing_Variable) {
  7279. o->mode = Addressing_Value;
  7280. }
  7281. if (t->Matrix.is_row_major) {
  7282. *max_count = t->Matrix.row_count;
  7283. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.column_count);
  7284. } else {
  7285. *max_count = t->Matrix.column_count;
  7286. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  7287. }
  7288. return true;
  7289. case Type_Slice:
  7290. o->type = t->Slice.elem;
  7291. if (o->mode != Addressing_Constant) {
  7292. o->mode = Addressing_Variable;
  7293. }
  7294. return true;
  7295. case Type_DynamicArray:
  7296. o->type = t->DynamicArray.elem;
  7297. if (o->mode != Addressing_Constant) {
  7298. o->mode = Addressing_Variable;
  7299. }
  7300. return true;
  7301. case Type_Struct:
  7302. if (t->Struct.soa_kind != StructSoa_None) {
  7303. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7304. *max_count = t->Struct.soa_count;
  7305. }
  7306. o->type = t->Struct.soa_elem;
  7307. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  7308. o->mode = Addressing_SoaVariable;
  7309. } else {
  7310. o->mode = Addressing_Value;
  7311. }
  7312. return true;
  7313. }
  7314. return false;
  7315. }
  7316. if (is_type_pointer(original_type) && indirection) {
  7317. Type *ptr = base_type(original_type);
  7318. if (ptr->kind == Type_MultiPointer && o->mode == Addressing_SoaVariable) {
  7319. o->type = ptr->MultiPointer.elem;
  7320. o->mode = Addressing_Value;
  7321. return true;
  7322. }
  7323. }
  7324. return false;
  7325. }
  7326. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  7327. if (is_type_untyped_uninit(x)) {
  7328. return true;
  7329. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  7330. return true;
  7331. } else if (is_type_untyped_uninit(y)) {
  7332. return true;
  7333. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  7334. return true;
  7335. }
  7336. return are_types_identical(x, y);
  7337. }
  7338. 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) {
  7339. if (!is_ast_range(node)) {
  7340. return false;
  7341. }
  7342. ast_node(ie, BinaryExpr, node);
  7343. check_expr_with_type_hint(c, x, ie->left, type_hint);
  7344. if (x->mode == Addressing_Invalid) {
  7345. return false;
  7346. }
  7347. check_expr_with_type_hint(c, y, ie->right, type_hint);
  7348. if (y->mode == Addressing_Invalid) {
  7349. return false;
  7350. }
  7351. convert_to_typed(c, x, y->type);
  7352. if (x->mode == Addressing_Invalid) {
  7353. return false;
  7354. }
  7355. convert_to_typed(c, y, x->type);
  7356. if (y->mode == Addressing_Invalid) {
  7357. return false;
  7358. }
  7359. convert_to_typed(c, x, default_type(y->type));
  7360. if (x->mode == Addressing_Invalid) {
  7361. return false;
  7362. }
  7363. convert_to_typed(c, y, default_type(x->type));
  7364. if (y->mode == Addressing_Invalid) {
  7365. return false;
  7366. }
  7367. if (!are_types_identical(x->type, y->type)) {
  7368. if (x->type != t_invalid &&
  7369. y->type != t_invalid) {
  7370. gbString xt = type_to_string(x->type);
  7371. gbString yt = type_to_string(y->type);
  7372. gbString expr_str = expr_to_string(x->expr);
  7373. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  7374. gb_string_free(expr_str);
  7375. gb_string_free(yt);
  7376. gb_string_free(xt);
  7377. }
  7378. return false;
  7379. }
  7380. Type *type = x->type;
  7381. if (is_for_loop) {
  7382. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  7383. error(ie->op, "Only numerical types are allowed within interval expressions");
  7384. return false;
  7385. }
  7386. } else {
  7387. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  7388. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  7389. return false;
  7390. }
  7391. }
  7392. if (x->mode == Addressing_Constant &&
  7393. y->mode == Addressing_Constant) {
  7394. ExactValue a = x->value;
  7395. ExactValue b = y->value;
  7396. GB_ASSERT(are_types_identical(x->type, y->type));
  7397. TokenKind op = Token_Lt;
  7398. switch (ie->op.kind) {
  7399. case Token_Ellipsis: op = Token_LtEq; break; // ..
  7400. case Token_RangeFull: op = Token_LtEq; break; // ..=
  7401. case Token_RangeHalf: op = Token_Lt; break; // ..<
  7402. default: error(ie->op, "Invalid range operator"); break;
  7403. }
  7404. bool ok = compare_exact_values(op, a, b);
  7405. if (!ok) {
  7406. // TODO(bill): Better error message
  7407. error(ie->op, "Invalid interval range");
  7408. return false;
  7409. }
  7410. ExactValue inline_for_depth = exact_value_sub(b, a);
  7411. if (ie->op.kind != Token_RangeHalf) {
  7412. inline_for_depth = exact_value_increment_one(inline_for_depth);
  7413. }
  7414. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  7415. } else if (inline_for_depth_ != nullptr) {
  7416. error(ie->op, "Interval expressions must be constant");
  7417. return false;
  7418. }
  7419. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  7420. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  7421. return true;
  7422. }
  7423. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  7424. if (is_operand_nil(*o)) {
  7425. return true;
  7426. }
  7427. Ast *expr = unparen_expr(o->expr);
  7428. if (expr != nullptr) {
  7429. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  7430. if (e != nullptr && e->kind == Entity_Procedure) {
  7431. return true;
  7432. }
  7433. if (expr->kind == Ast_ProcLit) {
  7434. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  7435. return true;
  7436. }
  7437. }
  7438. return o->mode == Addressing_Constant;
  7439. }
  7440. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  7441. if (is_type_enum(th)) {
  7442. Type *enum_type = base_type(th);
  7443. GB_ASSERT(enum_type->kind == Type_Enum);
  7444. String name = ise->selector->Ident.token.string;
  7445. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  7446. if (e == nullptr) {
  7447. return false;
  7448. }
  7449. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  7450. GB_ASSERT(e->kind == Entity_Constant);
  7451. o->value = e->Constant.value;
  7452. o->mode = Addressing_Constant;
  7453. o->type = e->type;
  7454. return true;
  7455. }
  7456. if (is_type_union(th)) {
  7457. TEMPORARY_ALLOCATOR_GUARD();
  7458. Type *union_type = base_type(th);
  7459. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  7460. for (Type *vt : union_type->Union.variants) {
  7461. Operand x = {};
  7462. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  7463. array_add(&operands, x);
  7464. }
  7465. }
  7466. if (operands.count == 1) {
  7467. *o = operands[0];
  7468. return true;
  7469. }
  7470. }
  7471. return false;
  7472. }
  7473. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7474. ast_node(ise, ImplicitSelectorExpr, node);
  7475. o->type = t_invalid;
  7476. o->expr = node;
  7477. o->mode = Addressing_Invalid;
  7478. Type *th = type_hint;
  7479. if (th == nullptr) {
  7480. gbString str = expr_to_string(node);
  7481. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  7482. gb_string_free(str);
  7483. return Expr_Expr;
  7484. }
  7485. o->type = th;
  7486. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  7487. if (!ok) {
  7488. String name = ise->selector->Ident.token.string;
  7489. if (is_type_enum(th)) {
  7490. ERROR_BLOCK();
  7491. Type *bt = base_type(th);
  7492. GB_ASSERT(bt->kind == Type_Enum);
  7493. gbString typ = type_to_string(th);
  7494. defer (gb_string_free(typ));
  7495. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  7496. check_did_you_mean_type(name, bt->Enum.fields);
  7497. } else if (is_type_bit_set(th) && is_type_enum(th->BitSet.elem)) {
  7498. ERROR_BLOCK();
  7499. gbString typ = type_to_string(th);
  7500. gbString str = expr_to_string(node);
  7501. error(node, "Cannot convert enum value to '%s'", typ);
  7502. error_line("\tSuggestion: Did you mean '{ %s }'?\n", str);
  7503. gb_string_free(typ);
  7504. gb_string_free(str);
  7505. } else {
  7506. gbString typ = type_to_string(th);
  7507. gbString str = expr_to_string(node);
  7508. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  7509. gb_string_free(str);
  7510. gb_string_free(typ);
  7511. }
  7512. }
  7513. o->expr = node;
  7514. return Expr_Expr;
  7515. }
  7516. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  7517. switch (x->mode) {
  7518. case Addressing_MapIndex:
  7519. case Addressing_OptionalOk:
  7520. case Addressing_OptionalOkPtr:
  7521. if (val_type_) *val_type_ = x->type;
  7522. break;
  7523. default:
  7524. if (ok_type_) *ok_type_ = x->type;
  7525. return;
  7526. }
  7527. Ast *expr = unparen_expr(x->expr);
  7528. if (expr->kind == Ast_CallExpr) {
  7529. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  7530. if (is_type_proc(pt)) {
  7531. Type *tuple = pt->Proc.results;
  7532. if (pt->Proc.result_count >= 2) {
  7533. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7534. }
  7535. if (change_operand) {
  7536. expr->CallExpr.optional_ok_one = false;
  7537. x->type = tuple;
  7538. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7539. }
  7540. return;
  7541. }
  7542. }
  7543. Type *tuple = make_optional_ok_type(x->type);
  7544. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7545. if (change_operand) {
  7546. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7547. x->type = tuple;
  7548. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  7549. }
  7550. }
  7551. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7552. ast_node(ie, MatrixIndexExpr, node);
  7553. check_expr(c, o, ie->expr);
  7554. node->viral_state_flags |= ie->expr->viral_state_flags;
  7555. if (o->mode == Addressing_Invalid) {
  7556. o->expr = node;
  7557. return;
  7558. }
  7559. Type *t = base_type(type_deref(o->type));
  7560. bool is_ptr = is_type_pointer(o->type);
  7561. bool is_const = o->mode == Addressing_Constant;
  7562. if (t->kind != Type_Matrix) {
  7563. gbString str = expr_to_string(o->expr);
  7564. gbString type_str = type_to_string(o->type);
  7565. defer (gb_string_free(str));
  7566. defer (gb_string_free(type_str));
  7567. if (is_const) {
  7568. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  7569. } else {
  7570. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  7571. }
  7572. o->mode = Addressing_Invalid;
  7573. o->expr = node;
  7574. return;
  7575. }
  7576. o->type = t->Matrix.elem;
  7577. if (is_ptr) {
  7578. o->mode = Addressing_Variable;
  7579. } else if (o->mode != Addressing_Variable) {
  7580. o->mode = Addressing_Value;
  7581. }
  7582. if (ie->row_index == nullptr) {
  7583. gbString str = expr_to_string(o->expr);
  7584. error(o->expr, "Missing row index for '%s'", str);
  7585. gb_string_free(str);
  7586. o->mode = Addressing_Invalid;
  7587. o->expr = node;
  7588. return;
  7589. }
  7590. if (ie->column_index == nullptr) {
  7591. gbString str = expr_to_string(o->expr);
  7592. error(o->expr, "Missing column index for '%s'", str);
  7593. gb_string_free(str);
  7594. o->mode = Addressing_Invalid;
  7595. o->expr = node;
  7596. return;
  7597. }
  7598. i64 row_count = t->Matrix.row_count;
  7599. i64 column_count = t->Matrix.column_count;
  7600. i64 row_index = 0;
  7601. i64 column_index = 0;
  7602. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7603. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7604. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7605. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7606. }
  7607. gb_unused(row_ok);
  7608. gb_unused(column_ok);
  7609. }
  7610. struct TypeAndToken {
  7611. Type *type;
  7612. Token token;
  7613. };
  7614. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7615. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7616. if (operand.mode != Addressing_Constant) {
  7617. return;
  7618. }
  7619. if (operand.value.kind == ExactValue_Invalid) {
  7620. return;
  7621. }
  7622. uintptr key = hash_exact_value(operand.value);
  7623. GB_ASSERT(key != 0);
  7624. isize count = multi_map_count(seen, key);
  7625. if (count) {
  7626. TEMPORARY_ALLOCATOR_GUARD();
  7627. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  7628. multi_map_get_all(seen, key, taps);
  7629. for (isize i = 0; i < count; i++) {
  7630. TypeAndToken tap = taps[i];
  7631. Operand to = {};
  7632. to.mode = Addressing_Value;
  7633. to.type = tap.type;
  7634. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7635. continue;
  7636. }
  7637. TokenPos pos = tap.token.pos;
  7638. if (use_expr) {
  7639. gbString expr_str = expr_to_string(operand.expr);
  7640. error(operand.expr,
  7641. "Duplicate case '%s'\n"
  7642. "\tprevious case at %s",
  7643. expr_str,
  7644. token_pos_to_string(pos));
  7645. gb_string_free(expr_str);
  7646. } else {
  7647. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7648. }
  7649. return;
  7650. }
  7651. }
  7652. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7653. multi_map_insert(seen, key, tap);
  7654. }
  7655. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7656. if (is_type_enum(x.type)) {
  7657. // TODO(bill): Fix this logic so it's fast!!!
  7658. i64 v0 = exact_value_to_i64(lhs.value);
  7659. i64 v1 = exact_value_to_i64(rhs.value);
  7660. Operand v = {};
  7661. v.mode = Addressing_Constant;
  7662. v.type = x.type;
  7663. v.expr = x.expr;
  7664. Type *bt = base_type(x.type);
  7665. GB_ASSERT(bt->kind == Type_Enum);
  7666. for (i64 vi = v0; vi <= v1; vi++) {
  7667. if (upper_op != Token_LtEq && vi == v1) {
  7668. break;
  7669. }
  7670. v.value = exact_value_i64(vi);
  7671. add_constant_switch_case(ctx, seen, v);
  7672. }
  7673. } else {
  7674. add_constant_switch_case(ctx, seen, lhs);
  7675. if (upper_op == Token_LtEq) {
  7676. add_constant_switch_case(ctx, seen, rhs);
  7677. }
  7678. }
  7679. }
  7680. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7681. add_constant_switch_case(ctx, seen, x);
  7682. }
  7683. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7684. ast_node(bd, BasicDirective, node);
  7685. ExprKind kind = Expr_Expr;
  7686. o->mode = Addressing_Constant;
  7687. String name = bd->name.string;
  7688. if (name == "file") {
  7689. String file = get_file_path_string(bd->token.pos.file_id);
  7690. switch (build_context.source_code_location_info) {
  7691. case SourceCodeLocationInfo_Normal:
  7692. break;
  7693. case SourceCodeLocationInfo_Obfuscated:
  7694. file = obfuscate_string(file, "F");
  7695. break;
  7696. case SourceCodeLocationInfo_Filename:
  7697. file = last_path_element(file);
  7698. break;
  7699. case SourceCodeLocationInfo_None:
  7700. file = str_lit("");
  7701. break;
  7702. }
  7703. o->type = t_untyped_string;
  7704. o->value = exact_value_string(file);
  7705. } else if (name == "directory") {
  7706. String file = get_file_path_string(bd->token.pos.file_id);
  7707. String path = dir_from_path(file);
  7708. switch (build_context.source_code_location_info) {
  7709. case SourceCodeLocationInfo_Normal:
  7710. break;
  7711. case SourceCodeLocationInfo_Obfuscated:
  7712. path = obfuscate_string(path, "D");
  7713. break;
  7714. case SourceCodeLocationInfo_Filename:
  7715. path = last_path_element(path);
  7716. break;
  7717. case SourceCodeLocationInfo_None:
  7718. path = str_lit("");
  7719. break;
  7720. }
  7721. o->type = t_untyped_string;
  7722. o->value = exact_value_string(path);
  7723. } else if (name == "line") {
  7724. i32 line = bd->token.pos.line;
  7725. switch (build_context.source_code_location_info) {
  7726. case SourceCodeLocationInfo_Normal:
  7727. break;
  7728. case SourceCodeLocationInfo_Obfuscated:
  7729. line = obfuscate_i32(line);
  7730. break;
  7731. case SourceCodeLocationInfo_Filename:
  7732. break;
  7733. case SourceCodeLocationInfo_None:
  7734. line = 0;
  7735. break;
  7736. }
  7737. o->type = t_untyped_integer;
  7738. o->value = exact_value_i64(line);
  7739. } else if (name == "procedure") {
  7740. if (c->curr_proc_decl == nullptr) {
  7741. error(node, "#procedure may only be used within procedures");
  7742. o->type = t_untyped_string;
  7743. o->value = exact_value_string(str_lit(""));
  7744. } else {
  7745. String p = c->proc_name;
  7746. switch (build_context.source_code_location_info) {
  7747. case SourceCodeLocationInfo_Normal:
  7748. break;
  7749. case SourceCodeLocationInfo_Obfuscated:
  7750. p = obfuscate_string(p, "P");
  7751. break;
  7752. case SourceCodeLocationInfo_Filename:
  7753. break;
  7754. case SourceCodeLocationInfo_None:
  7755. p = str_lit("");
  7756. break;
  7757. }
  7758. o->type = t_untyped_string;
  7759. o->value = exact_value_string(p);
  7760. }
  7761. } else if (name == "caller_location") {
  7762. init_core_source_code_location(c->checker);
  7763. error(node, "#caller_location may only be used as a default argument parameter");
  7764. o->type = t_source_code_location;
  7765. o->mode = Addressing_Value;
  7766. } else if (name == "caller_expression") {
  7767. error(node, "#caller_expression may only be used as a default argument parameter");
  7768. o->type = t_string;
  7769. o->mode = Addressing_Value;
  7770. } else if (name == "branch_location") {
  7771. if (!c->in_defer) {
  7772. error(node, "#branch_location may only be used within a 'defer' statement");
  7773. } else if (c->curr_proc_decl) {
  7774. Entity *e = c->curr_proc_decl->entity;
  7775. if (e != nullptr) {
  7776. GB_ASSERT(e->kind == Entity_Procedure);
  7777. e->Procedure.uses_branch_location = true;
  7778. }
  7779. }
  7780. o->type = t_source_code_location;
  7781. o->mode = Addressing_Value;
  7782. } else {
  7783. if (name == "location") {
  7784. init_core_source_code_location(c->checker);
  7785. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  7786. o->type = t_source_code_location;
  7787. o->mode = Addressing_Value;
  7788. } else if (
  7789. name == "assert" ||
  7790. name == "defined" ||
  7791. name == "config" ||
  7792. name == "exists" ||
  7793. name == "load" ||
  7794. name == "load_hash" ||
  7795. name == "load_directory" ||
  7796. name == "load_or"
  7797. ) {
  7798. error(node, "'#%.*s' must be used as a call", LIT(name));
  7799. o->type = t_invalid;
  7800. o->mode = Addressing_Invalid;
  7801. } else {
  7802. error(node, "Unknown directive: #%.*s", LIT(name));
  7803. o->type = t_invalid;
  7804. o->mode = Addressing_Invalid;
  7805. }
  7806. }
  7807. return kind;
  7808. }
  7809. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7810. ExprKind kind = Expr_Expr;
  7811. Operand cond = {Addressing_Invalid};
  7812. ast_node(te, TernaryIfExpr, node);
  7813. check_expr(c, &cond, te->cond);
  7814. node->viral_state_flags |= te->cond->viral_state_flags;
  7815. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7816. error(te->cond, "Non-boolean condition in ternary if expression");
  7817. }
  7818. Operand x = {Addressing_Invalid};
  7819. Operand y = {Addressing_Invalid};
  7820. check_expr_or_type(c, &x, te->x, type_hint);
  7821. node->viral_state_flags |= te->x->viral_state_flags;
  7822. if (te->y != nullptr) {
  7823. Type *th = type_hint;
  7824. if (type_hint == nullptr && is_type_typed(x.type)) {
  7825. th = x.type;
  7826. }
  7827. check_expr_or_type(c, &y, te->y, th);
  7828. node->viral_state_flags |= te->y->viral_state_flags;
  7829. } else {
  7830. error(node, "A ternary expression must have an else clause");
  7831. return kind;
  7832. }
  7833. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7834. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7835. gbString type_string = expr_to_string(type_expr);
  7836. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7837. gb_string_free(type_string);
  7838. return kind;
  7839. }
  7840. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7841. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7842. if (x.mode == Addressing_Invalid) {
  7843. return kind;
  7844. }
  7845. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7846. if (y.mode == Addressing_Invalid) {
  7847. x.mode = Addressing_Invalid;
  7848. return kind;
  7849. }
  7850. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7851. // x: union{f32} = f32(123) if cond else nil
  7852. if (type_hint && !is_type_any(type_hint)) {
  7853. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7854. check_cast(c, &x, type_hint);
  7855. check_cast(c, &y, type_hint);
  7856. }
  7857. }
  7858. if (!ternary_compare_types(x.type, y.type)) {
  7859. gbString its = type_to_string(x.type);
  7860. gbString ets = type_to_string(y.type);
  7861. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7862. gb_string_free(ets);
  7863. gb_string_free(its);
  7864. return kind;
  7865. }
  7866. o->type = x.type;
  7867. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  7868. o->type = y.type;
  7869. }
  7870. o->mode = Addressing_Value;
  7871. o->expr = node;
  7872. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7873. if (check_cast_internal(c, &x, type_hint) &&
  7874. check_cast_internal(c, &y, type_hint)) {
  7875. convert_to_typed(c, o, type_hint);
  7876. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7877. o->type = type_hint;
  7878. }
  7879. }
  7880. return kind;
  7881. }
  7882. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7883. ExprKind kind = Expr_Expr;
  7884. Operand cond = {};
  7885. ast_node(te, TernaryWhenExpr, node);
  7886. check_expr(c, &cond, te->cond);
  7887. node->viral_state_flags |= te->cond->viral_state_flags;
  7888. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7889. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7890. return kind;
  7891. }
  7892. if (cond.value.value_bool) {
  7893. check_expr_or_type(c, o, te->x, type_hint);
  7894. node->viral_state_flags |= te->x->viral_state_flags;
  7895. } else {
  7896. if (te->y != nullptr) {
  7897. check_expr_or_type(c, o, te->y, type_hint);
  7898. node->viral_state_flags |= te->y->viral_state_flags;
  7899. } else {
  7900. error(node, "A ternary when expression must have an else clause");
  7901. return kind;
  7902. }
  7903. }
  7904. return kind;
  7905. }
  7906. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7907. ast_node(oe, OrElseExpr, node);
  7908. String name = oe->token.string;
  7909. Ast *arg = oe->x;
  7910. Ast *default_value = oe->y;
  7911. Operand x = {};
  7912. Operand y = {};
  7913. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7914. if (is_load_directive_call(arg)) {
  7915. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7916. // Allow for chaining of '#load(path) or_else #load(path)'
  7917. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  7918. bool y_is_diverging = false;
  7919. check_expr_base(c, &y, default_value, x.type);
  7920. switch (y.mode) {
  7921. case Addressing_NoValue:
  7922. if (is_diverging_expr(y.expr)) {
  7923. // Allow
  7924. y.mode = Addressing_Value;
  7925. y_is_diverging = true;
  7926. } else {
  7927. error_operand_no_value(&y);
  7928. y.mode = Addressing_Invalid;
  7929. }
  7930. break;
  7931. case Addressing_Type:
  7932. error_operand_not_expression(&y);
  7933. y.mode = Addressing_Invalid;
  7934. break;
  7935. }
  7936. if (y.mode == Addressing_Invalid) {
  7937. o->mode = Addressing_Value;
  7938. o->type = t_invalid;
  7939. o->expr = node;
  7940. return Expr_Expr;
  7941. }
  7942. if (!y_is_diverging) {
  7943. check_assignment(c, &y, x.type, name);
  7944. if (y.mode != Addressing_Constant) {
  7945. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7946. }
  7947. }
  7948. }
  7949. if (res == LoadDirective_Success) {
  7950. *o = x;
  7951. } else {
  7952. *o = y;
  7953. }
  7954. o->expr = node;
  7955. return Expr_Expr;
  7956. }
  7957. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7958. if (x.mode == Addressing_Invalid) {
  7959. o->mode = Addressing_Value;
  7960. o->type = t_invalid;
  7961. o->expr = node;
  7962. return Expr_Expr;
  7963. }
  7964. Type *left_type = nullptr;
  7965. Type *right_type = nullptr;
  7966. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7967. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7968. bool y_is_diverging = false;
  7969. check_expr_base(c, &y, default_value, left_type);
  7970. switch (y.mode) {
  7971. case Addressing_NoValue:
  7972. if (is_diverging_expr(y.expr)) {
  7973. // Allow
  7974. y.mode = Addressing_Value;
  7975. y_is_diverging = true;
  7976. } else {
  7977. error_operand_no_value(&y);
  7978. y.mode = Addressing_Invalid;
  7979. }
  7980. break;
  7981. case Addressing_Type:
  7982. error_operand_not_expression(&y);
  7983. y.mode = Addressing_Invalid;
  7984. break;
  7985. }
  7986. if (y.mode == Addressing_Invalid) {
  7987. o->mode = Addressing_Value;
  7988. o->type = t_invalid;
  7989. o->expr = node;
  7990. return Expr_Expr;
  7991. }
  7992. if (left_type != nullptr) {
  7993. if (!y_is_diverging) {
  7994. if (is_type_tuple(left_type)) {
  7995. if (!is_type_tuple(y.type)) {
  7996. error(y.expr, "Found a single value where a %td-valued expression was expected", left_type->Tuple.variables.count);
  7997. } else if (!are_types_identical(left_type, y.type)) {
  7998. gbString xt = type_to_string(left_type);
  7999. gbString yt = type_to_string(y.type);
  8000. error(y.expr, "Mismatched types, expected (%s), got (%s)", xt, yt);
  8001. gb_string_free(yt);
  8002. gb_string_free(xt);
  8003. }
  8004. } else {
  8005. check_assignment(c, &y, left_type, name);
  8006. }
  8007. }
  8008. } else {
  8009. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8010. }
  8011. if (left_type == nullptr) {
  8012. left_type = t_invalid;
  8013. }
  8014. o->mode = Addressing_Value;
  8015. o->type = left_type;
  8016. o->expr = node;
  8017. return Expr_Expr;
  8018. }
  8019. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8020. ast_node(re, OrReturnExpr, node);
  8021. String name = re->token.string;
  8022. Operand x = {};
  8023. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  8024. if (x.mode == Addressing_Invalid) {
  8025. o->mode = Addressing_Value;
  8026. o->type = t_invalid;
  8027. o->expr = node;
  8028. return Expr_Expr;
  8029. }
  8030. Type *left_type = nullptr;
  8031. Type *right_type = nullptr;
  8032. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8033. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  8034. if (right_type == nullptr) {
  8035. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8036. } else {
  8037. Type *proc_type = base_type(c->curr_proc_sig);
  8038. GB_ASSERT(proc_type->kind == Type_Proc);
  8039. Type *result_type = proc_type->Proc.results;
  8040. if (result_type == nullptr) {
  8041. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  8042. } else {
  8043. GB_ASSERT(result_type->kind == Type_Tuple);
  8044. auto const &vars = result_type->Tuple.variables;
  8045. Type *end_type = vars[vars.count-1]->type;
  8046. if (vars.count > 1) {
  8047. if (!proc_type->Proc.has_named_results) {
  8048. 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));
  8049. }
  8050. }
  8051. Operand rhs = {};
  8052. rhs.type = right_type;
  8053. rhs.mode = Addressing_Value;
  8054. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  8055. // NOTE(bill): allow implicit conversion between boolean types
  8056. // within 'or_return' to improve the experience using third-party code
  8057. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  8058. ERROR_BLOCK();
  8059. // TODO(bill): better error message
  8060. gbString a = type_to_string(right_type);
  8061. gbString b = type_to_string(end_type);
  8062. gbString ret_type = type_to_string(result_type);
  8063. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  8064. if (vars.count == 1) {
  8065. error_line("\tProcedure return value type: %s\n", ret_type);
  8066. } else {
  8067. error_line("\tProcedure return value types: (%s)\n", ret_type);
  8068. }
  8069. gb_string_free(ret_type);
  8070. gb_string_free(b);
  8071. gb_string_free(a);
  8072. }
  8073. }
  8074. }
  8075. o->expr = node;
  8076. o->type = left_type;
  8077. if (left_type != nullptr) {
  8078. o->mode = Addressing_Value;
  8079. } else {
  8080. o->mode = Addressing_NoValue;
  8081. }
  8082. if (c->curr_proc_sig == nullptr) {
  8083. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8084. }
  8085. if (c->in_defer) {
  8086. error(node, "'or_return' cannot be used within a defer statement");
  8087. }
  8088. return Expr_Expr;
  8089. }
  8090. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8091. ast_node(be, OrBranchExpr, node);
  8092. String name = be->token.string;
  8093. Operand x = {};
  8094. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  8095. if (x.mode == Addressing_Invalid) {
  8096. o->mode = Addressing_Value;
  8097. o->type = t_invalid;
  8098. o->expr = node;
  8099. return Expr_Expr;
  8100. }
  8101. Type *left_type = nullptr;
  8102. Type *right_type = nullptr;
  8103. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8104. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  8105. if (right_type == nullptr) {
  8106. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8107. } else {
  8108. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  8109. // okay
  8110. } else {
  8111. gbString s = type_to_string(right_type);
  8112. error(node, "'%.*s' requires a boolean or nil-able type, got %s", LIT(name), s);
  8113. gb_string_free(s);
  8114. }
  8115. }
  8116. o->expr = node;
  8117. o->type = left_type;
  8118. if (left_type != nullptr) {
  8119. o->mode = Addressing_Value;
  8120. } else {
  8121. o->mode = Addressing_NoValue;
  8122. }
  8123. if (c->curr_proc_sig == nullptr) {
  8124. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8125. }
  8126. Ast *label = be->label;
  8127. switch (be->token.kind) {
  8128. case Token_or_break:
  8129. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  8130. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  8131. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  8132. }
  8133. break;
  8134. case Token_or_continue:
  8135. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  8136. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  8137. }
  8138. break;
  8139. }
  8140. if (label != nullptr) {
  8141. if (c->in_defer) {
  8142. error(label, "A labelled '%.*s' cannot be used within a 'defer'", LIT(name));
  8143. return Expr_Expr;
  8144. }
  8145. if (label->kind != Ast_Ident) {
  8146. error(label, "A branch statement's label name must be an identifier");
  8147. return Expr_Expr;
  8148. }
  8149. Ast *ident = label;
  8150. String name = ident->Ident.token.string;
  8151. Operand o = {};
  8152. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  8153. if (e == nullptr) {
  8154. error(ident, "Undeclared label name: %.*s", LIT(name));
  8155. return Expr_Expr;
  8156. }
  8157. add_entity_use(c, ident, e);
  8158. if (e->kind != Entity_Label) {
  8159. error(ident, "'%.*s' is not a label", LIT(name));
  8160. return Expr_Expr;
  8161. }
  8162. Ast *parent = e->Label.parent;
  8163. GB_ASSERT(parent != nullptr);
  8164. switch (parent->kind) {
  8165. case Ast_BlockStmt:
  8166. case Ast_IfStmt:
  8167. case Ast_SwitchStmt:
  8168. if (be->token.kind != Token_or_break) {
  8169. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  8170. }
  8171. break;
  8172. case Ast_RangeStmt:
  8173. case Ast_ForStmt:
  8174. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  8175. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  8176. }
  8177. break;
  8178. }
  8179. }
  8180. return Expr_Expr;
  8181. }
  8182. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  8183. Type *bt = base_type(type);
  8184. StringSet fields_visited = {};
  8185. defer (string_set_destroy(&fields_visited));
  8186. StringMap<String> fields_visited_through_raw_union = {};
  8187. defer (string_map_destroy(&fields_visited_through_raw_union));
  8188. String assignment_str = str_lit("structure literal");
  8189. if (bt->kind == Type_BitField) {
  8190. assignment_str = str_lit("bit_field literal");
  8191. }
  8192. for (Ast *elem : elems) {
  8193. if (elem->kind != Ast_FieldValue) {
  8194. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8195. continue;
  8196. }
  8197. ast_node(fv, FieldValue, elem);
  8198. Ast *ident = fv->field;
  8199. if (ident->kind == Ast_ImplicitSelectorExpr) {
  8200. gbString expr_str = expr_to_string(ident);
  8201. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  8202. gb_string_free(expr_str);
  8203. ident = ident->ImplicitSelectorExpr.selector;
  8204. }
  8205. if (ident->kind != Ast_Ident) {
  8206. gbString expr_str = expr_to_string(ident);
  8207. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  8208. gb_string_free(expr_str);
  8209. continue;
  8210. }
  8211. String name = ident->Ident.token.string;
  8212. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8213. bool is_unknown = sel.entity == nullptr;
  8214. if (is_unknown) {
  8215. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  8216. continue;
  8217. }
  8218. Entity *field = nullptr;
  8219. if (bt->kind == Type_Struct) {
  8220. field = bt->Struct.fields[sel.index[0]];
  8221. } else if (bt->kind == Type_BitField) {
  8222. field = bt->BitField.fields[sel.index[0]];
  8223. } else {
  8224. GB_PANIC("Unknown type");
  8225. }
  8226. add_entity_use(c, ident, field);
  8227. if (string_set_update(&fields_visited, name)) {
  8228. if (sel.index.count > 1) {
  8229. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8230. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8231. } else {
  8232. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  8233. }
  8234. } else {
  8235. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  8236. }
  8237. continue;
  8238. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8239. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8240. continue;
  8241. }
  8242. if (sel.indirect) {
  8243. 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));
  8244. continue;
  8245. }
  8246. if (sel.index.count > 1) {
  8247. GB_ASSERT(bt->kind == Type_Struct);
  8248. if (is_constant) {
  8249. Type *ft = type;
  8250. for (i32 index : sel.index) {
  8251. Type *bt = base_type(ft);
  8252. switch (bt->kind) {
  8253. case Type_Struct:
  8254. if (bt->Struct.is_raw_union) {
  8255. is_constant = false;
  8256. break;
  8257. }
  8258. ft = bt->Struct.fields[index]->type;
  8259. break;
  8260. case Type_Array:
  8261. ft = bt->Array.elem;
  8262. break;
  8263. case Type_BitField:
  8264. is_constant = false;
  8265. ft = bt->BitField.fields[index]->type;
  8266. break;
  8267. default:
  8268. GB_PANIC("invalid type: %s", type_to_string(ft));
  8269. break;
  8270. }
  8271. }
  8272. if (is_constant &&
  8273. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  8274. is_constant = false;
  8275. }
  8276. }
  8277. Type *nested_ft = bt;
  8278. for (i32 index : sel.index) {
  8279. Type *bt = base_type(nested_ft);
  8280. switch (bt->kind) {
  8281. case Type_Struct:
  8282. if (bt->Struct.is_raw_union) {
  8283. for (Entity *re : bt->Struct.fields) {
  8284. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  8285. }
  8286. }
  8287. nested_ft = bt->Struct.fields[index]->type;
  8288. break;
  8289. case Type_Array:
  8290. nested_ft = bt->Array.elem;
  8291. break;
  8292. case Type_BitField:
  8293. nested_ft = bt->BitField.fields[index]->type;
  8294. break;
  8295. default:
  8296. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  8297. break;
  8298. }
  8299. }
  8300. field = sel.entity;
  8301. }
  8302. Operand o = {};
  8303. check_expr_or_type(c, &o, fv->value, field->type);
  8304. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8305. is_constant = false;
  8306. }
  8307. if (is_constant) {
  8308. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8309. }
  8310. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  8311. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  8312. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  8313. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  8314. }
  8315. check_assignment(c, &o, field->type, assignment_str);
  8316. c->bit_field_bit_size = prev_bit_field_bit_size;
  8317. }
  8318. }
  8319. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  8320. type_expr = unparen_expr(type_expr);
  8321. if (type_expr == nullptr) {
  8322. return false;
  8323. }
  8324. // [?]Type
  8325. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  8326. Ast *count = type_expr->ArrayType.count;
  8327. if (count->kind == Ast_UnaryExpr &&
  8328. count->UnaryExpr.op.kind == Token_Question) {
  8329. return true;
  8330. }
  8331. }
  8332. return false;
  8333. }
  8334. gb_internal bool check_for_dynamic_literals(CheckerContext *c, Ast *node, AstCompoundLit *cl) {
  8335. if (cl->elems.count > 0 && (check_feature_flags(c, node) & OptInFeatureFlag_DynamicLiterals) == 0 && !build_context.dynamic_literals) {
  8336. ERROR_BLOCK();
  8337. error(node, "Compound literals of dynamic types are disabled by default");
  8338. error_line("\tSuggestion: If you want to enable them for this specific file, add '#+feature dynamic-literals' at the top of the file\n");
  8339. error_line("\tWarning: Please understand that dynamic literals will implicitly allocate using the current 'context.allocator' in that scope\n");
  8340. if (build_context.ODIN_DEFAULT_TO_NIL_ALLOCATOR) {
  8341. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8342. } else if (build_context.ODIN_DEFAULT_TO_PANIC_ALLOCATOR) {
  8343. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8344. }
  8345. return false;
  8346. }
  8347. return cl->elems.count > 0;
  8348. }
  8349. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8350. ExprKind kind = Expr_Expr;
  8351. ast_node(cl, CompoundLit, node);
  8352. Type *type = type_hint;
  8353. if (type != nullptr && is_type_untyped(type)) {
  8354. type = nullptr;
  8355. }
  8356. bool is_to_be_determined_array_count = false;
  8357. bool is_constant = true;
  8358. bool is_soa = false;
  8359. Ast *type_expr = cl->type;
  8360. bool used_type_hint_expr = false;
  8361. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  8362. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  8363. type_expr = clone_ast(c->type_hint_expr);
  8364. used_type_hint_expr = true;
  8365. }
  8366. }
  8367. if (type_expr != nullptr) {
  8368. type = nullptr;
  8369. // [?]Type
  8370. if (type_expr->kind == Ast_ArrayType) {
  8371. Ast *count = type_expr->ArrayType.count;
  8372. if (count != nullptr) {
  8373. if (count->kind == Ast_UnaryExpr &&
  8374. count->UnaryExpr.op.kind == Token_Question) {
  8375. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  8376. is_to_be_determined_array_count = true;
  8377. }
  8378. } else {
  8379. type = alloc_type_slice(check_type(c, type_expr->ArrayType.elem));
  8380. }
  8381. if (cl->elems.count > 0) {
  8382. if (type_expr->ArrayType.tag != nullptr) {
  8383. Ast *tag = type_expr->ArrayType.tag;
  8384. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8385. String name = tag->BasicDirective.name.string;
  8386. if (name == "soa") {
  8387. is_soa = true;
  8388. if (count == nullptr) {
  8389. error(node, "#soa slices are not supported for compound literals");
  8390. return kind;
  8391. } else if (count->kind == Ast_UnaryExpr &&
  8392. count->UnaryExpr.op.kind == Token_Question) {
  8393. error(node, "#soa fixed length arrays must specify their length and cannot use ?");
  8394. }
  8395. }
  8396. }
  8397. }
  8398. } else if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  8399. if (cl->elems.count > 0) {
  8400. Ast *tag = type_expr->DynamicArrayType.tag;
  8401. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8402. String name = tag->BasicDirective.name.string;
  8403. if (name == "soa") {
  8404. is_soa = true;
  8405. error(node, "#soa dynamic arrays are not supported for compound literals");
  8406. return kind;
  8407. }
  8408. }
  8409. }
  8410. if (type == nullptr) {
  8411. type = check_type(c, type_expr);
  8412. }
  8413. }
  8414. if (type == nullptr) {
  8415. error(node, "Missing type in compound literal");
  8416. return kind;
  8417. }
  8418. Type *t = base_type(type);
  8419. if (is_type_polymorphic(t)) {
  8420. gbString str = type_to_string(type);
  8421. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  8422. o->expr = node;
  8423. o->type = type;
  8424. gb_string_free(str);
  8425. return kind;
  8426. }
  8427. switch (t->kind) {
  8428. case Type_Struct:
  8429. if (cl->elems.count == 0) {
  8430. break; // NOTE(bill): No need to init
  8431. }
  8432. if (t->Struct.soa_kind == StructSoa_None) {
  8433. if (t->Struct.is_raw_union) {
  8434. if (cl->elems.count > 0) {
  8435. // NOTE: unions cannot be constant
  8436. is_constant = false;
  8437. if (cl->elems[0]->kind != Ast_FieldValue) {
  8438. gbString type_str = type_to_string(type);
  8439. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  8440. gb_string_free(type_str);
  8441. } else {
  8442. if (cl->elems.count != 1) {
  8443. gbString type_str = type_to_string(type);
  8444. 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);
  8445. gb_string_free(type_str);
  8446. } else {
  8447. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8448. }
  8449. }
  8450. }
  8451. break;
  8452. }
  8453. wait_signal_until_available(&t->Struct.fields_wait_signal);
  8454. isize field_count = t->Struct.fields.count;
  8455. isize min_field_count = t->Struct.fields.count;
  8456. for (isize i = min_field_count-1; i >= 0; i--) {
  8457. Entity *e = t->Struct.fields[i];
  8458. GB_ASSERT(e->kind == Entity_Variable);
  8459. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  8460. min_field_count--;
  8461. } else {
  8462. break;
  8463. }
  8464. }
  8465. if (cl->elems[0]->kind == Ast_FieldValue) {
  8466. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8467. } else {
  8468. bool seen_field_value = false;
  8469. for_array(index, cl->elems) {
  8470. Entity *field = nullptr;
  8471. Ast *elem = cl->elems[index];
  8472. if (elem->kind == Ast_FieldValue) {
  8473. seen_field_value = true;
  8474. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8475. continue;
  8476. } else if (seen_field_value) {
  8477. error(elem, "Value elements cannot be used after a 'field = value'");
  8478. continue;
  8479. }
  8480. if (index >= field_count) {
  8481. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8482. break;
  8483. }
  8484. if (field == nullptr) {
  8485. field = t->Struct.fields[index];
  8486. }
  8487. Operand o = {};
  8488. check_expr_or_type(c, &o, elem, field->type);
  8489. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8490. is_constant = false;
  8491. }
  8492. if (is_constant) {
  8493. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8494. }
  8495. check_assignment(c, &o, field->type, str_lit("structure literal"));
  8496. }
  8497. if (cl->elems.count < field_count) {
  8498. if (min_field_count < field_count) {
  8499. if (cl->elems.count < min_field_count) {
  8500. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  8501. }
  8502. } else {
  8503. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8504. }
  8505. }
  8506. }
  8507. break;
  8508. } else if (t->Struct.soa_kind != StructSoa_Fixed) {
  8509. error(node, "#soa slices and dynamic arrays are not supported for compound literals");
  8510. break;
  8511. }
  8512. /*fallthrough*/
  8513. case Type_Slice:
  8514. case Type_Array:
  8515. case Type_DynamicArray:
  8516. case Type_SimdVector:
  8517. case Type_Matrix:
  8518. {
  8519. Type *elem_type = nullptr;
  8520. String context_name = {};
  8521. i64 max_type_count = -1;
  8522. if (t->kind == Type_Struct) {
  8523. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8524. elem_type = t->Struct.soa_elem;
  8525. context_name = str_lit("#soa array literal");
  8526. if (!is_to_be_determined_array_count) {
  8527. max_type_count = t->Struct.soa_count;
  8528. }
  8529. } else if (t->kind == Type_Slice) {
  8530. elem_type = t->Slice.elem;
  8531. context_name = str_lit("slice literal");
  8532. } else if (t->kind == Type_Array) {
  8533. elem_type = t->Array.elem;
  8534. context_name = str_lit("array literal");
  8535. if (!is_to_be_determined_array_count) {
  8536. max_type_count = t->Array.count;
  8537. }
  8538. } else if (t->kind == Type_Array) {
  8539. elem_type = t->Array.elem;
  8540. context_name = str_lit("array literal");
  8541. if (!is_to_be_determined_array_count) {
  8542. max_type_count = t->Array.count;
  8543. }
  8544. } else if (t->kind == Type_DynamicArray) {
  8545. elem_type = t->DynamicArray.elem;
  8546. context_name = str_lit("dynamic array literal");
  8547. is_constant = false;
  8548. } else if (t->kind == Type_SimdVector) {
  8549. elem_type = t->SimdVector.elem;
  8550. context_name = str_lit("simd vector literal");
  8551. max_type_count = t->SimdVector.count;
  8552. } else if (t->kind == Type_Matrix) {
  8553. elem_type = t->Matrix.elem;
  8554. context_name = str_lit("matrix literal");
  8555. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  8556. } else {
  8557. GB_PANIC("unreachable");
  8558. }
  8559. i64 max = 0;
  8560. Type *bet = base_type(elem_type);
  8561. if (!elem_type_can_be_constant(bet)) {
  8562. is_constant = false;
  8563. }
  8564. if (bet == t_invalid) {
  8565. break;
  8566. }
  8567. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8568. RangeCache rc = range_cache_make(heap_allocator());
  8569. defer (range_cache_destroy(&rc));
  8570. for (Ast *elem : cl->elems) {
  8571. if (elem->kind != Ast_FieldValue) {
  8572. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8573. continue;
  8574. }
  8575. ast_node(fv, FieldValue, elem);
  8576. if (is_ast_range(fv->field)) {
  8577. Token op = fv->field->BinaryExpr.op;
  8578. Operand x = {};
  8579. Operand y = {};
  8580. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  8581. if (!ok) {
  8582. continue;
  8583. }
  8584. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  8585. error(x.expr, "Expected a constant integer as an array field");
  8586. continue;
  8587. }
  8588. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  8589. error(y.expr, "Expected a constant integer as an array field");
  8590. continue;
  8591. }
  8592. i64 lo = exact_value_to_i64(x.value);
  8593. i64 hi = exact_value_to_i64(y.value);
  8594. i64 max_index = hi;
  8595. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  8596. hi -= 1;
  8597. } else { // .. (inclusive)
  8598. max_index += 1;
  8599. }
  8600. bool new_range = range_cache_add_range(&rc, lo, hi);
  8601. if (!new_range) {
  8602. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  8603. continue;
  8604. }
  8605. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  8606. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  8607. continue;
  8608. }
  8609. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  8610. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  8611. continue;
  8612. }
  8613. if (max < hi) {
  8614. max = max_index;
  8615. }
  8616. Operand operand = {};
  8617. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8618. check_assignment(c, &operand, elem_type, context_name);
  8619. is_constant = is_constant && operand.mode == Addressing_Constant;
  8620. } else {
  8621. Operand op_index = {};
  8622. check_expr(c, &op_index, fv->field);
  8623. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  8624. error(elem, "Expected a constant integer as an array field");
  8625. continue;
  8626. }
  8627. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  8628. i64 index = exact_value_to_i64(op_index.value);
  8629. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  8630. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  8631. continue;
  8632. }
  8633. bool new_index = range_cache_add_index(&rc, index);
  8634. if (!new_index) {
  8635. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  8636. continue;
  8637. }
  8638. if (max < index+1) {
  8639. max = index+1;
  8640. }
  8641. Operand operand = {};
  8642. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8643. check_assignment(c, &operand, elem_type, context_name);
  8644. is_constant = is_constant && operand.mode == Addressing_Constant;
  8645. }
  8646. }
  8647. cl->max_count = max;
  8648. } else {
  8649. isize index = 0;
  8650. for (; index < cl->elems.count; index++) {
  8651. Ast *e = cl->elems[index];
  8652. if (e == nullptr) {
  8653. error(node, "Invalid literal element");
  8654. continue;
  8655. }
  8656. if (e->kind == Ast_FieldValue) {
  8657. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8658. continue;
  8659. }
  8660. if (0 <= max_type_count && max_type_count <= index) {
  8661. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8662. }
  8663. Operand operand = {};
  8664. check_expr_with_type_hint(c, &operand, e, elem_type);
  8665. check_assignment(c, &operand, elem_type, context_name);
  8666. is_constant = is_constant && operand.mode == Addressing_Constant;
  8667. }
  8668. if (max < index) {
  8669. max = index;
  8670. }
  8671. }
  8672. if (t->kind == Type_Array) {
  8673. if (is_to_be_determined_array_count) {
  8674. t->Array.count = max;
  8675. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8676. if (0 < max && max < t->Array.count) {
  8677. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8678. }
  8679. }
  8680. } else if (t->kind == Type_Struct) {
  8681. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8682. if (is_to_be_determined_array_count) {
  8683. t->Struct.soa_count = cast(i32)max;
  8684. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8685. if (0 < max && max < t->Struct.soa_count) {
  8686. error(node, "Expected %lld values for this #soa array literal, got %lld", cast(long long)t->Struct.soa_count, cast(long long)max);
  8687. }
  8688. }
  8689. }
  8690. if (t->kind == Type_SimdVector) {
  8691. if (!is_constant) {
  8692. // error(node, "Expected all constant elements for a simd vector");
  8693. }
  8694. }
  8695. if (t->kind == Type_DynamicArray) {
  8696. if (check_for_dynamic_literals(c, node, cl)) {
  8697. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  8698. add_package_dependency(c, "runtime", "__dynamic_array_append");
  8699. }
  8700. }
  8701. if (t->kind == Type_Matrix) {
  8702. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8703. if (0 < max && max < max_type_count) {
  8704. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  8705. }
  8706. }
  8707. }
  8708. break;
  8709. }
  8710. case Type_EnumeratedArray:
  8711. {
  8712. Type *elem_type = t->EnumeratedArray.elem;
  8713. Type *index_type = t->EnumeratedArray.index;
  8714. String context_name = str_lit("enumerated array literal");
  8715. i64 max_type_count = t->EnumeratedArray.count;
  8716. gbString index_type_str = type_to_string(index_type);
  8717. defer (gb_string_free(index_type_str));
  8718. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  8719. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  8720. String total_lo_string = {};
  8721. String total_hi_string = {};
  8722. GB_ASSERT(is_type_enum(index_type));
  8723. {
  8724. Type *bt = base_type(index_type);
  8725. GB_ASSERT(bt->kind == Type_Enum);
  8726. for (Entity *f : bt->Enum.fields) {
  8727. if (f->kind != Entity_Constant) {
  8728. continue;
  8729. }
  8730. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  8731. total_lo_string = f->token.string;
  8732. }
  8733. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  8734. total_hi_string = f->token.string;
  8735. }
  8736. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8737. break;
  8738. }
  8739. }
  8740. }
  8741. i64 max = 0;
  8742. Type *bet = base_type(elem_type);
  8743. if (!elem_type_can_be_constant(bet)) {
  8744. is_constant = false;
  8745. }
  8746. if (bet == t_invalid) {
  8747. break;
  8748. }
  8749. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8750. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8751. defer (map_destroy(&seen));
  8752. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8753. RangeCache rc = range_cache_make(heap_allocator());
  8754. defer (range_cache_destroy(&rc));
  8755. for (Ast *elem : cl->elems) {
  8756. if (elem->kind != Ast_FieldValue) {
  8757. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8758. continue;
  8759. }
  8760. ast_node(fv, FieldValue, elem);
  8761. if (is_ast_range(fv->field)) {
  8762. Token op = fv->field->BinaryExpr.op;
  8763. Operand x = {};
  8764. Operand y = {};
  8765. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8766. if (!ok) {
  8767. continue;
  8768. }
  8769. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8770. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8771. continue;
  8772. }
  8773. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8774. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8775. continue;
  8776. }
  8777. i64 lo = exact_value_to_i64(x.value);
  8778. i64 hi = exact_value_to_i64(y.value);
  8779. i64 max_index = hi;
  8780. if (op.kind == Token_RangeHalf) {
  8781. hi -= 1;
  8782. }
  8783. bool new_range = range_cache_add_range(&rc, lo, hi);
  8784. if (!new_range) {
  8785. gbString lo_str = expr_to_string(x.expr);
  8786. gbString hi_str = expr_to_string(y.expr);
  8787. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8788. gb_string_free(hi_str);
  8789. gb_string_free(lo_str);
  8790. continue;
  8791. }
  8792. // NOTE(bill): These are sanity checks for invalid enum values
  8793. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8794. gbString lo_str = expr_to_string(x.expr);
  8795. 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));
  8796. gb_string_free(lo_str);
  8797. continue;
  8798. }
  8799. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8800. gbString hi_str = expr_to_string(y.expr);
  8801. 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));
  8802. gb_string_free(hi_str);
  8803. continue;
  8804. }
  8805. if (max < hi) {
  8806. max = max_index;
  8807. }
  8808. Operand operand = {};
  8809. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8810. check_assignment(c, &operand, elem_type, context_name);
  8811. is_constant = is_constant && operand.mode == Addressing_Constant;
  8812. TokenKind upper_op = Token_LtEq;
  8813. if (op.kind == Token_RangeHalf) {
  8814. upper_op = Token_Lt;
  8815. }
  8816. add_to_seen_map(c, &seen, upper_op, x, x, y);
  8817. } else {
  8818. Operand op_index = {};
  8819. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8820. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8821. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8822. continue;
  8823. }
  8824. i64 index = exact_value_to_i64(op_index.value);
  8825. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8826. gbString idx_str = expr_to_string(op_index.expr);
  8827. 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));
  8828. gb_string_free(idx_str);
  8829. continue;
  8830. }
  8831. bool new_index = range_cache_add_index(&rc, index);
  8832. if (!new_index) {
  8833. gbString idx_str = expr_to_string(op_index.expr);
  8834. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8835. gb_string_free(idx_str);
  8836. continue;
  8837. }
  8838. if (max < index+1) {
  8839. max = index+1;
  8840. }
  8841. Operand operand = {};
  8842. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8843. check_assignment(c, &operand, elem_type, context_name);
  8844. is_constant = is_constant && operand.mode == Addressing_Constant;
  8845. add_to_seen_map(c, &seen, op_index);
  8846. }
  8847. }
  8848. cl->max_count = max;
  8849. } else {
  8850. isize index = 0;
  8851. for (; index < cl->elems.count; index++) {
  8852. Ast *e = cl->elems[index];
  8853. if (e == nullptr) {
  8854. error(node, "Invalid literal element");
  8855. continue;
  8856. }
  8857. if (e->kind == Ast_FieldValue) {
  8858. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8859. continue;
  8860. }
  8861. if (0 <= max_type_count && max_type_count <= index) {
  8862. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8863. }
  8864. Operand operand = {};
  8865. check_expr_with_type_hint(c, &operand, e, elem_type);
  8866. check_assignment(c, &operand, elem_type, context_name);
  8867. is_constant = is_constant && operand.mode == Addressing_Constant;
  8868. }
  8869. if (max < index) {
  8870. max = index;
  8871. }
  8872. }
  8873. bool was_error = false;
  8874. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8875. if (0 < max && max < t->EnumeratedArray.count) {
  8876. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  8877. was_error = true;
  8878. } else {
  8879. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  8880. was_error = true;
  8881. }
  8882. }
  8883. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  8884. if (cl->elems.count > 0 && !was_error && !is_partial) {
  8885. TEMPORARY_ALLOCATOR_GUARD();
  8886. Type *et = base_type(index_type);
  8887. GB_ASSERT(et->kind == Type_Enum);
  8888. auto fields = et->Enum.fields;
  8889. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  8890. for (Entity *f : fields) {
  8891. if (f->kind != Entity_Constant) {
  8892. continue;
  8893. }
  8894. ExactValue v = f->Constant.value;
  8895. uintptr hash = hash_exact_value(v);
  8896. auto found = map_get(&seen, hash);
  8897. if (!found) {
  8898. array_add(&unhandled, f);
  8899. }
  8900. }
  8901. if (unhandled.count > 0) {
  8902. ERROR_BLOCK();
  8903. if (unhandled.count == 1) {
  8904. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  8905. } else {
  8906. error(node, "Unhandled enumerated array cases:");
  8907. for_array(i, unhandled) {
  8908. Entity *f = unhandled[i];
  8909. error_line("\t%.*s\n", LIT(f->token.string));
  8910. }
  8911. }
  8912. if (!build_context.terse_errors) {
  8913. error_line("\n");
  8914. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  8915. }
  8916. }
  8917. }
  8918. break;
  8919. }
  8920. case Type_Basic: {
  8921. if (!is_type_any(t)) {
  8922. if (cl->elems.count != 0) {
  8923. gbString s = type_to_string(t);
  8924. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  8925. gb_string_free(s);
  8926. is_constant = false;
  8927. }
  8928. break;
  8929. }
  8930. if (cl->elems.count == 0) {
  8931. break; // NOTE(bill): No need to init
  8932. }
  8933. { // Checker values
  8934. Type *field_types[2] = {t_rawptr, t_typeid};
  8935. isize field_count = 2;
  8936. if (cl->elems[0]->kind == Ast_FieldValue) {
  8937. bool fields_visited[2] = {};
  8938. for_array(i, cl->elems) {
  8939. Ast *elem = cl->elems[i];
  8940. if (elem->kind != Ast_FieldValue) {
  8941. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8942. continue;
  8943. }
  8944. ast_node(fv, FieldValue, elem);
  8945. if (fv->field->kind != Ast_Ident) {
  8946. gbString expr_str = expr_to_string(fv->field);
  8947. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  8948. gb_string_free(expr_str);
  8949. continue;
  8950. }
  8951. String name = fv->field->Ident.token.string;
  8952. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8953. if (sel.entity == nullptr) {
  8954. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  8955. continue;
  8956. }
  8957. isize index = sel.index[0];
  8958. if (fields_visited[index]) {
  8959. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  8960. continue;
  8961. }
  8962. fields_visited[index] = true;
  8963. check_expr(c, o, fv->value);
  8964. // NOTE(bill): 'any' literals can never be constant
  8965. is_constant = false;
  8966. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8967. }
  8968. } else {
  8969. for_array(index, cl->elems) {
  8970. Ast *elem = cl->elems[index];
  8971. if (elem->kind == Ast_FieldValue) {
  8972. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8973. continue;
  8974. }
  8975. check_expr(c, o, elem);
  8976. if (index >= field_count) {
  8977. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  8978. break;
  8979. }
  8980. // NOTE(bill): 'any' literals can never be constant
  8981. is_constant = false;
  8982. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8983. }
  8984. if (cl->elems.count < field_count) {
  8985. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  8986. }
  8987. }
  8988. }
  8989. break;
  8990. }
  8991. case Type_Map: {
  8992. if (cl->elems.count == 0) {
  8993. break;
  8994. }
  8995. is_constant = false;
  8996. { // Checker values
  8997. bool key_is_typeid = is_type_typeid(t->Map.key);
  8998. bool value_is_typeid = is_type_typeid(t->Map.value);
  8999. for (Ast *elem : cl->elems) {
  9000. if (elem->kind != Ast_FieldValue) {
  9001. error(elem, "Only 'field = value' elements are allowed in a map literal");
  9002. continue;
  9003. }
  9004. ast_node(fv, FieldValue, elem);
  9005. if (key_is_typeid) {
  9006. check_expr_or_type(c, o, fv->field, t->Map.key);
  9007. } else {
  9008. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  9009. }
  9010. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  9011. if (o->mode == Addressing_Invalid) {
  9012. continue;
  9013. }
  9014. if (value_is_typeid) {
  9015. check_expr_or_type(c, o, fv->value, t->Map.value);
  9016. } else {
  9017. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  9018. }
  9019. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  9020. }
  9021. }
  9022. if (check_for_dynamic_literals(c, node, cl)) {
  9023. add_map_reserve_dependencies(c);
  9024. add_map_set_dependencies(c);
  9025. }
  9026. break;
  9027. }
  9028. case Type_BitSet: {
  9029. if (cl->elems.count == 0) {
  9030. break; // NOTE(bill): No need to init
  9031. }
  9032. Type *et = base_type(t->BitSet.elem);
  9033. isize field_count = 0;
  9034. if (et != nullptr && et->kind == Type_Enum) {
  9035. field_count = et->Enum.fields.count;
  9036. }
  9037. if (is_type_array(bit_set_to_int(t))) {
  9038. is_constant = false;
  9039. }
  9040. if (cl->elems[0]->kind == Ast_FieldValue) {
  9041. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  9042. is_constant = false;
  9043. } else {
  9044. for (Ast *elem : cl->elems) {
  9045. if (elem->kind == Ast_FieldValue) {
  9046. error(elem, "'field = value' in a bit_set a literal is not allowed");
  9047. continue;
  9048. }
  9049. check_expr_with_type_hint(c, o, elem, et);
  9050. if (is_constant) {
  9051. is_constant = o->mode == Addressing_Constant;
  9052. }
  9053. if (elem->kind == Ast_BinaryExpr) {
  9054. switch (elem->BinaryExpr.op.kind) {
  9055. case Token_Or:
  9056. {
  9057. gbString x = expr_to_string(elem->BinaryExpr.left);
  9058. gbString y = expr_to_string(elem->BinaryExpr.right);
  9059. gbString e = expr_to_string(elem);
  9060. error(elem, "Was the following intended? '%s, %s'; if not, surround the expression with parentheses '(%s)'", x, y, e);
  9061. gb_string_free(e);
  9062. gb_string_free(y);
  9063. gb_string_free(x);
  9064. }
  9065. break;
  9066. }
  9067. }
  9068. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  9069. if (o->mode == Addressing_Constant) {
  9070. i64 lower = t->BitSet.lower;
  9071. i64 upper = t->BitSet.upper;
  9072. i64 v = exact_value_to_i64(o->value);
  9073. if (lower <= v && v <= upper) {
  9074. // okay
  9075. } else {
  9076. gbString s = expr_to_string(o->expr);
  9077. error(elem, "Bit field value out of bounds, %s (%lld) not in the range %lld .. %lld", s, v, lower, upper);
  9078. gb_string_free(s);
  9079. continue;
  9080. }
  9081. }
  9082. }
  9083. }
  9084. break;
  9085. }
  9086. case Type_BitField: {
  9087. if (cl->elems.count == 0) {
  9088. break; // NOTE(bill): No need to init
  9089. }
  9090. is_constant = false;
  9091. if (cl->elems[0]->kind != Ast_FieldValue) {
  9092. gbString type_str = type_to_string(type);
  9093. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  9094. gb_string_free(type_str);
  9095. } else {
  9096. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  9097. }
  9098. break;
  9099. }
  9100. default: {
  9101. if (cl->elems.count == 0) {
  9102. break; // NOTE(bill): No need to init
  9103. }
  9104. gbString str = type_to_string(type);
  9105. error(node, "Invalid compound literal type '%s'", str);
  9106. gb_string_free(str);
  9107. return kind;
  9108. }
  9109. }
  9110. if (is_constant) {
  9111. o->mode = Addressing_Constant;
  9112. if (is_type_bit_set(type)) {
  9113. // NOTE(bill): Encode as an integer
  9114. Type *bt = base_type(type);
  9115. BigInt bits = {};
  9116. BigInt one = {};
  9117. big_int_from_u64(&one, 1);
  9118. for (Ast *e : cl->elems) {
  9119. GB_ASSERT(e->kind != Ast_FieldValue);
  9120. TypeAndValue tav = e->tav;
  9121. if (tav.mode != Addressing_Constant) {
  9122. continue;
  9123. }
  9124. if (tav.value.kind != ExactValue_Integer) {
  9125. continue;
  9126. }
  9127. i64 v = big_int_to_i64(&tav.value.value_integer);
  9128. i64 lower = bt->BitSet.lower;
  9129. u64 index = cast(u64)(v-lower);
  9130. BigInt bit = {};
  9131. big_int_from_u64(&bit, index);
  9132. big_int_shl(&bit, &one, &bit);
  9133. big_int_or(&bits, &bits, &bit);
  9134. }
  9135. o->value.kind = ExactValue_Integer;
  9136. o->value.value_integer = bits;
  9137. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  9138. ExactValue value = exact_value_compound(node);
  9139. Type *bt = core_type(type);
  9140. if (bt->kind == Type_Basic) {
  9141. if (bt->Basic.flags & BasicFlag_Boolean) {
  9142. value = exact_value_bool(false);
  9143. } else if (bt->Basic.flags & BasicFlag_Integer) {
  9144. value = exact_value_i64(0);
  9145. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  9146. value = exact_value_i64(0);
  9147. } else if (bt->Basic.flags & BasicFlag_Float) {
  9148. value = exact_value_float(0);
  9149. } else if (bt->Basic.flags & BasicFlag_Complex) {
  9150. value = exact_value_complex(0, 0);
  9151. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  9152. value = exact_value_quaternion(0, 0, 0, 0);
  9153. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  9154. value = exact_value_pointer(0);
  9155. } else if (bt->Basic.flags & BasicFlag_String) {
  9156. String empty_string = {};
  9157. value = exact_value_string(empty_string);
  9158. } else if (bt->Basic.flags & BasicFlag_Rune) {
  9159. value = exact_value_i64(0);
  9160. }
  9161. }
  9162. o->value = value;
  9163. } else {
  9164. o->value = exact_value_compound(node);
  9165. }
  9166. } else {
  9167. o->mode = Addressing_Value;
  9168. }
  9169. o->type = type;
  9170. return kind;
  9171. }
  9172. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9173. ExprKind kind = Expr_Expr;
  9174. ast_node(ta, TypeAssertion, node);
  9175. check_expr(c, o, ta->expr);
  9176. node->viral_state_flags |= ta->expr->viral_state_flags;
  9177. if (o->mode == Addressing_Invalid) {
  9178. o->expr = node;
  9179. return kind;
  9180. }
  9181. if (o->mode == Addressing_Constant) {
  9182. gbString expr_str = expr_to_string(o->expr);
  9183. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  9184. gb_string_free(expr_str);
  9185. o->mode = Addressing_Invalid;
  9186. o->expr = node;
  9187. return kind;
  9188. }
  9189. if (is_type_untyped(o->type)) {
  9190. gbString expr_str = expr_to_string(o->expr);
  9191. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  9192. gb_string_free(expr_str);
  9193. o->mode = Addressing_Invalid;
  9194. o->expr = node;
  9195. return kind;
  9196. }
  9197. Type *src = type_deref(o->type);
  9198. Type *bsrc = base_type(src);
  9199. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  9200. if (!is_type_union(src)) {
  9201. gbString str = type_to_string(o->type);
  9202. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  9203. gb_string_free(str);
  9204. o->mode = Addressing_Invalid;
  9205. o->expr = node;
  9206. return kind;
  9207. }
  9208. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  9209. bool allowed = false;
  9210. for (Type *vt : bsrc->Union.variants) {
  9211. if (are_types_identical(vt, type_hint)) {
  9212. allowed = true;
  9213. add_type_info_type(c, vt);
  9214. break;
  9215. }
  9216. }
  9217. if (allowed) {
  9218. add_type_info_type(c, o->type);
  9219. o->type = type_hint;
  9220. o->mode = Addressing_OptionalOk;
  9221. goto end;
  9222. }
  9223. }
  9224. if (bsrc->Union.variants.count != 1) {
  9225. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  9226. o->mode = Addressing_Invalid;
  9227. o->expr = node;
  9228. return kind;
  9229. }
  9230. add_type_info_type(c, o->type);
  9231. add_type_info_type(c, bsrc->Union.variants[0]);
  9232. o->type = bsrc->Union.variants[0];
  9233. o->mode = Addressing_OptionalOk;
  9234. } else {
  9235. Type *t = check_type(c, ta->type);
  9236. Type *dst = t;
  9237. if (is_type_union(src)) {
  9238. bool ok = false;
  9239. for (Type *vt : bsrc->Union.variants) {
  9240. if (are_types_identical(vt, dst)) {
  9241. ok = true;
  9242. break;
  9243. }
  9244. }
  9245. if (!ok) {
  9246. gbString expr_str = expr_to_string(o->expr);
  9247. gbString dst_type_str = type_to_string(t);
  9248. defer (gb_string_free(expr_str));
  9249. defer (gb_string_free(dst_type_str));
  9250. if (bsrc->Union.variants.count == 0) {
  9251. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  9252. } else {
  9253. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  9254. }
  9255. o->mode = Addressing_Invalid;
  9256. o->expr = node;
  9257. return kind;
  9258. }
  9259. add_type_info_type(c, o->type);
  9260. add_type_info_type(c, t);
  9261. o->type = t;
  9262. o->mode = Addressing_OptionalOk;
  9263. } else if (is_type_any(src)) {
  9264. o->type = t;
  9265. o->mode = Addressing_OptionalOk;
  9266. add_type_info_type(c, o->type);
  9267. add_type_info_type(c, t);
  9268. } else {
  9269. gbString str = type_to_string(o->type);
  9270. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  9271. gb_string_free(str);
  9272. o->mode = Addressing_Invalid;
  9273. o->expr = node;
  9274. return kind;
  9275. }
  9276. }
  9277. end:;
  9278. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  9279. add_package_dependency(c, "runtime", "type_assertion_check");
  9280. add_package_dependency(c, "runtime", "type_assertion_check2");
  9281. }
  9282. return kind;
  9283. }
  9284. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9285. ast_node(se, SelectorCallExpr, node);
  9286. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  9287. // COM APIs is a great example of where this kind of thing is extremely useful
  9288. // General idea:
  9289. //
  9290. // x->y(123) == x.y(x, 123)
  9291. //
  9292. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  9293. // Just regenerating a new AST aids things
  9294. //
  9295. // TODO(bill): Is this a good hack or not?
  9296. //
  9297. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  9298. if (se->modified_call) {
  9299. // Prevent double evaluation
  9300. o->expr = node;
  9301. o->type = node->tav.type;
  9302. o->value = node->tav.value;
  9303. o->mode = node->tav.mode;
  9304. return Expr_Expr;
  9305. }
  9306. bool allow_arrow_right_selector_expr;
  9307. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9308. c->allow_arrow_right_selector_expr = true;
  9309. Operand x = {};
  9310. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  9311. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9312. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  9313. o->mode = Addressing_Invalid;
  9314. o->type = t_invalid;
  9315. o->expr = node;
  9316. return kind;
  9317. }
  9318. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  9319. gbString type_str = type_to_string(x.type);
  9320. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  9321. gb_string_free(type_str);
  9322. o->mode = Addressing_Invalid;
  9323. o->type = t_invalid;
  9324. o->expr = node;
  9325. return Expr_Stmt;
  9326. }
  9327. ast_node(ce, CallExpr, se->call);
  9328. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  9329. Ast *first_arg = x.expr->SelectorExpr.expr;
  9330. GB_ASSERT(first_arg != nullptr);
  9331. Entity *e = entity_of_node(se->expr);
  9332. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  9333. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  9334. }
  9335. if (e->kind != Entity_ProcGroup) {
  9336. Type *pt = base_type(x.type);
  9337. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  9338. Type *first_type = nullptr;
  9339. String first_arg_name = {};
  9340. if (pt->Proc.param_count > 0) {
  9341. Entity *f = pt->Proc.params->Tuple.variables[0];
  9342. first_type = f->type;
  9343. first_arg_name = f->token.string;
  9344. }
  9345. if (first_arg_name.len == 0) {
  9346. first_arg_name = str_lit("_");
  9347. }
  9348. if (first_type == nullptr) {
  9349. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  9350. o->mode = Addressing_Invalid;
  9351. o->type = t_invalid;
  9352. o->expr = node;
  9353. return Expr_Stmt;
  9354. }
  9355. Operand y = {};
  9356. y.mode = first_arg->tav.mode;
  9357. y.type = first_arg->tav.type;
  9358. y.value = first_arg->tav.value;
  9359. if (check_is_assignable_to(c, &y, first_type)) {
  9360. // Do nothing, it's valid
  9361. } else {
  9362. Operand z = y;
  9363. z.type = type_deref(y.type);
  9364. if (check_is_assignable_to(c, &z, first_type)) {
  9365. // NOTE(bill): AST GENERATION HACK!
  9366. Token op = {Token_Pointer};
  9367. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  9368. } else if (y.mode == Addressing_Variable) {
  9369. Operand w = y;
  9370. w.type = alloc_type_pointer(y.type);
  9371. if (check_is_assignable_to(c, &w, first_type)) {
  9372. // NOTE(bill): AST GENERATION HACK!
  9373. Token op = {Token_And};
  9374. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  9375. }
  9376. }
  9377. }
  9378. if (ce->args.count > 0) {
  9379. bool fail = false;
  9380. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  9381. for (Ast *arg : ce->args) {
  9382. bool mix = false;
  9383. if (first_is_field_value) {
  9384. mix = arg->kind != Ast_FieldValue;
  9385. } else {
  9386. mix = arg->kind == Ast_FieldValue;
  9387. }
  9388. if (mix) {
  9389. fail = true;
  9390. break;
  9391. }
  9392. }
  9393. if (!fail && first_is_field_value) {
  9394. Token op = {Token_Eq};
  9395. AstFile *f = first_arg->file();
  9396. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  9397. }
  9398. }
  9399. }
  9400. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  9401. modified_args[0] = first_arg;
  9402. slice_copy(&modified_args, ce->args, 1);
  9403. ce->args = modified_args;
  9404. se->modified_call = true;
  9405. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9406. c->allow_arrow_right_selector_expr = true;
  9407. check_expr_base(c, o, se->call, type_hint);
  9408. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9409. o->expr = node;
  9410. return Expr_Expr;
  9411. }
  9412. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9413. ExprKind kind = Expr_Expr;
  9414. ast_node(ie, IndexExpr, node);
  9415. check_expr(c, o, ie->expr);
  9416. node->viral_state_flags |= ie->expr->viral_state_flags;
  9417. if (o->mode == Addressing_Invalid) {
  9418. o->expr = node;
  9419. return kind;
  9420. }
  9421. Type *t = base_type(type_deref(o->type));
  9422. bool is_ptr = is_type_pointer(o->type);
  9423. bool is_const = o->mode == Addressing_Constant;
  9424. if (is_type_map(t)) {
  9425. Operand key = {};
  9426. if (is_type_typeid(t->Map.key)) {
  9427. check_expr_or_type(c, &key, ie->index, t->Map.key);
  9428. } else {
  9429. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  9430. }
  9431. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  9432. if (key.mode == Addressing_Invalid) {
  9433. o->mode = Addressing_Invalid;
  9434. o->expr = node;
  9435. return kind;
  9436. }
  9437. o->mode = Addressing_MapIndex;
  9438. o->type = t->Map.value;
  9439. o->expr = node;
  9440. add_map_get_dependencies(c);
  9441. add_map_set_dependencies(c);
  9442. return Expr_Expr;
  9443. }
  9444. i64 max_count = -1;
  9445. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  9446. if (is_const) {
  9447. if (is_type_array(t)) {
  9448. // Okay
  9449. } else if (is_type_slice(t)) {
  9450. // Okay
  9451. } else if (is_type_enumerated_array(t)) {
  9452. // Okay
  9453. } else if (is_type_string(t)) {
  9454. // Okay
  9455. } else if (is_type_matrix(t)) {
  9456. // Okay
  9457. } else {
  9458. valid = false;
  9459. }
  9460. }
  9461. if (!valid) {
  9462. gbString str = expr_to_string(o->expr);
  9463. gbString type_str = type_to_string(o->type);
  9464. defer (gb_string_free(str));
  9465. defer (gb_string_free(type_str));
  9466. if (is_const) {
  9467. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  9468. } else {
  9469. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  9470. }
  9471. o->mode = Addressing_Invalid;
  9472. o->expr = node;
  9473. return kind;
  9474. }
  9475. if (ie->index == nullptr) {
  9476. gbString str = expr_to_string(o->expr);
  9477. error(o->expr, "Missing index for '%s'", str);
  9478. gb_string_free(str);
  9479. o->mode = Addressing_Invalid;
  9480. o->expr = node;
  9481. return kind;
  9482. }
  9483. Type *index_type_hint = nullptr;
  9484. if (is_type_enumerated_array(t)) {
  9485. Type *bt = base_type(t);
  9486. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  9487. index_type_hint = bt->EnumeratedArray.index;
  9488. }
  9489. i64 index = 0;
  9490. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  9491. if (is_const) {
  9492. if (index < 0) {
  9493. ERROR_BLOCK();
  9494. gbString str = expr_to_string(o->expr);
  9495. error(o->expr, "Cannot index a constant '%s'", str);
  9496. if (!build_context.terse_errors) {
  9497. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9498. }
  9499. gb_string_free(str);
  9500. o->mode = Addressing_Invalid;
  9501. o->expr = node;
  9502. return kind;
  9503. } else if (ok && !is_type_matrix(t)) {
  9504. TypeAndValue tav = type_and_value_of_expr(ie->expr);
  9505. ExactValue value = tav.value;
  9506. o->mode = Addressing_Constant;
  9507. bool success = false;
  9508. bool finish = false;
  9509. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  9510. if (!success) {
  9511. ERROR_BLOCK();
  9512. gbString str = expr_to_string(o->expr);
  9513. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  9514. if (!build_context.terse_errors) {
  9515. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9516. }
  9517. gb_string_free(str);
  9518. o->mode = Addressing_Invalid;
  9519. o->expr = node;
  9520. return kind;
  9521. }
  9522. }
  9523. }
  9524. if (type_hint != nullptr && is_type_matrix(t)) {
  9525. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  9526. // if a type hint exists
  9527. }
  9528. return kind;
  9529. }
  9530. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9531. ExprKind kind = Expr_Stmt;
  9532. ast_node(se, SliceExpr, node);
  9533. check_expr(c, o, se->expr);
  9534. node->viral_state_flags |= se->expr->viral_state_flags;
  9535. if (o->mode == Addressing_Invalid) {
  9536. o->mode = Addressing_Invalid;
  9537. o->expr = node;
  9538. return kind;
  9539. }
  9540. bool valid = false;
  9541. i64 max_count = -1;
  9542. Type *t = base_type(type_deref(o->type));
  9543. switch (t->kind) {
  9544. case Type_Basic:
  9545. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  9546. valid = true;
  9547. if (o->mode == Addressing_Constant) {
  9548. max_count = o->value.value_string.len;
  9549. }
  9550. o->type = type_deref(o->type);
  9551. }
  9552. break;
  9553. case Type_Array:
  9554. valid = true;
  9555. max_count = t->Array.count;
  9556. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9557. gbString str = expr_to_string(node);
  9558. error(node, "Cannot slice array '%s', value is not addressable", str);
  9559. gb_string_free(str);
  9560. o->mode = Addressing_Invalid;
  9561. o->expr = node;
  9562. return kind;
  9563. }
  9564. o->type = alloc_type_slice(t->Array.elem);
  9565. break;
  9566. case Type_MultiPointer:
  9567. valid = true;
  9568. o->type = type_deref(o->type);
  9569. break;
  9570. case Type_Slice:
  9571. valid = true;
  9572. o->type = type_deref(o->type);
  9573. break;
  9574. case Type_DynamicArray:
  9575. valid = true;
  9576. o->type = alloc_type_slice(t->DynamicArray.elem);
  9577. break;
  9578. case Type_Struct:
  9579. if (is_type_soa_struct(t)) {
  9580. valid = true;
  9581. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9582. max_count = t->Struct.soa_count;
  9583. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9584. gbString str = expr_to_string(node);
  9585. error(node, "Cannot slice #soa array '%s', value is not addressable", str);
  9586. gb_string_free(str);
  9587. o->mode = Addressing_Invalid;
  9588. o->expr = node;
  9589. return kind;
  9590. }
  9591. }
  9592. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  9593. }
  9594. break;
  9595. case Type_EnumeratedArray:
  9596. {
  9597. gbString str = expr_to_string(o->expr);
  9598. gbString type_str = type_to_string(o->type);
  9599. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  9600. gb_string_free(type_str);
  9601. gb_string_free(str);
  9602. o->mode = Addressing_Invalid;
  9603. o->expr = node;
  9604. return kind;
  9605. }
  9606. break;
  9607. }
  9608. if (!valid) {
  9609. gbString str = expr_to_string(o->expr);
  9610. gbString type_str = type_to_string(o->type);
  9611. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  9612. gb_string_free(type_str);
  9613. gb_string_free(str);
  9614. o->mode = Addressing_Invalid;
  9615. o->expr = node;
  9616. return kind;
  9617. }
  9618. if (se->low == nullptr && se->high != nullptr) {
  9619. // It is okay to continue as it will assume the 1st index is zero
  9620. }
  9621. i64 indices[2] = {};
  9622. Ast *nodes[2] = {se->low, se->high};
  9623. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9624. i64 index = max_count;
  9625. if (nodes[i] != nullptr) {
  9626. i64 capacity = -1;
  9627. if (max_count >= 0) {
  9628. capacity = max_count;
  9629. }
  9630. i64 j = 0;
  9631. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  9632. index = j;
  9633. }
  9634. node->viral_state_flags |= nodes[i]->viral_state_flags;
  9635. } else if (i == 0) {
  9636. index = 0;
  9637. }
  9638. indices[i] = index;
  9639. }
  9640. for (isize i = 0; i < gb_count_of(indices); i++) {
  9641. i64 a = indices[i];
  9642. for (isize j = i+1; j < gb_count_of(indices); j++) {
  9643. i64 b = indices[j];
  9644. if (a > b && b >= 0) {
  9645. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  9646. }
  9647. }
  9648. }
  9649. if (max_count < 0) {
  9650. if (o->mode == Addressing_Constant) {
  9651. gbString s = expr_to_string(se->expr);
  9652. error(se->expr, "Cannot slice constant value '%s'", s);
  9653. gb_string_free(s);
  9654. }
  9655. }
  9656. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  9657. /*
  9658. x[:] -> [^]T
  9659. x[i:] -> [^]T
  9660. x[:n] -> []T
  9661. x[i:n] -> []T
  9662. */
  9663. o->type = alloc_type_slice(t->MultiPointer.elem);
  9664. }
  9665. o->mode = Addressing_Value;
  9666. if (is_type_string(t) && max_count >= 0) {
  9667. bool all_constant = true;
  9668. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9669. if (nodes[i] != nullptr) {
  9670. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  9671. if (tav.mode != Addressing_Constant) {
  9672. all_constant = false;
  9673. break;
  9674. }
  9675. }
  9676. }
  9677. if (!all_constant) {
  9678. ERROR_BLOCK();
  9679. gbString str = expr_to_string(o->expr);
  9680. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  9681. if (!build_context.terse_errors) {
  9682. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9683. }
  9684. gb_string_free(str);
  9685. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  9686. o->expr = node;
  9687. return kind;
  9688. }
  9689. String s = {};
  9690. if (o->value.kind == ExactValue_String) {
  9691. s = o->value.value_string;
  9692. }
  9693. o->mode = Addressing_Constant;
  9694. o->type = t;
  9695. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9696. }
  9697. return kind;
  9698. }
  9699. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9700. u32 prev_state_flags = c->state_flags;
  9701. defer (c->state_flags = prev_state_flags);
  9702. if (node->state_flags != 0) {
  9703. u32 in = node->state_flags;
  9704. u32 out = c->state_flags;
  9705. if (in & StateFlag_no_bounds_check) {
  9706. out |= StateFlag_no_bounds_check;
  9707. out &= ~StateFlag_bounds_check;
  9708. } else if (in & StateFlag_bounds_check) {
  9709. out |= StateFlag_bounds_check;
  9710. out &= ~StateFlag_no_bounds_check;
  9711. }
  9712. if (in & StateFlag_no_type_assert) {
  9713. out |= StateFlag_no_type_assert;
  9714. out &= ~StateFlag_type_assert;
  9715. } else if (in & StateFlag_type_assert) {
  9716. out |= StateFlag_type_assert;
  9717. out &= ~StateFlag_no_type_assert;
  9718. }
  9719. c->state_flags = out;
  9720. }
  9721. ExprKind kind = Expr_Stmt;
  9722. o->mode = Addressing_Invalid;
  9723. o->type = t_invalid;
  9724. o->value = {ExactValue_Invalid};
  9725. switch (node->kind) {
  9726. default:
  9727. return kind;
  9728. case_ast_node(be, BadExpr, node)
  9729. return kind;
  9730. case_end;
  9731. case_ast_node(i, Implicit, node);
  9732. switch (i->kind) {
  9733. case Token_context:
  9734. {
  9735. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  9736. error(node, "'context' is only allowed within procedures");
  9737. return kind;
  9738. }
  9739. if (unparen_expr(c->assignment_lhs_hint) == node) {
  9740. c->scope->flags |= ScopeFlag_ContextDefined;
  9741. }
  9742. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  9743. error(node, "'context' has not been defined within this scope");
  9744. // Continue with value
  9745. }
  9746. init_core_context(c->checker);
  9747. o->mode = Addressing_Context;
  9748. o->type = t_context;
  9749. }
  9750. break;
  9751. default:
  9752. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  9753. return kind;
  9754. }
  9755. case_end;
  9756. case_ast_node(i, Ident, node);
  9757. check_ident(c, o, node, nullptr, type_hint, false);
  9758. case_end;
  9759. case_ast_node(u, Uninit, node);
  9760. o->mode = Addressing_Value;
  9761. o->type = t_untyped_uninit;
  9762. error(node, "Global variables will always be zeroed if left unassigned, --- is disallowed");
  9763. case_end;
  9764. case_ast_node(bl, BasicLit, node);
  9765. Type *t = t_invalid;
  9766. switch (node->tav.value.kind) {
  9767. case ExactValue_String: t = t_untyped_string; break;
  9768. case ExactValue_Float: t = t_untyped_float; break;
  9769. case ExactValue_Complex: t = t_untyped_complex; break;
  9770. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  9771. case ExactValue_Integer:
  9772. t = t_untyped_integer;
  9773. if (bl->token.kind == Token_Rune) {
  9774. t = t_untyped_rune;
  9775. }
  9776. break;
  9777. default:
  9778. GB_PANIC("Unhandled value type for basic literal");
  9779. break;
  9780. }
  9781. o->mode = Addressing_Constant;
  9782. o->type = t;
  9783. o->value = node->tav.value;
  9784. case_end;
  9785. case_ast_node(bd, BasicDirective, node);
  9786. kind = check_basic_directive_expr(c, o, node, type_hint);
  9787. case_end;
  9788. case_ast_node(pg, ProcGroup, node);
  9789. error(node, "Illegal use of a procedure group");
  9790. o->mode = Addressing_Invalid;
  9791. case_end;
  9792. case_ast_node(pl, ProcLit, node);
  9793. CheckerContext ctx = *c;
  9794. DeclInfo *decl = nullptr;
  9795. Type *type = alloc_type(Type_Proc);
  9796. check_open_scope(&ctx, pl->type);
  9797. {
  9798. decl = make_decl_info(ctx.scope, ctx.decl);
  9799. decl->proc_lit = node;
  9800. ctx.decl = decl;
  9801. defer (ctx.decl = ctx.decl->parent);
  9802. if (pl->tags != 0) {
  9803. error(node, "A procedure literal cannot have tags");
  9804. pl->tags = 0; // TODO(bill): Should I zero this?!
  9805. }
  9806. check_procedure_type(&ctx, type, pl->type);
  9807. if (!is_type_proc(type)) {
  9808. gbString str = expr_to_string(node);
  9809. error(node, "Invalid procedure literal '%s'", str);
  9810. gb_string_free(str);
  9811. check_close_scope(&ctx);
  9812. return kind;
  9813. }
  9814. if (pl->body == nullptr) {
  9815. error(node, "A procedure literal must have a body");
  9816. return kind;
  9817. }
  9818. pl->decl = decl;
  9819. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  9820. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  9821. array_add(&ctx.checker->nested_proc_lits, decl);
  9822. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  9823. }
  9824. check_close_scope(&ctx);
  9825. o->mode = Addressing_Value;
  9826. o->type = type;
  9827. case_end;
  9828. case_ast_node(te, TernaryIfExpr, node);
  9829. kind = check_ternary_if_expr(c, o, node, type_hint);
  9830. case_end;
  9831. case_ast_node(te, TernaryWhenExpr, node);
  9832. kind = check_ternary_when_expr(c, o, node, type_hint);
  9833. case_end;
  9834. case_ast_node(oe, OrElseExpr, node);
  9835. return check_or_else_expr(c, o, node, type_hint);
  9836. case_end;
  9837. case_ast_node(re, OrReturnExpr, node);
  9838. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  9839. return check_or_return_expr(c, o, node, type_hint);
  9840. case_end;
  9841. case_ast_node(re, OrBranchExpr, node);
  9842. return check_or_branch_expr(c, o, node, type_hint);
  9843. case_end;
  9844. case_ast_node(cl, CompoundLit, node);
  9845. kind = check_compound_literal(c, o, node, type_hint);
  9846. case_end;
  9847. case_ast_node(pe, ParenExpr, node);
  9848. kind = check_expr_base(c, o, pe->expr, type_hint);
  9849. node->viral_state_flags |= pe->expr->viral_state_flags;
  9850. o->expr = node;
  9851. case_end;
  9852. case_ast_node(te, TagExpr, node);
  9853. String name = te->name.string;
  9854. error(node, "Unknown tag expression, #%.*s", LIT(name));
  9855. if (te->expr) {
  9856. kind = check_expr_base(c, o, te->expr, type_hint);
  9857. node->viral_state_flags |= te->expr->viral_state_flags;
  9858. }
  9859. o->expr = node;
  9860. case_end;
  9861. case_ast_node(ta, TypeAssertion, node);
  9862. kind = check_type_assertion(c, o, node, type_hint);
  9863. case_end;
  9864. case_ast_node(tc, TypeCast, node);
  9865. check_expr_or_type(c, o, tc->type);
  9866. if (o->mode != Addressing_Type) {
  9867. gbString str = expr_to_string(tc->type);
  9868. error(tc->type, "Expected a type, got %s", str);
  9869. gb_string_free(str);
  9870. o->mode = Addressing_Invalid;
  9871. }
  9872. if (o->mode == Addressing_Invalid) {
  9873. o->expr = node;
  9874. return kind;
  9875. }
  9876. Type *type = o->type;
  9877. check_expr_base(c, o, tc->expr, type);
  9878. node->viral_state_flags |= tc->expr->viral_state_flags;
  9879. if (o->mode != Addressing_Invalid) {
  9880. switch (tc->token.kind) {
  9881. case Token_transmute:
  9882. check_transmute(c, node, o, type, true);
  9883. break;
  9884. case Token_cast:
  9885. check_cast(c, o, type, true);
  9886. break;
  9887. default:
  9888. error(node, "Invalid AST: Invalid casting expression");
  9889. o->mode = Addressing_Invalid;
  9890. break;
  9891. }
  9892. }
  9893. return Expr_Expr;
  9894. case_end;
  9895. case_ast_node(ac, AutoCast, node);
  9896. check_expr_base(c, o, ac->expr, type_hint);
  9897. node->viral_state_flags |= ac->expr->viral_state_flags;
  9898. if (o->mode == Addressing_Invalid) {
  9899. o->expr = node;
  9900. return kind;
  9901. }
  9902. if (type_hint) {
  9903. check_cast(c, o, type_hint);
  9904. }
  9905. o->expr = node;
  9906. return Expr_Expr;
  9907. case_end;
  9908. case_ast_node(ue, UnaryExpr, node);
  9909. Type *th = type_hint;
  9910. if (ue->op.kind == Token_And) {
  9911. th = type_deref(th);
  9912. }
  9913. check_expr_base(c, o, ue->expr, th);
  9914. node->viral_state_flags |= ue->expr->viral_state_flags;
  9915. if (o->mode != Addressing_Invalid) {
  9916. check_unary_expr(c, o, ue->op, node);
  9917. }
  9918. o->expr = node;
  9919. return Expr_Expr;
  9920. case_end;
  9921. case_ast_node(be, BinaryExpr, node);
  9922. check_binary_expr(c, o, node, type_hint, true);
  9923. if (o->mode == Addressing_Invalid) {
  9924. o->expr = node;
  9925. return kind;
  9926. }
  9927. case_end;
  9928. case_ast_node(se, SelectorExpr, node);
  9929. check_selector(c, o, node, type_hint);
  9930. node->viral_state_flags |= se->expr->viral_state_flags;
  9931. case_end;
  9932. case_ast_node(se, SelectorCallExpr, node);
  9933. return check_selector_call_expr(c, o, node, type_hint);
  9934. case_end;
  9935. case_ast_node(ise, ImplicitSelectorExpr, node);
  9936. return check_implicit_selector_expr(c, o, node, type_hint);
  9937. case_end;
  9938. case_ast_node(ie, IndexExpr, node);
  9939. kind = check_index_expr(c, o, node, type_hint);
  9940. case_end;
  9941. case_ast_node(se, SliceExpr, node);
  9942. kind = check_slice_expr(c, o, node, type_hint);
  9943. case_end;
  9944. case_ast_node(mie, MatrixIndexExpr, node);
  9945. check_matrix_index_expr(c, o, node, type_hint);
  9946. o->expr = node;
  9947. return Expr_Expr;
  9948. case_end;
  9949. case_ast_node(ce, CallExpr, node);
  9950. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  9951. case_end;
  9952. case_ast_node(de, DerefExpr, node);
  9953. check_expr_or_type(c, o, de->expr);
  9954. node->viral_state_flags |= de->expr->viral_state_flags;
  9955. if (o->mode == Addressing_Invalid) {
  9956. o->mode = Addressing_Invalid;
  9957. o->expr = node;
  9958. return kind;
  9959. } else if (o->mode == Addressing_Type) {
  9960. gbString str = expr_to_string(o->expr);
  9961. error(o->expr, "Cannot dereference '%s' because it is a type", str);
  9962. o->mode = Addressing_Invalid;
  9963. o->expr = node;
  9964. return kind;
  9965. } else {
  9966. Type *t = base_type(o->type);
  9967. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  9968. o->mode = Addressing_Variable;
  9969. o->type = t->Pointer.elem;
  9970. } else if (t->kind == Type_SoaPointer) {
  9971. o->mode = Addressing_SoaVariable;
  9972. o->type = type_deref(t);
  9973. } else {
  9974. gbString str = expr_to_string(o->expr);
  9975. gbString typ = type_to_string(o->type);
  9976. ERROR_BLOCK();
  9977. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  9978. if (o->type && is_type_multi_pointer(o->type)) {
  9979. if (!build_context.terse_errors) {
  9980. error_line("\tDid you mean '%s[0]'?\n", str);
  9981. }
  9982. }
  9983. gb_string_free(typ);
  9984. gb_string_free(str);
  9985. o->mode = Addressing_Invalid;
  9986. o->expr = node;
  9987. return kind;
  9988. }
  9989. }
  9990. case_end;
  9991. case_ast_node(ia, InlineAsmExpr, node);
  9992. if (c->curr_proc_decl == nullptr) {
  9993. error(node, "Inline asm expressions are only allowed within a procedure body");
  9994. }
  9995. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  9996. Type *return_type = nullptr;
  9997. for_array(i, ia->param_types) {
  9998. param_types[i] = check_type(c, ia->param_types[i]);
  9999. }
  10000. if (ia->return_type != nullptr) {
  10001. return_type = check_type(c, ia->return_type);
  10002. }
  10003. Operand x = {};
  10004. check_expr(c, &x, ia->asm_string);
  10005. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  10006. error(x.expr, "Expected a constant string for the inline asm main parameter");
  10007. }
  10008. check_expr(c, &x, ia->constraints_string);
  10009. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  10010. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  10011. }
  10012. Scope *scope = create_scope(c->info, c->scope);
  10013. scope->flags |= ScopeFlag_Proc;
  10014. Type *params = alloc_type_tuple();
  10015. Type *results = alloc_type_tuple();
  10016. if (param_types.count != 0) {
  10017. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  10018. for_array(i, param_types) {
  10019. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  10020. }
  10021. }
  10022. if (return_type != nullptr) {
  10023. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  10024. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  10025. }
  10026. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  10027. o->type = pt;
  10028. o->mode = Addressing_Value;
  10029. o->expr = node;
  10030. return Expr_Expr;
  10031. case_end;
  10032. case Ast_DistinctType:
  10033. case Ast_TypeidType:
  10034. case Ast_PolyType:
  10035. case Ast_ProcType:
  10036. case Ast_PointerType:
  10037. case Ast_MultiPointerType:
  10038. case Ast_ArrayType:
  10039. case Ast_DynamicArrayType:
  10040. case Ast_StructType:
  10041. case Ast_UnionType:
  10042. case Ast_EnumType:
  10043. case Ast_MapType:
  10044. case Ast_BitSetType:
  10045. case Ast_MatrixType:
  10046. case Ast_RelativeType:
  10047. o->mode = Addressing_Type;
  10048. o->type = check_type(c, node);
  10049. break;
  10050. }
  10051. kind = Expr_Expr;
  10052. o->expr = node;
  10053. return kind;
  10054. }
  10055. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  10056. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  10057. if (o->type != nullptr && core_type(o->type) == nullptr) {
  10058. o->type = t_invalid;
  10059. gbString xs = expr_to_string(o->expr);
  10060. if (o->mode == Addressing_Type) {
  10061. error(o->expr, "Invalid type usage '%s'", xs);
  10062. } else {
  10063. error(o->expr, "Invalid expression '%s'", xs);
  10064. }
  10065. gb_string_free(xs);
  10066. }
  10067. if (o->type != nullptr && is_type_untyped(o->type)) {
  10068. add_untyped(c, node, o->mode, o->type, o->value);
  10069. }
  10070. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  10071. add_type_and_value(c, node, o->mode, o->type, o->value);
  10072. return kind;
  10073. }
  10074. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  10075. check_expr_base(c, o, e, nullptr);
  10076. switch (o->mode) {
  10077. default:
  10078. return; // NOTE(bill): Valid
  10079. case Addressing_NoValue:
  10080. error_operand_no_value(o);
  10081. break;
  10082. }
  10083. o->mode = Addressing_Invalid;
  10084. }
  10085. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  10086. check_expr_base(c, o, e, nullptr);
  10087. switch (o->mode) {
  10088. default:
  10089. return; // NOTE(bill): Valid
  10090. case Addressing_NoValue:
  10091. error_operand_no_value(o);
  10092. break;
  10093. case Addressing_Type:
  10094. error_operand_not_expression(o);
  10095. break;
  10096. }
  10097. o->mode = Addressing_Invalid;
  10098. }
  10099. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10100. check_expr_base(c, o, e, type_hint);
  10101. switch (o->mode) {
  10102. default:
  10103. return; // NOTE(bill): Valid
  10104. case Addressing_NoValue:
  10105. error_operand_no_value(o);
  10106. break;
  10107. case Addressing_Type:
  10108. error_operand_not_expression(o);
  10109. break;
  10110. }
  10111. o->mode = Addressing_Invalid;
  10112. }
  10113. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  10114. if (o->mode == Addressing_Value) {
  10115. // NOTE(bill): Tuples are not first class thus never named
  10116. if (o->type->kind == Type_Tuple) {
  10117. isize count = o->type->Tuple.variables.count;
  10118. error(o->expr,
  10119. "%td-valued expression found where single value expected", count);
  10120. o->mode = Addressing_Invalid;
  10121. GB_ASSERT(count != 1);
  10122. }
  10123. }
  10124. }
  10125. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  10126. check_multi_expr(c, o, e);
  10127. check_not_tuple(c, o);
  10128. }
  10129. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10130. check_expr_base(c, o, e, type_hint);
  10131. check_not_tuple(c, o);
  10132. error_operand_no_value(o);
  10133. }
  10134. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  10135. switch (v.kind) {
  10136. case ExactValue_Invalid:
  10137. return true;
  10138. case ExactValue_Bool:
  10139. return !v.value_bool;
  10140. case ExactValue_String:
  10141. return v.value_string.len == 0;
  10142. case ExactValue_Integer:
  10143. return big_int_is_zero(&v.value_integer);
  10144. case ExactValue_Float:
  10145. return v.value_float == 0.0;
  10146. case ExactValue_Complex:
  10147. if (v.value_complex) {
  10148. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  10149. }
  10150. return true;
  10151. case ExactValue_Quaternion:
  10152. if (v.value_quaternion) {
  10153. return v.value_quaternion->real == 0.0 &&
  10154. v.value_quaternion->imag == 0.0 &&
  10155. v.value_quaternion->jmag == 0.0 &&
  10156. v.value_quaternion->kmag == 0.0;
  10157. }
  10158. return true;
  10159. case ExactValue_Pointer:
  10160. return v.value_pointer == 0;
  10161. case ExactValue_Compound:
  10162. if (v.value_compound == nullptr) {
  10163. return true;
  10164. } else {
  10165. ast_node(cl, CompoundLit, v.value_compound);
  10166. if (cl->elems.count == 0) {
  10167. return true;
  10168. } else {
  10169. for (Ast *elem : cl->elems) {
  10170. if (elem->tav.mode != Addressing_Constant) {
  10171. return false;
  10172. }
  10173. if (!is_exact_value_zero(elem->tav.value)) {
  10174. return false;
  10175. }
  10176. }
  10177. return true;
  10178. }
  10179. }
  10180. case ExactValue_Procedure:
  10181. return v.value_procedure == nullptr;
  10182. case ExactValue_Typeid:
  10183. return v.value_typeid == nullptr;
  10184. }
  10185. return true;
  10186. }
  10187. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  10188. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  10189. for_array(i, params) {
  10190. if (i > 0) {
  10191. str = gb_string_appendc(str, ", ");
  10192. }
  10193. str = write_expr_to_string(str, params[i], false);
  10194. }
  10195. return str;
  10196. }
  10197. gb_internal gbString string_append_string(gbString str, String string) {
  10198. if (string.len > 0) {
  10199. return gb_string_append_length(str, &string[0], string.len);
  10200. }
  10201. return str;
  10202. }
  10203. gb_internal gbString string_append_token(gbString str, Token token) {
  10204. str = string_append_string(str, token.string);
  10205. return str;
  10206. }
  10207. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  10208. if (node == nullptr)
  10209. return str;
  10210. if (is_ast_stmt(node)) {
  10211. GB_ASSERT("stmt passed to write_expr_to_string");
  10212. }
  10213. switch (node->kind) {
  10214. default:
  10215. str = gb_string_appendc(str, "(BadExpr)");
  10216. break;
  10217. case_ast_node(i, Ident, node);
  10218. str = string_append_token(str, i->token);
  10219. case_end;
  10220. case_ast_node(i, Implicit, node);
  10221. str = string_append_token(str, *i);
  10222. case_end;
  10223. case_ast_node(bl, BasicLit, node);
  10224. str = string_append_token(str, bl->token);
  10225. case_end;
  10226. case_ast_node(bd, BasicDirective, node);
  10227. str = gb_string_append_rune(str, '#');
  10228. str = string_append_string(str, bd->name.string);
  10229. case_end;
  10230. case_ast_node(ud, Uninit, node);
  10231. str = gb_string_appendc(str, "---");
  10232. case_end;
  10233. case_ast_node(pg, ProcGroup, node);
  10234. str = gb_string_appendc(str, "proc{");
  10235. for_array(i, pg->args) {
  10236. if (i > 0) str = gb_string_appendc(str, ", ");
  10237. str = write_expr_to_string(str, pg->args[i], shorthand);
  10238. }
  10239. str = gb_string_append_rune(str, '}');
  10240. case_end;
  10241. case_ast_node(pl, ProcLit, node);
  10242. str = write_expr_to_string(str, pl->type, shorthand);
  10243. if (pl->body) {
  10244. str = gb_string_appendc(str, " {...}");
  10245. } else {
  10246. str = gb_string_appendc(str, " ---");
  10247. }
  10248. case_end;
  10249. case_ast_node(cl, CompoundLit, node);
  10250. str = write_expr_to_string(str, cl->type, shorthand);
  10251. str = gb_string_append_rune(str, '{');
  10252. if (shorthand) {
  10253. str = gb_string_appendc(str, "...");
  10254. } else {
  10255. for_array(i, cl->elems) {
  10256. if (i > 0) str = gb_string_appendc(str, ", ");
  10257. str = write_expr_to_string(str, cl->elems[i], shorthand);
  10258. }
  10259. }
  10260. str = gb_string_append_rune(str, '}');
  10261. case_end;
  10262. case_ast_node(te, TagExpr, node);
  10263. str = gb_string_append_rune(str, '#');
  10264. str = string_append_token(str, te->name);
  10265. str = write_expr_to_string(str, te->expr, shorthand);
  10266. case_end;
  10267. case_ast_node(ue, UnaryExpr, node);
  10268. str = string_append_token(str, ue->op);
  10269. str = write_expr_to_string(str, ue->expr, shorthand);
  10270. case_end;
  10271. case_ast_node(de, DerefExpr, node);
  10272. str = write_expr_to_string(str, de->expr, shorthand);
  10273. str = gb_string_append_rune(str, '^');
  10274. case_end;
  10275. case_ast_node(be, BinaryExpr, node);
  10276. str = write_expr_to_string(str, be->left, shorthand);
  10277. str = gb_string_append_rune(str, ' ');
  10278. str = string_append_token(str, be->op);
  10279. str = gb_string_append_rune(str, ' ');
  10280. str = write_expr_to_string(str, be->right, shorthand);
  10281. case_end;
  10282. case_ast_node(te, TernaryIfExpr, node);
  10283. TokenPos x = ast_token(te->x).pos;
  10284. TokenPos cond = ast_token(te->cond).pos;
  10285. if (x < cond) {
  10286. str = write_expr_to_string(str, te->x, shorthand);
  10287. str = gb_string_appendc(str, " if ");
  10288. str = write_expr_to_string(str, te->cond, shorthand);
  10289. str = gb_string_appendc(str, " else ");
  10290. str = write_expr_to_string(str, te->y, shorthand);
  10291. } else {
  10292. str = write_expr_to_string(str, te->cond, shorthand);
  10293. str = gb_string_appendc(str, " ? ");
  10294. str = write_expr_to_string(str, te->x, shorthand);
  10295. str = gb_string_appendc(str, " : ");
  10296. str = write_expr_to_string(str, te->y, shorthand);
  10297. }
  10298. case_end;
  10299. case_ast_node(te, TernaryWhenExpr, node);
  10300. str = write_expr_to_string(str, te->x, shorthand);
  10301. str = gb_string_appendc(str, " when ");
  10302. str = write_expr_to_string(str, te->cond, shorthand);
  10303. str = gb_string_appendc(str, " else ");
  10304. str = write_expr_to_string(str, te->y, shorthand);
  10305. case_end;
  10306. case_ast_node(oe, OrElseExpr, node);
  10307. str = write_expr_to_string(str, oe->x, shorthand);
  10308. str = gb_string_appendc(str, " or_else ");
  10309. str = write_expr_to_string(str, oe->y, shorthand);
  10310. case_end;
  10311. case_ast_node(oe, OrReturnExpr, node);
  10312. str = write_expr_to_string(str, oe->expr, shorthand);
  10313. str = gb_string_appendc(str, " or_return");
  10314. case_end;
  10315. case_ast_node(oe, OrBranchExpr, node);
  10316. str = write_expr_to_string(str, oe->expr, shorthand);
  10317. str = gb_string_append_rune(str, ' ');
  10318. str = string_append_token(str, oe->token);
  10319. if (oe->label) {
  10320. str = gb_string_append_rune(str, ' ');
  10321. str = write_expr_to_string(str, oe->label, shorthand);
  10322. }
  10323. case_end;
  10324. case_ast_node(pe, ParenExpr, node);
  10325. str = gb_string_append_rune(str, '(');
  10326. str = write_expr_to_string(str, pe->expr, shorthand);
  10327. str = gb_string_append_rune(str, ')');
  10328. case_end;
  10329. case_ast_node(se, SelectorExpr, node);
  10330. str = write_expr_to_string(str, se->expr, shorthand);
  10331. str = string_append_token(str, se->token);
  10332. str = write_expr_to_string(str, se->selector, shorthand);
  10333. case_end;
  10334. case_ast_node(se, ImplicitSelectorExpr, node);
  10335. str = gb_string_append_rune(str, '.');
  10336. str = write_expr_to_string(str, se->selector, shorthand);
  10337. case_end;
  10338. case_ast_node(se, SelectorCallExpr, node);
  10339. str = write_expr_to_string(str, se->expr, shorthand);
  10340. str = gb_string_appendc(str, "(");
  10341. ast_node(ce, CallExpr, se->call);
  10342. isize start = se->modified_call ? 1 : 0;
  10343. for (isize i = start; i < ce->args.count; i++) {
  10344. Ast *arg = ce->args[i];
  10345. if (i > start) {
  10346. str = gb_string_appendc(str, ", ");
  10347. }
  10348. str = write_expr_to_string(str, arg, shorthand);
  10349. }
  10350. str = gb_string_appendc(str, ")");
  10351. case_end;
  10352. case_ast_node(ta, TypeAssertion, node);
  10353. str = write_expr_to_string(str, ta->expr, shorthand);
  10354. if (ta->type != nullptr &&
  10355. ta->type->kind == Ast_UnaryExpr &&
  10356. ta->type->UnaryExpr.op.kind == Token_Question) {
  10357. str = gb_string_appendc(str, ".?");
  10358. } else {
  10359. str = gb_string_appendc(str, ".(");
  10360. str = write_expr_to_string(str, ta->type, shorthand);
  10361. str = gb_string_append_rune(str, ')');
  10362. }
  10363. case_end;
  10364. case_ast_node(tc, TypeCast, node);
  10365. str = string_append_token(str, tc->token);
  10366. str = gb_string_append_rune(str, '(');
  10367. str = write_expr_to_string(str, tc->type, shorthand);
  10368. str = gb_string_append_rune(str, ')');
  10369. str = write_expr_to_string(str, tc->expr, shorthand);
  10370. case_end;
  10371. case_ast_node(ac, AutoCast, node);
  10372. str = string_append_token(str, ac->token);
  10373. str = gb_string_append_rune(str, ' ');
  10374. str = write_expr_to_string(str, ac->expr, shorthand);
  10375. case_end;
  10376. case_ast_node(ie, IndexExpr, node);
  10377. str = write_expr_to_string(str, ie->expr, shorthand);
  10378. str = gb_string_append_rune(str, '[');
  10379. str = write_expr_to_string(str, ie->index, shorthand);
  10380. str = gb_string_append_rune(str, ']');
  10381. case_end;
  10382. case_ast_node(se, SliceExpr, node);
  10383. str = write_expr_to_string(str, se->expr, shorthand);
  10384. str = gb_string_append_rune(str, '[');
  10385. str = write_expr_to_string(str, se->low, shorthand);
  10386. str = string_append_token(str, se->interval);
  10387. str = write_expr_to_string(str, se->high, shorthand);
  10388. str = gb_string_append_rune(str, ']');
  10389. case_end;
  10390. case_ast_node(mie, MatrixIndexExpr, node);
  10391. str = write_expr_to_string(str, mie->expr, shorthand);
  10392. str = gb_string_append_rune(str, '[');
  10393. str = write_expr_to_string(str, mie->row_index, shorthand);
  10394. str = gb_string_appendc(str, ", ");
  10395. str = write_expr_to_string(str, mie->column_index, shorthand);
  10396. str = gb_string_append_rune(str, ']');
  10397. case_end;
  10398. case_ast_node(e, Ellipsis, node);
  10399. str = gb_string_appendc(str, "..");
  10400. str = write_expr_to_string(str, e->expr, shorthand);
  10401. case_end;
  10402. case_ast_node(fv, FieldValue, node);
  10403. str = write_expr_to_string(str, fv->field, shorthand);
  10404. str = gb_string_appendc(str, " = ");
  10405. str = write_expr_to_string(str, fv->value, shorthand);
  10406. case_end;
  10407. case_ast_node(fv, EnumFieldValue, node);
  10408. str = write_expr_to_string(str, fv->name, shorthand);
  10409. if (fv->value) {
  10410. str = gb_string_appendc(str, " = ");
  10411. str = write_expr_to_string(str, fv->value, shorthand);
  10412. }
  10413. case_end;
  10414. case_ast_node(ht, HelperType, node);
  10415. str = gb_string_appendc(str, "#type ");
  10416. str = write_expr_to_string(str, ht->type, shorthand);
  10417. case_end;
  10418. case_ast_node(ht, DistinctType, node);
  10419. str = gb_string_appendc(str, "distinct ");
  10420. str = write_expr_to_string(str, ht->type, shorthand);
  10421. case_end;
  10422. case_ast_node(pt, PolyType, node);
  10423. str = gb_string_append_rune(str, '$');
  10424. str = write_expr_to_string(str, pt->type, shorthand);
  10425. if (pt->specialization != nullptr) {
  10426. str = gb_string_append_rune(str, '/');
  10427. str = write_expr_to_string(str, pt->specialization, shorthand);
  10428. }
  10429. case_end;
  10430. case_ast_node(pt, PointerType, node);
  10431. if (pt->tag) {
  10432. str = write_expr_to_string(str, pt->tag, false);
  10433. }
  10434. str = gb_string_append_rune(str, '^');
  10435. str = write_expr_to_string(str, pt->type, shorthand);
  10436. case_end;
  10437. case_ast_node(pt, MultiPointerType, node);
  10438. str = gb_string_appendc(str, "[^]");
  10439. str = write_expr_to_string(str, pt->type, shorthand);
  10440. case_end;
  10441. case_ast_node(at, ArrayType, node);
  10442. if (at->tag) {
  10443. str = write_expr_to_string(str, at->tag, false);
  10444. }
  10445. str = gb_string_append_rune(str, '[');
  10446. if (at->count != nullptr &&
  10447. at->count->kind == Ast_UnaryExpr &&
  10448. at->count->UnaryExpr.op.kind == Token_Question) {
  10449. str = gb_string_appendc(str, "?");
  10450. } else {
  10451. str = write_expr_to_string(str, at->count, shorthand);
  10452. }
  10453. str = gb_string_append_rune(str, ']');
  10454. str = write_expr_to_string(str, at->elem, shorthand);
  10455. case_end;
  10456. case_ast_node(at, DynamicArrayType, node);
  10457. if (at->tag) {
  10458. str = write_expr_to_string(str, at->tag, false);
  10459. }
  10460. str = gb_string_appendc(str, "[dynamic]");
  10461. str = write_expr_to_string(str, at->elem, shorthand);
  10462. case_end;
  10463. case_ast_node(bs, BitSetType, node);
  10464. str = gb_string_appendc(str, "bit_set[");
  10465. str = write_expr_to_string(str, bs->elem, shorthand);
  10466. str = gb_string_appendc(str, "]");
  10467. case_end;
  10468. case_ast_node(mt, MapType, node);
  10469. str = gb_string_appendc(str, "map[");
  10470. str = write_expr_to_string(str, mt->key, shorthand);
  10471. str = gb_string_append_rune(str, ']');
  10472. str = write_expr_to_string(str, mt->value, shorthand);
  10473. case_end;
  10474. case_ast_node(mt, MatrixType, node);
  10475. str = gb_string_appendc(str, "matrix[");
  10476. str = write_expr_to_string(str, mt->row_count, shorthand);
  10477. str = gb_string_appendc(str, ", ");
  10478. str = write_expr_to_string(str, mt->column_count, shorthand);
  10479. str = gb_string_append_rune(str, ']');
  10480. str = write_expr_to_string(str, mt->elem, shorthand);
  10481. case_end;
  10482. case_ast_node(f, Field, node);
  10483. if (f->flags&FieldFlag_using) {
  10484. str = gb_string_appendc(str, "using ");
  10485. }
  10486. if (f->flags&FieldFlag_no_alias) {
  10487. str = gb_string_appendc(str, "#no_alias ");
  10488. }
  10489. if (f->flags&FieldFlag_c_vararg) {
  10490. str = gb_string_appendc(str, "#c_vararg ");
  10491. }
  10492. if (f->flags&FieldFlag_any_int) {
  10493. str = gb_string_appendc(str, "#any_int ");
  10494. }
  10495. if (f->flags&FieldFlag_no_broadcast) {
  10496. str = gb_string_appendc(str, "#no_broadcast ");
  10497. }
  10498. if (f->flags&FieldFlag_const) {
  10499. str = gb_string_appendc(str, "#const ");
  10500. }
  10501. if (f->flags&FieldFlag_subtype) {
  10502. str = gb_string_appendc(str, "#subtype ");
  10503. }
  10504. for_array(i, f->names) {
  10505. Ast *name = f->names[i];
  10506. if (i > 0) str = gb_string_appendc(str, ", ");
  10507. str = write_expr_to_string(str, name, shorthand);
  10508. }
  10509. if (f->names.count > 0) {
  10510. if (f->type == nullptr && f->default_value != nullptr) {
  10511. str = gb_string_append_rune(str, ' ');
  10512. }
  10513. str = gb_string_appendc(str, ":");
  10514. }
  10515. if (f->type != nullptr) {
  10516. str = gb_string_append_rune(str, ' ');
  10517. str = write_expr_to_string(str, f->type, shorthand);
  10518. }
  10519. if (f->default_value != nullptr) {
  10520. if (f->type != nullptr) {
  10521. str = gb_string_append_rune(str, ' ');
  10522. }
  10523. str = gb_string_appendc(str, "= ");
  10524. str = write_expr_to_string(str, f->default_value, shorthand);
  10525. }
  10526. case_end;
  10527. case_ast_node(f, FieldList, node);
  10528. bool has_name = false;
  10529. for_array(i, f->list) {
  10530. ast_node(field, Field, f->list[i]);
  10531. if (field->names.count > 1) {
  10532. has_name = true;
  10533. break;
  10534. }
  10535. if (field->names.count == 0) {
  10536. continue;
  10537. }
  10538. if (!is_blank_ident(field->names[0])) {
  10539. has_name = true;
  10540. break;
  10541. }
  10542. }
  10543. for_array(i, f->list) {
  10544. if (i > 0) str = gb_string_appendc(str, ", ");
  10545. if (has_name) {
  10546. str = write_expr_to_string(str, f->list[i], shorthand);
  10547. } else {
  10548. ast_node(field, Field, f->list[i]);
  10549. if (field->flags&FieldFlag_using) {
  10550. str = gb_string_appendc(str, "using ");
  10551. }
  10552. if (field->flags&FieldFlag_no_alias) {
  10553. str = gb_string_appendc(str, "#no_alias ");
  10554. }
  10555. if (field->flags&FieldFlag_c_vararg) {
  10556. str = gb_string_appendc(str, "#c_vararg ");
  10557. }
  10558. if (field->flags&FieldFlag_any_int) {
  10559. str = gb_string_appendc(str, "#any_int ");
  10560. }
  10561. if (field->flags&FieldFlag_no_broadcast) {
  10562. str = gb_string_appendc(str, "#no_broadcast ");
  10563. }
  10564. if (field->flags&FieldFlag_const) {
  10565. str = gb_string_appendc(str, "#const ");
  10566. }
  10567. if (field->flags&FieldFlag_subtype) {
  10568. str = gb_string_appendc(str, "#subtype ");
  10569. }
  10570. str = write_expr_to_string(str, field->type, shorthand);
  10571. }
  10572. }
  10573. case_end;
  10574. case_ast_node(ce, CallExpr, node);
  10575. switch (ce->inlining) {
  10576. case ProcInlining_inline:
  10577. str = gb_string_appendc(str, "#force_inline ");
  10578. break;
  10579. case ProcInlining_no_inline:
  10580. str = gb_string_appendc(str, "#force_no_inline ");
  10581. break;
  10582. }
  10583. str = write_expr_to_string(str, ce->proc, shorthand);
  10584. str = gb_string_appendc(str, "(");
  10585. isize idx0 = cast(isize)ce->was_selector;
  10586. for (isize i = idx0; i < ce->args.count; i++) {
  10587. Ast *arg = ce->args[i];
  10588. if (i > idx0) {
  10589. str = gb_string_appendc(str, ", ");
  10590. }
  10591. str = write_expr_to_string(str, arg, shorthand);
  10592. }
  10593. str = gb_string_appendc(str, ")");
  10594. case_end;
  10595. case_ast_node(tt, TypeidType, node);
  10596. str = gb_string_appendc(str, "typeid");
  10597. if (tt->specialization) {
  10598. str = gb_string_appendc(str, "/");
  10599. str = write_expr_to_string(str, tt->specialization, shorthand);
  10600. }
  10601. case_end;
  10602. case_ast_node(pt, ProcType, node);
  10603. str = gb_string_appendc(str, "proc(");
  10604. str = write_expr_to_string(str, pt->params, shorthand);
  10605. str = gb_string_appendc(str, ")");
  10606. if (pt->results != nullptr) {
  10607. str = gb_string_appendc(str, " -> ");
  10608. bool parens_needed = false;
  10609. if (pt->results && pt->results->kind == Ast_FieldList) {
  10610. for (Ast *field : pt->results->FieldList.list) {
  10611. ast_node(f, Field, field);
  10612. if (f->names.count != 0) {
  10613. parens_needed = true;
  10614. break;
  10615. }
  10616. }
  10617. }
  10618. if (parens_needed) {
  10619. str = gb_string_append_rune(str, '(');
  10620. }
  10621. str = write_expr_to_string(str, pt->results, shorthand);
  10622. if (parens_needed) {
  10623. str = gb_string_append_rune(str, ')');
  10624. }
  10625. }
  10626. case_end;
  10627. case_ast_node(st, StructType, node);
  10628. str = gb_string_appendc(str, "struct ");
  10629. if (st->polymorphic_params) {
  10630. str = gb_string_append_rune(str, '(');
  10631. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10632. str = gb_string_appendc(str, ") ");
  10633. }
  10634. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  10635. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  10636. if (st->align) {
  10637. str = gb_string_appendc(str, "#align ");
  10638. str = write_expr_to_string(str, st->align, shorthand);
  10639. str = gb_string_append_rune(str, ' ');
  10640. }
  10641. str = gb_string_append_rune(str, '{');
  10642. if (shorthand) {
  10643. str = gb_string_appendc(str, "...");
  10644. } else {
  10645. str = write_struct_fields_to_string(str, st->fields);
  10646. }
  10647. str = gb_string_append_rune(str, '}');
  10648. case_end;
  10649. case_ast_node(st, UnionType, node);
  10650. str = gb_string_appendc(str, "union ");
  10651. if (st->polymorphic_params) {
  10652. str = gb_string_append_rune(str, '(');
  10653. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10654. str = gb_string_appendc(str, ") ");
  10655. }
  10656. switch (st->kind) {
  10657. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  10658. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  10659. }
  10660. if (st->align) {
  10661. str = gb_string_appendc(str, "#align ");
  10662. str = write_expr_to_string(str, st->align, shorthand);
  10663. str = gb_string_append_rune(str, ' ');
  10664. }
  10665. str = gb_string_append_rune(str, '{');
  10666. if (shorthand) {
  10667. str = gb_string_appendc(str, "...");
  10668. } else {
  10669. str = write_struct_fields_to_string(str, st->variants);
  10670. }
  10671. str = gb_string_append_rune(str, '}');
  10672. case_end;
  10673. case_ast_node(et, EnumType, node);
  10674. str = gb_string_appendc(str, "enum ");
  10675. if (et->base_type != nullptr) {
  10676. str = write_expr_to_string(str, et->base_type, shorthand);
  10677. str = gb_string_append_rune(str, ' ');
  10678. }
  10679. str = gb_string_append_rune(str, '{');
  10680. if (shorthand) {
  10681. str = gb_string_appendc(str, "...");
  10682. } else {
  10683. for_array(i, et->fields) {
  10684. if (i > 0) {
  10685. str = gb_string_appendc(str, ", ");
  10686. }
  10687. str = write_expr_to_string(str, et->fields[i], shorthand);
  10688. }
  10689. }
  10690. str = gb_string_append_rune(str, '}');
  10691. case_end;
  10692. case_ast_node(rt, RelativeType, node);
  10693. str = write_expr_to_string(str, rt->tag, shorthand);
  10694. str = gb_string_appendc(str, "" );
  10695. str = write_expr_to_string(str, rt->type, shorthand);
  10696. case_end;
  10697. case_ast_node(f, BitFieldField, node);
  10698. str = write_expr_to_string(str, f->name, shorthand);
  10699. str = gb_string_appendc(str, ": ");
  10700. str = write_expr_to_string(str, f->type, shorthand);
  10701. str = gb_string_appendc(str, " | ");
  10702. str = write_expr_to_string(str, f->bit_size, shorthand);
  10703. case_end;
  10704. case_ast_node(bf, BitFieldType, node);
  10705. str = gb_string_appendc(str, "bit_field ");
  10706. if (!shorthand) {
  10707. str = write_expr_to_string(str, bf->backing_type, shorthand);
  10708. }
  10709. str = gb_string_appendc(str, " {");
  10710. if (shorthand) {
  10711. str = gb_string_appendc(str, "...");
  10712. } else {
  10713. for_array(i, bf->fields) {
  10714. if (i > 0) {
  10715. str = gb_string_appendc(str, ", ");
  10716. }
  10717. str = write_expr_to_string(str, bf->fields[i], false);
  10718. }
  10719. }
  10720. str = gb_string_appendc(str, "}");
  10721. case_end;
  10722. case_ast_node(ia, InlineAsmExpr, node);
  10723. str = gb_string_appendc(str, "asm(");
  10724. for_array(i, ia->param_types) {
  10725. if (i > 0) {
  10726. str = gb_string_appendc(str, ", ");
  10727. }
  10728. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  10729. }
  10730. str = gb_string_appendc(str, ")");
  10731. if (ia->return_type != nullptr) {
  10732. str = gb_string_appendc(str, " -> ");
  10733. str = write_expr_to_string(str, ia->return_type, shorthand);
  10734. }
  10735. if (ia->has_side_effects) {
  10736. str = gb_string_appendc(str, " #side_effects");
  10737. }
  10738. if (ia->is_align_stack) {
  10739. str = gb_string_appendc(str, " #stack_align");
  10740. }
  10741. if (ia->dialect) {
  10742. str = gb_string_appendc(str, " #");
  10743. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  10744. }
  10745. str = gb_string_appendc(str, " {");
  10746. if (shorthand) {
  10747. str = gb_string_appendc(str, "...");
  10748. } else {
  10749. str = write_expr_to_string(str, ia->asm_string, shorthand);
  10750. str = gb_string_appendc(str, ", ");
  10751. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  10752. }
  10753. str = gb_string_appendc(str, "}");
  10754. case_end;
  10755. }
  10756. return str;
  10757. }
  10758. gb_internal gbString expr_to_string(Ast *expression) {
  10759. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  10760. }
  10761. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  10762. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  10763. }
  10764. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  10765. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  10766. }