check_expr.cpp 329 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432
  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 Entity * find_polymorphic_record_entity (CheckerContext *c, Type *original_type, isize param_count, Array<Operand> const &ordered_operands, bool *failure);
  73. gb_internal void check_not_tuple (CheckerContext *c, Operand *operand);
  74. gb_internal void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
  75. gb_internal gbString expr_to_string (Ast *expression);
  76. gb_internal gbString expr_to_string (Ast *expression, gbAllocator allocator);
  77. gb_internal void update_untyped_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
  78. gb_internal bool check_is_terminating (Ast *node, String const &label);
  79. gb_internal bool check_has_break (Ast *stmt, String const &label, bool implicit);
  80. gb_internal void check_stmt (CheckerContext *c, Ast *node, u32 flags);
  81. gb_internal void check_stmt_list (CheckerContext *c, Slice<Ast *> const &stmts, u32 flags);
  82. gb_internal void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
  83. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
  84. gb_internal bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> const *operands = nullptr);
  85. gb_internal void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
  86. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  87. gb_internal void check_union_type (CheckerContext *c, Type *union_type, Ast *node, Array<Operand> *poly_operands,
  88. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  89. gb_internal Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  90. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0);
  91. gb_internal void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
  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. enum LoadDirectiveResult {
  104. LoadDirective_Success = 0,
  105. LoadDirective_Error = 1,
  106. LoadDirective_NotFound = 2,
  107. };
  108. gb_internal bool is_load_directive_call(Ast *call) {
  109. call = unparen_expr(call);
  110. if (call->kind != Ast_CallExpr) {
  111. return false;
  112. }
  113. ast_node(ce, CallExpr, call);
  114. if (ce->proc->kind != Ast_BasicDirective) {
  115. return false;
  116. }
  117. ast_node(bd, BasicDirective, ce->proc);
  118. String name = bd->name.string;
  119. return name == "load";
  120. }
  121. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  122. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  123. auto results = did_you_mean_results(d);
  124. if (results.count != 0) {
  125. error_line("\tSuggestion: Did you mean?\n");
  126. for (auto const &result : results) {
  127. String const &target = result.target;
  128. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  129. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  130. }
  131. }
  132. }
  133. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  134. if (e->kind != Entity_TypeName) {
  135. return;
  136. }
  137. if (e->TypeName.objc_metadata == nullptr) {
  138. return;
  139. }
  140. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  141. Type *t = base_type(e->type);
  142. GB_ASSERT(t->kind == Type_Struct);
  143. if (is_type) {
  144. for (auto const &entry : objc_metadata->type_entries) {
  145. string_set_add(set, entry.name);
  146. }
  147. } else {
  148. for (auto const &entry : objc_metadata->value_entries) {
  149. string_set_add(set, entry.name);
  150. }
  151. }
  152. for (Entity *f : t->Struct.fields) {
  153. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  154. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  155. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  156. }
  157. }
  158. }
  159. }
  160. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  161. if (build_context.terse_errors) { return; }
  162. ERROR_BLOCK();
  163. GB_ASSERT(e->kind == Entity_TypeName);
  164. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  165. auto *objc_metadata = e->TypeName.objc_metadata;
  166. MUTEX_GUARD(objc_metadata->mutex);
  167. StringSet set = {};
  168. defer (string_set_destroy(&set));
  169. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  170. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  171. defer (did_you_mean_destroy(&d));
  172. for (String const &target : set) {
  173. did_you_mean_append(&d, target);
  174. }
  175. check_did_you_mean_print(&d, prefix);
  176. }
  177. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  178. if (build_context.terse_errors) { return; }
  179. ERROR_BLOCK();
  180. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  181. defer (did_you_mean_destroy(&d));
  182. for (Entity *e : fields) {
  183. did_you_mean_append(&d, e->token.string);
  184. }
  185. check_did_you_mean_print(&d, prefix);
  186. }
  187. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  188. if (build_context.terse_errors) { return; }
  189. ERROR_BLOCK();
  190. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  191. defer (did_you_mean_destroy(&d));
  192. for (Entity *e : fields) {
  193. did_you_mean_append(&d, e->token.string);
  194. }
  195. check_did_you_mean_print(&d, prefix);
  196. }
  197. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  198. if (build_context.terse_errors) { return; }
  199. ERROR_BLOCK();
  200. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  201. defer (did_you_mean_destroy(&d));
  202. rw_mutex_shared_lock(&scope->mutex);
  203. for (auto const &entry : scope->elements) {
  204. Entity *e = entry.value;
  205. did_you_mean_append(&d, e->token.string);
  206. }
  207. rw_mutex_shared_unlock(&scope->mutex);
  208. check_did_you_mean_print(&d, prefix);
  209. }
  210. gb_internal Entity *entity_from_expr(Ast *expr) {
  211. expr = unparen_expr(expr);
  212. switch (expr->kind) {
  213. case Ast_Ident:
  214. return expr->Ident.entity;
  215. case Ast_SelectorExpr:
  216. return entity_from_expr(expr->SelectorExpr.selector);
  217. }
  218. return nullptr;
  219. }
  220. gb_internal void error_operand_not_expression(Operand *o) {
  221. if (o->mode == Addressing_Type) {
  222. gbString err = expr_to_string(o->expr);
  223. error(o->expr, "'%s' is not an expression but a type", err);
  224. gb_string_free(err);
  225. o->mode = Addressing_Invalid;
  226. }
  227. }
  228. gb_internal void error_operand_no_value(Operand *o) {
  229. if (o->mode == Addressing_NoValue) {
  230. gbString err = expr_to_string(o->expr);
  231. Ast *x = unparen_expr(o->expr);
  232. if (x->kind == Ast_CallExpr) {
  233. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  234. } else {
  235. error(o->expr, "'%s' used as a value", err);
  236. }
  237. gb_string_free(err);
  238. o->mode = Addressing_Invalid;
  239. }
  240. }
  241. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  242. if (build_context.dynamic_map_calls) {
  243. add_package_dependency(c, "runtime", "__dynamic_map_get");
  244. } else {
  245. add_package_dependency(c, "runtime", "map_desired_position");
  246. add_package_dependency(c, "runtime", "map_probe_distance");
  247. }
  248. }
  249. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  250. init_core_source_code_location(c->checker);
  251. if (t_map_set_proc == nullptr) {
  252. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  253. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  254. }
  255. if (build_context.dynamic_map_calls) {
  256. add_package_dependency(c, "runtime", "__dynamic_map_set");
  257. } else {
  258. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  259. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  260. }
  261. }
  262. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  263. init_core_source_code_location(c->checker);
  264. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  265. }
  266. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  267. Scope *s = c->scope;
  268. check_collect_entities(c, nodes);
  269. for (auto const &entry : s->elements) {
  270. Entity *e = entry.value;
  271. switch (e->kind) {
  272. case Entity_Constant:
  273. case Entity_TypeName:
  274. case Entity_Procedure:
  275. break;
  276. default:
  277. continue;
  278. }
  279. DeclInfo *d = decl_info_of_entity(e);
  280. if (d != nullptr) {
  281. check_entity_decl(c, e, d, nullptr);
  282. }
  283. }
  284. }
  285. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  286. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  287. ///////////////////////////////////////////////////////////////////////////////
  288. // //
  289. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  290. // //
  291. ///////////////////////////////////////////////////////////////////////////////
  292. CheckerInfo *info = old_c->info;
  293. if (base_entity == nullptr) {
  294. return false;
  295. }
  296. if (!is_type_proc(base_entity->type)) {
  297. return false;
  298. }
  299. if (base_entity->flags & EntityFlag_Disabled) {
  300. return false;
  301. }
  302. String name = base_entity->token.string;
  303. Type *src = base_type(base_entity->type);
  304. Type *dst = nullptr;
  305. if (type != nullptr) {
  306. dst = base_type(type);
  307. }
  308. if (param_operands == nullptr) {
  309. GB_ASSERT(dst != nullptr);
  310. }
  311. if (param_operands != nullptr) {
  312. GB_ASSERT(dst == nullptr);
  313. }
  314. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  315. return false;
  316. }
  317. if (dst != nullptr) {
  318. if (dst->Proc.is_polymorphic) {
  319. return false;
  320. }
  321. if (dst->Proc.param_count != src->Proc.param_count ||
  322. dst->Proc.result_count != src->Proc.result_count) {
  323. return false;
  324. }
  325. }
  326. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  327. if (old_decl == nullptr) {
  328. return false;
  329. }
  330. gbAllocator a = heap_allocator();
  331. Array<Operand> operands = {};
  332. if (param_operands) {
  333. operands = *param_operands;
  334. } else {
  335. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  336. for (isize i = 0; i < dst->Proc.param_count; i++) {
  337. Entity *param = dst->Proc.params->Tuple.variables[i];
  338. Operand o = {Addressing_Value};
  339. o.type = param->type;
  340. array_add(&operands, o);
  341. }
  342. }
  343. defer (if (param_operands == nullptr) {
  344. array_free(&operands);
  345. });
  346. CheckerContext nctx = *old_c;
  347. Scope *scope = create_scope(info, base_entity->scope);
  348. scope->flags |= ScopeFlag_Proc;
  349. nctx.scope = scope;
  350. nctx.allow_polymorphic_types = true;
  351. if (nctx.polymorphic_scope == nullptr) {
  352. nctx.polymorphic_scope = scope;
  353. }
  354. auto *pt = &src->Proc;
  355. // NOTE(bill): This is slightly memory leaking if the type already exists
  356. // Maybe it's better to check with the previous types first?
  357. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  358. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  359. if (!success) {
  360. return false;
  361. }
  362. GenProcsData *gen_procs = nullptr;
  363. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  364. GB_ASSERT(base_entity->kind == Entity_Procedure);
  365. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  366. gen_procs = base_entity->Procedure.gen_procs;
  367. if (gen_procs) {
  368. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  369. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  370. for (Entity *other : gen_procs->procs) {
  371. Type *pt = base_type(other->type);
  372. if (are_types_identical(pt, final_proc_type)) {
  373. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  374. if (poly_proc_data) {
  375. poly_proc_data->gen_entity = other;
  376. }
  377. return true;
  378. }
  379. }
  380. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  381. } else {
  382. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  383. gen_procs->procs.allocator = heap_allocator();
  384. base_entity->Procedure.gen_procs = gen_procs;
  385. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  386. }
  387. {
  388. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  389. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  390. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  391. nctx.no_polymorphic_errors = false;
  392. // NOTE(bill): Reset scope from the failed procedure type
  393. scope_reset(scope);
  394. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  395. Ast *cloned_proc_type_node = clone_ast(pt->node);
  396. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  397. if (!success) {
  398. return false;
  399. }
  400. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  401. for (Entity *other : gen_procs->procs) {
  402. Type *pt = base_type(other->type);
  403. if (are_types_identical(pt, final_proc_type)) {
  404. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  405. if (poly_proc_data) {
  406. poly_proc_data->gen_entity = other;
  407. }
  408. DeclInfo *decl = other->decl_info;
  409. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  410. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  411. proc_info->file = other->file;
  412. proc_info->token = other->token;
  413. proc_info->decl = decl;
  414. proc_info->type = other->type;
  415. proc_info->body = decl->proc_lit->ProcLit.body;
  416. proc_info->tags = other->Procedure.tags;;
  417. proc_info->generated_from_polymorphic = true;
  418. proc_info->poly_def_node = poly_def_node;
  419. check_procedure_later(nctx.checker, proc_info);
  420. }
  421. return true;
  422. }
  423. }
  424. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  425. }
  426. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  427. ast_node(pl, ProcLit, proc_lit);
  428. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  429. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  430. final_proc_type->Proc.is_poly_specialized = true;
  431. final_proc_type->Proc.is_polymorphic = true;
  432. final_proc_type->Proc.variadic = src->Proc.variadic;
  433. final_proc_type->Proc.require_results = src->Proc.require_results;
  434. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  435. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  436. final_proc_type->Proc.diverging = src->Proc.diverging;
  437. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  438. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  439. for (isize i = 0; i < operands.count; i++) {
  440. Operand o = operands[i];
  441. if (final_proc_type == o.type ||
  442. base_entity->type == o.type) {
  443. // NOTE(bill): Cycle
  444. final_proc_type->Proc.is_poly_specialized = false;
  445. break;
  446. }
  447. }
  448. u64 tags = base_entity->Procedure.tags;
  449. Ast *ident = clone_ast(base_entity->identifier);
  450. Token token = ident->Ident.token;
  451. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  452. d->gen_proc_type = final_proc_type;
  453. d->type_expr = pl->type;
  454. d->proc_lit = proc_lit;
  455. d->proc_checked_state = ProcCheckedState_Unchecked;
  456. d->defer_use_checked = false;
  457. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  458. entity->identifier = ident;
  459. add_entity_and_decl_info(&nctx, ident, entity, d);
  460. // NOTE(bill): Set the scope afterwards as this is not real overloading
  461. entity->scope = scope->parent;
  462. entity->file = base_entity->file;
  463. entity->pkg = base_entity->pkg;
  464. entity->flags = 0;
  465. d->entity = entity;
  466. AstFile *file = nullptr;
  467. {
  468. Scope *s = entity->scope;
  469. while (s != nullptr && s->file == nullptr) {
  470. file = s->file;
  471. s = s->parent;
  472. }
  473. }
  474. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  475. array_add(&gen_procs->procs, entity);
  476. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  477. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  478. proc_info->file = file;
  479. proc_info->token = token;
  480. proc_info->decl = d;
  481. proc_info->type = final_proc_type;
  482. proc_info->body = pl->body;
  483. proc_info->tags = tags;
  484. proc_info->generated_from_polymorphic = true;
  485. proc_info->poly_def_node = poly_def_node;
  486. if (poly_proc_data) {
  487. poly_proc_data->gen_entity = entity;
  488. poly_proc_data->proc_info = proc_info;
  489. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  490. }
  491. // NOTE(bill): Check the newly generated procedure body
  492. check_procedure_later(nctx.checker, proc_info);
  493. return true;
  494. }
  495. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  496. if (operand->expr == nullptr) return false;
  497. Entity *base_entity = entity_of_node(operand->expr);
  498. if (base_entity == nullptr) return false;
  499. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  500. }
  501. 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) {
  502. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  503. }
  504. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  505. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  506. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  507. #define MAXIMUM_TYPE_DISTANCE 10
  508. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type) {
  509. if (c == nullptr) {
  510. GB_ASSERT(operand->mode == Addressing_Value);
  511. GB_ASSERT(is_type_typed(operand->type));
  512. }
  513. if (operand->mode == Addressing_Invalid ||
  514. type == t_invalid) {
  515. return -1;
  516. }
  517. if (operand->mode == Addressing_Builtin) {
  518. return -1;
  519. }
  520. if (operand->mode == Addressing_Type) {
  521. if (is_type_typeid(type)) {
  522. if (is_type_polymorphic(operand->type)) {
  523. return -1;
  524. }
  525. add_type_info_type(c, operand->type);
  526. return 4;
  527. }
  528. return -1;
  529. }
  530. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  531. return -1;
  532. }
  533. Type *s = operand->type;
  534. if (are_types_identical(s, type)) {
  535. return 0;
  536. }
  537. Type *src = base_type(s);
  538. Type *dst = base_type(type);
  539. if (is_type_untyped_uninit(src)) {
  540. return 1;
  541. }
  542. if (is_type_untyped_nil(src)) {
  543. if (type_has_nil(dst)) {
  544. return 1;
  545. }
  546. return -1;
  547. }
  548. if (is_type_untyped(src)) {
  549. if (is_type_any(dst)) {
  550. // NOTE(bill): Anything can cast to 'Any'
  551. add_type_info_type(c, s);
  552. return MAXIMUM_TYPE_DISTANCE;
  553. }
  554. if (dst->kind == Type_Basic) {
  555. if (operand->mode == Addressing_Constant) {
  556. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  557. if (is_type_typed(dst) && src->kind == Type_Basic) {
  558. switch (src->Basic.kind) {
  559. case Basic_UntypedBool:
  560. if (is_type_boolean(dst)) {
  561. return 1;
  562. }
  563. break;
  564. case Basic_UntypedRune:
  565. if (is_type_integer(dst) || is_type_rune(dst)) {
  566. return 1;
  567. }
  568. break;
  569. case Basic_UntypedInteger:
  570. if (is_type_integer(dst) || is_type_rune(dst)) {
  571. return 1;
  572. }
  573. break;
  574. case Basic_UntypedString:
  575. if (is_type_string(dst)) {
  576. return 1;
  577. }
  578. break;
  579. case Basic_UntypedFloat:
  580. if (is_type_float(dst)) {
  581. return 1;
  582. }
  583. break;
  584. case Basic_UntypedComplex:
  585. if (is_type_complex(dst)) {
  586. return 1;
  587. }
  588. if (is_type_quaternion(dst)) {
  589. return 2;
  590. }
  591. break;
  592. case Basic_UntypedQuaternion:
  593. if (is_type_quaternion(dst)) {
  594. return 1;
  595. }
  596. break;
  597. }
  598. }
  599. return 2;
  600. }
  601. return -1;
  602. }
  603. if (src->kind == Type_Basic) {
  604. Type *d = base_array_type(dst);
  605. i64 score = -1;
  606. switch (src->Basic.kind) {
  607. case Basic_UntypedBool:
  608. if (is_type_boolean(d)) {
  609. score = 1;
  610. }
  611. break;
  612. case Basic_UntypedRune:
  613. if (is_type_integer(d) || is_type_rune(d)) {
  614. score = 1;
  615. }
  616. break;
  617. case Basic_UntypedInteger:
  618. if (is_type_integer(d) || is_type_rune(d)) {
  619. score = 1;
  620. }
  621. break;
  622. case Basic_UntypedString:
  623. if (is_type_string(d)) {
  624. score = 1;
  625. }
  626. break;
  627. case Basic_UntypedFloat:
  628. if (is_type_float(d)) {
  629. score = 1;
  630. }
  631. break;
  632. case Basic_UntypedComplex:
  633. if (is_type_complex(d)) {
  634. score = 1;
  635. }
  636. if (is_type_quaternion(d)) {
  637. score = 2;
  638. }
  639. break;
  640. case Basic_UntypedQuaternion:
  641. if (is_type_quaternion(d)) {
  642. score = 1;
  643. }
  644. break;
  645. }
  646. if (score > 0) {
  647. if (is_type_typed(d)) {
  648. score += 1;
  649. }
  650. if (d != dst) {
  651. score += 6;
  652. }
  653. }
  654. return score;
  655. }
  656. }
  657. }
  658. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  659. if (c->in_enum_type) {
  660. return 3;
  661. }
  662. }
  663. {
  664. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  665. if (subtype_level > 0) {
  666. return 4 + subtype_level;
  667. }
  668. }
  669. // rawptr <- ^T
  670. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  671. return 5;
  672. }
  673. // rawptr <- [^]T
  674. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  675. return 5;
  676. }
  677. // ^T <- [^]T
  678. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  679. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  680. return 4;
  681. }
  682. }
  683. // [^]T <- ^T
  684. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  685. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  686. return 4;
  687. }
  688. }
  689. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  690. bool modify_type = !c->no_polymorphic_errors;
  691. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  692. return 2;
  693. }
  694. }
  695. if (is_type_union(dst)) {
  696. for (Type *vt : dst->Union.variants) {
  697. if (are_types_identical(vt, s)) {
  698. return 1;
  699. }
  700. }
  701. if (dst->Union.variants.count == 1) {
  702. Type *vt = dst->Union.variants[0];
  703. i64 score = check_distance_between_types(c, operand, vt);
  704. if (score >= 0) {
  705. return score+2;
  706. }
  707. } else if (is_type_untyped(src)) {
  708. i64 prev_lowest_score = -1;
  709. i64 lowest_score = -1;
  710. for (Type *vt : dst->Union.variants) {
  711. i64 score = check_distance_between_types(c, operand, vt);
  712. if (score >= 0) {
  713. if (lowest_score < 0) {
  714. lowest_score = score;
  715. } else {
  716. if (prev_lowest_score < 0) {
  717. prev_lowest_score = lowest_score;
  718. } else {
  719. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  720. }
  721. lowest_score = gb_min(lowest_score, score);
  722. }
  723. }
  724. }
  725. if (lowest_score >= 0) {
  726. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  727. return lowest_score+2;
  728. }
  729. }
  730. }
  731. }
  732. if (is_type_relative_pointer(dst)) {
  733. i64 score = check_distance_between_types(c, operand, dst->RelativePointer.pointer_type);
  734. if (score >= 0) {
  735. return score+2;
  736. }
  737. }
  738. if (is_type_relative_multi_pointer(dst)) {
  739. i64 score = check_distance_between_types(c, operand, dst->RelativeMultiPointer.pointer_type);
  740. if (score >= 0) {
  741. return score+2;
  742. }
  743. }
  744. if (is_type_proc(dst)) {
  745. if (are_types_identical(src, dst)) {
  746. return 3;
  747. }
  748. PolyProcData poly_proc_data = {};
  749. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  750. Entity *e = poly_proc_data.gen_entity;
  751. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  752. add_entity_use(c, operand->expr, e);
  753. return 4;
  754. }
  755. }
  756. if (is_type_complex_or_quaternion(dst)) {
  757. Type *elem = base_complex_elem_type(dst);
  758. if (are_types_identical(elem, base_type(src))) {
  759. return 5;
  760. }
  761. }
  762. if (is_type_array(dst)) {
  763. Type *elem = base_array_type(dst);
  764. i64 distance = check_distance_between_types(c, operand, elem);
  765. if (distance >= 0) {
  766. return distance + 6;
  767. }
  768. }
  769. if (is_type_simd_vector(dst)) {
  770. Type *dst_elem = base_array_type(dst);
  771. i64 distance = check_distance_between_types(c, operand, dst_elem);
  772. if (distance >= 0) {
  773. return distance + 6;
  774. }
  775. }
  776. if (is_type_matrix(dst)) {
  777. if (are_types_identical(src, dst)) {
  778. return 5;
  779. }
  780. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  781. Type *dst_elem = base_array_type(dst);
  782. i64 distance = check_distance_between_types(c, operand, dst_elem);
  783. if (distance >= 0) {
  784. return distance + 7;
  785. }
  786. }
  787. }
  788. if (is_type_any(dst)) {
  789. if (!is_type_polymorphic(src)) {
  790. if (operand->mode == Addressing_Context && operand->type == t_context) {
  791. return -1;
  792. } else {
  793. // NOTE(bill): Anything can cast to 'Any'
  794. add_type_info_type(c, s);
  795. return MAXIMUM_TYPE_DISTANCE;
  796. }
  797. }
  798. }
  799. Ast *expr = unparen_expr(operand->expr);
  800. if (expr != nullptr) {
  801. if (expr->kind == Ast_AutoCast) {
  802. Operand x = *operand;
  803. x.expr = expr->AutoCast.expr;
  804. if (check_cast_internal(c, &x, type)) {
  805. return MAXIMUM_TYPE_DISTANCE;
  806. }
  807. }
  808. }
  809. return -1;
  810. }
  811. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  812. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  813. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  814. // TODO(bill): A decent score function
  815. i64 d = distance*distance; // x^2
  816. if (is_variadic && d >= 0) {
  817. d += distance + 1; // x^2 + x + 1
  818. }
  819. return gb_max(c - d, 0);
  820. }
  821. gb_internal bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_, bool is_variadic=false) {
  822. i64 score = 0;
  823. i64 distance = check_distance_between_types(c, operand, type);
  824. bool ok = distance >= 0;
  825. if (ok) {
  826. score = assign_score_function(distance, is_variadic);
  827. }
  828. if (score_) *score_ = score;
  829. return ok;
  830. }
  831. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type) {
  832. i64 score = 0;
  833. return check_is_assignable_to_with_score(c, operand, type, &score);
  834. }
  835. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  836. Operand x = {};
  837. x.type = src;
  838. x.mode = Addressing_Value;
  839. return check_is_assignable_to(nullptr, &x, dst);
  840. }
  841. gb_internal AstPackage *get_package_of_type(Type *type) {
  842. for (;;) {
  843. if (type == nullptr) {
  844. return nullptr;
  845. }
  846. switch (type->kind) {
  847. case Type_Basic:
  848. return builtin_pkg;
  849. case Type_Named:
  850. if (type->Named.type_name != nullptr) {
  851. return type->Named.type_name->pkg;
  852. }
  853. return nullptr;
  854. case Type_Pointer:
  855. type = type->Pointer.elem;
  856. continue;
  857. case Type_Array:
  858. type = type->Array.elem;
  859. continue;
  860. case Type_Slice:
  861. type = type->Slice.elem;
  862. continue;
  863. case Type_DynamicArray:
  864. type = type->DynamicArray.elem;
  865. continue;
  866. case Type_RelativePointer:
  867. type = type->RelativePointer.pointer_type;
  868. continue;
  869. case Type_RelativeMultiPointer:
  870. type = type->RelativeMultiPointer.pointer_type;
  871. continue;
  872. }
  873. return nullptr;
  874. }
  875. }
  876. // NOTE(bill): 'content_name' is for debugging and error messages
  877. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  878. check_not_tuple(c, operand);
  879. if (operand->mode == Addressing_Invalid) {
  880. return;
  881. }
  882. if (is_type_untyped(operand->type)) {
  883. Type *target_type = type;
  884. if (type == nullptr || is_type_any(type)) {
  885. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  886. error(operand->expr, "Use of --- in %.*s", LIT(context_name));
  887. operand->mode = Addressing_Invalid;
  888. return;
  889. }
  890. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  891. error(operand->expr, "Use of untyped nil in %.*s", LIT(context_name));
  892. operand->mode = Addressing_Invalid;
  893. return;
  894. }
  895. target_type = default_type(operand->type);
  896. if (type != nullptr && !is_type_any(type)) {
  897. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  898. }
  899. add_type_info_type(c, type);
  900. add_type_info_type(c, target_type);
  901. }
  902. convert_to_typed(c, operand, target_type);
  903. if (operand->mode == Addressing_Invalid) {
  904. return;
  905. }
  906. }
  907. if (type == nullptr) {
  908. return;
  909. }
  910. if (operand->mode == Addressing_ProcGroup) {
  911. bool good = false;
  912. if (type != nullptr && is_type_proc(type)) {
  913. Array<Entity *> procs = proc_group_entities(c, *operand);
  914. // NOTE(bill): These should be done
  915. for (Entity *e : procs) {
  916. Type *t = base_type(e->type);
  917. if (t == t_invalid) {
  918. continue;
  919. }
  920. Operand x = {};
  921. x.mode = Addressing_Value;
  922. x.type = t;
  923. if (check_is_assignable_to(c, &x, type)) {
  924. add_entity_use(c, operand->expr, e);
  925. good = true;
  926. break;
  927. }
  928. }
  929. }
  930. if (!good) {
  931. gbString expr_str = expr_to_string(operand->expr);
  932. gbString op_type_str = type_to_string(operand->type);
  933. gbString type_str = type_to_string(type);
  934. defer (gb_string_free(type_str));
  935. defer (gb_string_free(op_type_str));
  936. defer (gb_string_free(expr_str));
  937. // TODO(bill): is this a good enough error message?
  938. error(operand->expr,
  939. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s",
  940. expr_str,
  941. op_type_str,
  942. LIT(context_name));
  943. operand->mode = Addressing_Invalid;
  944. }
  945. convert_to_typed(c, operand, type);
  946. return;
  947. }
  948. if (check_is_assignable_to(c, operand, type)) {
  949. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  950. add_type_info_type(c, operand->type);
  951. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  952. }
  953. } else {
  954. gbString expr_str = expr_to_string(operand->expr);
  955. gbString op_type_str = type_to_string(operand->type);
  956. gbString type_str = type_to_string(type);
  957. defer (gb_string_free(type_str));
  958. defer (gb_string_free(op_type_str));
  959. defer (gb_string_free(expr_str));
  960. switch (operand->mode) {
  961. case Addressing_Builtin:
  962. error(operand->expr,
  963. "Cannot assign built-in procedure '%s' in %.*s",
  964. expr_str,
  965. LIT(context_name));
  966. break;
  967. case Addressing_Type:
  968. if (is_type_polymorphic(operand->type)) {
  969. error(operand->expr,
  970. "Cannot assign '%s' which is a polymorphic type in %.*s",
  971. op_type_str,
  972. LIT(context_name));
  973. } else {
  974. error(operand->expr,
  975. "Cannot assign '%s' which is a type in %.*s",
  976. op_type_str,
  977. LIT(context_name));
  978. }
  979. break;
  980. default:
  981. // TODO(bill): is this a good enough error message?
  982. {
  983. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  984. gbString type_extra = gb_string_make(heap_allocator(), "");
  985. defer (gb_string_free(op_type_extra));
  986. defer (gb_string_free(type_extra));
  987. isize on = gb_string_length(op_type_str);
  988. isize tn = gb_string_length(type_str);
  989. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  990. AstPackage *op_pkg = get_package_of_type(operand->type);
  991. AstPackage *type_pkg = get_package_of_type(type);
  992. if (op_pkg != nullptr) {
  993. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  994. }
  995. if (type_pkg != nullptr) {
  996. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  997. }
  998. }
  999. ERROR_BLOCK();
  1000. error(operand->expr,
  1001. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s",
  1002. expr_str,
  1003. op_type_str, op_type_extra,
  1004. type_str, type_extra,
  1005. LIT(context_name));
  1006. check_assignment_error_suggestion(c, operand, type);
  1007. }
  1008. break;
  1009. }
  1010. operand->mode = Addressing_Invalid;
  1011. return;
  1012. }
  1013. }
  1014. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1015. Type *gt = *gt_;
  1016. GB_ASSERT(gt->kind == Type_Generic);
  1017. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1018. GB_ASSERT(e != nullptr);
  1019. if (e->kind == Entity_TypeName) {
  1020. *gt_ = nullptr;
  1021. *dst_count = source_count;
  1022. e->kind = Entity_Constant;
  1023. e->Constant.value = exact_value_i64(source_count);
  1024. e->type = t_untyped_integer;
  1025. return true;
  1026. } else if (e->kind == Entity_Constant) {
  1027. *gt_ = nullptr;
  1028. if (e->Constant.value.kind != ExactValue_Integer) {
  1029. return false;
  1030. }
  1031. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1032. if (count != source_count) {
  1033. return false;
  1034. }
  1035. *dst_count = source_count;
  1036. return true;
  1037. }
  1038. return false;
  1039. }
  1040. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1041. Operand o = {Addressing_Value};
  1042. o.type = source;
  1043. switch (poly->kind) {
  1044. case Type_Basic:
  1045. if (compound) return are_types_identical(poly, source);
  1046. return check_is_assignable_to(c, &o, poly);
  1047. case Type_Named: {
  1048. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1049. return true;
  1050. }
  1051. if (compound || !is_type_generic(poly)) {
  1052. return are_types_identical(poly, source);
  1053. }
  1054. return check_is_assignable_to(c, &o, poly);
  1055. }
  1056. case Type_Generic: {
  1057. if (poly->Generic.specialized != nullptr) {
  1058. Type *s = poly->Generic.specialized;
  1059. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1060. return false;
  1061. }
  1062. }
  1063. if (modify_type) {
  1064. Type *ds = default_type(source);
  1065. gb_memmove(poly, ds, gb_size_of(Type));
  1066. }
  1067. return true;
  1068. }
  1069. case Type_Pointer:
  1070. if (source->kind == Type_Pointer) {
  1071. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1072. if (level > 0) {
  1073. return true;
  1074. }
  1075. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1076. } else if (source->kind == Type_MultiPointer) {
  1077. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1078. if (level > 0) {
  1079. return true;
  1080. }
  1081. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1082. }
  1083. return false;
  1084. case Type_MultiPointer:
  1085. if (source->kind == Type_MultiPointer) {
  1086. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1087. if (level > 0) {
  1088. return true;
  1089. }
  1090. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1091. } else if (source->kind == Type_Pointer) {
  1092. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1093. if (level > 0) {
  1094. return true;
  1095. }
  1096. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1097. }
  1098. return false;
  1099. case Type_Array:
  1100. if (source->kind == Type_Array) {
  1101. if (poly->Array.generic_count != nullptr) {
  1102. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1103. return false;
  1104. }
  1105. }
  1106. if (poly->Array.count == source->Array.count) {
  1107. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1108. }
  1109. } else if (source->kind == Type_EnumeratedArray) {
  1110. if (poly->Array.generic_count != nullptr) {
  1111. Type *gt = poly->Array.generic_count;
  1112. GB_ASSERT(gt->kind == Type_Generic);
  1113. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1114. GB_ASSERT(e != nullptr);
  1115. if (e->kind == Entity_TypeName) {
  1116. Type *index = source->EnumeratedArray.index;
  1117. Type *it = base_type(index);
  1118. if (it->kind != Type_Enum) {
  1119. return false;
  1120. }
  1121. poly->kind = Type_EnumeratedArray;
  1122. poly->cached_size = -1;
  1123. poly->cached_align = -1;
  1124. poly->flags.exchange(source->flags);
  1125. poly->failure = false;
  1126. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1127. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1128. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1129. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1130. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1131. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1132. e->kind = Entity_TypeName;
  1133. e->TypeName.is_type_alias = true;
  1134. e->type = index;
  1135. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1136. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1137. }
  1138. }
  1139. }
  1140. }
  1141. return false;
  1142. case Type_EnumeratedArray:
  1143. if (source->kind == Type_EnumeratedArray) {
  1144. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1145. return false;
  1146. }
  1147. if (poly->EnumeratedArray.op) {
  1148. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1149. return false;
  1150. }
  1151. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1152. return false;
  1153. }
  1154. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1155. return false;
  1156. }
  1157. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1158. }
  1159. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1160. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1161. return index || elem;
  1162. }
  1163. return false;
  1164. case Type_DynamicArray:
  1165. if (source->kind == Type_DynamicArray) {
  1166. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1167. }
  1168. return false;
  1169. case Type_Slice:
  1170. if (source->kind == Type_Slice) {
  1171. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1172. }
  1173. return false;
  1174. case Type_Enum:
  1175. return false;
  1176. case Type_BitSet:
  1177. if (source->kind == Type_BitSet) {
  1178. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1179. return false;
  1180. }
  1181. if (poly->BitSet.underlying == nullptr) {
  1182. if (modify_type) {
  1183. poly->BitSet.underlying = source->BitSet.underlying;
  1184. }
  1185. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1186. return false;
  1187. }
  1188. return true;
  1189. }
  1190. return false;
  1191. case Type_Union:
  1192. if (source->kind == Type_Union) {
  1193. TypeUnion *x = &poly->Union;
  1194. TypeUnion *y = &source->Union;
  1195. if (x->variants.count != y->variants.count) {
  1196. return false;
  1197. }
  1198. for_array(i, x->variants) {
  1199. Type *a = x->variants[i];
  1200. Type *b = y->variants[i];
  1201. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1202. if (!ok) return false;
  1203. }
  1204. return true;
  1205. }
  1206. return false;
  1207. case Type_Struct:
  1208. if (source->kind == Type_Struct) {
  1209. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1210. poly->Struct.soa_kind != StructSoa_None) {
  1211. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1212. if (ok) switch (source->Struct.soa_kind) {
  1213. case StructSoa_Fixed:
  1214. default:
  1215. GB_PANIC("Unhandled SOA Kind");
  1216. break;
  1217. case StructSoa_Slice:
  1218. if (modify_type) {
  1219. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1220. gb_memmove(poly, type, gb_size_of(*type));
  1221. }
  1222. break;
  1223. case StructSoa_Dynamic:
  1224. if (modify_type) {
  1225. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1226. gb_memmove(poly, type, gb_size_of(*type));
  1227. }
  1228. break;
  1229. }
  1230. return ok;
  1231. }
  1232. // NOTE(bill): Check for subtypes of
  1233. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1234. }
  1235. return false;
  1236. case Type_Tuple:
  1237. GB_PANIC("This should never happen");
  1238. return false;
  1239. case Type_Proc:
  1240. if (source->kind == Type_Proc) {
  1241. TypeProc *x = &poly->Proc;
  1242. TypeProc *y = &source->Proc;
  1243. if (x->calling_convention != y->calling_convention) {
  1244. return false;
  1245. }
  1246. if (x->c_vararg != y->c_vararg) {
  1247. return false;
  1248. }
  1249. if (x->variadic != y->variadic) {
  1250. return false;
  1251. }
  1252. if (x->param_count != y->param_count) {
  1253. return false;
  1254. }
  1255. if (x->result_count != y->result_count) {
  1256. return false;
  1257. }
  1258. for (isize i = 0; i < x->param_count; i++) {
  1259. Entity *a = x->params->Tuple.variables[i];
  1260. Entity *b = y->params->Tuple.variables[i];
  1261. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1262. if (!ok) return false;
  1263. }
  1264. for (isize i = 0; i < x->result_count; i++) {
  1265. Entity *a = x->results->Tuple.variables[i];
  1266. Entity *b = y->results->Tuple.variables[i];
  1267. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1268. if (!ok) return false;
  1269. }
  1270. return true;
  1271. }
  1272. return false;
  1273. case Type_Map:
  1274. if (source->kind == Type_Map) {
  1275. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1276. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1277. if (key || value) {
  1278. poly->Map.lookup_result_type = nullptr;
  1279. init_map_internal_types(poly);
  1280. return true;
  1281. }
  1282. }
  1283. return false;
  1284. case Type_Matrix:
  1285. if (source->kind == Type_Matrix) {
  1286. if (poly->Matrix.generic_row_count != nullptr) {
  1287. poly->Matrix.stride_in_bytes = 0;
  1288. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1289. return false;
  1290. }
  1291. }
  1292. if (poly->Matrix.generic_column_count != nullptr) {
  1293. poly->Matrix.stride_in_bytes = 0;
  1294. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1295. return false;
  1296. }
  1297. }
  1298. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1299. poly->Matrix.column_count == source->Matrix.column_count) {
  1300. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1301. }
  1302. }
  1303. return false;
  1304. case Type_SimdVector:
  1305. if (source->kind == Type_SimdVector) {
  1306. if (poly->SimdVector.generic_count != nullptr) {
  1307. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1308. return false;
  1309. }
  1310. }
  1311. if (poly->SimdVector.count == source->SimdVector.count) {
  1312. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1313. }
  1314. }
  1315. return false;
  1316. }
  1317. return false;
  1318. }
  1319. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1320. if (curr->state != EntityState_InProgress) {
  1321. return false;
  1322. }
  1323. for_array(i, *c->type_path) {
  1324. Entity *prev = c->type_path->data[i];
  1325. if (prev == curr) {
  1326. if (report) {
  1327. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1328. for (isize j = i; j < c->type_path->count; j++) {
  1329. Entity *curr = (*c->type_path)[j];
  1330. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1331. }
  1332. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1333. curr->type = t_invalid;
  1334. }
  1335. return true;
  1336. }
  1337. }
  1338. return false;
  1339. }
  1340. struct CIdentSuggestion {
  1341. String name;
  1342. String msg;
  1343. };
  1344. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1345. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1346. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1347. {str_lit("sizeof"), str_lit("'size_of'?")},
  1348. {str_lit("alignof"), str_lit("'align_of'?")},
  1349. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1350. {str_lit("_Bool"), str_lit("'bool'?")},
  1351. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1352. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1353. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1354. {str_lit("float"), str_lit("'f32'?")},
  1355. {str_lit("double"), str_lit("'f64'?")},
  1356. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1357. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1358. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1359. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1360. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1361. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1362. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1363. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1364. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1365. {str_lit("uint8_t"), str_lit("'u8'?")},
  1366. {str_lit("int8_t"), str_lit("'i8'?")},
  1367. {str_lit("uint16_t"), str_lit("'u16'?")},
  1368. {str_lit("int16_t"), str_lit("'i16'?")},
  1369. {str_lit("uint32_t"), str_lit("'u32'?")},
  1370. {str_lit("int32_t"), str_lit("'i32'?")},
  1371. {str_lit("uint64_t"), str_lit("'u64'?")},
  1372. {str_lit("int64_t"), str_lit("'i64'?")},
  1373. {str_lit("uint128_t"), str_lit("'u128'?")},
  1374. {str_lit("int128_t"), str_lit("'i128'?")},
  1375. {str_lit("float32"), str_lit("'f32'?")},
  1376. {str_lit("float64"), str_lit("'f64'?")},
  1377. {str_lit("float32_t"), str_lit("'f32'?")},
  1378. {str_lit("float64_t"), str_lit("'f64'?")},
  1379. };
  1380. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1381. GB_ASSERT(n->kind == Ast_Ident);
  1382. o->mode = Addressing_Invalid;
  1383. o->expr = n;
  1384. String name = n->Ident.token.string;
  1385. Entity *e = scope_lookup(c->scope, name);
  1386. if (e == nullptr) {
  1387. if (is_blank_ident(name)) {
  1388. error(n, "'_' cannot be used as a value");
  1389. } else {
  1390. ERROR_BLOCK();
  1391. error(n, "Undeclared name: %.*s", LIT(name));
  1392. // NOTE(bill): Loads of checks for C programmers
  1393. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1394. if (name == suggestion.name) {
  1395. error_line("\tSuggestion: Did you mean %s\n", LIT(suggestion.msg));
  1396. }
  1397. }
  1398. }
  1399. o->type = t_invalid;
  1400. o->mode = Addressing_Invalid;
  1401. if (named_type != nullptr) {
  1402. set_base_type(named_type, t_invalid);
  1403. }
  1404. return nullptr;
  1405. }
  1406. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1407. if (e->parent_proc_decl != nullptr &&
  1408. e->parent_proc_decl != c->curr_proc_decl) {
  1409. if (e->kind == Entity_Variable) {
  1410. if ((e->flags & EntityFlag_Static) == 0) {
  1411. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1412. return nullptr;
  1413. }
  1414. } else if (e->kind == Entity_Label) {
  1415. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1416. return nullptr;
  1417. }
  1418. }
  1419. if (e->kind == Entity_ProcGroup) {
  1420. auto *pge = &e->ProcGroup;
  1421. DeclInfo *d = decl_info_of_entity(e);
  1422. check_entity_decl(c, e, d, nullptr);
  1423. Array<Entity *> procs = pge->entities;
  1424. bool skip = false;
  1425. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1426. // NOTE(bill): These should be done
  1427. for (Entity *proc : procs) {
  1428. Type *t = base_type(proc->type);
  1429. if (t == t_invalid) {
  1430. continue;
  1431. }
  1432. Operand x = {};
  1433. x.mode = Addressing_Value;
  1434. x.type = t;
  1435. if (check_is_assignable_to(c, &x, type_hint)) {
  1436. e = proc;
  1437. add_entity_use(c, n, e);
  1438. skip = true;
  1439. break;
  1440. }
  1441. }
  1442. }
  1443. if (!skip) {
  1444. o->mode = Addressing_ProcGroup;
  1445. o->type = t_invalid;
  1446. o->proc_group = e;
  1447. return nullptr;
  1448. }
  1449. }
  1450. add_entity_use(c, n, e);
  1451. if (e->state == EntityState_Unresolved) {
  1452. check_entity_decl(c, e, nullptr, named_type);
  1453. }
  1454. if (e->type == nullptr) {
  1455. // TODO(bill): Which is correct? return or compiler_error?
  1456. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1457. return nullptr;
  1458. }
  1459. e->flags |= EntityFlag_Used;
  1460. Type *type = e->type;
  1461. o->type = type;
  1462. switch (e->kind) {
  1463. case Entity_Constant:
  1464. if (type == t_invalid) {
  1465. o->type = t_invalid;
  1466. return e;
  1467. }
  1468. o->value = e->Constant.value;
  1469. if (o->value.kind == ExactValue_Invalid) {
  1470. return e;
  1471. }
  1472. if (o->value.kind == ExactValue_Procedure) {
  1473. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1474. if (proc != nullptr) {
  1475. o->mode = Addressing_Value;
  1476. o->type = proc->type;
  1477. return proc;
  1478. }
  1479. }
  1480. o->mode = Addressing_Constant;
  1481. break;
  1482. case Entity_Variable:
  1483. e->flags |= EntityFlag_Used;
  1484. if (type == t_invalid) {
  1485. o->type = t_invalid;
  1486. return e;
  1487. }
  1488. o->mode = Addressing_Variable;
  1489. if (e->flags & EntityFlag_Value) {
  1490. o->mode = Addressing_Value;
  1491. }
  1492. break;
  1493. case Entity_Procedure:
  1494. o->mode = Addressing_Value;
  1495. o->value = exact_value_procedure(n);
  1496. break;
  1497. case Entity_Builtin:
  1498. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1499. o->mode = Addressing_Builtin;
  1500. break;
  1501. case Entity_TypeName:
  1502. o->mode = Addressing_Type;
  1503. if (check_cycle(c, e, true)) {
  1504. o->type = t_invalid;
  1505. }
  1506. if (o->type != nullptr && type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1507. o->type = base_type(o->type);
  1508. }
  1509. break;
  1510. case Entity_ImportName:
  1511. if (!allow_import_name) {
  1512. error(n, "Use of import '%.*s' not in selector", LIT(name));
  1513. }
  1514. return e;
  1515. case Entity_LibraryName:
  1516. if (!allow_import_name) {
  1517. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1518. }
  1519. return e;
  1520. case Entity_Label:
  1521. o->mode = Addressing_NoValue;
  1522. break;
  1523. case Entity_Nil:
  1524. o->mode = Addressing_Value;
  1525. break;
  1526. default:
  1527. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1528. break;
  1529. }
  1530. return e;
  1531. }
  1532. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1533. if (o->type == nullptr) {
  1534. gbString str = expr_to_string(o->expr);
  1535. error(o->expr, "Expression has no value '%s'", str);
  1536. gb_string_free(str);
  1537. return false;
  1538. }
  1539. Type *type = base_type(core_array_type(o->type));
  1540. gbString str = nullptr;
  1541. switch (op.kind) {
  1542. case Token_Add:
  1543. case Token_Sub:
  1544. if (!is_type_numeric(type)) {
  1545. str = expr_to_string(o->expr);
  1546. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1547. gb_string_free(str);
  1548. }
  1549. break;
  1550. case Token_Xor:
  1551. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1552. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1553. }
  1554. break;
  1555. case Token_Not:
  1556. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1557. ERROR_BLOCK();
  1558. str = expr_to_string(o->expr);
  1559. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1560. gb_string_free(str);
  1561. if (is_type_integer(type)) {
  1562. error_line("\tSuggestion: Did you mean to use the bitwise not operator '~'?\n");
  1563. }
  1564. } else {
  1565. o->type = t_untyped_bool;
  1566. }
  1567. break;
  1568. default:
  1569. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1570. return false;
  1571. }
  1572. return true;
  1573. }
  1574. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1575. Type *main_type = o->type;
  1576. Type *type = base_type(core_array_type(main_type));
  1577. Type *ct = core_type(type);
  1578. switch (op.kind) {
  1579. case Token_Sub:
  1580. case Token_SubEq:
  1581. if (is_type_bit_set(type)) {
  1582. return true;
  1583. } else if (!is_type_numeric(type)) {
  1584. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1585. return false;
  1586. }
  1587. break;
  1588. case Token_Quo:
  1589. case Token_QuoEq:
  1590. if (is_type_matrix(main_type)) {
  1591. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1592. return false;
  1593. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1594. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1595. return false;
  1596. }
  1597. /*fallthrough*/
  1598. case Token_Mul:
  1599. case Token_MulEq:
  1600. case Token_AddEq:
  1601. if (is_type_bit_set(type)) {
  1602. return true;
  1603. } else if (!is_type_numeric(type)) {
  1604. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1605. return false;
  1606. }
  1607. break;
  1608. case Token_Add:
  1609. if (is_type_string(type)) {
  1610. if (o->mode == Addressing_Constant) {
  1611. return true;
  1612. }
  1613. error(op, "String concatenation is only allowed with constant strings");
  1614. return false;
  1615. } else if (is_type_bit_set(type)) {
  1616. return true;
  1617. } else if (!is_type_numeric(type)) {
  1618. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1619. return false;
  1620. }
  1621. break;
  1622. case Token_And:
  1623. case Token_Or:
  1624. case Token_AndEq:
  1625. case Token_OrEq:
  1626. case Token_Xor:
  1627. case Token_XorEq:
  1628. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1629. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1630. return false;
  1631. }
  1632. break;
  1633. case Token_Mod:
  1634. case Token_ModMod:
  1635. case Token_ModEq:
  1636. case Token_ModModEq:
  1637. if (is_type_matrix(main_type)) {
  1638. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1639. return false;
  1640. }
  1641. if (!is_type_integer(type)) {
  1642. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1643. return false;
  1644. } else if (is_type_simd_vector(main_type)) {
  1645. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1646. return false;
  1647. }
  1648. break;
  1649. case Token_AndNot:
  1650. case Token_AndNotEq:
  1651. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1652. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1653. return false;
  1654. }
  1655. break;
  1656. case Token_CmpAnd:
  1657. case Token_CmpOr:
  1658. case Token_CmpAndEq:
  1659. case Token_CmpOrEq:
  1660. if (!is_type_boolean(type)) {
  1661. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1662. return false;
  1663. }
  1664. break;
  1665. default:
  1666. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1667. return false;
  1668. }
  1669. return true;
  1670. }
  1671. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1672. if (in_value.kind == ExactValue_Invalid) {
  1673. // NOTE(bill): There's already been an error
  1674. return true;
  1675. }
  1676. type = core_type(type);
  1677. if (type == t_invalid) {
  1678. return false;
  1679. } else if (is_type_boolean(type)) {
  1680. return in_value.kind == ExactValue_Bool;
  1681. } else if (is_type_string(type)) {
  1682. return in_value.kind == ExactValue_String;
  1683. } else if (is_type_integer(type) || is_type_rune(type)) {
  1684. if (in_value.kind == ExactValue_Bool) {
  1685. return false;
  1686. }
  1687. ExactValue v = exact_value_to_integer(in_value);
  1688. if (v.kind != ExactValue_Integer) {
  1689. return false;
  1690. }
  1691. if (out_value) *out_value = v;
  1692. if (is_type_untyped(type)) {
  1693. return true;
  1694. }
  1695. BigInt i = v.value_integer;
  1696. i64 byte_size = type_size_of(type);
  1697. BigInt umax = {};
  1698. BigInt imin = {};
  1699. BigInt imax = {};
  1700. if (c->bit_field_bit_size > 0) {
  1701. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1702. big_int_from_u64(&umax, 1);
  1703. big_int_from_i64(&imin, 1);
  1704. big_int_from_i64(&imax, 1);
  1705. BigInt bu = {};
  1706. BigInt bi = {};
  1707. big_int_from_i64(&bu, bit_size);
  1708. big_int_from_i64(&bi, bit_size-1);
  1709. big_int_shl_eq(&umax, &bu);
  1710. mp_decr(&umax);
  1711. big_int_shl_eq(&imin, &bi);
  1712. big_int_neg(&imin, &imin);
  1713. big_int_shl_eq(&imax, &bi);
  1714. mp_decr(&imax);
  1715. } else {
  1716. if (byte_size < 16) {
  1717. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1718. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1719. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1720. } else {
  1721. big_int_from_u64(&umax, 1);
  1722. big_int_from_i64(&imin, 1);
  1723. big_int_from_i64(&imax, 1);
  1724. BigInt bi128 = {};
  1725. BigInt bi127 = {};
  1726. big_int_from_i64(&bi128, 128);
  1727. big_int_from_i64(&bi127, 127);
  1728. big_int_shl_eq(&umax, &bi128);
  1729. mp_decr(&umax);
  1730. big_int_shl_eq(&imin, &bi127);
  1731. big_int_neg(&imin, &imin);
  1732. big_int_shl_eq(&imax, &bi127);
  1733. mp_decr(&imax);
  1734. }
  1735. }
  1736. switch (type->Basic.kind) {
  1737. case Basic_rune:
  1738. case Basic_i8:
  1739. case Basic_i16:
  1740. case Basic_i32:
  1741. case Basic_i64:
  1742. case Basic_i128:
  1743. case Basic_int:
  1744. case Basic_i16le:
  1745. case Basic_i32le:
  1746. case Basic_i64le:
  1747. case Basic_i128le:
  1748. case Basic_i16be:
  1749. case Basic_i32be:
  1750. case Basic_i64be:
  1751. case Basic_i128be:
  1752. {
  1753. // return imin <= i && i <= imax;
  1754. int a = big_int_cmp(&imin, &i);
  1755. int b = big_int_cmp(&i, &imax);
  1756. return (a <= 0) && (b <= 0);
  1757. }
  1758. case Basic_u8:
  1759. case Basic_u16:
  1760. case Basic_u32:
  1761. case Basic_u64:
  1762. case Basic_u128:
  1763. case Basic_uint:
  1764. case Basic_uintptr:
  1765. case Basic_u16le:
  1766. case Basic_u32le:
  1767. case Basic_u64le:
  1768. case Basic_u128le:
  1769. case Basic_u16be:
  1770. case Basic_u32be:
  1771. case Basic_u64be:
  1772. case Basic_u128be:
  1773. {
  1774. // return 0ull <= i && i <= umax;
  1775. int b = big_int_cmp(&i, &umax);
  1776. return !i.sign && (b <= 0);
  1777. }
  1778. case Basic_UntypedInteger:
  1779. return true;
  1780. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1781. }
  1782. } else if (is_type_float(type)) {
  1783. ExactValue v = exact_value_to_float(in_value);
  1784. if (v.kind != ExactValue_Float) {
  1785. return false;
  1786. }
  1787. if (out_value) *out_value = v;
  1788. switch (type->Basic.kind) {
  1789. case Basic_f16:
  1790. case Basic_f32:
  1791. case Basic_f64:
  1792. return true;
  1793. case Basic_f16le:
  1794. case Basic_f16be:
  1795. case Basic_f32le:
  1796. case Basic_f32be:
  1797. case Basic_f64le:
  1798. case Basic_f64be:
  1799. return true;
  1800. case Basic_UntypedFloat:
  1801. return true;
  1802. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1803. }
  1804. } else if (is_type_complex(type)) {
  1805. ExactValue v = exact_value_to_complex(in_value);
  1806. if (v.kind != ExactValue_Complex) {
  1807. return false;
  1808. }
  1809. switch (type->Basic.kind) {
  1810. case Basic_complex32:
  1811. case Basic_complex64:
  1812. case Basic_complex128: {
  1813. ExactValue real = exact_value_real(v);
  1814. ExactValue imag = exact_value_imag(v);
  1815. if (real.kind != ExactValue_Invalid &&
  1816. imag.kind != ExactValue_Invalid) {
  1817. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1818. return true;
  1819. }
  1820. break;
  1821. }
  1822. case Basic_UntypedComplex:
  1823. return true;
  1824. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1825. }
  1826. return false;
  1827. } else if (is_type_quaternion(type)) {
  1828. ExactValue v = exact_value_to_quaternion(in_value);
  1829. if (v.kind != ExactValue_Quaternion) {
  1830. return false;
  1831. }
  1832. switch (type->Basic.kind) {
  1833. case Basic_quaternion64:
  1834. case Basic_quaternion128:
  1835. case Basic_quaternion256: {
  1836. ExactValue real = exact_value_real(v);
  1837. ExactValue imag = exact_value_imag(v);
  1838. ExactValue jmag = exact_value_jmag(v);
  1839. ExactValue kmag = exact_value_kmag(v);
  1840. if (real.kind != ExactValue_Invalid &&
  1841. imag.kind != ExactValue_Invalid) {
  1842. 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));
  1843. return true;
  1844. }
  1845. break;
  1846. }
  1847. case Basic_UntypedComplex:
  1848. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  1849. return true;
  1850. case Basic_UntypedQuaternion:
  1851. return true;
  1852. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1853. }
  1854. return false;
  1855. } else if (is_type_pointer(type)) {
  1856. if (in_value.kind == ExactValue_Pointer) {
  1857. return true;
  1858. }
  1859. if (in_value.kind == ExactValue_Integer) {
  1860. return false;
  1861. // return true;
  1862. }
  1863. if (in_value.kind == ExactValue_String) {
  1864. return false;
  1865. }
  1866. if (out_value) *out_value = in_value;
  1867. } else if (is_type_bit_set(type)) {
  1868. if (in_value.kind == ExactValue_Integer) {
  1869. return true;
  1870. }
  1871. }
  1872. return false;
  1873. }
  1874. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  1875. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  1876. gbString b = type_to_string(type);
  1877. i64 sz = type_size_of(type);
  1878. i64 bit_size = 8*sz;
  1879. bool size_changed = false;
  1880. if (max_bit_size > 0) {
  1881. size_changed = (bit_size != max_bit_size);
  1882. bit_size = gb_min(bit_size, max_bit_size);
  1883. }
  1884. BigInt *bi = &o->value.value_integer;
  1885. if (is_type_unsigned(type)) {
  1886. if (big_int_is_neg(bi)) {
  1887. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  1888. } else {
  1889. BigInt one = big_int_make_u64(1);
  1890. BigInt max_size = big_int_make_u64(1);
  1891. BigInt bits = big_int_make_i64(bit_size);
  1892. big_int_shl_eq(&max_size, &bits);
  1893. big_int_sub_eq(&max_size, &one);
  1894. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1895. if (size_changed) {
  1896. 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));
  1897. } else {
  1898. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1899. }
  1900. }
  1901. } else {
  1902. BigInt zero = big_int_make_u64(0);
  1903. BigInt one = big_int_make_u64(1);
  1904. BigInt max_size = big_int_make_u64(1);
  1905. BigInt bits = big_int_make_i64(bit_size - 1);
  1906. big_int_shl_eq(&max_size, &bits);
  1907. String max_size_str = {};
  1908. if (big_int_is_neg(bi)) {
  1909. big_int_neg(&max_size, &max_size);
  1910. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1911. } else {
  1912. big_int_sub_eq(&max_size, &one);
  1913. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1914. }
  1915. if (size_changed) {
  1916. 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));
  1917. } else {
  1918. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1919. }
  1920. }
  1921. gb_string_free(b);
  1922. return true;
  1923. }
  1924. return false;
  1925. }
  1926. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  1927. gbString a = expr_to_string(o->expr);
  1928. gbString b = type_to_string(type);
  1929. defer(
  1930. gb_string_free(b);
  1931. gb_string_free(a);
  1932. );
  1933. Type *src = base_type(o->type);
  1934. Type *dst = base_type(type);
  1935. if (is_type_array(src) && is_type_slice(dst)) {
  1936. Type *s = src->Array.elem;
  1937. Type *d = dst->Slice.elem;
  1938. if (are_types_identical(s, d)) {
  1939. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1940. }
  1941. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  1942. Type *s = src->DynamicArray.elem;
  1943. Type *d = dst->Slice.elem;
  1944. if (are_types_identical(s, d)) {
  1945. error_line("\tSuggestion: the dynamic array expression may be sliced with %s[:]\n", a);
  1946. }
  1947. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  1948. error_line("\tSuggestion: the expression may be directly casted to type %s\n", b);
  1949. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1950. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1951. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable, \n");
  1952. error_line("\t whereas slices in general are assumed to be mutable.\n");
  1953. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  1954. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  1955. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  1956. return;
  1957. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  1958. gbString s = expr_to_string(c->type_hint_expr);
  1959. error_line("\tSuggestion: make sure that `%s` is attached to the compound literal directly\n", s);
  1960. gb_string_free(s);
  1961. } else if (is_type_pointer(type) &&
  1962. o->mode == Addressing_Variable &&
  1963. are_types_identical(type_deref(type), o->type)) {
  1964. gbString s = expr_to_string(o->expr);
  1965. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  1966. gb_string_free(s);
  1967. } else if (is_type_pointer(o->type) &&
  1968. are_types_identical(type_deref(o->type), type)) {
  1969. gbString s = expr_to_string(o->expr);
  1970. error_line("\tSuggestion: Did you mean `%s^`\n", s);
  1971. gb_string_free(s);
  1972. }
  1973. }
  1974. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1975. gbString a = expr_to_string(o->expr);
  1976. gbString b = type_to_string(type);
  1977. defer(
  1978. gb_string_free(b);
  1979. gb_string_free(a);
  1980. );
  1981. Type *src = base_type(o->type);
  1982. Type *dst = base_type(type);
  1983. if (is_type_array(src) && is_type_slice(dst)) {
  1984. Type *s = src->Array.elem;
  1985. Type *d = dst->Slice.elem;
  1986. if (are_types_identical(s, d)) {
  1987. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1988. }
  1989. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  1990. if (is_type_uintptr(type)) {
  1991. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  1992. } else {
  1993. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  1994. i64 x = type_size_of(o->type);
  1995. i64 y = type_size_of(type);
  1996. if (x != y) {
  1997. 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);
  1998. }
  1999. }
  2000. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2001. if (is_type_uintptr(o->type)) {
  2002. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2003. } else {
  2004. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2005. }
  2006. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2007. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2008. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2009. return;
  2010. }
  2011. }
  2012. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2013. GB_ASSERT(o->mode == Addressing_Constant);
  2014. ExactValue out_value = o->value;
  2015. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2016. o->value = out_value;
  2017. return true;
  2018. } else {
  2019. o->value = out_value;
  2020. gbString a = expr_to_string(o->expr);
  2021. gbString b = type_to_string(type);
  2022. gbString c = type_to_string(o->type);
  2023. gbString s = exact_value_to_string(o->value);
  2024. defer(
  2025. gb_string_free(s);
  2026. gb_string_free(c);
  2027. gb_string_free(b);
  2028. gb_string_free(a);
  2029. o->mode = Addressing_Invalid;
  2030. );
  2031. ERROR_BLOCK();
  2032. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2033. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2034. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2035. } else {
  2036. i64 max_bit_size = 0;
  2037. if (ctx->bit_field_bit_size) {
  2038. max_bit_size = ctx->bit_field_bit_size;
  2039. }
  2040. if (are_types_identical(o->type, type)) {
  2041. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2042. } else {
  2043. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2044. }
  2045. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2046. }
  2047. } else {
  2048. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2049. check_assignment_error_suggestion(ctx, o, type);
  2050. }
  2051. return false;
  2052. }
  2053. }
  2054. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2055. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2056. if (o->expr->SelectorExpr.is_bit_field) {
  2057. return true;
  2058. }
  2059. }
  2060. if (o->mode == Addressing_OptionalOk) {
  2061. Ast *expr = unselector_expr(o->expr);
  2062. if (expr->kind != Ast_TypeAssertion) {
  2063. return true;
  2064. }
  2065. ast_node(ta, TypeAssertion, expr);
  2066. TypeAndValue tv = ta->expr->tav;
  2067. if (is_type_pointer(tv.type)) {
  2068. return false;
  2069. }
  2070. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2071. return false;
  2072. }
  2073. if (is_type_any(tv.type)) {
  2074. return false;
  2075. }
  2076. return true;
  2077. }
  2078. if (o->mode == Addressing_MapIndex) {
  2079. return false;
  2080. }
  2081. Ast *expr = unparen_expr(o->expr);
  2082. if (expr->kind == Ast_CompoundLit) {
  2083. return false;
  2084. }
  2085. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2086. }
  2087. gb_internal void check_old_for_or_switch_value_usage(Ast *expr) {
  2088. if (!(build_context.strict_style || (check_vet_flags(expr) & VetFlag_Style))) {
  2089. return;
  2090. }
  2091. Entity *e = entity_of_node(expr);
  2092. if (e != nullptr && (e->flags & EntityFlag_OldForOrSwitchValue) != 0) {
  2093. GB_ASSERT(e->kind == Entity_Variable);
  2094. ERROR_BLOCK();
  2095. if ((e->flags & EntityFlag_ForValue) != 0) {
  2096. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2097. error(expr, "Assuming a for-in defined value is addressable as the iterable is passed by value has been disallowed with '-strict-style'.");
  2098. if (is_type_map(parent_type)) {
  2099. error_line("\tSuggestion: Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2100. } else {
  2101. error_line("\tSuggestion: Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2102. }
  2103. } else {
  2104. GB_ASSERT((e->flags & EntityFlag_SwitchValue) != 0);
  2105. error(expr, "Assuming a switch-in defined value is addressable as the iterable is passed by value has been disallowed with '-strict-style'.");
  2106. error_line("\tSuggestion: Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2107. }
  2108. }
  2109. }
  2110. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2111. switch (op.kind) {
  2112. case Token_And: { // Pointer address
  2113. if (check_is_not_addressable(c, o)) {
  2114. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2115. ast_node(ue, UnaryExpr, node);
  2116. gbString str = expr_to_string(ue->expr);
  2117. defer (gb_string_free(str));
  2118. Entity *e = entity_of_node(ue->expr);
  2119. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2120. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2121. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2122. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2123. } else {
  2124. switch (o->mode) {
  2125. case Addressing_Constant:
  2126. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2127. break;
  2128. case Addressing_SwizzleValue:
  2129. case Addressing_SwizzleVariable:
  2130. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2131. break;
  2132. default:
  2133. {
  2134. ERROR_BLOCK();
  2135. error(op, "Cannot take the pointer address of '%s'", str);
  2136. if (e != nullptr && (e->flags & EntityFlag_ForValue) != 0) {
  2137. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2138. if (parent_type != nullptr && is_type_string(parent_type)) {
  2139. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2140. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2141. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2142. } else {
  2143. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2144. }
  2145. }
  2146. if (e != nullptr && (e->flags & EntityFlag_SwitchValue) != 0) {
  2147. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2148. }
  2149. }
  2150. break;
  2151. }
  2152. }
  2153. }
  2154. o->mode = Addressing_Invalid;
  2155. return;
  2156. }
  2157. if (o->mode == Addressing_SoaVariable) {
  2158. ast_node(ue, UnaryExpr, node);
  2159. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2160. ast_node(ie, IndexExpr, ue->expr);
  2161. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2162. GB_ASSERT(is_type_soa_struct(soa_type));
  2163. o->type = alloc_type_soa_pointer(soa_type);
  2164. } else {
  2165. o->type = alloc_type_pointer(o->type);
  2166. }
  2167. } else {
  2168. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2169. ast_node(ue, UnaryExpr, node);
  2170. check_old_for_or_switch_value_usage(ue->expr);
  2171. }
  2172. o->type = alloc_type_pointer(o->type);
  2173. }
  2174. switch (o->mode) {
  2175. case Addressing_OptionalOk:
  2176. case Addressing_MapIndex:
  2177. o->mode = Addressing_OptionalOkPtr;
  2178. break;
  2179. default:
  2180. o->mode = Addressing_Value;
  2181. break;
  2182. }
  2183. return;
  2184. }
  2185. }
  2186. if (!check_unary_op(c, o, op)) {
  2187. o->mode = Addressing_Invalid;
  2188. return;
  2189. }
  2190. if (o->mode == Addressing_Constant) {
  2191. Type *type = base_type(o->type);
  2192. if (!is_type_constant_type(o->type)) {
  2193. gbString xt = type_to_string(o->type);
  2194. gbString err_str = expr_to_string(node);
  2195. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2196. gb_string_free(err_str);
  2197. gb_string_free(xt);
  2198. o->mode = Addressing_Invalid;
  2199. return;
  2200. }
  2201. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2202. gbString err_str = expr_to_string(node);
  2203. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2204. gb_string_free(err_str);
  2205. o->mode = Addressing_Invalid;
  2206. return;
  2207. }
  2208. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2209. gbString err_str = expr_to_string(node);
  2210. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2211. gb_string_free(err_str);
  2212. o->mode = Addressing_Invalid;
  2213. return;
  2214. }
  2215. i32 precision = 0;
  2216. if (is_type_typed(type)) {
  2217. precision = cast(i32)(8 * type_size_of(type));
  2218. }
  2219. bool is_unsigned = is_type_unsigned(type);
  2220. if (is_type_rune(type)) {
  2221. GB_ASSERT(!is_unsigned);
  2222. }
  2223. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2224. if (is_type_typed(type)) {
  2225. if (node != nullptr) {
  2226. o->expr = node;
  2227. }
  2228. check_is_expressible(c, o, type);
  2229. }
  2230. return;
  2231. }
  2232. o->mode = Addressing_Value;
  2233. }
  2234. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2235. if (t == nullptr) {
  2236. return;
  2237. }
  2238. t = base_type(t);
  2239. if (!is_type_comparable(t)) {
  2240. return;
  2241. }
  2242. switch (t->kind) {
  2243. case Type_Basic:
  2244. switch (t->Basic.kind) {
  2245. case Basic_complex32:
  2246. add_package_dependency(c, "runtime", "complex32_eq");
  2247. add_package_dependency(c, "runtime", "complex32_ne");
  2248. break;
  2249. case Basic_complex64:
  2250. add_package_dependency(c, "runtime", "complex64_eq");
  2251. add_package_dependency(c, "runtime", "complex64_ne");
  2252. break;
  2253. case Basic_complex128:
  2254. add_package_dependency(c, "runtime", "complex128_eq");
  2255. add_package_dependency(c, "runtime", "complex128_ne");
  2256. break;
  2257. case Basic_quaternion64:
  2258. add_package_dependency(c, "runtime", "quaternion64_eq");
  2259. add_package_dependency(c, "runtime", "quaternion64_ne");
  2260. break;
  2261. case Basic_quaternion128:
  2262. add_package_dependency(c, "runtime", "quaternion128_eq");
  2263. add_package_dependency(c, "runtime", "quaternion128_ne");
  2264. break;
  2265. case Basic_quaternion256:
  2266. add_package_dependency(c, "runtime", "quaternion256_eq");
  2267. add_package_dependency(c, "runtime", "quaternion256_ne");
  2268. break;
  2269. case Basic_cstring:
  2270. add_package_dependency(c, "runtime", "cstring_eq");
  2271. add_package_dependency(c, "runtime", "cstring_ne");
  2272. break;
  2273. case Basic_string:
  2274. add_package_dependency(c, "runtime", "string_eq");
  2275. add_package_dependency(c, "runtime", "string_ne");
  2276. break;
  2277. }
  2278. break;
  2279. case Type_Struct:
  2280. for (Entity *field : t->Struct.fields) {
  2281. add_comparison_procedures_for_fields(c, field->type);
  2282. }
  2283. break;
  2284. }
  2285. }
  2286. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2287. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2288. bool comp = are_types_identical(x->type, y->type);
  2289. switch (op) {
  2290. case Token_CmpEq: /* comp = comp; */ break;
  2291. case Token_NotEq: comp = !comp; break;
  2292. }
  2293. x->mode = Addressing_Constant;
  2294. x->type = t_untyped_bool;
  2295. x->value = exact_value_bool(comp);
  2296. return;
  2297. }
  2298. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2299. add_type_info_type(c, x->type);
  2300. add_type_info_type(c, y->type);
  2301. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2302. x->mode = Addressing_Value;
  2303. x->type = t_untyped_bool;
  2304. return;
  2305. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2306. add_type_info_type(c, x->type);
  2307. add_type_info_type(c, y->type);
  2308. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2309. x->mode = Addressing_Value;
  2310. x->type = t_untyped_bool;
  2311. return;
  2312. }
  2313. TEMPORARY_ALLOCATOR_GUARD();
  2314. gbString err_str = nullptr;
  2315. if (check_is_assignable_to(c, x, y->type) ||
  2316. check_is_assignable_to(c, y, x->type)) {
  2317. Type *err_type = x->type;
  2318. bool defined = false;
  2319. switch (op) {
  2320. case Token_CmpEq:
  2321. case Token_NotEq:
  2322. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2323. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2324. (is_operand_nil(*y) && type_has_nil(x->type));
  2325. break;
  2326. case Token_Lt:
  2327. case Token_Gt:
  2328. case Token_LtEq:
  2329. case Token_GtEq:
  2330. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2331. defined = true;
  2332. } else {
  2333. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2334. }
  2335. break;
  2336. }
  2337. if (!defined) {
  2338. gbString xs = type_to_string(x->type, temporary_allocator());
  2339. gbString ys = type_to_string(y->type, temporary_allocator());
  2340. err_str = gb_string_make(temporary_allocator(),
  2341. gb_bprintf("operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2342. );
  2343. } else {
  2344. Type *comparison_type = x->type;
  2345. if (x->type == err_type && is_operand_nil(*x)) {
  2346. comparison_type = y->type;
  2347. }
  2348. add_comparison_procedures_for_fields(c, comparison_type);
  2349. }
  2350. } else {
  2351. gbString xt, yt;
  2352. if (x->mode == Addressing_ProcGroup) {
  2353. xt = gb_string_make(temporary_allocator(), "procedure group");
  2354. } else {
  2355. xt = type_to_string(x->type);
  2356. }
  2357. if (y->mode == Addressing_ProcGroup) {
  2358. yt = gb_string_make(temporary_allocator(), "procedure group");
  2359. } else {
  2360. yt = type_to_string(y->type);
  2361. }
  2362. err_str = gb_string_make(temporary_allocator(), gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  2363. }
  2364. if (err_str != nullptr) {
  2365. error(node, "Cannot compare expression, %s", err_str);
  2366. x->type = t_untyped_bool;
  2367. } else {
  2368. if (x->mode == Addressing_Constant &&
  2369. y->mode == Addressing_Constant) {
  2370. if (is_type_constant_type(x->type)) {
  2371. if (is_type_bit_set(x->type)) {
  2372. switch (op) {
  2373. case Token_CmpEq:
  2374. case Token_NotEq:
  2375. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2376. break;
  2377. case Token_Lt:
  2378. case Token_LtEq:
  2379. {
  2380. ExactValue lhs = x->value;
  2381. ExactValue rhs = y->value;
  2382. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2383. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2384. if (op == Token_Lt) {
  2385. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2386. }
  2387. x->value = res;
  2388. break;
  2389. }
  2390. case Token_Gt:
  2391. case Token_GtEq:
  2392. {
  2393. ExactValue lhs = x->value;
  2394. ExactValue rhs = y->value;
  2395. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2396. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2397. if (op == Token_Gt) {
  2398. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2399. }
  2400. x->value = res;
  2401. break;
  2402. }
  2403. }
  2404. } else {
  2405. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2406. }
  2407. } else {
  2408. x->mode = Addressing_Value;
  2409. }
  2410. } else {
  2411. x->mode = Addressing_Value;
  2412. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2413. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2414. i64 size = 0;
  2415. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2416. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2417. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2418. switch (op) {
  2419. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2420. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2421. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2422. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2423. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2424. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2425. }
  2426. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2427. switch (op) {
  2428. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2429. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2430. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2431. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2432. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2433. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2434. }
  2435. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2436. switch (op) {
  2437. case Token_CmpEq:
  2438. switch (8*size) {
  2439. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2440. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2441. }
  2442. break;
  2443. case Token_NotEq:
  2444. switch (8*size) {
  2445. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2446. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2447. }
  2448. break;
  2449. }
  2450. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2451. switch (op) {
  2452. case Token_CmpEq:
  2453. switch (8*size) {
  2454. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2455. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2456. }
  2457. break;
  2458. case Token_NotEq:
  2459. switch (8*size) {
  2460. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2461. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2462. }
  2463. break;
  2464. }
  2465. }
  2466. }
  2467. x->type = t_untyped_bool;
  2468. }
  2469. }
  2470. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2471. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2472. ast_node(be, BinaryExpr, node);
  2473. ExactValue x_val = {};
  2474. if (x->mode == Addressing_Constant) {
  2475. x_val = exact_value_to_integer(x->value);
  2476. }
  2477. bool x_is_untyped = is_type_untyped(x->type);
  2478. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  2479. gbString err_str = expr_to_string(x->expr);
  2480. error(node, "Shifted operand '%s' must be an integer", err_str);
  2481. gb_string_free(err_str);
  2482. x->mode = Addressing_Invalid;
  2483. return;
  2484. }
  2485. if (is_type_unsigned(y->type)) {
  2486. } else if (is_type_untyped(y->type)) {
  2487. convert_to_typed(c, y, t_untyped_integer);
  2488. if (y->mode == Addressing_Invalid) {
  2489. x->mode = Addressing_Invalid;
  2490. return;
  2491. }
  2492. } else {
  2493. gbString err_str = expr_to_string(y->expr);
  2494. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2495. gb_string_free(err_str);
  2496. x->mode = Addressing_Invalid;
  2497. return;
  2498. }
  2499. if (x->mode == Addressing_Constant) {
  2500. if (y->mode == Addressing_Constant) {
  2501. ExactValue y_val = exact_value_to_integer(y->value);
  2502. if (y_val.kind != ExactValue_Integer) {
  2503. gbString err_str = expr_to_string(y->expr);
  2504. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2505. gb_string_free(err_str);
  2506. x->mode = Addressing_Invalid;
  2507. return;
  2508. }
  2509. BigInt max_shift = {};
  2510. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2511. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  2512. gbString err_str = expr_to_string(y->expr);
  2513. error(node, "Shift amount too large: '%s'", err_str);
  2514. gb_string_free(err_str);
  2515. x->mode = Addressing_Invalid;
  2516. return;
  2517. }
  2518. if (!is_type_integer(x->type)) {
  2519. // NOTE(bill): It could be an untyped float but still representable
  2520. // as an integer
  2521. x->type = t_untyped_integer;
  2522. }
  2523. x->expr = node;
  2524. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  2525. if (is_type_typed(x->type)) {
  2526. check_is_expressible(c, x, x->type);
  2527. }
  2528. return;
  2529. }
  2530. TokenPos pos = ast_token(x->expr).pos;
  2531. if (x_is_untyped) {
  2532. if (x->expr != nullptr) {
  2533. x->expr->tav.is_lhs = true;
  2534. }
  2535. x->mode = Addressing_Value;
  2536. if (type_hint) {
  2537. if (is_type_integer(type_hint)) {
  2538. x->type = type_hint;
  2539. } else {
  2540. gbString x_str = expr_to_string(x->expr);
  2541. gbString to_type = type_to_string(type_hint);
  2542. error(node, "Conversion of shifted operand '%s' to '%s' is not allowed", x_str, to_type);
  2543. gb_string_free(x_str);
  2544. gb_string_free(to_type);
  2545. x->mode = Addressing_Invalid;
  2546. }
  2547. } else if (!is_type_integer(x->type)) {
  2548. gbString x_str = expr_to_string(x->expr);
  2549. error(node, "Non-integer shifted operand '%s' is not allowed", x_str);
  2550. gb_string_free(x_str);
  2551. x->mode = Addressing_Invalid;
  2552. }
  2553. // x->value = x_val;
  2554. return;
  2555. }
  2556. }
  2557. if (y->mode == Addressing_Constant && big_int_is_neg(&y->value.value_integer)) {
  2558. gbString err_str = expr_to_string(y->expr);
  2559. error(node, "Shift amount cannot be negative: '%s'", err_str);
  2560. gb_string_free(err_str);
  2561. }
  2562. if (!is_type_integer(x->type)) {
  2563. gbString err_str = expr_to_string(x->expr);
  2564. error(node, "Shift operand '%s' must be an integer", err_str);
  2565. gb_string_free(err_str);
  2566. x->mode = Addressing_Invalid;
  2567. return;
  2568. }
  2569. if (is_type_untyped(y->type)) {
  2570. convert_to_typed(c, y, t_uint);
  2571. }
  2572. x->mode = Addressing_Value;
  2573. }
  2574. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2575. if (check_is_assignable_to(c, operand, y)) {
  2576. return true;
  2577. }
  2578. bool is_constant = operand->mode == Addressing_Constant;
  2579. Type *x = operand->type;
  2580. Type *src = core_type(x);
  2581. Type *dst = core_type(y);
  2582. if (are_types_identical(src, dst)) {
  2583. return true;
  2584. }
  2585. // if (is_type_tuple(src)) {
  2586. // Ast *expr = unparen_expr(operand->expr);
  2587. // if (expr && expr->kind == Ast_CallExpr) {
  2588. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2589. // ast_node(ce, CallExpr, expr);
  2590. // Type *pt = base_type(type_of_expr(ce->proc));
  2591. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2592. // if (pt->Proc.result_count > 0) {
  2593. // Operand op = *operand;
  2594. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2595. // bool ok = check_is_castable_to(c, &op, y);
  2596. // if (ok) {
  2597. // ce->optional_ok_one = true;
  2598. // }
  2599. // return ok;
  2600. // }
  2601. // }
  2602. // }
  2603. // }
  2604. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2605. if (is_type_u8_array(dst)) {
  2606. String s = operand->value.value_string;
  2607. return s.len == dst->Array.count;
  2608. }
  2609. if (is_type_rune_array(dst)) {
  2610. String s = operand->value.value_string;
  2611. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2612. }
  2613. }
  2614. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2615. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2616. return dst->Array.count == src->Array.count;
  2617. }
  2618. }
  2619. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2620. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2621. }
  2622. // Cast between booleans and integers
  2623. if (is_type_boolean(src) || is_type_integer(src)) {
  2624. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2625. return true;
  2626. }
  2627. }
  2628. // Cast between numbers
  2629. if (is_type_integer(src) || is_type_float(src)) {
  2630. if (is_type_integer(dst) || is_type_float(dst)) {
  2631. return true;
  2632. }
  2633. }
  2634. if (is_type_bit_field(src)) {
  2635. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2636. }
  2637. if (is_type_bit_field(dst)) {
  2638. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2639. }
  2640. if (is_type_integer(src) && is_type_rune(dst)) {
  2641. return true;
  2642. }
  2643. if (is_type_rune(src) && is_type_integer(dst)) {
  2644. return true;
  2645. }
  2646. if (is_type_complex(src) && is_type_complex(dst)) {
  2647. return true;
  2648. }
  2649. if (is_type_float(src) && is_type_complex(dst)) {
  2650. return true;
  2651. }
  2652. if (is_type_float(src) && is_type_quaternion(dst)) {
  2653. return true;
  2654. }
  2655. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2656. return true;
  2657. }
  2658. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2659. return true;
  2660. }
  2661. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2662. GB_ASSERT(src->kind == Type_Matrix);
  2663. GB_ASSERT(dst->kind == Type_Matrix);
  2664. Operand op = *operand;
  2665. op.type = src->Matrix.elem;
  2666. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2667. return false;
  2668. }
  2669. if (src->Matrix.row_count != src->Matrix.column_count) {
  2670. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2671. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2672. return src_count == dst_count;
  2673. }
  2674. return is_matrix_square(dst) && is_matrix_square(src);
  2675. }
  2676. // Cast between pointers
  2677. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2678. return true;
  2679. }
  2680. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2681. return true;
  2682. }
  2683. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2684. return true;
  2685. }
  2686. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2687. return true;
  2688. }
  2689. // uintptr <-> pointer
  2690. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2691. return true;
  2692. }
  2693. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2694. return true;
  2695. }
  2696. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2697. return true;
  2698. }
  2699. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2700. return true;
  2701. }
  2702. // []byte/[]u8 <-> string (not cstring)
  2703. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2704. return true;
  2705. }
  2706. // cstring -> string
  2707. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2708. if (operand->mode != Addressing_Constant) {
  2709. add_package_dependency(c, "runtime", "cstring_to_string");
  2710. }
  2711. return true;
  2712. }
  2713. // cstring -> ^u8
  2714. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2715. return !is_constant;
  2716. }
  2717. // cstring -> [^]u8
  2718. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2719. return !is_constant;
  2720. }
  2721. // cstring -> rawptr
  2722. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2723. return !is_constant;
  2724. }
  2725. // ^u8 -> cstring
  2726. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2727. return !is_constant;
  2728. }
  2729. // [^]u8 -> cstring
  2730. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2731. return !is_constant;
  2732. }
  2733. // rawptr -> cstring
  2734. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2735. return !is_constant;
  2736. }
  2737. // proc <-> proc
  2738. if (is_type_proc(src) && is_type_proc(dst)) {
  2739. if (is_type_polymorphic(dst)) {
  2740. if (is_type_polymorphic(src) &&
  2741. operand->mode == Addressing_Variable) {
  2742. return true;
  2743. }
  2744. return false;
  2745. }
  2746. return true;
  2747. }
  2748. // proc -> rawptr
  2749. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2750. return true;
  2751. }
  2752. // rawptr -> proc
  2753. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2754. return true;
  2755. }
  2756. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2757. if (src->SimdVector.count != dst->SimdVector.count) {
  2758. return false;
  2759. }
  2760. Type *elem_src = base_array_type(src);
  2761. Type *elem_dst = base_array_type(dst);
  2762. Operand x = {};
  2763. x.type = elem_src;
  2764. x.mode = Addressing_Value;
  2765. return check_is_castable_to(c, &x, elem_dst);
  2766. }
  2767. if (is_type_simd_vector(dst)) {
  2768. Type *elem = base_array_type(dst);
  2769. if (check_is_castable_to(c, operand, elem)) {
  2770. return true;
  2771. }
  2772. }
  2773. return false;
  2774. }
  2775. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2776. bool is_const_expr = x->mode == Addressing_Constant;
  2777. Type *bt = base_type(type);
  2778. if (is_const_expr && is_type_constant_type(bt)) {
  2779. if (core_type(bt)->kind == Type_Basic) {
  2780. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2781. return true;
  2782. } else if (check_is_castable_to(c, x, type)) {
  2783. if (is_type_pointer(type)) {
  2784. return true;
  2785. }
  2786. }
  2787. } else if (check_is_castable_to(c, x, type)) {
  2788. x->value = {};
  2789. x->mode = Addressing_Value;
  2790. return true;
  2791. }
  2792. } else if (check_is_castable_to(c, x, type)) {
  2793. if (x->mode != Addressing_Constant) {
  2794. x->mode = Addressing_Value;
  2795. } else if (is_type_slice(type) && is_type_string(x->type)) {
  2796. x->mode = Addressing_Value;
  2797. } else if (is_type_union(type)) {
  2798. x->mode = Addressing_Value;
  2799. }
  2800. if (x->mode == Addressing_Value) {
  2801. x->value = {};
  2802. }
  2803. return true;
  2804. }
  2805. return false;
  2806. }
  2807. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type) {
  2808. if (!is_operand_value(*x)) {
  2809. error(x->expr, "Only values can be casted");
  2810. x->mode = Addressing_Invalid;
  2811. return;
  2812. }
  2813. bool is_const_expr = x->mode == Addressing_Constant;
  2814. bool can_convert = check_cast_internal(c, x, type);
  2815. if (!can_convert) {
  2816. TEMPORARY_ALLOCATOR_GUARD();
  2817. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  2818. gbString to_type = type_to_string(type, temporary_allocator());
  2819. gbString from_type = type_to_string(x->type, temporary_allocator());
  2820. x->mode = Addressing_Invalid;
  2821. ERROR_BLOCK();
  2822. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  2823. if (is_const_expr) {
  2824. gbString val_str = exact_value_to_string(x->value);
  2825. if (is_type_float(x->type) && is_type_integer(type)) {
  2826. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  2827. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2828. x->mode = Addressing_Constant;
  2829. x->type = type;
  2830. } else {
  2831. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  2832. if (is_type_numeric(type)) {
  2833. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2834. x->mode = Addressing_Constant;
  2835. x->type = type;
  2836. }
  2837. }
  2838. gb_string_free(val_str);
  2839. }
  2840. check_cast_error_suggestion(c, x, type);
  2841. return;
  2842. }
  2843. if (is_type_untyped(x->type)) {
  2844. Type *final_type = type;
  2845. if (is_const_expr && !is_type_constant_type(type)) {
  2846. final_type = default_type(x->type);
  2847. }
  2848. update_untyped_expr_type(c, x->expr, final_type, true);
  2849. } else {
  2850. Type *src = core_type(x->type);
  2851. Type *dst = core_type(type);
  2852. if (src != dst) {
  2853. bool const REQUIRE = true;
  2854. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  2855. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  2856. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  2857. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  2858. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  2859. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  2860. } else if (src == t_f16 && is_type_float(dst)) {
  2861. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  2862. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  2863. } else if (is_type_float(dst) && dst == t_f16) {
  2864. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  2865. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  2866. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  2867. }
  2868. }
  2869. }
  2870. x->type = type;
  2871. }
  2872. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  2873. if (!is_operand_value(*o)) {
  2874. error(o->expr, "'transmute' can only be applied to values");
  2875. o->mode = Addressing_Invalid;
  2876. return false;
  2877. }
  2878. // if (o->mode == Addressing_Constant) {
  2879. // gbString expr_str = expr_to_string(o->expr);
  2880. // error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  2881. // gb_string_free(expr_str);
  2882. // o->mode = Addressing_Invalid;
  2883. // o->expr = node;
  2884. // return false;
  2885. // }
  2886. Type *src_t = o->type;
  2887. Type *dst_t = t;
  2888. Type *src_bt = base_type(src_t);
  2889. Type *dst_bt = base_type(dst_t);
  2890. if (is_type_untyped(src_t)) {
  2891. gbString expr_str = expr_to_string(o->expr);
  2892. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  2893. gb_string_free(expr_str);
  2894. o->mode = Addressing_Invalid;
  2895. o->expr = node;
  2896. return false;
  2897. }
  2898. if (dst_bt == nullptr || dst_bt == t_invalid) {
  2899. GB_ASSERT(global_error_collector.count != 0);
  2900. o->mode = Addressing_Invalid;
  2901. o->expr = node;
  2902. return false;
  2903. }
  2904. if (src_bt == nullptr || src_bt == t_invalid) {
  2905. // NOTE(bill): this should be an error
  2906. GB_ASSERT(global_error_collector.count != 0);
  2907. o->mode = Addressing_Value;
  2908. o->expr = node;
  2909. o->type = dst_t;
  2910. return true;
  2911. }
  2912. i64 srcz = type_size_of(src_t);
  2913. i64 dstz = type_size_of(dst_t);
  2914. if (srcz != dstz) {
  2915. gbString expr_str = expr_to_string(o->expr);
  2916. gbString type_str = type_to_string(dst_t);
  2917. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  2918. gb_string_free(type_str);
  2919. gb_string_free(expr_str);
  2920. o->mode = Addressing_Invalid;
  2921. o->expr = node;
  2922. return false;
  2923. }
  2924. o->expr = node;
  2925. o->type = dst_t;
  2926. if (o->mode == Addressing_Constant) {
  2927. if (are_types_identical(src_bt, dst_bt)) {
  2928. return true;
  2929. }
  2930. if (is_type_integer(src_t) && is_type_integer(dst_t)) {
  2931. if (types_have_same_internal_endian(src_t, dst_t)) {
  2932. ExactValue src_v = exact_value_to_integer(o->value);
  2933. GB_ASSERT(src_v.kind == ExactValue_Integer);
  2934. BigInt v = src_v.value_integer;
  2935. BigInt smax = {};
  2936. BigInt umax = {};
  2937. big_int_from_u64(&smax, 0);
  2938. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  2939. big_int_from_u64(&umax, 1);
  2940. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  2941. big_int_shl_eq(&umax, &sz_in_bits);
  2942. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  2943. if (big_int_cmp(&v, &smax) >= 0) {
  2944. big_int_sub_eq(&v, &umax);
  2945. }
  2946. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  2947. if (big_int_is_neg(&v)) {
  2948. big_int_add_eq(&v, &umax);
  2949. }
  2950. }
  2951. o->value.kind = ExactValue_Integer;
  2952. o->value.value_integer = v;
  2953. return true;
  2954. }
  2955. }
  2956. }
  2957. o->mode = Addressing_Value;
  2958. o->value = {};
  2959. return true;
  2960. }
  2961. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  2962. if (is_type_array(x->type) && !is_type_array(y->type)) {
  2963. if (check_is_assignable_to(c, y, x->type)) {
  2964. if (check_binary_op(c, x, op)) {
  2965. return true;
  2966. }
  2967. }
  2968. }
  2969. return false;
  2970. }
  2971. gb_internal bool is_ise_expr(Ast *node) {
  2972. node = unparen_expr(node);
  2973. return node->kind == Ast_ImplicitSelectorExpr;
  2974. }
  2975. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  2976. if (use_lhs_as_type_hint) { // RHS in this case
  2977. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  2978. }
  2979. return false;
  2980. }
  2981. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  2982. Type *xt = base_type(matrix);
  2983. if (type_hint != nullptr) {
  2984. Type *th = base_type(type_hint);
  2985. if (are_types_identical(th, xt)) {
  2986. return type_hint;
  2987. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  2988. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  2989. // ignore
  2990. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  2991. xt->Matrix.column_count == th->Matrix.column_count) {
  2992. return type_hint;
  2993. }
  2994. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  2995. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  2996. // ignore
  2997. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  2998. return type_hint;
  2999. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3000. return type_hint;
  3001. }
  3002. }
  3003. }
  3004. return matrix;
  3005. }
  3006. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3007. if (!check_binary_op(c, x, op)) {
  3008. x->mode = Addressing_Invalid;
  3009. return;
  3010. }
  3011. Type *xt = base_type(x->type);
  3012. Type *yt = base_type(y->type);
  3013. if (is_type_matrix(x->type)) {
  3014. GB_ASSERT(xt->kind == Type_Matrix);
  3015. if (op.kind == Token_Mul) {
  3016. if (yt->kind == Type_Matrix) {
  3017. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3018. goto matrix_error;
  3019. }
  3020. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3021. goto matrix_error;
  3022. }
  3023. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3024. goto matrix_error;
  3025. }
  3026. x->mode = Addressing_Value;
  3027. if (are_types_identical(xt, yt)) {
  3028. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3029. // prefer the named type
  3030. x->type = y->type;
  3031. }
  3032. } else {
  3033. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3034. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3035. }
  3036. goto matrix_success;
  3037. } else if (yt->kind == Type_Array) {
  3038. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3039. goto matrix_error;
  3040. }
  3041. if (xt->Matrix.column_count != yt->Array.count) {
  3042. goto matrix_error;
  3043. }
  3044. // Treat arrays as column vectors
  3045. x->mode = Addressing_Value;
  3046. if (xt->Matrix.row_count == yt->Array.count) {
  3047. x->type = y->type;
  3048. } else {
  3049. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3050. }
  3051. goto matrix_success;
  3052. }
  3053. }
  3054. if (!are_types_identical(xt, yt)) {
  3055. goto matrix_error;
  3056. }
  3057. x->mode = Addressing_Value;
  3058. x->type = xt;
  3059. goto matrix_success;
  3060. } else {
  3061. GB_ASSERT(!is_type_matrix(xt));
  3062. GB_ASSERT(is_type_matrix(yt));
  3063. if (op.kind == Token_Mul) {
  3064. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3065. if (xt->kind == Type_Array) {
  3066. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3067. goto matrix_error;
  3068. }
  3069. if (xt->Array.count != yt->Matrix.row_count) {
  3070. goto matrix_error;
  3071. }
  3072. // Treat arrays as row vectors
  3073. x->mode = Addressing_Value;
  3074. if (yt->Matrix.column_count == xt->Array.count) {
  3075. x->type = x->type;
  3076. } else {
  3077. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3078. }
  3079. goto matrix_success;
  3080. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3081. x->type = check_matrix_type_hint(y->type, type_hint);
  3082. return;
  3083. }
  3084. }
  3085. if (!are_types_identical(xt, yt)) {
  3086. goto matrix_error;
  3087. }
  3088. x->mode = Addressing_Value;
  3089. x->type = xt;
  3090. goto matrix_success;
  3091. }
  3092. matrix_success:
  3093. x->type = check_matrix_type_hint(x->type, type_hint);
  3094. return;
  3095. matrix_error:
  3096. gbString xts = type_to_string(x->type);
  3097. gbString yts = type_to_string(y->type);
  3098. gbString expr_str = expr_to_string(x->expr);
  3099. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3100. gb_string_free(expr_str);
  3101. gb_string_free(yts);
  3102. gb_string_free(xts);
  3103. x->type = t_invalid;
  3104. x->mode = Addressing_Invalid;
  3105. return;
  3106. }
  3107. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3108. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3109. Operand y_ = {}, *y = &y_;
  3110. ast_node(be, BinaryExpr, node);
  3111. defer({
  3112. node->viral_state_flags |= be->left->viral_state_flags;
  3113. node->viral_state_flags |= be->right->viral_state_flags;
  3114. });
  3115. Token op = be->op;
  3116. switch (op.kind) {
  3117. case Token_CmpEq:
  3118. case Token_NotEq: {
  3119. // NOTE(bill): Allow comparisons between types
  3120. if (is_ise_expr(be->left)) {
  3121. // Evalute the right before the left for an '.X' expression
  3122. check_expr_or_type(c, y, be->right, type_hint);
  3123. check_expr_or_type(c, x, be->left, y->type);
  3124. } else {
  3125. check_expr_or_type(c, x, be->left, type_hint);
  3126. check_expr_or_type(c, y, be->right, x->type);
  3127. }
  3128. bool xt = x->mode == Addressing_Type;
  3129. bool yt = y->mode == Addressing_Type;
  3130. // If only one is a type, this is an error
  3131. if (xt ^ yt) {
  3132. GB_ASSERT(xt != yt);
  3133. if (xt) {
  3134. if (!is_type_typeid(y->type)) {
  3135. error_operand_not_expression(x);
  3136. }
  3137. }
  3138. if (yt) {
  3139. if (!is_type_typeid(x->type)) {
  3140. error_operand_not_expression(y);
  3141. }
  3142. }
  3143. }
  3144. break;
  3145. }
  3146. case Token_in:
  3147. case Token_not_in:
  3148. {
  3149. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3150. check_expr(c, y, be->right);
  3151. Type *rhs_type = type_deref(y->type);
  3152. if (is_type_bit_set(rhs_type)) {
  3153. Type *elem = base_type(rhs_type)->BitSet.elem;
  3154. check_expr_with_type_hint(c, x, be->left, elem);
  3155. } else if (is_type_map(rhs_type)) {
  3156. Type *key = base_type(rhs_type)->Map.key;
  3157. check_expr_with_type_hint(c, x, be->left, key);
  3158. } else {
  3159. check_expr(c, x, be->left);
  3160. }
  3161. if (x->mode == Addressing_Invalid) {
  3162. return;
  3163. }
  3164. if (y->mode == Addressing_Invalid) {
  3165. x->mode = Addressing_Invalid;
  3166. x->expr = y->expr;
  3167. return;
  3168. }
  3169. if (is_type_map(rhs_type)) {
  3170. Type *yt = base_type(rhs_type);
  3171. if (op.kind == Token_in) {
  3172. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3173. } else {
  3174. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3175. }
  3176. add_map_get_dependencies(c);
  3177. } else if (is_type_bit_set(rhs_type)) {
  3178. Type *yt = base_type(rhs_type);
  3179. if (op.kind == Token_in) {
  3180. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3181. } else {
  3182. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3183. }
  3184. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3185. ExactValue k = exact_value_to_integer(x->value);
  3186. ExactValue v = exact_value_to_integer(y->value);
  3187. GB_ASSERT(k.kind == ExactValue_Integer);
  3188. GB_ASSERT(v.kind == ExactValue_Integer);
  3189. i64 key = big_int_to_i64(&k.value_integer);
  3190. i64 lower = yt->BitSet.lower;
  3191. i64 upper = yt->BitSet.upper;
  3192. if (lower <= key && key <= upper) {
  3193. i64 bit = 1ll<<key;
  3194. i64 bits = big_int_to_i64(&v.value_integer);
  3195. x->mode = Addressing_Constant;
  3196. x->type = t_untyped_bool;
  3197. if (op.kind == Token_in) {
  3198. x->value = exact_value_bool((bit & bits) != 0);
  3199. } else {
  3200. x->value = exact_value_bool((bit & bits) == 0);
  3201. }
  3202. x->expr = node;
  3203. return;
  3204. } else {
  3205. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3206. x->mode = Addressing_Invalid;
  3207. }
  3208. }
  3209. } else {
  3210. gbString t = type_to_string(y->type);
  3211. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3212. gb_string_free(t);
  3213. x->expr = node;
  3214. x->mode = Addressing_Invalid;
  3215. return;
  3216. }
  3217. if (x->mode != Addressing_Invalid) {
  3218. x->mode = Addressing_Value;
  3219. x->type = t_untyped_bool;
  3220. }
  3221. x->expr = node;
  3222. return;
  3223. }
  3224. default:
  3225. if (is_ise_expr(be->left)) {
  3226. // Evalute the right before the left for an '.X' expression
  3227. check_expr_or_type(c, y, be->right, type_hint);
  3228. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3229. check_expr_or_type(c, x, be->left, y->type);
  3230. } else {
  3231. check_expr_with_type_hint(c, x, be->left, type_hint);
  3232. }
  3233. } else {
  3234. check_expr_with_type_hint(c, x, be->left, type_hint);
  3235. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3236. check_expr_with_type_hint(c, y, be->right, x->type);
  3237. } else {
  3238. check_expr_with_type_hint(c, y, be->right, type_hint);
  3239. }
  3240. }
  3241. break;
  3242. }
  3243. if (x->mode == Addressing_Invalid) {
  3244. return;
  3245. }
  3246. if (y->mode == Addressing_Invalid) {
  3247. x->mode = Addressing_Invalid;
  3248. x->expr = y->expr;
  3249. return;
  3250. }
  3251. if (x->mode == Addressing_Builtin) {
  3252. x->mode = Addressing_Invalid;
  3253. error(x->expr, "built-in expression in binary expression");
  3254. return;
  3255. }
  3256. if (y->mode == Addressing_Builtin) {
  3257. x->mode = Addressing_Invalid;
  3258. error(y->expr, "built-in expression in binary expression");
  3259. return;
  3260. }
  3261. if (x->mode == Addressing_ProcGroup) {
  3262. x->mode = Addressing_Invalid;
  3263. if (x->proc_group != nullptr) {
  3264. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3265. } else {
  3266. error(x->expr, "procedure group used in binary expression");
  3267. }
  3268. return;
  3269. }
  3270. if (y->mode == Addressing_ProcGroup) {
  3271. x->mode = Addressing_Invalid;
  3272. if (x->proc_group != nullptr) {
  3273. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3274. } else {
  3275. error(y->expr, "procedure group used in binary expression");
  3276. }
  3277. return;
  3278. }
  3279. if (token_is_shift(op.kind)) {
  3280. check_shift(c, x, y, node, type_hint);
  3281. return;
  3282. }
  3283. switch (op.kind) {
  3284. case Token_Quo:
  3285. case Token_Mod:
  3286. case Token_ModMod:
  3287. case Token_QuoEq:
  3288. case Token_ModEq:
  3289. case Token_ModModEq:
  3290. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3291. is_type_float(x->type) && is_type_untyped(x->type)) {
  3292. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3293. gbString t = type_to_string(y->type);
  3294. if (x->value.kind != ExactValue_Invalid) {
  3295. gbString s = exact_value_to_string(x->value);
  3296. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3297. gb_string_free(s);
  3298. } else {
  3299. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3300. }
  3301. gb_string_free(t);
  3302. }
  3303. break;
  3304. }
  3305. convert_to_typed(c, x, y->type);
  3306. if (x->mode == Addressing_Invalid) {
  3307. return;
  3308. }
  3309. convert_to_typed(c, y, x->type);
  3310. if (y->mode == Addressing_Invalid) {
  3311. x->mode = Addressing_Invalid;
  3312. return;
  3313. }
  3314. if (token_is_comparison(op.kind)) {
  3315. check_comparison(c, node, x, y, op.kind);
  3316. return;
  3317. }
  3318. if (check_binary_array_expr(c, op, x, y)) {
  3319. x->mode = Addressing_Value;
  3320. x->type = x->type;
  3321. return;
  3322. }
  3323. if (check_binary_array_expr(c, op, y, x)) {
  3324. x->mode = Addressing_Value;
  3325. x->type = y->type;
  3326. return;
  3327. }
  3328. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3329. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3330. x->expr = node;
  3331. return;
  3332. }
  3333. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3334. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3335. // NOTE(bill, 2022-06-26)
  3336. // Allow any boolean types within `&&` and `||`
  3337. // This is an exception to all other binary expressions since the result
  3338. // of a comparison will always be an untyped boolean, and allowing
  3339. // any boolean between these two simplifies a lot of expressions
  3340. } else if (!are_types_identical(x->type, y->type)) {
  3341. if (x->type != t_invalid &&
  3342. y->type != t_invalid) {
  3343. gbString xt = type_to_string(x->type);
  3344. gbString yt = type_to_string(y->type);
  3345. gbString expr_str = expr_to_string(node);
  3346. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3347. gb_string_free(expr_str);
  3348. gb_string_free(yt);
  3349. gb_string_free(xt);
  3350. }
  3351. x->mode = Addressing_Invalid;
  3352. return;
  3353. }
  3354. if (!check_binary_op(c, x, op)) {
  3355. x->mode = Addressing_Invalid;
  3356. return;
  3357. }
  3358. switch (op.kind) {
  3359. case Token_Quo:
  3360. case Token_Mod:
  3361. case Token_ModMod:
  3362. case Token_QuoEq:
  3363. case Token_ModEq:
  3364. case Token_ModModEq:
  3365. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3366. y->mode == Addressing_Constant) {
  3367. bool fail = false;
  3368. switch (y->value.kind) {
  3369. case ExactValue_Integer:
  3370. if (big_int_is_zero(&y->value.value_integer)) {
  3371. fail = true;
  3372. }
  3373. break;
  3374. case ExactValue_Float:
  3375. if (y->value.value_float == 0.0) {
  3376. fail = true;
  3377. }
  3378. break;
  3379. }
  3380. if (fail) {
  3381. error(y->expr, "Division by zero not allowed");
  3382. x->mode = Addressing_Invalid;
  3383. return;
  3384. }
  3385. }
  3386. break;
  3387. case Token_CmpAnd:
  3388. case Token_CmpOr:
  3389. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3390. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3391. }
  3392. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3393. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3394. }
  3395. break;
  3396. }
  3397. if (x->mode == Addressing_Constant &&
  3398. y->mode == Addressing_Constant) {
  3399. ExactValue a = x->value;
  3400. ExactValue b = y->value;
  3401. if (!is_type_constant_type(x->type)) {
  3402. x->mode = Addressing_Value;
  3403. return;
  3404. }
  3405. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3406. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3407. }
  3408. if (is_type_bit_set(x->type)) {
  3409. switch (op.kind) {
  3410. case Token_Add: op.kind = Token_Or; break;
  3411. case Token_Sub: op.kind = Token_AndNot; break;
  3412. }
  3413. }
  3414. x->value = exact_binary_operator_value(op.kind, a, b);
  3415. if (is_type_typed(x->type)) {
  3416. if (node != nullptr) {
  3417. x->expr = node;
  3418. }
  3419. check_is_expressible(c, x, x->type);
  3420. }
  3421. return;
  3422. } else if (is_type_string(x->type)) {
  3423. error(node, "String concatenation is only allowed with constant strings");
  3424. x->mode = Addressing_Invalid;
  3425. return;
  3426. }
  3427. bool REQUIRE = true;
  3428. Type *bt = base_type(x->type);
  3429. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3430. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3431. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3432. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3433. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3434. }
  3435. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3436. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3437. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3438. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3439. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3440. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3441. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3442. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3443. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3444. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3445. }
  3446. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3447. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3448. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3449. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3450. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3451. case Basic_u128:
  3452. case Basic_i128:
  3453. if (is_arch_wasm()) {
  3454. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3455. }
  3456. break;
  3457. }
  3458. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3459. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3460. case Basic_u128:
  3461. case Basic_i128:
  3462. if (is_arch_wasm()) {
  3463. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3464. }
  3465. break;
  3466. }
  3467. }
  3468. x->mode = Addressing_Value;
  3469. }
  3470. gb_internal Operand make_operand_from_node(Ast *node) {
  3471. GB_ASSERT(node != nullptr);
  3472. Operand x = {};
  3473. x.expr = node;
  3474. x.mode = node->tav.mode;
  3475. x.type = node->tav.type;
  3476. x.value = node->tav.value;
  3477. return x;
  3478. }
  3479. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3480. GB_ASSERT(e != nullptr);
  3481. ExprInfo *old = check_get_expr_info(c, e);
  3482. if (old == nullptr) {
  3483. if (type != nullptr && type != t_invalid) {
  3484. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3485. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3486. if (e->kind == Ast_TernaryIfExpr) {
  3487. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3488. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3489. }
  3490. }
  3491. }
  3492. return;
  3493. }
  3494. switch (e->kind) {
  3495. case_ast_node(ue, UnaryExpr, e);
  3496. if (old->value.kind != ExactValue_Invalid) {
  3497. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3498. // They don't need to be updated as they will be updated later and
  3499. // checked at the end of general checking stage.
  3500. break;
  3501. }
  3502. update_untyped_expr_type(c, ue->expr, type, final);
  3503. case_end;
  3504. case_ast_node(be, BinaryExpr, e);
  3505. if (old->value.kind != ExactValue_Invalid) {
  3506. // See above note in UnaryExpr case
  3507. break;
  3508. }
  3509. if (token_is_comparison(be->op.kind)) {
  3510. // NOTE(bill): Do nothing as the types are fine
  3511. } else if (token_is_shift(be->op.kind)) {
  3512. update_untyped_expr_type(c, be->left, type, final);
  3513. } else {
  3514. update_untyped_expr_type(c, be->left, type, final);
  3515. update_untyped_expr_type(c, be->right, type, final);
  3516. }
  3517. case_end;
  3518. case_ast_node(te, TernaryIfExpr, e);
  3519. if (old->value.kind != ExactValue_Invalid) {
  3520. // See above note in UnaryExpr case
  3521. break;
  3522. }
  3523. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3524. // having an untyped value
  3525. Operand x = make_operand_from_node(te->x);
  3526. Operand y = make_operand_from_node(te->y);
  3527. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3528. update_untyped_expr_type(c, te->x, type, final);
  3529. }
  3530. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3531. update_untyped_expr_type(c, te->y, type, final);
  3532. }
  3533. case_end;
  3534. case_ast_node(te, TernaryWhenExpr, e);
  3535. if (old->value.kind != ExactValue_Invalid) {
  3536. // See above note in UnaryExpr case
  3537. break;
  3538. }
  3539. update_untyped_expr_type(c, te->x, type, final);
  3540. update_untyped_expr_type(c, te->y, type, final);
  3541. case_end;
  3542. case_ast_node(ore, OrReturnExpr, e);
  3543. if (old->value.kind != ExactValue_Invalid) {
  3544. // See above note in UnaryExpr case
  3545. break;
  3546. }
  3547. update_untyped_expr_type(c, ore->expr, type, final);
  3548. case_end;
  3549. case_ast_node(obe, OrBranchExpr, e);
  3550. if (old->value.kind != ExactValue_Invalid) {
  3551. // See above note in UnaryExpr case
  3552. break;
  3553. }
  3554. update_untyped_expr_type(c, obe->expr, type, final);
  3555. case_end;
  3556. case_ast_node(oee, OrElseExpr, e);
  3557. if (old->value.kind != ExactValue_Invalid) {
  3558. // See above note in UnaryExpr case
  3559. break;
  3560. }
  3561. update_untyped_expr_type(c, oee->x, type, final);
  3562. update_untyped_expr_type(c, oee->y, type, final);
  3563. case_end;
  3564. case_ast_node(pe, ParenExpr, e);
  3565. update_untyped_expr_type(c, pe->expr, type, final);
  3566. case_end;
  3567. }
  3568. if (!final && is_type_untyped(type)) {
  3569. old->type = base_type(type);
  3570. return;
  3571. }
  3572. // We need to remove it and then give it a new one
  3573. check_remove_expr_info(c, e);
  3574. if (old->is_lhs && !is_type_integer(type)) {
  3575. gbString expr_str = expr_to_string(e);
  3576. gbString type_str = type_to_string(type);
  3577. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3578. gb_string_free(type_str);
  3579. gb_string_free(expr_str);
  3580. return;
  3581. }
  3582. add_type_and_value(c, e, old->mode, type, old->value);
  3583. }
  3584. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3585. GB_ASSERT(e != nullptr);
  3586. ExprInfo *found = check_get_expr_info(c, e);
  3587. if (found) {
  3588. found->value = value;
  3589. }
  3590. }
  3591. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type) {
  3592. gbString expr_str = expr_to_string(operand->expr);
  3593. gbString type_str = type_to_string(target_type);
  3594. gbString from_type_str = type_to_string(operand->type);
  3595. char const *extra_text = "";
  3596. if (operand->mode == Addressing_Constant) {
  3597. if (big_int_is_zero(&operand->value.value_integer)) {
  3598. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3599. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3600. extra_text = " - Did you want 'nil'?";
  3601. }
  3602. }
  3603. }
  3604. ERROR_BLOCK();
  3605. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3606. if (operand->value.kind == ExactValue_String) {
  3607. String key = operand->value.value_string;
  3608. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3609. Type *et = base_type(target_type);
  3610. check_did_you_mean_type(key, et->Enum.fields, ".");
  3611. }
  3612. }
  3613. gb_string_free(from_type_str);
  3614. gb_string_free(type_str);
  3615. gb_string_free(expr_str);
  3616. operand->mode = Addressing_Invalid;
  3617. }
  3618. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3619. Type *t = core_type(type);
  3620. if (is_type_boolean(t)) {
  3621. // v = exact_value_to_boolean(v);
  3622. } else if (is_type_float(t)) {
  3623. v = exact_value_to_float(v);
  3624. } else if (is_type_integer(t)) {
  3625. v = exact_value_to_integer(v);
  3626. } else if (is_type_pointer(t)) {
  3627. v = exact_value_to_integer(v);
  3628. } else if (is_type_complex(t)) {
  3629. v = exact_value_to_complex(v);
  3630. } else if (is_type_quaternion(t)) {
  3631. v = exact_value_to_quaternion(v);
  3632. }
  3633. return v;
  3634. }
  3635. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3636. GB_ASSERT_NOT_NULL(target_type);
  3637. if (operand->mode == Addressing_Invalid ||
  3638. operand->mode == Addressing_Type ||
  3639. is_type_typed(operand->type) ||
  3640. target_type == t_invalid) {
  3641. return;
  3642. }
  3643. if (is_type_untyped(target_type)) {
  3644. GB_ASSERT(operand->type->kind == Type_Basic);
  3645. GB_ASSERT(target_type->kind == Type_Basic);
  3646. BasicKind x_kind = operand->type->Basic.kind;
  3647. BasicKind y_kind = target_type->Basic.kind;
  3648. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3649. if (x_kind < y_kind) {
  3650. operand->type = target_type;
  3651. update_untyped_expr_type(c, operand->expr, target_type, false);
  3652. }
  3653. } else if (x_kind != y_kind) {
  3654. operand->mode = Addressing_Invalid;
  3655. convert_untyped_error(c, operand, target_type);
  3656. return;
  3657. }
  3658. return;
  3659. }
  3660. Type *t = base_type(target_type);
  3661. if (c->in_enum_type) {
  3662. t = core_type(target_type);
  3663. }
  3664. switch (t->kind) {
  3665. case Type_Basic:
  3666. if (operand->mode == Addressing_Constant) {
  3667. check_is_expressible(c, operand, t);
  3668. if (operand->mode == Addressing_Invalid) {
  3669. return;
  3670. }
  3671. update_untyped_expr_value(c, operand->expr, operand->value);
  3672. } else {
  3673. switch (operand->type->Basic.kind) {
  3674. case Basic_UntypedBool:
  3675. if (!is_type_boolean(target_type)) {
  3676. operand->mode = Addressing_Invalid;
  3677. convert_untyped_error(c, operand, target_type);
  3678. return;
  3679. }
  3680. break;
  3681. case Basic_UntypedInteger:
  3682. case Basic_UntypedFloat:
  3683. case Basic_UntypedComplex:
  3684. case Basic_UntypedQuaternion:
  3685. case Basic_UntypedRune:
  3686. if (!is_type_numeric(target_type)) {
  3687. operand->mode = Addressing_Invalid;
  3688. convert_untyped_error(c, operand, target_type);
  3689. return;
  3690. }
  3691. break;
  3692. case Basic_UntypedNil:
  3693. if (is_type_any(target_type)) {
  3694. // target_type = t_untyped_nil;
  3695. } else if (is_type_cstring(target_type)) {
  3696. // target_type = t_untyped_nil;
  3697. } else if (!type_has_nil(target_type)) {
  3698. operand->mode = Addressing_Invalid;
  3699. convert_untyped_error(c, operand, target_type);
  3700. return;
  3701. }
  3702. break;
  3703. }
  3704. }
  3705. break;
  3706. case Type_Array: {
  3707. Type *elem = base_array_type(t);
  3708. if (check_is_assignable_to(c, operand, elem)) {
  3709. operand->mode = Addressing_Value;
  3710. } else {
  3711. if (operand->value.kind == ExactValue_String) {
  3712. String s = operand->value.value_string;
  3713. if (is_type_u8_array(t)) {
  3714. if (s.len == t->Array.count) {
  3715. break;
  3716. }
  3717. } else if (is_type_rune_array(t)) {
  3718. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  3719. if (rune_count == t->Array.count) {
  3720. break;
  3721. }
  3722. }
  3723. }
  3724. operand->mode = Addressing_Invalid;
  3725. convert_untyped_error(c, operand, target_type);
  3726. return;
  3727. }
  3728. break;
  3729. }
  3730. case Type_Matrix: {
  3731. Type *elem = base_array_type(t);
  3732. if (check_is_assignable_to(c, operand, elem)) {
  3733. if (t->Matrix.row_count != t->Matrix.column_count) {
  3734. operand->mode = Addressing_Invalid;
  3735. ERROR_BLOCK();
  3736. convert_untyped_error(c, operand, target_type);
  3737. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  3738. return;
  3739. } else {
  3740. operand->mode = Addressing_Value;
  3741. }
  3742. } else {
  3743. operand->mode = Addressing_Invalid;
  3744. convert_untyped_error(c, operand, target_type);
  3745. return;
  3746. }
  3747. break;
  3748. }
  3749. case Type_Union:
  3750. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  3751. TEMPORARY_ALLOCATOR_GUARD();
  3752. isize count = t->Union.variants.count;
  3753. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  3754. isize valid_count = 0;
  3755. isize first_success_index = -1;
  3756. for_array(i, t->Union.variants) {
  3757. Type *vt = t->Union.variants[i];
  3758. i64 score = 0;
  3759. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  3760. valids[valid_count].index = i;
  3761. valids[valid_count].score = score;
  3762. valid_count += 1;
  3763. if (first_success_index < 0) {
  3764. first_success_index = i;
  3765. }
  3766. }
  3767. }
  3768. if (valid_count > 1) {
  3769. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  3770. i64 best_score = valids[0].score;
  3771. for (isize i = 1; i < valid_count; i++) {
  3772. auto v = valids[i];
  3773. if (best_score > v.score) {
  3774. valid_count = i;
  3775. break;
  3776. }
  3777. best_score = v.score;
  3778. }
  3779. first_success_index = valids[0].index;
  3780. }
  3781. gbString type_str = type_to_string(target_type);
  3782. defer (gb_string_free(type_str));
  3783. if (valid_count == 1) {
  3784. operand->mode = Addressing_Value;
  3785. operand->type = t->Union.variants[first_success_index];
  3786. target_type = t->Union.variants[first_success_index];
  3787. break;
  3788. } else if (valid_count > 1) {
  3789. ERROR_BLOCK();
  3790. GB_ASSERT(first_success_index >= 0);
  3791. operand->mode = Addressing_Invalid;
  3792. convert_untyped_error(c, operand, target_type);
  3793. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  3794. i32 j = 0;
  3795. for (i32 i = 0; i < valid_count; i++) {
  3796. ValidIndexAndScore valid = valids[i];
  3797. if (j > 0 && valid_count > 2) error_line(", ");
  3798. if (j == valid_count-1) {
  3799. if (valid_count == 2) error_line(" ");
  3800. error_line("or ");
  3801. }
  3802. gbString str = type_to_string(t->Union.variants[valid.index]);
  3803. error_line("'%s'", str);
  3804. gb_string_free(str);
  3805. j++;
  3806. }
  3807. error_line("\n\n");
  3808. return;
  3809. } else if (is_type_untyped_uninit(operand->type)) {
  3810. target_type = t_untyped_uninit;
  3811. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  3812. ERROR_BLOCK();
  3813. operand->mode = Addressing_Invalid;
  3814. convert_untyped_error(c, operand, target_type);
  3815. if (count > 0) {
  3816. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  3817. error_line("\t");
  3818. for (i32 i = 0; i < count; i++) {
  3819. Type *v = t->Union.variants[i];
  3820. if (i > 0 && count > 2) error_line(", ");
  3821. if (i == count-1) {
  3822. if (count == 2) error_line(" ");
  3823. if (count > 1) {
  3824. error_line("or ");
  3825. }
  3826. }
  3827. gbString str = type_to_string(v);
  3828. error_line("'%s'", str);
  3829. gb_string_free(str);
  3830. }
  3831. error_line("\n\n");
  3832. }
  3833. return;
  3834. }
  3835. }
  3836. /* fallthrough */
  3837. default:
  3838. if (is_type_untyped_uninit(operand->type)) {
  3839. target_type = t_untyped_uninit;
  3840. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  3841. target_type = t_untyped_nil;
  3842. } else {
  3843. operand->mode = Addressing_Invalid;
  3844. convert_untyped_error(c, operand, target_type);
  3845. return;
  3846. }
  3847. break;
  3848. }
  3849. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  3850. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  3851. } else {
  3852. target_type = default_type(operand->type);
  3853. }
  3854. }
  3855. update_untyped_expr_type(c, operand->expr, target_type, true);
  3856. operand->type = target_type;
  3857. }
  3858. 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) {
  3859. Operand operand = {Addressing_Invalid};
  3860. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  3861. if (operand.mode == Addressing_Invalid) {
  3862. if (value) *value = 0;
  3863. return false;
  3864. }
  3865. Type *index_type = t_int;
  3866. if (type_hint != nullptr) {
  3867. index_type = type_hint;
  3868. }
  3869. convert_to_typed(c, &operand, index_type);
  3870. if (operand.mode == Addressing_Invalid) {
  3871. if (value) *value = 0;
  3872. return false;
  3873. }
  3874. if (type_hint != nullptr) {
  3875. if (!check_is_assignable_to(c, &operand, type_hint)) {
  3876. gbString expr_str = expr_to_string(operand.expr);
  3877. gbString index_type_str = type_to_string(type_hint);
  3878. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  3879. gb_string_free(index_type_str);
  3880. gb_string_free(expr_str);
  3881. if (value) *value = 0;
  3882. return false;
  3883. }
  3884. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  3885. gbString expr_str = expr_to_string(operand.expr);
  3886. gbString type_str = type_to_string(operand.type);
  3887. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  3888. gb_string_free(type_str);
  3889. gb_string_free(expr_str);
  3890. if (value) *value = 0;
  3891. return false;
  3892. }
  3893. if (operand.mode == Addressing_Constant &&
  3894. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  3895. BigInt i = exact_value_to_integer(operand.value).value_integer;
  3896. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  3897. TEMPORARY_ALLOCATOR_GUARD();
  3898. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3899. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3900. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  3901. if (value) *value = 0;
  3902. return false;
  3903. }
  3904. if (max_count >= 0) {
  3905. if (is_type_enum(index_type)) {
  3906. Type *bt = base_type(index_type);
  3907. GB_ASSERT(bt->kind == Type_Enum);
  3908. ExactValue const &lo = *bt->Enum.min_value;
  3909. ExactValue const &hi = *bt->Enum.max_value;
  3910. String lo_str = {};
  3911. String hi_str = {};
  3912. if (bt->Enum.fields.count > 0) {
  3913. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  3914. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  3915. lo_str = bt->Enum.fields[lo_idx]->token.string;
  3916. hi_str = bt->Enum.fields[hi_idx]->token.string;
  3917. }
  3918. bool out_of_bounds = false;
  3919. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  3920. out_of_bounds = true;
  3921. }
  3922. if (out_of_bounds) {
  3923. gbString expr_str = expr_to_string(operand.expr);
  3924. if (lo_str.len > 0) {
  3925. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  3926. } else {
  3927. gbString index_type_str = type_to_string(index_type);
  3928. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  3929. gb_string_free(index_type_str);
  3930. }
  3931. gb_string_free(expr_str);
  3932. return false;
  3933. }
  3934. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  3935. return true;
  3936. } else { // NOTE(bill): Do array bound checking
  3937. i64 v = -1;
  3938. if (i.used <= 1) {
  3939. v = big_int_to_i64(&i);
  3940. }
  3941. if (value) *value = v;
  3942. bool out_of_bounds = false;
  3943. if (v < 0) {
  3944. out_of_bounds = true;
  3945. } else if (open_range) {
  3946. out_of_bounds = v > max_count;
  3947. } else {
  3948. out_of_bounds = v >= max_count;
  3949. }
  3950. if (out_of_bounds) {
  3951. TEMPORARY_ALLOCATOR_GUARD();
  3952. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3953. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3954. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  3955. return false;
  3956. }
  3957. return true;
  3958. }
  3959. } else {
  3960. if (value) *value = exact_value_to_i64(operand.value);
  3961. return true;
  3962. }
  3963. }
  3964. // NOTE(bill): It's alright :D
  3965. if (value) *value = -1;
  3966. return true;
  3967. }
  3968. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  3969. if (value.kind == ExactValue_String) {
  3970. GB_ASSERT(0 <= index && index < value.value_string.len);
  3971. u8 val = value.value_string[index];
  3972. if (success_) *success_ = true;
  3973. if (finish_) *finish_ = true;
  3974. return exact_value_u64(val);
  3975. }
  3976. if (value.kind != ExactValue_Compound) {
  3977. if (success_) *success_ = true;
  3978. if (finish_) *finish_ = true;
  3979. return value;
  3980. }
  3981. Ast *node = value.value_compound;
  3982. switch (node->kind) {
  3983. case_ast_node(cl, CompoundLit, node);
  3984. if (cl->elems.count == 0) {
  3985. if (success_) *success_ = true;
  3986. if (finish_) *finish_ = true;
  3987. return empty_exact_value;
  3988. }
  3989. if (cl->elems[0]->kind == Ast_FieldValue) {
  3990. if (is_type_struct(node->tav.type)) {
  3991. bool found = false;
  3992. for (Ast *elem : cl->elems) {
  3993. if (elem->kind != Ast_FieldValue) {
  3994. continue;
  3995. }
  3996. ast_node(fv, FieldValue, elem);
  3997. String name = fv->field->Ident.token.string;
  3998. Selection sub_sel = lookup_field(node->tav.type, name, false);
  3999. defer (array_free(&sub_sel.index));
  4000. if (sub_sel.index[0] == index) {
  4001. value = fv->value->tav.value;
  4002. found = true;
  4003. break;
  4004. }
  4005. }
  4006. if (!found) {
  4007. // Use the zero value if it is not found
  4008. value = {};
  4009. }
  4010. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4011. for (Ast *elem : cl->elems) {
  4012. if (elem->kind != Ast_FieldValue) {
  4013. continue;
  4014. }
  4015. ast_node(fv, FieldValue, elem);
  4016. if (is_ast_range(fv->field)) {
  4017. ast_node(ie, BinaryExpr, fv->field);
  4018. TypeAndValue lo_tav = ie->left->tav;
  4019. TypeAndValue hi_tav = ie->right->tav;
  4020. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4021. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4022. TokenKind op = ie->op.kind;
  4023. i64 lo = exact_value_to_i64(lo_tav.value);
  4024. i64 hi = exact_value_to_i64(hi_tav.value);
  4025. i64 corrected_index = index;
  4026. if (is_type_enumerated_array(node->tav.type)) {
  4027. Type *bt = base_type(node->tav.type);
  4028. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4029. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4030. }
  4031. if (op != Token_RangeHalf) {
  4032. if (lo <= corrected_index && corrected_index <= hi) {
  4033. TypeAndValue tav = fv->value->tav;
  4034. if (success_) *success_ = true;
  4035. if (finish_) *finish_ = false;
  4036. return tav.value;
  4037. }
  4038. } else {
  4039. if (lo <= corrected_index && corrected_index < hi) {
  4040. TypeAndValue tav = fv->value->tav;
  4041. if (success_) *success_ = true;
  4042. if (finish_) *finish_ = false;
  4043. return tav.value;
  4044. }
  4045. }
  4046. } else {
  4047. TypeAndValue index_tav = fv->field->tav;
  4048. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4049. ExactValue index_value = index_tav.value;
  4050. if (is_type_enumerated_array(node->tav.type)) {
  4051. Type *bt = base_type(node->tav.type);
  4052. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4053. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4054. }
  4055. i64 field_index = exact_value_to_i64(index_value);
  4056. if (index == field_index) {
  4057. TypeAndValue tav = fv->value->tav;
  4058. if (success_) *success_ = true;
  4059. if (finish_) *finish_ = false;
  4060. return tav.value;;
  4061. }
  4062. }
  4063. }
  4064. }
  4065. } else {
  4066. i32 count = (i32)cl->elems.count;
  4067. if (count < index) {
  4068. if (success_) *success_ = false;
  4069. if (finish_) *finish_ = true;
  4070. return empty_exact_value;
  4071. }
  4072. if (cl->elems.count <= index) {
  4073. if (success_) *success_ = false;
  4074. if (finish_) *finish_ = false;
  4075. return value;
  4076. }
  4077. TypeAndValue tav = cl->elems[index]->tav;
  4078. if (tav.mode == Addressing_Constant) {
  4079. if (success_) *success_ = true;
  4080. if (finish_) *finish_ = false;
  4081. return tav.value;
  4082. } else {
  4083. GB_ASSERT(is_type_untyped_nil(tav.type));
  4084. if (success_) *success_ = true;
  4085. if (finish_) *finish_ = false;
  4086. return tav.value;
  4087. }
  4088. }
  4089. case_end;
  4090. default:
  4091. if (success_) *success_ = true;
  4092. if (finish_) *finish_ = true;
  4093. return empty_exact_value;
  4094. }
  4095. if (finish_) *finish_ = false;
  4096. return value;
  4097. }
  4098. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4099. if (operand->mode != Addressing_Constant) {
  4100. if (success_) *success_ = false;
  4101. return empty_exact_value;
  4102. }
  4103. if (sel.indirect) {
  4104. if (success_) *success_ = false;
  4105. return empty_exact_value;
  4106. }
  4107. if (sel.index.count == 0) {
  4108. if (success_) *success_ = false;
  4109. return empty_exact_value;
  4110. }
  4111. ExactValue value = operand->value;
  4112. if (value.kind == ExactValue_Compound) {
  4113. while (sel.index.count > 0) {
  4114. i32 index = sel.index[0];
  4115. sel = sub_selection(sel, 1);
  4116. bool finish = false;
  4117. value = get_constant_field_single(c, value, index, success_, &finish);
  4118. if (finish) {
  4119. return value;
  4120. }
  4121. }
  4122. if (success_) *success_ = true;
  4123. return value;
  4124. } else if (value.kind == ExactValue_Quaternion) {
  4125. // @QuaternionLayout
  4126. Quaternion256 q = *value.value_quaternion;
  4127. GB_ASSERT(sel.index.count == 1);
  4128. switch (sel.index[0]) {
  4129. case 3: // w
  4130. if (success_) *success_ = true;
  4131. return exact_value_float(q.real);
  4132. case 0: // x
  4133. if (success_) *success_ = true;
  4134. return exact_value_float(q.imag);
  4135. case 1: // y
  4136. if (success_) *success_ = true;
  4137. return exact_value_float(q.jmag);
  4138. case 2: // z
  4139. if (success_) *success_ = true;
  4140. return exact_value_float(q.kmag);
  4141. }
  4142. if (success_) *success_ = false;
  4143. return empty_exact_value;
  4144. } else if (value.kind == ExactValue_Complex) {
  4145. // @QuaternionLayout
  4146. Complex128 c = *value.value_complex;
  4147. GB_ASSERT(sel.index.count == 1);
  4148. switch (sel.index[0]) {
  4149. case 0: // real
  4150. if (success_) *success_ = true;
  4151. return exact_value_float(c.real);
  4152. case 1: // imag
  4153. if (success_) *success_ = true;
  4154. return exact_value_float(c.imag);
  4155. }
  4156. if (success_) *success_ = false;
  4157. return empty_exact_value;
  4158. }
  4159. if (success_) *success_ = true;
  4160. return empty_exact_value;
  4161. }
  4162. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4163. Type *array_type = base_type(type_deref(original_type));
  4164. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4165. if (array_type->kind == Type_SimdVector) {
  4166. Type *elem_type = array_type->SimdVector.elem;
  4167. return alloc_type_simd_vector(new_count, elem_type);
  4168. }
  4169. Type *elem_type = array_type->Array.elem;
  4170. Type *swizzle_array_type = nullptr;
  4171. Type *bth = base_type(type_deref(type_hint));
  4172. if (bth != nullptr && bth->kind == Type_Array &&
  4173. bth->Array.count == new_count &&
  4174. are_types_identical(bth->Array.elem, elem_type)) {
  4175. swizzle_array_type = type_hint;
  4176. } else {
  4177. i64 max_count = array_type->Array.count;
  4178. if (new_count == max_count) {
  4179. swizzle_array_type = original_type;
  4180. } else {
  4181. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4182. }
  4183. }
  4184. return swizzle_array_type;
  4185. }
  4186. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4187. bool is_declared = entity != nullptr;
  4188. if (is_declared) {
  4189. if (entity->kind == Entity_Builtin) {
  4190. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4191. // This means that we should just ignore the found result through it
  4192. *allow_builtin = entity->scope == import_scope ||
  4193. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4194. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4195. is_declared = false;
  4196. }
  4197. }
  4198. return is_declared;
  4199. }
  4200. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4201. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4202. if (node->kind == Ast_Ident) {
  4203. String name = node->Ident.token.string;
  4204. return scope_lookup(c->scope, name);
  4205. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4206. ast_node(se, SelectorExpr, node);
  4207. if (se->token.kind == Token_ArrowRight) {
  4208. return nullptr;
  4209. }
  4210. Ast *op_expr = se->expr;
  4211. Ast *selector = unparen_expr(se->selector);
  4212. if (selector == nullptr) {
  4213. return nullptr;
  4214. }
  4215. if (selector->kind != Ast_Ident) {
  4216. return nullptr;
  4217. }
  4218. Entity *entity = nullptr;
  4219. Entity *expr_entity = nullptr;
  4220. bool check_op_expr = true;
  4221. if (op_expr->kind == Ast_Ident) {
  4222. String op_name = op_expr->Ident.token.string;
  4223. Entity *e = scope_lookup(c->scope, op_name);
  4224. if (e == nullptr) {
  4225. return nullptr;
  4226. }
  4227. add_entity_use(c, op_expr, e);
  4228. expr_entity = e;
  4229. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4230. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4231. // It pretty much needs to be in this order and this way
  4232. // If you can clean this up, please do but be really careful
  4233. String import_name = op_name;
  4234. Scope *import_scope = e->ImportName.scope;
  4235. String entity_name = selector->Ident.token.string;
  4236. check_op_expr = false;
  4237. entity = scope_lookup_current(import_scope, entity_name);
  4238. bool allow_builtin = false;
  4239. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4240. return nullptr;
  4241. }
  4242. check_entity_decl(c, entity, nullptr, nullptr);
  4243. if (entity->kind == Entity_ProcGroup) {
  4244. return entity;
  4245. }
  4246. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4247. }
  4248. }
  4249. Operand operand = {};
  4250. if (check_op_expr) {
  4251. check_expr_base(c, &operand, op_expr, nullptr);
  4252. if (operand.mode == Addressing_Invalid) {
  4253. return nullptr;
  4254. }
  4255. }
  4256. if (entity == nullptr && selector->kind == Ast_Ident) {
  4257. String field_name = selector->Ident.token.string;
  4258. if (is_type_dynamic_array(type_deref(operand.type))) {
  4259. init_mem_allocator(c->checker);
  4260. }
  4261. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4262. entity = sel.entity;
  4263. }
  4264. if (entity != nullptr) {
  4265. return entity;
  4266. }
  4267. }
  4268. return nullptr;
  4269. }
  4270. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4271. ast_node(se, SelectorExpr, node);
  4272. bool check_op_expr = true;
  4273. Entity *expr_entity = nullptr;
  4274. Entity *entity = nullptr;
  4275. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4276. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4277. error(node, "Illegal use of -> selector shorthand outside of a call");
  4278. operand->mode = Addressing_Invalid;
  4279. operand->expr = node;
  4280. return nullptr;
  4281. }
  4282. operand->expr = node;
  4283. Ast *op_expr = se->expr;
  4284. Ast *selector = unparen_expr(se->selector);
  4285. if (selector == nullptr) {
  4286. operand->mode = Addressing_Invalid;
  4287. operand->expr = node;
  4288. return nullptr;
  4289. }
  4290. if (selector->kind != Ast_Ident) {
  4291. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4292. operand->mode = Addressing_Invalid;
  4293. operand->expr = node;
  4294. return nullptr;
  4295. }
  4296. if (op_expr->kind == Ast_Ident) {
  4297. String op_name = op_expr->Ident.token.string;
  4298. Entity *e = scope_lookup(c->scope, op_name);
  4299. add_entity_use(c, op_expr, e);
  4300. expr_entity = e;
  4301. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4302. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4303. // It pretty much needs to be in this order and this way
  4304. // If you can clean this up, please do but be really careful
  4305. String import_name = op_name;
  4306. Scope *import_scope = e->ImportName.scope;
  4307. String entity_name = selector->Ident.token.string;
  4308. check_op_expr = false;
  4309. entity = scope_lookup_current(import_scope, entity_name);
  4310. bool allow_builtin = false;
  4311. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4312. ERROR_BLOCK();
  4313. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4314. operand->mode = Addressing_Invalid;
  4315. operand->expr = node;
  4316. check_did_you_mean_scope(entity_name, import_scope);
  4317. return nullptr;
  4318. }
  4319. check_entity_decl(c, entity, nullptr, nullptr);
  4320. if (entity->kind == Entity_ProcGroup) {
  4321. operand->mode = Addressing_ProcGroup;
  4322. operand->proc_group = entity;
  4323. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4324. return entity;
  4325. }
  4326. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4327. if (!is_entity_exported(entity, allow_builtin)) {
  4328. gbString sel_str = expr_to_string(selector);
  4329. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4330. gb_string_free(sel_str);
  4331. // NOTE(bill): make the state valid still, even if it's "invalid"
  4332. // operand->mode = Addressing_Invalid;
  4333. // operand->expr = node;
  4334. // return nullptr;
  4335. }
  4336. if (entity->kind == Entity_ProcGroup) {
  4337. Array<Entity *> procs = entity->ProcGroup.entities;
  4338. bool skip = false;
  4339. for (Entity *p : procs) {
  4340. Type *t = base_type(p->type);
  4341. if (t == t_invalid) {
  4342. continue;
  4343. }
  4344. Operand x = {};
  4345. x.mode = Addressing_Value;
  4346. x.type = t;
  4347. if (type_hint != nullptr) {
  4348. if (check_is_assignable_to(c, &x, type_hint)) {
  4349. entity = p;
  4350. skip = true;
  4351. break;
  4352. }
  4353. }
  4354. }
  4355. if (!skip) {
  4356. GB_ASSERT(entity != nullptr);
  4357. operand->mode = Addressing_ProcGroup;
  4358. operand->type = t_invalid;
  4359. operand->expr = node;
  4360. operand->proc_group = entity;
  4361. return entity;
  4362. }
  4363. }
  4364. }
  4365. }
  4366. if (check_op_expr) {
  4367. check_expr_base(c, operand, op_expr, nullptr);
  4368. if (operand->mode == Addressing_Invalid) {
  4369. operand->mode = Addressing_Invalid;
  4370. operand->expr = node;
  4371. return nullptr;
  4372. }
  4373. }
  4374. if (entity == nullptr && selector->kind == Ast_Ident) {
  4375. String field_name = selector->Ident.token.string;
  4376. Type *t = type_deref(operand->type);
  4377. if (t == nullptr) {
  4378. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4379. } else if (is_type_dynamic_array(t)) {
  4380. init_mem_allocator(c->checker);
  4381. }
  4382. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4383. entity = sel.entity;
  4384. // NOTE(bill): Add type info needed for fields like 'names'
  4385. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4386. add_type_info_type(c, operand->type);
  4387. }
  4388. if (is_type_enum(operand->type)) {
  4389. add_type_info_type(c, operand->type);
  4390. }
  4391. }
  4392. if (entity == nullptr && selector->kind == Ast_Ident && (is_type_array(type_deref(operand->type)) || is_type_simd_vector(type_deref(operand->type)))) {
  4393. String field_name = selector->Ident.token.string;
  4394. if (1 < field_name.len && field_name.len <= 4) {
  4395. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4396. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4397. bool found_xyzw = false;
  4398. bool found_rgba = false;
  4399. for (isize i = 0; i < field_name.len; i++) {
  4400. bool valid = false;
  4401. for (isize j = 0; j < 4; j++) {
  4402. if (field_name.text[i] == swizzles_xyzw[j]) {
  4403. found_xyzw = true;
  4404. valid = true;
  4405. break;
  4406. }
  4407. if (field_name.text[i] == swizzles_rgba[j]) {
  4408. found_rgba = true;
  4409. valid = true;
  4410. break;
  4411. }
  4412. }
  4413. if (!valid) {
  4414. goto end_of_array_selector_swizzle;
  4415. }
  4416. }
  4417. u8 *swizzles = nullptr;
  4418. u8 index_count = cast(u8)field_name.len;
  4419. if (found_xyzw && found_rgba) {
  4420. gbString op_str = expr_to_string(op_expr);
  4421. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4422. gb_string_free(op_str);
  4423. operand->mode = Addressing_Invalid;
  4424. operand->expr = node;
  4425. return nullptr;
  4426. }
  4427. u8 indices = 0;
  4428. if (found_xyzw) {
  4429. swizzles = swizzles_xyzw;
  4430. } else if (found_rgba) {
  4431. swizzles = swizzles_rgba;
  4432. }
  4433. for (isize i = 0; i < field_name.len; i++) {
  4434. for (isize j = 0; j < 4; j++) {
  4435. if (field_name.text[i] == swizzles[j]) {
  4436. indices |= cast(u8)(j)<<(i*2);
  4437. break;
  4438. }
  4439. }
  4440. }
  4441. Type *original_type = operand->type;
  4442. Type *array_type = base_type(type_deref(original_type));
  4443. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4444. i64 array_count = get_array_type_count(array_type);
  4445. for (u8 i = 0; i < index_count; i++) {
  4446. u8 idx = indices>>(i*2) & 3;
  4447. if (idx >= array_count) {
  4448. char c = 0;
  4449. if (found_xyzw) {
  4450. c = swizzles_xyzw[idx];
  4451. } else if (found_rgba) {
  4452. c = swizzles_rgba[idx];
  4453. } else {
  4454. GB_PANIC("unknown swizzle kind");
  4455. }
  4456. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4457. break;
  4458. }
  4459. }
  4460. se->swizzle_count = index_count;
  4461. se->swizzle_indices = indices;
  4462. AddressingMode prev_mode = operand->mode;
  4463. operand->mode = Addressing_SwizzleValue;
  4464. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4465. operand->expr = node;
  4466. switch (prev_mode) {
  4467. case Addressing_Variable:
  4468. case Addressing_SoaVariable:
  4469. case Addressing_SwizzleVariable:
  4470. operand->mode = Addressing_SwizzleVariable;
  4471. break;
  4472. }
  4473. if (array_type->kind == Type_SimdVector) {
  4474. operand->mode = Addressing_Value;
  4475. }
  4476. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4477. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4478. return swizzle_entity;
  4479. }
  4480. end_of_array_selector_swizzle:;
  4481. }
  4482. if (entity == nullptr) {
  4483. gbString op_str = expr_to_string(op_expr);
  4484. gbString type_str = type_to_string_shorthand(operand->type);
  4485. gbString sel_str = expr_to_string(selector);
  4486. if (operand->mode == Addressing_Type) {
  4487. if (is_type_polymorphic(operand->type, true)) {
  4488. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4489. } else {
  4490. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4491. }
  4492. } else {
  4493. ERROR_BLOCK();
  4494. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4495. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4496. String const &name = selector->Ident.token.string;
  4497. Type *bt = base_type(operand->type);
  4498. if (operand->type->kind == Type_Named &&
  4499. operand->type->Named.type_name &&
  4500. operand->type->Named.type_name->kind == Entity_TypeName &&
  4501. operand->type->Named.type_name->TypeName.objc_metadata) {
  4502. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4503. } else if (bt->kind == Type_Struct) {
  4504. check_did_you_mean_type(name, bt->Struct.fields);
  4505. } else if (bt->kind == Type_Enum) {
  4506. check_did_you_mean_type(name, bt->Enum.fields);
  4507. }
  4508. }
  4509. }
  4510. gb_string_free(sel_str);
  4511. gb_string_free(type_str);
  4512. gb_string_free(op_str);
  4513. operand->mode = Addressing_Invalid;
  4514. operand->expr = node;
  4515. return nullptr;
  4516. }
  4517. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4518. bool success = false;
  4519. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4520. if (success) {
  4521. operand->mode = Addressing_Constant;
  4522. operand->expr = node;
  4523. operand->value = field_value;
  4524. operand->type = entity->type;
  4525. add_entity_use(c, selector, entity);
  4526. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4527. return entity;
  4528. }
  4529. gbString op_str = expr_to_string(op_expr);
  4530. gbString type_str = type_to_string_shorthand(operand->type);
  4531. gbString sel_str = expr_to_string(selector);
  4532. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4533. gb_string_free(sel_str);
  4534. gb_string_free(type_str);
  4535. gb_string_free(op_str);
  4536. operand->mode = Addressing_Invalid;
  4537. operand->expr = node;
  4538. return nullptr;
  4539. }
  4540. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4541. bool success = false;
  4542. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4543. if (success) {
  4544. operand->mode = Addressing_Constant;
  4545. operand->expr = node;
  4546. operand->value = field_value;
  4547. operand->type = entity->type;
  4548. add_entity_use(c, selector, entity);
  4549. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4550. return entity;
  4551. }
  4552. gbString op_str = expr_to_string(op_expr);
  4553. gbString type_str = type_to_string_shorthand(operand->type);
  4554. gbString sel_str = expr_to_string(selector);
  4555. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4556. gb_string_free(sel_str);
  4557. gb_string_free(type_str);
  4558. gb_string_free(op_str);
  4559. operand->mode = Addressing_Invalid;
  4560. operand->expr = node;
  4561. return nullptr;
  4562. }
  4563. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4564. gbString op_str = expr_to_string(op_expr);
  4565. gbString type_str = type_to_string_shorthand(operand->type);
  4566. gbString sel_str = expr_to_string(selector);
  4567. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4568. gb_string_free(sel_str);
  4569. gb_string_free(type_str);
  4570. gb_string_free(op_str);
  4571. operand->mode = Addressing_Invalid;
  4572. operand->expr = node;
  4573. return nullptr;
  4574. }
  4575. add_entity_use(c, selector, entity);
  4576. operand->type = entity->type;
  4577. operand->expr = node;
  4578. if (entity->flags & EntityFlag_BitFieldField) {
  4579. add_package_dependency(c, "runtime", "__write_bits");
  4580. add_package_dependency(c, "runtime", "__read_bits");
  4581. }
  4582. switch (entity->kind) {
  4583. case Entity_Constant:
  4584. operand->value = entity->Constant.value;
  4585. operand->mode = Addressing_Constant;
  4586. if (operand->value.kind == ExactValue_Procedure) {
  4587. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4588. if (proc != nullptr) {
  4589. operand->mode = Addressing_Value;
  4590. operand->type = proc->type;
  4591. }
  4592. }
  4593. break;
  4594. case Entity_Variable:
  4595. if (sel.is_bit_field) {
  4596. se->is_bit_field = true;
  4597. }
  4598. if (sel.indirect) {
  4599. operand->mode = Addressing_Variable;
  4600. } else if (operand->mode == Addressing_Context) {
  4601. // Do nothing
  4602. } else if (operand->mode == Addressing_MapIndex) {
  4603. operand->mode = Addressing_Value;
  4604. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4605. operand->mode = Addressing_SoaVariable;
  4606. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4607. operand->mode = Addressing_Value;
  4608. } else if (operand->mode == Addressing_SoaVariable) {
  4609. operand->mode = Addressing_Variable;
  4610. } else if (operand->mode != Addressing_Value) {
  4611. operand->mode = Addressing_Variable;
  4612. } else {
  4613. operand->mode = Addressing_Value;
  4614. }
  4615. break;
  4616. case Entity_TypeName:
  4617. operand->mode = Addressing_Type;
  4618. break;
  4619. case Entity_Procedure:
  4620. operand->mode = Addressing_Value;
  4621. operand->value = exact_value_procedure(node);
  4622. break;
  4623. case Entity_Builtin:
  4624. operand->mode = Addressing_Builtin;
  4625. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  4626. break;
  4627. case Entity_ProcGroup:
  4628. operand->mode = Addressing_ProcGroup;
  4629. operand->proc_group = entity;
  4630. break;
  4631. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  4632. case Entity_Nil:
  4633. operand->mode = Addressing_Value;
  4634. break;
  4635. }
  4636. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4637. return entity;
  4638. }
  4639. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  4640. ptr = base_type(ptr);
  4641. if (is_type_pointer(ptr)) {
  4642. if (is_type_rawptr(ptr)) {
  4643. return false;
  4644. }
  4645. if (elem) *elem = ptr->Pointer.elem;
  4646. return true;
  4647. }
  4648. return false;
  4649. }
  4650. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  4651. elem = core_type(elem);
  4652. if (is_type_internally_pointer_like(elem)) {
  4653. return true;
  4654. }
  4655. if (elem->kind == Type_BitSet) {
  4656. elem = bit_set_to_int(elem);
  4657. }
  4658. if (elem->kind != Type_Basic) {
  4659. return false;
  4660. }
  4661. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  4662. }
  4663. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  4664. switch (node->kind) {
  4665. case_ast_node(i, Ident, node);
  4666. String name = i->token.string;
  4667. if (nested) {
  4668. Entity *e = scope_lookup_current(s, name);
  4669. if (e != nullptr) {
  4670. if (out_scope) *out_scope = e->scope;
  4671. return true;
  4672. }
  4673. } else {
  4674. Entity *e = scope_lookup(s, name);
  4675. if (e != nullptr) {
  4676. if (out_scope) *out_scope = e->scope;
  4677. return true;
  4678. }
  4679. }
  4680. case_end;
  4681. case_ast_node(se, SelectorExpr, node);
  4682. Ast *lhs = se->expr;
  4683. Ast *rhs = se->selector;
  4684. Scope *lhs_scope = nullptr;
  4685. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  4686. return check_identifier_exists(lhs_scope, rhs, true);
  4687. }
  4688. case_end;
  4689. }
  4690. return false;
  4691. }
  4692. gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) {
  4693. if (o.type && is_type_no_copy(o.type)) {
  4694. Ast *expr = unparen_expr(o.expr);
  4695. if (expr && o.mode != Addressing_Constant) {
  4696. if (expr->kind == Ast_CallExpr) {
  4697. // Okay
  4698. } else {
  4699. error(o.expr, "Invalid use of #no_copy value in %.*s", LIT(context));
  4700. return true;
  4701. }
  4702. }
  4703. }
  4704. return false;
  4705. }
  4706. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  4707. bool optional_ok = false;
  4708. isize tuple_index = 0;
  4709. for (Ast *rhs_expr : rhs) {
  4710. CheckerContext c_ = *ctx;
  4711. CheckerContext *c = &c_;
  4712. Operand o = {};
  4713. Type *type_hint = nullptr;
  4714. if (tuple_index < lhs.count) {
  4715. type_hint = lhs[tuple_index].type;
  4716. }
  4717. check_expr_base(c, &o, rhs_expr, type_hint);
  4718. if (o.mode == Addressing_NoValue) {
  4719. error_operand_no_value(&o);
  4720. o.mode = Addressing_Invalid;
  4721. }
  4722. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4723. if (lhs.count == 2 && rhs.count == 1 &&
  4724. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4725. Ast *expr = unparen_expr(o.expr);
  4726. Operand val0 = o;
  4727. Operand val1 = o;
  4728. val0.mode = Addressing_Value;
  4729. val1.mode = Addressing_Value;
  4730. val1.type = t_untyped_bool;
  4731. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4732. if (expr->kind == Ast_TypeAssertion &&
  4733. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4734. // NOTE(bill): Used only for optimizations in the backend
  4735. if (is_blank_ident(lhs[0].expr)) {
  4736. expr->TypeAssertion.ignores[0] = true;
  4737. }
  4738. if (is_blank_ident(lhs[1].expr)) {
  4739. expr->TypeAssertion.ignores[1] = true;
  4740. }
  4741. }
  4742. array_add(operands, val0);
  4743. array_add(operands, val1);
  4744. optional_ok = true;
  4745. tuple_index += 2;
  4746. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  4747. Type *tuple = o.type;
  4748. GB_ASSERT(tuple->Tuple.variables.count == 2);
  4749. Ast *expr = unparen_expr(o.expr);
  4750. if (expr->kind == Ast_CallExpr) {
  4751. expr->CallExpr.optional_ok_one = true;
  4752. }
  4753. Operand val = o;
  4754. val.type = tuple->Tuple.variables[0]->type;
  4755. val.mode = Addressing_Value;
  4756. array_add(operands, val);
  4757. tuple_index += tuple->Tuple.variables.count;
  4758. } else {
  4759. array_add(operands, o);
  4760. tuple_index += 1;
  4761. }
  4762. } else {
  4763. TypeTuple *tuple = &o.type->Tuple;
  4764. for (Entity *e : tuple->variables) {
  4765. o.type = e->type;
  4766. array_add(operands, o);
  4767. check_no_copy_assignment(o, str_lit("assignment"));
  4768. }
  4769. tuple_index += tuple->variables.count;
  4770. }
  4771. }
  4772. return optional_ok;
  4773. }
  4774. typedef u32 UnpackFlags;
  4775. enum UnpackFlag : u32 {
  4776. UnpackFlag_None = 0,
  4777. UnpackFlag_AllowOk = 1<<0,
  4778. UnpackFlag_IsVariadic = 1<<1,
  4779. UnpackFlag_AllowUndef = 1<<2,
  4780. };
  4781. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags) {
  4782. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  4783. if (lhs == nullptr || c->decl == nullptr) {
  4784. return tuple_count;
  4785. }
  4786. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  4787. Entity *e = lhs[tuple_index + j];
  4788. if (e == nullptr) {
  4789. continue;
  4790. }
  4791. DeclInfo *decl = decl_info_of_entity(e);
  4792. if (decl == nullptr) {
  4793. continue;
  4794. }
  4795. rw_mutex_shared_lock(&decl->deps_mutex);
  4796. rw_mutex_lock(&c->decl->deps_mutex);
  4797. for (Entity *dep : decl->deps) {
  4798. ptr_set_add(&c->decl->deps, dep);
  4799. }
  4800. rw_mutex_unlock(&c->decl->deps_mutex);
  4801. rw_mutex_shared_unlock(&decl->deps_mutex);
  4802. }
  4803. return tuple_count;
  4804. };
  4805. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  4806. bool is_variadic = (flags & UnpackFlag_IsVariadic) != 0;
  4807. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  4808. bool optional_ok = false;
  4809. isize tuple_index = 0;
  4810. for (Ast *rhs : rhs_arguments) {
  4811. if (rhs->kind == Ast_FieldValue) {
  4812. error(rhs, "Invalid use of 'field = value'");
  4813. rhs = rhs->FieldValue.value;
  4814. }
  4815. CheckerContext c_ = *ctx;
  4816. CheckerContext *c = &c_;
  4817. Operand o = {};
  4818. Type *type_hint = nullptr;
  4819. if (lhs != nullptr && tuple_index < lhs_count) {
  4820. // NOTE(bill): override DeclInfo for dependency
  4821. Entity *e = lhs[tuple_index];
  4822. if (e != nullptr) {
  4823. type_hint = e->type;
  4824. if (e->flags & EntityFlag_Ellipsis) {
  4825. GB_ASSERT(is_type_slice(e->type));
  4826. GB_ASSERT(e->type->kind == Type_Slice);
  4827. type_hint = e->type->Slice.elem;
  4828. }
  4829. }
  4830. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  4831. // NOTE(bill): override DeclInfo for dependency
  4832. Entity *e = lhs[lhs_count-1];
  4833. if (e != nullptr) {
  4834. type_hint = e->type;
  4835. if (e->flags & EntityFlag_Ellipsis) {
  4836. GB_ASSERT(is_type_slice(e->type));
  4837. GB_ASSERT(e->type->kind == Type_Slice);
  4838. type_hint = e->type->Slice.elem;
  4839. }
  4840. }
  4841. }
  4842. Ast *rhs_expr = unparen_expr(rhs);
  4843. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  4844. // NOTE(bill): Just handle this very specific logic here
  4845. o.type = t_untyped_uninit;
  4846. o.mode = Addressing_Value;
  4847. o.expr = rhs;
  4848. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  4849. } else {
  4850. check_expr_base(c, &o, rhs, type_hint);
  4851. }
  4852. if (o.mode == Addressing_NoValue) {
  4853. error_operand_no_value(&o);
  4854. o.mode = Addressing_Invalid;
  4855. }
  4856. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4857. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  4858. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4859. Ast *expr = unparen_expr(o.expr);
  4860. Operand val0 = o;
  4861. Operand val1 = o;
  4862. val0.mode = Addressing_Value;
  4863. val1.mode = Addressing_Value;
  4864. val1.type = t_untyped_bool;
  4865. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4866. if (expr->kind == Ast_TypeAssertion &&
  4867. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4868. // NOTE(bill): Used only for optimizations in the backend
  4869. if (is_blank_ident(lhs[0]->token)) {
  4870. expr->TypeAssertion.ignores[0] = true;
  4871. }
  4872. if (is_blank_ident(lhs[1]->token)) {
  4873. expr->TypeAssertion.ignores[1] = true;
  4874. }
  4875. }
  4876. array_add(operands, val0);
  4877. array_add(operands, val1);
  4878. optional_ok = true;
  4879. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  4880. } else {
  4881. array_add(operands, o);
  4882. tuple_index += 1;
  4883. }
  4884. } else {
  4885. TypeTuple *tuple = &o.type->Tuple;
  4886. for (Entity *e : tuple->variables) {
  4887. o.type = e->type;
  4888. array_add(operands, o);
  4889. }
  4890. isize count = tuple->variables.count;
  4891. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  4892. }
  4893. }
  4894. return optional_ok;
  4895. }
  4896. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  4897. GB_ASSERT(pt != nullptr);
  4898. GB_ASSERT(pt->kind == Type_Proc);
  4899. isize param_count = 0;
  4900. isize param_count_excluding_defaults = 0;
  4901. bool variadic = pt->Proc.variadic;
  4902. TypeTuple *param_tuple = nullptr;
  4903. if (pt->Proc.params != nullptr) {
  4904. param_tuple = &pt->Proc.params->Tuple;
  4905. param_count = param_tuple->variables.count;
  4906. if (variadic) {
  4907. for (isize i = param_count-1; i >= 0; i--) {
  4908. Entity *e = param_tuple->variables[i];
  4909. if (e->kind == Entity_TypeName) {
  4910. break;
  4911. }
  4912. if (e->kind == Entity_Variable) {
  4913. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4914. param_count--;
  4915. continue;
  4916. }
  4917. }
  4918. break;
  4919. }
  4920. param_count--;
  4921. }
  4922. }
  4923. param_count_excluding_defaults = param_count;
  4924. if (param_tuple != nullptr) {
  4925. for (isize i = param_count-1; i >= 0; i--) {
  4926. Entity *e = param_tuple->variables[i];
  4927. if (e->kind == Entity_TypeName) {
  4928. break;
  4929. }
  4930. if (e->kind == Entity_Variable) {
  4931. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4932. param_count_excluding_defaults--;
  4933. continue;
  4934. }
  4935. }
  4936. break;
  4937. }
  4938. }
  4939. if (param_count_) *param_count_ = param_count;
  4940. return param_count_excluding_defaults;
  4941. }
  4942. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  4943. isize param_count = pt->param_count;
  4944. for (isize i = 0; i < param_count; i++) {
  4945. Entity *e = pt->params->Tuple.variables[i];
  4946. String name = e->token.string;
  4947. if (is_blank_ident(name)) {
  4948. continue;
  4949. }
  4950. if (name == parameter_name) {
  4951. return i;
  4952. }
  4953. }
  4954. return -1;
  4955. }
  4956. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  4957. type = base_type(type);
  4958. GB_ASSERT(type->kind == Type_Proc);
  4959. return lookup_procedure_parameter(&type->Proc, parameter_name);
  4960. }
  4961. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  4962. Entity *entity, Type *proc_type,
  4963. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  4964. CallArgumentErrorMode show_error_mode,
  4965. CallArgumentData *data) {
  4966. TEMPORARY_ALLOCATOR_GUARD();
  4967. CallArgumentError err = CallArgumentError_None;
  4968. ast_node(ce, CallExpr, call);
  4969. GB_ASSERT(is_type_proc(proc_type));
  4970. proc_type = base_type(proc_type);
  4971. TypeProc *pt = &proc_type->Proc;
  4972. isize param_count = 0;
  4973. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  4974. bool variadic = pt->variadic;
  4975. bool vari_expand = (ce->ellipsis.pos.line != 0);
  4976. i64 score = 0;
  4977. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  4978. Type *final_proc_type = proc_type;
  4979. Entity *gen_entity = nullptr;
  4980. if (vari_expand && !variadic) {
  4981. if (show_error) {
  4982. error(ce->ellipsis,
  4983. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  4984. LIT(ce->proc->Ident.token.string));
  4985. }
  4986. err = CallArgumentError_NonVariadicExpand;
  4987. } else if (vari_expand && pt->c_vararg) {
  4988. if (show_error) {
  4989. error(ce->ellipsis,
  4990. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  4991. LIT(ce->proc->Ident.token.string));
  4992. }
  4993. err = CallArgumentError_NonVariadicExpand;
  4994. }
  4995. GB_ASSERT(ce->split_args);
  4996. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  4997. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  4998. defer ({
  4999. for (Operand const &o : ordered_operands) {
  5000. if (o.expr != nullptr) {
  5001. call->viral_state_flags |= o.expr->viral_state_flags;
  5002. }
  5003. }
  5004. });
  5005. isize positional_operand_count = positional_operands.count;
  5006. if (variadic) {
  5007. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5008. } else if (positional_operand_count > pt->param_count) {
  5009. err = CallArgumentError_TooManyArguments;
  5010. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5011. if (show_error) {
  5012. gbString proc_str = expr_to_string(ce->proc);
  5013. defer (gb_string_free(proc_str));
  5014. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5015. }
  5016. return err;
  5017. }
  5018. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5019. for (isize i = 0; i < positional_operand_count; i++) {
  5020. ordered_operands[i] = positional_operands[i];
  5021. visited[i] = true;
  5022. }
  5023. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5024. bool named_variadic_param = false;
  5025. if (named_operands.count != 0) {
  5026. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5027. for_array(i, ce->split_args->named) {
  5028. Ast *arg = ce->split_args->named[i];
  5029. Operand operand = named_operands[i];
  5030. ast_node(fv, FieldValue, arg);
  5031. if (fv->field->kind != Ast_Ident) {
  5032. if (show_error) {
  5033. gbString expr_str = expr_to_string(fv->field);
  5034. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5035. gb_string_free(expr_str);
  5036. }
  5037. err = CallArgumentError_InvalidFieldValue;
  5038. continue;
  5039. }
  5040. String name = fv->field->Ident.token.string;
  5041. isize param_index = lookup_procedure_parameter(pt, name);
  5042. if (param_index < 0) {
  5043. if (show_error) {
  5044. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5045. }
  5046. err = CallArgumentError_ParameterNotFound;
  5047. continue;
  5048. }
  5049. if (pt->variadic && param_index == pt->variadic_index) {
  5050. named_variadic_param = true;
  5051. }
  5052. if (visited[param_index]) {
  5053. if (show_error) {
  5054. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5055. }
  5056. err = CallArgumentError_DuplicateParameter;
  5057. continue;
  5058. }
  5059. visited[param_index] = true;
  5060. ordered_operands[param_index] = operand;
  5061. }
  5062. }
  5063. isize dummy_argument_count = 0;
  5064. bool actually_variadic = false;
  5065. if (variadic) {
  5066. if (visited[pt->variadic_index] &&
  5067. positional_operand_count < positional_operands.count) {
  5068. if (show_error) {
  5069. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5070. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5071. }
  5072. err = CallArgumentError_DuplicateParameter;
  5073. } else if (!visited[pt->variadic_index]) {
  5074. visited[pt->variadic_index] = true;
  5075. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5076. if (vari_expand) {
  5077. GB_ASSERT(variadic_operands.count != 0);
  5078. *variadic_operand = variadic_operands[0];
  5079. variadic_operand->type = default_type(variadic_operand->type);
  5080. actually_variadic = true;
  5081. } else {
  5082. AstFile *f = call->file();
  5083. // HACK(bill): this is an awful hack
  5084. Operand o = {};
  5085. o.mode = Addressing_Value;
  5086. o.expr = ast_ident(f, make_token_ident("nil"));
  5087. o.expr->Ident.token.pos = ast_token(call).pos;
  5088. if (variadic_operands.count != 0) {
  5089. actually_variadic = true;
  5090. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5091. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5092. o.type = vt->type;
  5093. } else {
  5094. dummy_argument_count += 1;
  5095. o.type = t_untyped_nil;
  5096. }
  5097. *variadic_operand = o;
  5098. }
  5099. }
  5100. }
  5101. for (Operand const &o : ordered_operands) {
  5102. if (o.mode != Addressing_Invalid) {
  5103. check_no_copy_assignment(o, str_lit("procedure call expression"));
  5104. }
  5105. }
  5106. for (isize i = 0; i < pt->param_count; i++) {
  5107. if (!visited[i]) {
  5108. Entity *e = pt->params->Tuple.variables[i];
  5109. if (e->kind == Entity_Variable) {
  5110. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5111. ordered_operands[i].mode = Addressing_Value;
  5112. ordered_operands[i].type = e->type;
  5113. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5114. dummy_argument_count += 1;
  5115. score += assign_score_function(1);
  5116. continue;
  5117. }
  5118. }
  5119. if (show_error) {
  5120. if (e->kind == Entity_TypeName) {
  5121. error(call, "Type parameter '%.*s' is missing in procedure call",
  5122. LIT(e->token.string));
  5123. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5124. // Ignore
  5125. } else {
  5126. gbString str = type_to_string(e->type);
  5127. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5128. LIT(e->token.string), str);
  5129. gb_string_free(str);
  5130. }
  5131. }
  5132. err = CallArgumentError_ParameterMissing;
  5133. }
  5134. }
  5135. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5136. i64 s = 0;
  5137. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic)) {
  5138. bool ok = false;
  5139. if (e && e->flags & EntityFlag_AnyInt) {
  5140. if (is_type_integer(param_type)) {
  5141. ok = check_is_castable_to(c, o, param_type);
  5142. }
  5143. }
  5144. if (ok) {
  5145. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5146. } else {
  5147. if (show_error) {
  5148. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5149. Type *src = base_type(o->type);
  5150. Type *dst = base_type(param_type);
  5151. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  5152. gbString a = expr_to_string(o->expr);
  5153. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  5154. gb_string_free(a);
  5155. }
  5156. }
  5157. err = CallArgumentError_WrongTypes;
  5158. }
  5159. } else if (show_error) {
  5160. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5161. }
  5162. if (e && e->flags & EntityFlag_ConstInput) {
  5163. if (o->mode != Addressing_Constant) {
  5164. if (show_error) {
  5165. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5166. }
  5167. err = CallArgumentError_NoneConstantParameter;
  5168. }
  5169. }
  5170. if (!err && is_type_any(param_type)) {
  5171. add_type_info_type(c, o->type);
  5172. }
  5173. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5174. add_type_info_type(c, o->type);
  5175. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5176. } else if (show_error && is_type_untyped(o->type)) {
  5177. update_untyped_expr_type(c, o->expr, param_type, true);
  5178. }
  5179. return s;
  5180. };
  5181. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5182. err = CallArgumentError_None;
  5183. if (variadic) {
  5184. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5185. Type *t = pt->params->Tuple.variables[0]->type;
  5186. if (is_type_polymorphic(t)) {
  5187. if (show_error) {
  5188. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5189. }
  5190. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5191. }
  5192. }
  5193. } else {
  5194. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5195. PolyProcData poly_proc_data = {};
  5196. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5197. gen_entity = poly_proc_data.gen_entity;
  5198. Type *gept = base_type(gen_entity->type);
  5199. GB_ASSERT(is_type_proc(gept));
  5200. final_proc_type = gen_entity->type;
  5201. pt = &gept->Proc;
  5202. } else {
  5203. err = CallArgumentError_WrongTypes;
  5204. }
  5205. }
  5206. for (isize i = 0; i < pt->param_count; i++) {
  5207. Operand *o = &ordered_operands[i];
  5208. if (o->mode == Addressing_Invalid) {
  5209. continue;
  5210. }
  5211. Entity *e = pt->params->Tuple.variables[i];
  5212. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5213. if (e->kind == Entity_TypeName) {
  5214. GB_ASSERT(pt->is_polymorphic);
  5215. if (o->mode != Addressing_Type) {
  5216. if (show_error) {
  5217. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5218. }
  5219. err = CallArgumentError_WrongTypes;
  5220. }
  5221. if (are_types_identical(e->type, o->type)) {
  5222. score += assign_score_function(1);
  5223. } else {
  5224. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5225. }
  5226. continue;
  5227. }
  5228. if (param_is_variadic) {
  5229. continue;
  5230. }
  5231. score += eval_param_and_score(c, o, e->type, err, param_is_variadic, e, show_error);
  5232. }
  5233. }
  5234. if (variadic) {
  5235. Type *slice = pt->params->Tuple.variables[pt->variadic_index]->type;
  5236. GB_ASSERT(is_type_slice(slice));
  5237. Type *elem = base_type(slice)->Slice.elem;
  5238. Type *t = elem;
  5239. if (is_type_polymorphic(t)) {
  5240. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5241. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5242. }
  5243. for_array(operand_index, variadic_operands) {
  5244. Operand *o = &variadic_operands[operand_index];
  5245. if (vari_expand) {
  5246. t = slice;
  5247. if (operand_index > 0) {
  5248. if (show_error) {
  5249. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5250. }
  5251. if (data) {
  5252. data->score = score;
  5253. data->result_type = final_proc_type->Proc.results;
  5254. data->gen_entity = gen_entity;
  5255. }
  5256. return CallArgumentError_MultipleVariadicExpand;
  5257. }
  5258. }
  5259. score += eval_param_and_score(c, o, t, err, true, nullptr, show_error);
  5260. }
  5261. }
  5262. if (data) {
  5263. data->score = score;
  5264. data->result_type = final_proc_type->Proc.results;
  5265. data->gen_entity = gen_entity;
  5266. Ast *proc_lit = nullptr;
  5267. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5268. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5269. if (vp && vp->kind == Ast_ProcLit) {
  5270. proc_lit = vp;
  5271. }
  5272. }
  5273. if (proc_lit == nullptr) {
  5274. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5275. }
  5276. }
  5277. return err;
  5278. }
  5279. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5280. GB_ASSERT(ce != nullptr);
  5281. if (ce->args.count == 0) {
  5282. return false;
  5283. }
  5284. return ce->args[0]->kind == Ast_FieldValue;
  5285. }
  5286. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  5287. Entity **lhs = nullptr;
  5288. isize lhs_count = -1;
  5289. if (proc_type == nullptr) {
  5290. return nullptr;
  5291. }
  5292. GB_ASSERT(is_type_proc(proc_type));
  5293. TypeProc *pt = &base_type(proc_type)->Proc;
  5294. *is_variadic = pt->variadic;
  5295. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5296. if (pt->params != nullptr) {
  5297. lhs = pt->params->Tuple.variables.data;
  5298. lhs_count = pt->params->Tuple.variables.count;
  5299. }
  5300. } else {
  5301. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5302. if (pt->params == nullptr) {
  5303. lhs_count = 0;
  5304. } else {
  5305. lhs_count = pt->params->Tuple.variables.count;
  5306. }
  5307. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5308. for (isize i = 0; i < lhs_count; i++) {
  5309. Entity *e = pt->params->Tuple.variables[i];
  5310. if (!is_type_polymorphic(e->type)) {
  5311. lhs[i] = e;
  5312. }
  5313. }
  5314. }
  5315. if (lhs_count_) *lhs_count_ = lhs_count;
  5316. return lhs;
  5317. }
  5318. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5319. if (clauses != nullptr) {
  5320. for (Ast *clause : *clauses) {
  5321. Operand o = {};
  5322. check_expr(ctx, &o, clause);
  5323. if (o.mode != Addressing_Constant) {
  5324. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5325. if (print_err && call_expr) error(call_expr, "at caller location");
  5326. return false;
  5327. } else if (o.value.kind != ExactValue_Bool) {
  5328. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5329. if (print_err && call_expr) error(call_expr, "at caller location");
  5330. return false;
  5331. } else if (!o.value.value_bool) {
  5332. if (print_err) {
  5333. ERROR_BLOCK();
  5334. gbString str = expr_to_string(clause);
  5335. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5336. gb_string_free(str);
  5337. if (scope != nullptr) {
  5338. isize print_count = 0;
  5339. for (auto const &entry : scope->elements) {
  5340. Entity *e = entry.value;
  5341. switch (e->kind) {
  5342. case Entity_TypeName: {
  5343. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5344. gbString str = type_to_string(e->type);
  5345. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5346. gb_string_free(str);
  5347. print_count += 1;
  5348. break;
  5349. }
  5350. case Entity_Constant: {
  5351. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5352. gbString str = exact_value_to_string(e->Constant.value);
  5353. if (is_type_untyped(e->type)) {
  5354. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5355. } else {
  5356. gbString t = type_to_string(e->type);
  5357. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5358. gb_string_free(t);
  5359. }
  5360. gb_string_free(str);
  5361. print_count += 1;
  5362. break;
  5363. }
  5364. }
  5365. }
  5366. }
  5367. if (call_expr) error(call_expr, "at caller location");
  5368. }
  5369. return false;
  5370. }
  5371. }
  5372. }
  5373. return true;
  5374. }
  5375. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5376. bool success = true;
  5377. type = base_type(type);
  5378. if (named_args.count > 0) {
  5379. TypeProc *pt = nullptr;
  5380. if (is_type_proc(type)) {
  5381. pt = &type->Proc;
  5382. }
  5383. for_array(i, named_args) {
  5384. Ast *arg = named_args[i];
  5385. if (arg->kind != Ast_FieldValue) {
  5386. if (show_error) {
  5387. error(arg, "Expected a 'field = value'");
  5388. }
  5389. return false;
  5390. }
  5391. ast_node(fv, FieldValue, arg);
  5392. if (fv->field->kind != Ast_Ident) {
  5393. if (show_error) {
  5394. gbString expr_str = expr_to_string(fv->field);
  5395. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5396. gb_string_free(expr_str);
  5397. }
  5398. success = false;
  5399. continue;
  5400. }
  5401. String key = fv->field->Ident.token.string;
  5402. Ast *value = fv->value;
  5403. Type *type_hint = nullptr;
  5404. if (pt) {
  5405. isize param_index = lookup_procedure_parameter(pt, key);
  5406. if (param_index < 0) {
  5407. if (show_error) {
  5408. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5409. }
  5410. success = false;
  5411. continue;
  5412. }
  5413. Entity *e = pt->params->Tuple.variables[param_index];
  5414. if (!is_type_polymorphic(e->type)) {
  5415. type_hint = e->type;
  5416. }
  5417. }
  5418. Operand o = {};
  5419. check_expr_with_type_hint(c, &o, value, type_hint);
  5420. if (o.mode == Addressing_Invalid) {
  5421. success = false;
  5422. }
  5423. array_add(named_operands, o);
  5424. }
  5425. }
  5426. return success;
  5427. }
  5428. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5429. Entity *e, Type *proc_type,
  5430. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5431. CallArgumentErrorMode show_error_mode,
  5432. CallArgumentData *data) {
  5433. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5434. Ast *ident = operand->expr;
  5435. while (ident->kind == Ast_SelectorExpr) {
  5436. Ast *s = ident->SelectorExpr.selector;
  5437. ident = s;
  5438. }
  5439. if (e == nullptr) {
  5440. e = entity_of_node(ident);
  5441. if (e != nullptr) {
  5442. proc_type = e->type;
  5443. }
  5444. }
  5445. GB_ASSERT(proc_type != nullptr);
  5446. proc_type = base_type(proc_type);
  5447. GB_ASSERT(proc_type->kind == Type_Proc);
  5448. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5449. if (return_on_failure && err != CallArgumentError_None) {
  5450. return false;
  5451. }
  5452. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5453. if (!return_on_failure && entity_to_use != nullptr) {
  5454. add_entity_use(c, ident, entity_to_use);
  5455. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5456. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5457. }
  5458. if (data->gen_entity != nullptr) {
  5459. Entity *e = data->gen_entity;
  5460. DeclInfo *decl = data->gen_entity->decl_info;
  5461. CheckerContext ctx = *c;
  5462. ctx.scope = decl->scope;
  5463. ctx.decl = decl;
  5464. ctx.proc_name = e->token.string;
  5465. ctx.curr_proc_decl = decl;
  5466. ctx.curr_proc_sig = e->type;
  5467. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5468. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5469. if (return_on_failure) {
  5470. if (!ok) {
  5471. return false;
  5472. }
  5473. } else {
  5474. decl->where_clauses_evaluated = true;
  5475. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5476. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5477. }
  5478. if (is_type_proc(data->gen_entity->type)) {
  5479. Type *t = base_type(entity_to_use->type);
  5480. data->result_type = t->Proc.results;
  5481. }
  5482. }
  5483. }
  5484. return true;
  5485. }
  5486. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5487. ast_node(ce, CallExpr, call);
  5488. GB_ASSERT(ce->split_args != nullptr);
  5489. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5490. Slice<Ast *> const &named_args = ce->split_args->named;
  5491. CallArgumentData data = {};
  5492. data.result_type = t_invalid;
  5493. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5494. auto procs = proc_group_entities_cloned(c, *operand);
  5495. if (procs.count > 1) {
  5496. isize max_arg_count = positional_args.count + named_args.count;
  5497. for (Ast *arg : positional_args) {
  5498. // NOTE(bill): The only thing that may have multiple values
  5499. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5500. arg = strip_or_return_expr(arg);
  5501. if (arg && arg->kind == Ast_CallExpr) {
  5502. max_arg_count = ISIZE_MAX;
  5503. break;
  5504. }
  5505. }
  5506. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5507. // NOTE(bill): The only thing that may have multiple values
  5508. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5509. if (arg->kind == Ast_FieldValue) {
  5510. arg = strip_or_return_expr(arg->FieldValue.value);
  5511. if (arg && arg->kind == Ast_CallExpr) {
  5512. max_arg_count = ISIZE_MAX;
  5513. break;
  5514. }
  5515. }
  5516. }
  5517. // ignore named arguments first
  5518. for (Ast *arg : named_args) {
  5519. if (arg->kind != Ast_FieldValue) {
  5520. continue;
  5521. }
  5522. ast_node(fv, FieldValue, arg);
  5523. if (fv->field->kind != Ast_Ident) {
  5524. continue;
  5525. }
  5526. String key = fv->field->Ident.token.string;
  5527. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5528. Type *t = procs[proc_index]->type;
  5529. if (is_type_proc(t)) {
  5530. isize param_index = lookup_procedure_parameter(t, key);
  5531. if (param_index < 0) {
  5532. array_unordered_remove(&procs, proc_index);
  5533. }
  5534. }
  5535. }
  5536. }
  5537. if (procs.count == 0) {
  5538. // if any of the named arguments are wrong, the `procs` will be empty
  5539. // just start from scratch
  5540. array_free(&procs);
  5541. procs = proc_group_entities_cloned(c, *operand);
  5542. }
  5543. // filter by positional argument length
  5544. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5545. Entity *proc = procs[proc_index];
  5546. Type *pt = base_type(proc->type);
  5547. if (!(pt != nullptr && is_type_proc(pt))) {
  5548. proc_index++;
  5549. continue;
  5550. }
  5551. isize param_count = 0;
  5552. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5553. if (param_count_excluding_defaults > max_arg_count) {
  5554. array_unordered_remove(&procs, proc_index);
  5555. continue;
  5556. }
  5557. proc_index++;
  5558. }
  5559. }
  5560. Entity **lhs = nullptr;
  5561. isize lhs_count = -1;
  5562. bool is_variadic = false;
  5563. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5564. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5565. defer (array_free(&positional_operands));
  5566. defer (array_free(&named_operands));
  5567. if (procs.count == 1) {
  5568. Entity *e = procs[0];
  5569. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  5570. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5571. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5572. check_call_arguments_single(c, call, operand,
  5573. e, e->type,
  5574. positional_operands, named_operands,
  5575. CallArgumentErrorMode::ShowErrors,
  5576. &data);
  5577. }
  5578. return data;
  5579. }
  5580. {
  5581. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  5582. // where the same positional parameter has the same type value (and ellipsis)
  5583. isize proc_arg_count = -1;
  5584. for (Entity *p : procs) {
  5585. Type *pt = base_type(p->type);
  5586. if (pt != nullptr && is_type_proc(pt)) {
  5587. if (proc_arg_count < 0) {
  5588. proc_arg_count = pt->Proc.param_count;
  5589. } else {
  5590. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  5591. }
  5592. }
  5593. }
  5594. if (proc_arg_count >= 0) {
  5595. lhs_count = proc_arg_count;
  5596. if (lhs_count > 0) {
  5597. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  5598. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  5599. Entity *e = nullptr;
  5600. for (Entity *p : procs) {
  5601. Type *pt = base_type(p->type);
  5602. if (!(pt != nullptr && is_type_proc(pt))) {
  5603. continue;
  5604. }
  5605. if (e == nullptr) {
  5606. e = pt->Proc.params->Tuple.variables[param_index];
  5607. } else {
  5608. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  5609. if (e == f) {
  5610. continue;
  5611. }
  5612. if (are_types_identical(e->type, f->type)) {
  5613. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  5614. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  5615. if (ee == fe) {
  5616. continue;
  5617. }
  5618. }
  5619. // NOTE(bill): Entities are not close enough to be used
  5620. e = nullptr;
  5621. break;
  5622. }
  5623. }
  5624. lhs[param_index] = e;
  5625. }
  5626. }
  5627. }
  5628. }
  5629. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5630. for_array(i, named_args) {
  5631. Ast *arg = named_args[i];
  5632. if (arg->kind != Ast_FieldValue) {
  5633. error(arg, "Expected a 'field = value'");
  5634. return data;
  5635. }
  5636. ast_node(fv, FieldValue, arg);
  5637. if (fv->field->kind != Ast_Ident) {
  5638. gbString expr_str = expr_to_string(fv->field);
  5639. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5640. gb_string_free(expr_str);
  5641. return data;
  5642. }
  5643. String key = fv->field->Ident.token.string;
  5644. Ast *value = fv->value;
  5645. Type *type_hint = nullptr;
  5646. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  5647. Entity *e = lhs[lhs_idx];
  5648. if (e != nullptr && e->token.string == key &&
  5649. !is_type_polymorphic(e->type)) {
  5650. type_hint = e->type;
  5651. break;
  5652. }
  5653. }
  5654. Operand o = {};
  5655. check_expr_with_type_hint(c, &o, value, type_hint);
  5656. array_add(&named_operands, o);
  5657. }
  5658. gb_free(heap_allocator(), lhs);
  5659. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  5660. defer (array_free(&valids));
  5661. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  5662. defer (array_free(&proc_entities));
  5663. for (Entity *proc : procs) {
  5664. array_add(&proc_entities, proc);
  5665. }
  5666. gbString expr_name = expr_to_string(operand->expr);
  5667. defer (gb_string_free(expr_name));
  5668. for_array(i, procs) {
  5669. Entity *p = procs[i];
  5670. Type *pt = base_type(p->type);
  5671. if (pt != nullptr && is_type_proc(pt)) {
  5672. CallArgumentData data = {};
  5673. CheckerContext ctx = *c;
  5674. ctx.no_polymorphic_errors = true;
  5675. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  5676. ctx.hide_polymorphic_errors = true;
  5677. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  5678. p, pt,
  5679. positional_operands, named_operands,
  5680. CallArgumentErrorMode::NoErrors,
  5681. &data);
  5682. if (!is_a_candidate) {
  5683. continue;
  5684. }
  5685. isize index = i;
  5686. ValidIndexAndScore item = {};
  5687. item.score = data.score;
  5688. if (data.gen_entity != nullptr) {
  5689. array_add(&proc_entities, data.gen_entity);
  5690. index = proc_entities.count-1;
  5691. // prefer non-polymorphic procedures over polymorphic
  5692. item.score += assign_score_function(1);
  5693. }
  5694. item.index = index;
  5695. array_add(&valids, item);
  5696. }
  5697. }
  5698. if (valids.count > 1) {
  5699. array_sort(valids, valid_index_and_score_cmp);
  5700. i64 best_score = valids[0].score;
  5701. Entity *best_entity = proc_entities[valids[0].index];
  5702. GB_ASSERT(best_entity != nullptr);
  5703. for (isize i = 1; i < valids.count; i++) {
  5704. if (best_score > valids[i].score) {
  5705. valids.count = i;
  5706. break;
  5707. }
  5708. if (best_entity == proc_entities[valids[i].index]) {
  5709. valids.count = i;
  5710. break;
  5711. }
  5712. }
  5713. }
  5714. auto print_argument_types = [&]() {
  5715. error_line("\tGiven argument types: (");
  5716. isize i = 0;
  5717. for (Operand const &o : positional_operands) {
  5718. if (i++ > 0) error_line(", ");
  5719. gbString type = type_to_string(o.type);
  5720. defer (gb_string_free(type));
  5721. error_line("%s", type);
  5722. }
  5723. for (Operand const &o : named_operands) {
  5724. if (i++ > 0) error_line(", ");
  5725. gbString type = type_to_string(o.type);
  5726. defer (gb_string_free(type));
  5727. if (i < ce->split_args->named.count) {
  5728. Ast *named_field = ce->split_args->named[i];
  5729. ast_node(fv, FieldValue, named_field);
  5730. gbString field = expr_to_string(fv->field);
  5731. defer (gb_string_free(field));
  5732. error_line("%s = %s", field, type);
  5733. } else {
  5734. error_line("%s", type);
  5735. }
  5736. }
  5737. error_line(")\n");
  5738. };
  5739. if (valids.count == 0) {
  5740. ERROR_BLOCK();
  5741. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  5742. if (positional_operands.count == 0 && named_operands.count == 0) {
  5743. error_line("\tNo given arguments\n");
  5744. } else {
  5745. print_argument_types();
  5746. }
  5747. if (procs.count == 0) {
  5748. procs = proc_group_entities_cloned(c, *operand);
  5749. }
  5750. if (procs.count > 0) {
  5751. error_line("Did you mean to use one of the following:\n");
  5752. }
  5753. isize max_name_length = 0;
  5754. isize max_type_length = 0;
  5755. for (Entity *proc : procs) {
  5756. Type *t = base_type(proc->type);
  5757. if (t == t_invalid) continue;
  5758. String prefix = {};
  5759. String prefix_sep = {};
  5760. if (proc->pkg) {
  5761. prefix = proc->pkg->name;
  5762. prefix_sep = str_lit(".");
  5763. }
  5764. String name = proc->token.string;
  5765. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  5766. gbString pt;
  5767. if (t->Proc.node != nullptr) {
  5768. pt = expr_to_string(t->Proc.node);
  5769. } else {
  5770. pt = type_to_string(t);
  5771. }
  5772. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  5773. gb_string_free(pt);
  5774. }
  5775. isize max_spaces = gb_max(max_name_length, max_type_length);
  5776. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  5777. for (isize i = 0; i < max_spaces; i++) {
  5778. spaces[i] = ' ';
  5779. }
  5780. spaces[max_spaces] = 0;
  5781. for (Entity *proc : procs) {
  5782. TokenPos pos = proc->token.pos;
  5783. Type *t = base_type(proc->type);
  5784. if (t == t_invalid) continue;
  5785. GB_ASSERT(t->kind == Type_Proc);
  5786. gbString pt;
  5787. defer (gb_string_free(pt));
  5788. if (t->Proc.node != nullptr) {
  5789. pt = expr_to_string(t->Proc.node);
  5790. } else {
  5791. pt = type_to_string(t);
  5792. }
  5793. String prefix = {};
  5794. String prefix_sep = {};
  5795. if (proc->pkg) {
  5796. prefix = proc->pkg->name;
  5797. prefix_sep = str_lit(".");
  5798. }
  5799. String name = proc->token.string;
  5800. isize len = prefix.len + prefix_sep.len + name.len;
  5801. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  5802. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  5803. char const *sep = "::";
  5804. if (proc->kind == Entity_Variable) {
  5805. sep = ":=";
  5806. }
  5807. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  5808. LIT(prefix), LIT(prefix_sep), LIT(name),
  5809. name_padding, spaces,
  5810. sep,
  5811. pt,
  5812. type_padding, spaces,
  5813. token_pos_to_string(pos)
  5814. );
  5815. }
  5816. if (procs.count > 0) {
  5817. error_line("\n");
  5818. }
  5819. data.result_type = t_invalid;
  5820. } else if (valids.count > 1) {
  5821. ERROR_BLOCK();
  5822. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  5823. print_argument_types();
  5824. for (auto const &valid : valids) {
  5825. Entity *proc = proc_entities[valid.index];
  5826. GB_ASSERT(proc != nullptr);
  5827. TokenPos pos = proc->token.pos;
  5828. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  5829. gbString pt = nullptr;
  5830. defer (gb_string_free(pt));
  5831. if (t->Proc.node != nullptr) {
  5832. pt = expr_to_string(t->Proc.node);
  5833. } else {
  5834. pt = type_to_string(t);
  5835. }
  5836. String name = proc->token.string;
  5837. char const *sep = "::";
  5838. if (proc->kind == Entity_Variable) {
  5839. sep = ":=";
  5840. }
  5841. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  5842. if (proc->decl_info->proc_lit != nullptr) {
  5843. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  5844. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  5845. if (pl->where_token.kind != Token_Invalid) {
  5846. error_line("\n\t\twhere ");
  5847. for_array(j, pl->where_clauses) {
  5848. Ast *clause = pl->where_clauses[j];
  5849. if (j != 0) {
  5850. error_line("\t\t ");
  5851. }
  5852. gbString str = expr_to_string(clause);
  5853. error_line("%s", str);
  5854. gb_string_free(str);
  5855. if (j != pl->where_clauses.count-1) {
  5856. error_line(",");
  5857. }
  5858. }
  5859. error_line("\n\t");
  5860. }
  5861. }
  5862. error_line("at %s\n", token_pos_to_string(pos));
  5863. }
  5864. data.result_type = t_invalid;
  5865. } else {
  5866. GB_ASSERT(valids.count == 1);
  5867. Ast *ident = operand->expr;
  5868. while (ident->kind == Ast_SelectorExpr) {
  5869. Ast *s = ident->SelectorExpr.selector;
  5870. ident = s;
  5871. }
  5872. Entity *e = proc_entities[valids[0].index];
  5873. GB_ASSERT(e != nullptr);
  5874. Array<Operand> named_operands = {};
  5875. check_call_arguments_single(c, call, operand,
  5876. e, e->type,
  5877. positional_operands, named_operands,
  5878. CallArgumentErrorMode::ShowErrors,
  5879. &data);
  5880. return data;
  5881. }
  5882. return data;
  5883. }
  5884. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  5885. Type *proc_type = nullptr;
  5886. CallArgumentData data = {};
  5887. data.result_type = t_invalid;
  5888. proc_type = base_type(operand->type);
  5889. TypeProc *pt = nullptr;
  5890. if (proc_type) {
  5891. pt = &proc_type->Proc;
  5892. }
  5893. TEMPORARY_ALLOCATOR_GUARD();
  5894. ast_node(ce, CallExpr, call);
  5895. bool any_failure = false;
  5896. // Split positional and named args into separate arrays/slices
  5897. Slice<Ast *> positional_args = {};
  5898. Slice<Ast *> named_args = {};
  5899. if (ce->split_args == nullptr) {
  5900. positional_args = ce->args;
  5901. for (isize i = 0; i < ce->args.count; i++) {
  5902. Ast *arg = ce->args.data[i];
  5903. if (arg->kind == Ast_FieldValue) {
  5904. positional_args.count = i;
  5905. break;
  5906. }
  5907. }
  5908. named_args = slice(ce->args, positional_args.count, ce->args.count);
  5909. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  5910. split_args->positional = positional_args;
  5911. split_args->named = named_args;
  5912. ce->split_args = split_args;
  5913. } else {
  5914. positional_args = ce->split_args->positional;
  5915. named_args = ce->split_args->named;
  5916. }
  5917. if (operand->mode == Addressing_ProcGroup) {
  5918. return check_call_arguments_proc_group(c, operand, call);
  5919. }
  5920. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  5921. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5922. defer (array_free(&positional_operands));
  5923. defer (array_free(&named_operands));
  5924. if (positional_args.count > 0) {
  5925. isize lhs_count = -1;
  5926. bool is_variadic = false;
  5927. Entity **lhs = nullptr;
  5928. if (pt != nullptr) {
  5929. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  5930. }
  5931. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5932. }
  5933. if (named_args.count > 0) {
  5934. for_array(i, named_args) {
  5935. Ast *arg = named_args[i];
  5936. if (arg->kind != Ast_FieldValue) {
  5937. error(arg, "Expected a 'field = value'");
  5938. return data;
  5939. }
  5940. ast_node(fv, FieldValue, arg);
  5941. if (fv->field->kind != Ast_Ident) {
  5942. gbString expr_str = expr_to_string(fv->field);
  5943. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5944. any_failure = true;
  5945. gb_string_free(expr_str);
  5946. continue;
  5947. }
  5948. String key = fv->field->Ident.token.string;
  5949. Ast *value = fv->value;
  5950. isize param_index = lookup_procedure_parameter(pt, key);
  5951. Type *type_hint = nullptr;
  5952. if (param_index >= 0) {
  5953. Entity *e = pt->params->Tuple.variables[param_index];
  5954. type_hint = e->type;
  5955. }
  5956. Operand o = {};
  5957. check_expr_with_type_hint(c, &o, value, type_hint);
  5958. if (o.mode == Addressing_Invalid) {
  5959. any_failure = true;
  5960. }
  5961. array_add(&named_operands, o);
  5962. }
  5963. }
  5964. if (!any_failure) {
  5965. check_call_arguments_single(c, call, operand,
  5966. nullptr, proc_type,
  5967. positional_operands, named_operands,
  5968. CallArgumentErrorMode::ShowErrors,
  5969. &data);
  5970. } else if (pt) {
  5971. data.result_type = pt->results;
  5972. }
  5973. return data;
  5974. }
  5975. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  5976. if (!is_type_polymorphic_record(t)) {
  5977. return -1;
  5978. }
  5979. TypeTuple *params = get_record_polymorphic_params(t);
  5980. if (params == nullptr) {
  5981. return -1;
  5982. }
  5983. for_array(i, params->variables) {
  5984. Entity *e = params->variables[i];
  5985. String name = e->token.string;
  5986. if (is_blank_ident(name)) {
  5987. continue;
  5988. }
  5989. if (name == parameter_name) {
  5990. return i;
  5991. }
  5992. }
  5993. return -1;
  5994. }
  5995. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  5996. ast_node(ce, CallExpr, call);
  5997. Type *original_type = operand->type;
  5998. GB_ASSERT(is_type_polymorphic_record(original_type));
  5999. bool show_error = true;
  6000. Array<Operand> operands = {};
  6001. defer (array_free(&operands));
  6002. bool named_fields = false;
  6003. {
  6004. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6005. auto prev_type_path = c->type_path;
  6006. c->type_path = new_checker_type_path();
  6007. defer ({
  6008. destroy_checker_type_path(c->type_path);
  6009. c->type_path = prev_type_path;
  6010. });
  6011. if (is_call_expr_field_value(ce)) {
  6012. named_fields = true;
  6013. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6014. for_array(i, ce->args) {
  6015. Ast *arg = ce->args[i];
  6016. ast_node(fv, FieldValue, arg);
  6017. if (fv->field->kind == Ast_Ident) {
  6018. String name = fv->field->Ident.token.string;
  6019. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6020. if (index >= 0) {
  6021. TypeTuple *params = get_record_polymorphic_params(original_type);
  6022. Entity *e = params->variables[index];
  6023. if (e->kind == Entity_Constant) {
  6024. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6025. continue;
  6026. }
  6027. }
  6028. }
  6029. check_expr_or_type(c, &operands[i], fv->value);
  6030. }
  6031. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6032. if (vari_expand) {
  6033. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6034. }
  6035. } else {
  6036. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6037. Entity **lhs = nullptr;
  6038. isize lhs_count = -1;
  6039. TypeTuple *params = get_record_polymorphic_params(original_type);
  6040. if (params != nullptr) {
  6041. lhs = params->variables.data;
  6042. lhs_count = params->variables.count;
  6043. }
  6044. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6045. }
  6046. }
  6047. CallArgumentError err = CallArgumentError_None;
  6048. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6049. isize param_count = tuple->variables.count;
  6050. isize minimum_param_count = param_count;
  6051. for (; minimum_param_count > 0; minimum_param_count--) {
  6052. Entity *e = tuple->variables[minimum_param_count-1];
  6053. if (e->kind != Entity_Constant) {
  6054. break;
  6055. }
  6056. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6057. break;
  6058. }
  6059. }
  6060. Array<Operand> ordered_operands = operands;
  6061. if (!named_fields) {
  6062. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6063. array_copy(&ordered_operands, operands, 0);
  6064. } else {
  6065. TEMPORARY_ALLOCATOR_GUARD();
  6066. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6067. // LEAK(bill)
  6068. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6069. for_array(i, ce->args) {
  6070. Ast *arg = ce->args[i];
  6071. ast_node(fv, FieldValue, arg);
  6072. if (fv->field->kind != Ast_Ident) {
  6073. if (show_error) {
  6074. gbString expr_str = expr_to_string(fv->field);
  6075. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6076. gb_string_free(expr_str);
  6077. }
  6078. err = CallArgumentError_InvalidFieldValue;
  6079. continue;
  6080. }
  6081. String name = fv->field->Ident.token.string;
  6082. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6083. if (index < 0) {
  6084. if (show_error) {
  6085. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6086. }
  6087. err = CallArgumentError_ParameterNotFound;
  6088. continue;
  6089. }
  6090. if (visited[index]) {
  6091. if (show_error) {
  6092. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6093. }
  6094. err = CallArgumentError_DuplicateParameter;
  6095. continue;
  6096. }
  6097. visited[index] = true;
  6098. ordered_operands[index] = operands[i];
  6099. }
  6100. for (isize i = 0; i < param_count; i++) {
  6101. if (!visited[i]) {
  6102. Entity *e = tuple->variables[i];
  6103. if (is_blank_ident(e->token)) {
  6104. continue;
  6105. }
  6106. if (show_error) {
  6107. if (e->kind == Entity_TypeName) {
  6108. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6109. LIT(e->token.string));
  6110. } else {
  6111. gbString str = type_to_string(e->type);
  6112. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6113. LIT(e->token.string), str);
  6114. gb_string_free(str);
  6115. }
  6116. }
  6117. err = CallArgumentError_ParameterMissing;
  6118. }
  6119. }
  6120. }
  6121. if (err != 0) {
  6122. operand->mode = Addressing_Invalid;
  6123. return err;
  6124. }
  6125. while (ordered_operands.count > 0) {
  6126. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6127. break;
  6128. }
  6129. array_pop(&ordered_operands);
  6130. }
  6131. if (minimum_param_count != param_count) {
  6132. if (param_count < ordered_operands.count) {
  6133. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6134. err = CallArgumentError_TooManyArguments;
  6135. } else if (minimum_param_count > ordered_operands.count) {
  6136. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6137. err = CallArgumentError_TooFewArguments;
  6138. }
  6139. } else {
  6140. if (param_count < ordered_operands.count) {
  6141. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6142. err = CallArgumentError_TooManyArguments;
  6143. } else if (param_count > ordered_operands.count) {
  6144. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6145. err = CallArgumentError_TooFewArguments;
  6146. }
  6147. }
  6148. if (err != 0) {
  6149. return err;
  6150. }
  6151. if (minimum_param_count != param_count) {
  6152. array_resize(&ordered_operands, param_count);
  6153. isize missing_count = 0;
  6154. // NOTE(bill): Replace missing operands with the default values (if possible)
  6155. for_array(i, ordered_operands) {
  6156. Operand *o = &ordered_operands[i];
  6157. if (o->expr == nullptr) {
  6158. Entity *e = tuple->variables[i];
  6159. if (e->kind == Entity_Constant) {
  6160. missing_count += 1;
  6161. o->mode = Addressing_Constant;
  6162. o->type = default_type(e->type);
  6163. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6164. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6165. o->value = e->Constant.param_value.value;
  6166. }
  6167. } else if (e->kind == Entity_TypeName) {
  6168. missing_count += 1;
  6169. o->mode = Addressing_Type;
  6170. o->type = e->type;
  6171. o->expr = e->identifier;
  6172. }
  6173. }
  6174. }
  6175. }
  6176. isize oo_count = gb_min(param_count, ordered_operands.count);
  6177. i64 score = 0;
  6178. for (isize i = 0; i < oo_count; i++) {
  6179. Entity *e = tuple->variables[i];
  6180. Operand *o = &ordered_operands[i];
  6181. if (o->mode == Addressing_Invalid) {
  6182. continue;
  6183. }
  6184. if (e->kind == Entity_TypeName) {
  6185. if (o->mode != Addressing_Type) {
  6186. if (show_error) {
  6187. gbString expr = expr_to_string(o->expr);
  6188. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6189. gb_string_free(expr);
  6190. }
  6191. err = CallArgumentError_WrongTypes;
  6192. }
  6193. if (are_types_identical(e->type, o->type)) {
  6194. score += assign_score_function(1);
  6195. } else {
  6196. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6197. }
  6198. } else {
  6199. i64 s = 0;
  6200. if (o->type->kind == Type_Generic) {
  6201. // Polymorphic name!
  6202. score += assign_score_function(1);
  6203. continue;
  6204. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6205. if (show_error) {
  6206. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6207. }
  6208. err = CallArgumentError_WrongTypes;
  6209. }
  6210. o->type = e->type;
  6211. if (o->mode != Addressing_Constant) {
  6212. bool valid = false;
  6213. if (is_type_proc(o->type)) {
  6214. Entity *proc_entity = entity_from_expr(o->expr);
  6215. valid = proc_entity != nullptr;
  6216. }
  6217. if (!valid) {
  6218. if (show_error) {
  6219. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6220. }
  6221. err = CallArgumentError_NoneConstantParameter;
  6222. }
  6223. }
  6224. score += s;
  6225. }
  6226. // NOTE(bill): Add type info the parameters
  6227. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6228. // add_type_info_type(c, o->type);
  6229. }
  6230. if (show_error && err) {
  6231. return err;
  6232. }
  6233. {
  6234. bool failure = false;
  6235. Entity *found_entity = find_polymorphic_record_entity(c, original_type, param_count, ordered_operands, &failure);
  6236. if (found_entity) {
  6237. operand->mode = Addressing_Type;
  6238. operand->type = found_entity->type;
  6239. return err;
  6240. }
  6241. CheckerContext ctx = *c;
  6242. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6243. ctx.scope = polymorphic_record_parent_scope(original_type);
  6244. GB_ASSERT(ctx.scope != nullptr);
  6245. Type *bt = base_type(original_type);
  6246. String generated_name = make_string_c(expr_to_string(call));
  6247. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6248. if (bt->kind == Type_Struct) {
  6249. Ast *node = clone_ast(bt->Struct.node);
  6250. Type *struct_type = alloc_type_struct();
  6251. struct_type->Struct.node = node;
  6252. struct_type->Struct.polymorphic_parent = original_type;
  6253. set_base_type(named_type, struct_type);
  6254. check_open_scope(&ctx, node);
  6255. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6256. check_close_scope(&ctx);
  6257. } else if (bt->kind == Type_Union) {
  6258. Ast *node = clone_ast(bt->Union.node);
  6259. Type *union_type = alloc_type_union();
  6260. union_type->Union.node = node;
  6261. union_type->Union.polymorphic_parent = original_type;
  6262. set_base_type(named_type, union_type);
  6263. check_open_scope(&ctx, node);
  6264. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6265. check_close_scope(&ctx);
  6266. } else {
  6267. GB_PANIC("Unsupported parametric polymorphic record type");
  6268. }
  6269. bt = base_type(named_type);
  6270. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6271. GB_ASSERT(original_type->kind == Type_Named);
  6272. Entity *e = original_type->Named.type_name;
  6273. GB_ASSERT(e->kind == Entity_TypeName);
  6274. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6275. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6276. Type *params = nullptr;
  6277. switch (bt->kind) {
  6278. case Type_Struct: params = bt->Struct.polymorphic_params; break;
  6279. case Type_Union: params = bt->Union.polymorphic_params; break;
  6280. }
  6281. if (params != nullptr) for_array(i, params->Tuple.variables) {
  6282. Entity *v = params->Tuple.variables[i];
  6283. String name = v->token.string;
  6284. if (i > 0) {
  6285. s = gb_string_append_fmt(s, ", ");
  6286. }
  6287. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6288. if (v->kind == Entity_TypeName) {
  6289. if (v->type->kind != Type_Generic) {
  6290. s = gb_string_append_fmt(s, "=");
  6291. s = write_type_to_string(s, v->type, false);
  6292. }
  6293. } else if (v->kind == Entity_Constant) {
  6294. s = gb_string_append_fmt(s, "=");
  6295. s = write_exact_value_to_string(s, v->Constant.value);
  6296. }
  6297. }
  6298. s = gb_string_append_fmt(s, ")");
  6299. String new_name = make_string_c(s);
  6300. named_type->Named.name = new_name;
  6301. if (named_type->Named.type_name) {
  6302. named_type->Named.type_name->token.string = new_name;
  6303. }
  6304. }
  6305. operand->mode = Addressing_Type;
  6306. operand->type = named_type;
  6307. }
  6308. return err;
  6309. }
  6310. // returns true on success
  6311. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6312. bool success = true;
  6313. if (args.count > 0) {
  6314. if (allow_mixed) {
  6315. bool was_named = false;
  6316. for (Ast *arg : args) {
  6317. if (was_named && arg->kind != Ast_FieldValue) {
  6318. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6319. success = false;
  6320. break;
  6321. }
  6322. was_named = was_named || arg->kind == Ast_FieldValue;
  6323. }
  6324. } else {
  6325. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6326. for (Ast *arg : args) {
  6327. bool mix = false;
  6328. if (first_is_field_value) {
  6329. mix = arg->kind != Ast_FieldValue;
  6330. } else {
  6331. mix = arg->kind == Ast_FieldValue;
  6332. }
  6333. if (mix) {
  6334. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6335. success = false;
  6336. }
  6337. }
  6338. }
  6339. }
  6340. return success;
  6341. }
  6342. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6343. operand->mode = Addressing_Invalid; \
  6344. operand->expr = call; \
  6345. return Expr_Stmt; \
  6346. }
  6347. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6348. if (proc != nullptr &&
  6349. proc->kind == Ast_BasicDirective) {
  6350. ast_node(bd, BasicDirective, proc);
  6351. String name = bd->name.string;
  6352. if (
  6353. name == "location" ||
  6354. name == "assert" ||
  6355. name == "panic" ||
  6356. name == "defined" ||
  6357. name == "config" ||
  6358. name == "load" ||
  6359. name == "load_directory" ||
  6360. name == "load_hash"
  6361. ) {
  6362. operand->mode = Addressing_Builtin;
  6363. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6364. operand->expr = proc;
  6365. operand->type = t_invalid;
  6366. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6367. } else {
  6368. error(proc, "Unknown directive: #%.*s", LIT(name));
  6369. operand->expr = proc;
  6370. operand->type = t_invalid;
  6371. operand->mode = Addressing_Invalid;
  6372. return Expr_Expr;
  6373. }
  6374. if (inlining != ProcInlining_none) {
  6375. error(call, "Inlining operators are not allowed on built-in procedures");
  6376. }
  6377. } else {
  6378. if (proc != nullptr) {
  6379. check_expr_or_type(c, operand, proc);
  6380. } else {
  6381. GB_ASSERT(operand->expr != nullptr);
  6382. }
  6383. }
  6384. if (operand->mode == Addressing_Invalid) {
  6385. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6386. for (Ast *arg : args) {
  6387. if (arg->kind == Ast_FieldValue) {
  6388. arg = arg->FieldValue.value;
  6389. }
  6390. check_expr_base(c, operand, arg, nullptr);
  6391. }
  6392. operand->mode = Addressing_Invalid;
  6393. operand->expr = call;
  6394. return Expr_Stmt;
  6395. }
  6396. if (operand->mode == Addressing_Type) {
  6397. Type *t = operand->type;
  6398. if (is_type_polymorphic_record(t)) {
  6399. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6400. if (!is_type_named(t)) {
  6401. gbString s = expr_to_string(operand->expr);
  6402. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6403. gb_string_free(s);
  6404. operand->mode = Addressing_Invalid;
  6405. operand->type = t_invalid;;
  6406. return Expr_Expr;
  6407. }
  6408. auto err = check_polymorphic_record_type(c, operand, call);
  6409. if (err == 0) {
  6410. Ast *ident = operand->expr;
  6411. while (ident->kind == Ast_SelectorExpr) {
  6412. Ast *s = ident->SelectorExpr.selector;
  6413. ident = s;
  6414. }
  6415. Type *ot = operand->type;
  6416. GB_ASSERT(ot->kind == Type_Named);
  6417. Entity *e = ot->Named.type_name;
  6418. add_entity_use(c, ident, e);
  6419. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6420. } else {
  6421. operand->mode = Addressing_Invalid;
  6422. operand->type = t_invalid;
  6423. }
  6424. } else {
  6425. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6426. operand->mode = Addressing_Invalid;
  6427. isize arg_count = args.count;
  6428. switch (arg_count) {
  6429. case 0:
  6430. {
  6431. gbString str = type_to_string(t);
  6432. error(call, "Missing argument in conversion to '%s'", str);
  6433. gb_string_free(str);
  6434. } break;
  6435. default:
  6436. {
  6437. gbString str = type_to_string(t);
  6438. error(call, "Too many arguments in conversion to '%s'", str);
  6439. gb_string_free(str);
  6440. } break;
  6441. case 1: {
  6442. Ast *arg = args[0];
  6443. if (arg->kind == Ast_FieldValue) {
  6444. error(call, "'field = value' cannot be used in a type conversion");
  6445. arg = arg->FieldValue.value;
  6446. // NOTE(bill): Carry on the cast regardless
  6447. }
  6448. check_expr_with_type_hint(c, operand, arg, t);
  6449. if (operand->mode != Addressing_Invalid) {
  6450. if (is_type_polymorphic(t)) {
  6451. error(call, "A polymorphic type cannot be used in a type conversion");
  6452. } else {
  6453. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  6454. // as it assumes it is determining the type
  6455. check_cast(c, operand, t);
  6456. }
  6457. }
  6458. operand->type = t;
  6459. operand->expr = call;
  6460. if (operand->mode != Addressing_Invalid) {
  6461. update_untyped_expr_type(c, arg, t, false);
  6462. }
  6463. break;
  6464. }
  6465. }
  6466. }
  6467. return Expr_Expr;
  6468. }
  6469. if (operand->mode == Addressing_Builtin) {
  6470. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  6471. i32 id = operand->builtin_id;
  6472. Entity *e = entity_of_node(operand->expr);
  6473. if (e != nullptr && e->token.string == "expand_to_tuple") {
  6474. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  6475. }
  6476. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  6477. operand->mode = Addressing_Invalid;
  6478. operand->type = t_invalid;
  6479. }
  6480. operand->expr = call;
  6481. return builtin_procs[id].kind;
  6482. }
  6483. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  6484. Entity *initial_entity = entity_of_node(operand->expr);
  6485. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  6486. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  6487. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  6488. if (c->decl) {
  6489. c->decl->defer_used += 1;
  6490. }
  6491. }
  6492. add_entity_use(c, operand->expr, initial_entity);
  6493. if (initial_entity->Procedure.entry_point_only) {
  6494. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  6495. // Okay
  6496. } else {
  6497. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  6498. }
  6499. }
  6500. }
  6501. if (operand->mode != Addressing_ProcGroup) {
  6502. Type *proc_type = base_type(operand->type);
  6503. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  6504. bool valid_mode = is_operand_value(*operand);
  6505. if (!valid_type || !valid_mode) {
  6506. Ast *e = operand->expr;
  6507. gbString str = expr_to_string(e);
  6508. gbString type_str = type_to_string(operand->type);
  6509. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  6510. gb_string_free(type_str);
  6511. gb_string_free(str);
  6512. operand->mode = Addressing_Invalid;
  6513. operand->expr = call;
  6514. return Expr_Stmt;
  6515. }
  6516. }
  6517. CallArgumentData data = check_call_arguments(c, operand, call);
  6518. Type *result_type = data.result_type;
  6519. gb_zero_item(operand);
  6520. operand->expr = call;
  6521. if (result_type == t_invalid) {
  6522. operand->mode = Addressing_Invalid;
  6523. operand->type = t_invalid;
  6524. return Expr_Stmt;
  6525. }
  6526. Type *pt = base_type(operand->type);
  6527. if (pt == nullptr) {
  6528. pt = t_invalid;
  6529. }
  6530. if (pt == t_invalid) {
  6531. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6532. pt = type_of_expr(operand->expr->CallExpr.proc);
  6533. }
  6534. if (pt == t_invalid && data.gen_entity) {
  6535. pt = data.gen_entity->type;
  6536. }
  6537. }
  6538. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  6539. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  6540. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  6541. }
  6542. }
  6543. if (result_type == nullptr) {
  6544. operand->mode = Addressing_NoValue;
  6545. } else {
  6546. GB_ASSERT(is_type_tuple(result_type));
  6547. isize count = result_type->Tuple.variables.count;
  6548. switch (count) {
  6549. case 0:
  6550. operand->mode = Addressing_NoValue;
  6551. break;
  6552. case 1:
  6553. operand->mode = Addressing_Value;
  6554. operand->type = result_type->Tuple.variables[0]->type;
  6555. break;
  6556. default:
  6557. operand->mode = Addressing_Value;
  6558. operand->type = result_type;
  6559. break;
  6560. }
  6561. }
  6562. switch (inlining) {
  6563. case ProcInlining_inline:
  6564. if (proc != nullptr) {
  6565. Entity *e = entity_from_expr(proc);
  6566. if (e != nullptr && e->kind == Entity_Procedure) {
  6567. DeclInfo *decl = e->decl_info;
  6568. if (decl->proc_lit) {
  6569. ast_node(pl, ProcLit, decl->proc_lit);
  6570. if (pl->inlining == ProcInlining_no_inline) {
  6571. error(call, "'#force_inline' cannot be applied to a procedure that has be marked as '#force_no_inline'");
  6572. }
  6573. }
  6574. }
  6575. }
  6576. break;
  6577. case ProcInlining_no_inline:
  6578. break;
  6579. }
  6580. operand->expr = call;
  6581. {
  6582. Type *type = nullptr;
  6583. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6584. type = type_of_expr(operand->expr->CallExpr.proc);
  6585. }
  6586. if (type == nullptr) {
  6587. type = pt;
  6588. }
  6589. type = base_type(type);
  6590. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  6591. operand->mode = Addressing_OptionalOk;
  6592. operand->type = type->Proc.results->Tuple.variables[0]->type;
  6593. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6594. operand->expr->CallExpr.optional_ok_one = true;
  6595. }
  6596. }
  6597. }
  6598. return Expr_Expr;
  6599. }
  6600. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  6601. check_expr_base(c, o, e, t);
  6602. check_not_tuple(c, o);
  6603. char const *err_str = nullptr;
  6604. switch (o->mode) {
  6605. case Addressing_NoValue:
  6606. err_str = "used as a value";
  6607. break;
  6608. case Addressing_Type:
  6609. if (t == nullptr || !is_type_typeid(t)) {
  6610. err_str = "is not an expression but a type, in this context it is ambiguous";
  6611. }
  6612. break;
  6613. case Addressing_Builtin:
  6614. err_str = "must be called";
  6615. break;
  6616. }
  6617. if (err_str != nullptr) {
  6618. gbString str = expr_to_string(e);
  6619. error(e, "'%s' %s", str, err_str);
  6620. gb_string_free(str);
  6621. o->mode = Addressing_Invalid;
  6622. }
  6623. }
  6624. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  6625. switch (t->kind) {
  6626. case Type_Basic:
  6627. if (t->Basic.kind == Basic_string) {
  6628. if (o->mode == Addressing_Constant) {
  6629. *max_count = o->value.value_string.len;
  6630. }
  6631. if (o->mode != Addressing_Constant) {
  6632. o->mode = Addressing_Value;
  6633. }
  6634. o->type = t_u8;
  6635. return true;
  6636. } else if (t->Basic.kind == Basic_UntypedString) {
  6637. if (o->mode == Addressing_Constant) {
  6638. *max_count = o->value.value_string.len;
  6639. o->type = t_u8;
  6640. return true;
  6641. }
  6642. return false;
  6643. }
  6644. break;
  6645. case Type_MultiPointer:
  6646. o->type = t->MultiPointer.elem;
  6647. if (o->mode != Addressing_Constant) {
  6648. o->mode = Addressing_Variable;
  6649. }
  6650. return true;
  6651. case Type_Array:
  6652. *max_count = t->Array.count;
  6653. if (indirection) {
  6654. o->mode = Addressing_Variable;
  6655. } else if (o->mode != Addressing_Variable &&
  6656. o->mode != Addressing_Constant) {
  6657. o->mode = Addressing_Value;
  6658. }
  6659. o->type = t->Array.elem;
  6660. return true;
  6661. case Type_EnumeratedArray:
  6662. *max_count = t->EnumeratedArray.count;
  6663. if (indirection) {
  6664. o->mode = Addressing_Variable;
  6665. } else if (o->mode != Addressing_Variable &&
  6666. o->mode != Addressing_Constant) {
  6667. o->mode = Addressing_Value;
  6668. }
  6669. o->type = t->EnumeratedArray.elem;
  6670. return true;
  6671. case Type_Matrix:
  6672. *max_count = t->Matrix.column_count;
  6673. if (indirection) {
  6674. o->mode = Addressing_Variable;
  6675. } else if (o->mode != Addressing_Variable) {
  6676. o->mode = Addressing_Value;
  6677. }
  6678. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  6679. return true;
  6680. case Type_Slice:
  6681. o->type = t->Slice.elem;
  6682. if (o->mode != Addressing_Constant) {
  6683. o->mode = Addressing_Variable;
  6684. }
  6685. return true;
  6686. case Type_RelativeMultiPointer:
  6687. {
  6688. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  6689. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  6690. o->type = pointer_type->MultiPointer.elem;
  6691. if (o->mode != Addressing_Constant) {
  6692. o->mode = Addressing_Variable;
  6693. }
  6694. }
  6695. return true;
  6696. case Type_DynamicArray:
  6697. o->type = t->DynamicArray.elem;
  6698. if (o->mode != Addressing_Constant) {
  6699. o->mode = Addressing_Variable;
  6700. }
  6701. return true;
  6702. case Type_Struct:
  6703. if (t->Struct.soa_kind != StructSoa_None) {
  6704. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6705. *max_count = t->Struct.soa_count;
  6706. }
  6707. o->type = t->Struct.soa_elem;
  6708. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  6709. o->mode = Addressing_SoaVariable;
  6710. } else {
  6711. o->mode = Addressing_Value;
  6712. }
  6713. return true;
  6714. }
  6715. return false;
  6716. }
  6717. if (is_type_pointer(original_type) && indirection) {
  6718. Type *ptr = base_type(original_type);
  6719. if (ptr->kind == Type_Pointer && o->mode == Addressing_SoaVariable) {
  6720. o->type = ptr->Pointer.elem;
  6721. o->mode = Addressing_Value;
  6722. return true;
  6723. }
  6724. }
  6725. return false;
  6726. }
  6727. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  6728. if (is_type_untyped_uninit(x)) {
  6729. return true;
  6730. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  6731. return true;
  6732. } else if (is_type_untyped_uninit(y)) {
  6733. return true;
  6734. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  6735. return true;
  6736. }
  6737. return are_types_identical(x, y);
  6738. }
  6739. 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) {
  6740. if (!is_ast_range(node)) {
  6741. return false;
  6742. }
  6743. ast_node(ie, BinaryExpr, node);
  6744. check_expr_with_type_hint(c, x, ie->left, type_hint);
  6745. if (x->mode == Addressing_Invalid) {
  6746. return false;
  6747. }
  6748. check_expr_with_type_hint(c, y, ie->right, type_hint);
  6749. if (y->mode == Addressing_Invalid) {
  6750. return false;
  6751. }
  6752. convert_to_typed(c, x, y->type);
  6753. if (x->mode == Addressing_Invalid) {
  6754. return false;
  6755. }
  6756. convert_to_typed(c, y, x->type);
  6757. if (y->mode == Addressing_Invalid) {
  6758. return false;
  6759. }
  6760. convert_to_typed(c, x, default_type(y->type));
  6761. if (x->mode == Addressing_Invalid) {
  6762. return false;
  6763. }
  6764. convert_to_typed(c, y, default_type(x->type));
  6765. if (y->mode == Addressing_Invalid) {
  6766. return false;
  6767. }
  6768. if (!are_types_identical(x->type, y->type)) {
  6769. if (x->type != t_invalid &&
  6770. y->type != t_invalid) {
  6771. gbString xt = type_to_string(x->type);
  6772. gbString yt = type_to_string(y->type);
  6773. gbString expr_str = expr_to_string(x->expr);
  6774. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  6775. gb_string_free(expr_str);
  6776. gb_string_free(yt);
  6777. gb_string_free(xt);
  6778. }
  6779. return false;
  6780. }
  6781. Type *type = x->type;
  6782. if (is_for_loop) {
  6783. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  6784. error(ie->op, "Only numerical types are allowed within interval expressions");
  6785. return false;
  6786. }
  6787. } else {
  6788. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  6789. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  6790. return false;
  6791. }
  6792. }
  6793. if (x->mode == Addressing_Constant &&
  6794. y->mode == Addressing_Constant) {
  6795. ExactValue a = x->value;
  6796. ExactValue b = y->value;
  6797. GB_ASSERT(are_types_identical(x->type, y->type));
  6798. TokenKind op = Token_Lt;
  6799. switch (ie->op.kind) {
  6800. case Token_Ellipsis: op = Token_LtEq; break; // ..
  6801. case Token_RangeFull: op = Token_LtEq; break; // ..=
  6802. case Token_RangeHalf: op = Token_Lt; break; // ..<
  6803. default: error(ie->op, "Invalid range operator"); break;
  6804. }
  6805. bool ok = compare_exact_values(op, a, b);
  6806. if (!ok) {
  6807. // TODO(bill): Better error message
  6808. error(ie->op, "Invalid interval range");
  6809. return false;
  6810. }
  6811. ExactValue inline_for_depth = exact_value_sub(b, a);
  6812. if (ie->op.kind != Token_RangeHalf) {
  6813. inline_for_depth = exact_value_increment_one(inline_for_depth);
  6814. }
  6815. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  6816. } else if (inline_for_depth_ != nullptr) {
  6817. error(ie->op, "Interval expressions must be constant");
  6818. return false;
  6819. }
  6820. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  6821. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  6822. return true;
  6823. }
  6824. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  6825. if (is_operand_nil(*o)) {
  6826. return true;
  6827. }
  6828. Ast *expr = unparen_expr(o->expr);
  6829. if (expr != nullptr) {
  6830. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  6831. if (e != nullptr && e->kind == Entity_Procedure) {
  6832. return true;
  6833. }
  6834. if (expr->kind == Ast_ProcLit) {
  6835. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  6836. return true;
  6837. }
  6838. }
  6839. return o->mode == Addressing_Constant;
  6840. }
  6841. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  6842. if (is_type_enum(th)) {
  6843. Type *enum_type = base_type(th);
  6844. GB_ASSERT(enum_type->kind == Type_Enum);
  6845. String name = ise->selector->Ident.token.string;
  6846. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  6847. if (e == nullptr) {
  6848. return false;
  6849. }
  6850. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  6851. GB_ASSERT(e->kind == Entity_Constant);
  6852. o->value = e->Constant.value;
  6853. o->mode = Addressing_Constant;
  6854. o->type = e->type;
  6855. return true;
  6856. }
  6857. if (is_type_union(th)) {
  6858. TEMPORARY_ALLOCATOR_GUARD();
  6859. Type *union_type = base_type(th);
  6860. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  6861. for (Type *vt : union_type->Union.variants) {
  6862. Operand x = {};
  6863. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  6864. array_add(&operands, x);
  6865. }
  6866. }
  6867. if (operands.count == 1) {
  6868. *o = operands[0];
  6869. return true;
  6870. }
  6871. }
  6872. return false;
  6873. }
  6874. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6875. ast_node(ise, ImplicitSelectorExpr, node);
  6876. o->type = t_invalid;
  6877. o->expr = node;
  6878. o->mode = Addressing_Invalid;
  6879. Type *th = type_hint;
  6880. if (th == nullptr) {
  6881. gbString str = expr_to_string(node);
  6882. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  6883. gb_string_free(str);
  6884. return Expr_Expr;
  6885. }
  6886. o->type = th;
  6887. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  6888. if (!ok) {
  6889. String name = ise->selector->Ident.token.string;
  6890. if (is_type_enum(th)) {
  6891. ERROR_BLOCK();
  6892. Type *bt = base_type(th);
  6893. GB_ASSERT(bt->kind == Type_Enum);
  6894. gbString typ = type_to_string(th);
  6895. defer (gb_string_free(typ));
  6896. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  6897. check_did_you_mean_type(name, bt->Enum.fields);
  6898. } else {
  6899. gbString typ = type_to_string(th);
  6900. gbString str = expr_to_string(node);
  6901. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  6902. gb_string_free(str);
  6903. gb_string_free(typ);
  6904. }
  6905. }
  6906. o->expr = node;
  6907. return Expr_Expr;
  6908. }
  6909. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  6910. switch (x->mode) {
  6911. case Addressing_MapIndex:
  6912. case Addressing_OptionalOk:
  6913. case Addressing_OptionalOkPtr:
  6914. if (val_type_) *val_type_ = x->type;
  6915. break;
  6916. default:
  6917. if (ok_type_) *ok_type_ = x->type;
  6918. return;
  6919. }
  6920. Ast *expr = unparen_expr(x->expr);
  6921. if (expr->kind == Ast_CallExpr) {
  6922. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  6923. if (is_type_proc(pt)) {
  6924. Type *tuple = pt->Proc.results;
  6925. if (pt->Proc.result_count >= 2) {
  6926. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6927. }
  6928. if (change_operand) {
  6929. expr->CallExpr.optional_ok_one = false;
  6930. x->type = tuple;
  6931. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6932. }
  6933. return;
  6934. }
  6935. }
  6936. Type *tuple = make_optional_ok_type(x->type);
  6937. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6938. if (change_operand) {
  6939. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6940. x->type = tuple;
  6941. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  6942. }
  6943. }
  6944. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6945. ast_node(ie, MatrixIndexExpr, node);
  6946. check_expr(c, o, ie->expr);
  6947. node->viral_state_flags |= ie->expr->viral_state_flags;
  6948. if (o->mode == Addressing_Invalid) {
  6949. o->expr = node;
  6950. return;
  6951. }
  6952. Type *t = base_type(type_deref(o->type));
  6953. bool is_ptr = is_type_pointer(o->type);
  6954. bool is_const = o->mode == Addressing_Constant;
  6955. if (t->kind != Type_Matrix) {
  6956. gbString str = expr_to_string(o->expr);
  6957. gbString type_str = type_to_string(o->type);
  6958. defer (gb_string_free(str));
  6959. defer (gb_string_free(type_str));
  6960. if (is_const) {
  6961. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  6962. } else {
  6963. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  6964. }
  6965. o->mode = Addressing_Invalid;
  6966. o->expr = node;
  6967. return;
  6968. }
  6969. o->type = t->Matrix.elem;
  6970. if (is_ptr) {
  6971. o->mode = Addressing_Variable;
  6972. } else if (o->mode != Addressing_Variable) {
  6973. o->mode = Addressing_Value;
  6974. }
  6975. if (ie->row_index == nullptr) {
  6976. gbString str = expr_to_string(o->expr);
  6977. error(o->expr, "Missing row index for '%s'", str);
  6978. gb_string_free(str);
  6979. o->mode = Addressing_Invalid;
  6980. o->expr = node;
  6981. return;
  6982. }
  6983. if (ie->column_index == nullptr) {
  6984. gbString str = expr_to_string(o->expr);
  6985. error(o->expr, "Missing column index for '%s'", str);
  6986. gb_string_free(str);
  6987. o->mode = Addressing_Invalid;
  6988. o->expr = node;
  6989. return;
  6990. }
  6991. i64 row_count = t->Matrix.row_count;
  6992. i64 column_count = t->Matrix.column_count;
  6993. i64 row_index = 0;
  6994. i64 column_index = 0;
  6995. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  6996. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  6997. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  6998. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  6999. }
  7000. gb_unused(row_ok);
  7001. gb_unused(column_ok);
  7002. }
  7003. struct TypeAndToken {
  7004. Type *type;
  7005. Token token;
  7006. };
  7007. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7008. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7009. if (operand.mode != Addressing_Constant) {
  7010. return;
  7011. }
  7012. if (operand.value.kind == ExactValue_Invalid) {
  7013. return;
  7014. }
  7015. uintptr key = hash_exact_value(operand.value);
  7016. TypeAndToken *found = map_get(seen, key);
  7017. if (found != nullptr) {
  7018. TEMPORARY_ALLOCATOR_GUARD();
  7019. isize count = multi_map_count(seen, key);
  7020. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  7021. multi_map_get_all(seen, key, taps);
  7022. for (isize i = 0; i < count; i++) {
  7023. TypeAndToken tap = taps[i];
  7024. Operand to = {};
  7025. to.mode = Addressing_Value;
  7026. to.type = tap.type;
  7027. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7028. continue;
  7029. }
  7030. TokenPos pos = tap.token.pos;
  7031. if (use_expr) {
  7032. gbString expr_str = expr_to_string(operand.expr);
  7033. error(operand.expr,
  7034. "Duplicate case '%s'\n"
  7035. "\tprevious case at %s",
  7036. expr_str,
  7037. token_pos_to_string(pos));
  7038. gb_string_free(expr_str);
  7039. } else {
  7040. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7041. }
  7042. return;
  7043. }
  7044. }
  7045. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7046. multi_map_insert(seen, key, tap);
  7047. }
  7048. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7049. if (is_type_enum(x.type)) {
  7050. // TODO(bill): Fix this logic so it's fast!!!
  7051. i64 v0 = exact_value_to_i64(lhs.value);
  7052. i64 v1 = exact_value_to_i64(rhs.value);
  7053. Operand v = {};
  7054. v.mode = Addressing_Constant;
  7055. v.type = x.type;
  7056. v.expr = x.expr;
  7057. Type *bt = base_type(x.type);
  7058. GB_ASSERT(bt->kind == Type_Enum);
  7059. for (i64 vi = v0; vi <= v1; vi++) {
  7060. if (upper_op != Token_LtEq && vi == v1) {
  7061. break;
  7062. }
  7063. v.value = exact_value_i64(vi);
  7064. add_constant_switch_case(ctx, seen, v);
  7065. }
  7066. } else {
  7067. add_constant_switch_case(ctx, seen, lhs);
  7068. if (upper_op == Token_LtEq) {
  7069. add_constant_switch_case(ctx, seen, rhs);
  7070. }
  7071. }
  7072. }
  7073. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7074. add_constant_switch_case(ctx, seen, x);
  7075. }
  7076. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7077. ast_node(bd, BasicDirective, node);
  7078. ExprKind kind = Expr_Expr;
  7079. o->mode = Addressing_Constant;
  7080. String name = bd->name.string;
  7081. if (name == "file") {
  7082. o->type = t_untyped_string;
  7083. o->value = exact_value_string(get_file_path_string(bd->token.pos.file_id));
  7084. } else if (name == "line") {
  7085. o->type = t_untyped_integer;
  7086. o->value = exact_value_i64(bd->token.pos.line);
  7087. } else if (name == "procedure") {
  7088. if (c->curr_proc_decl == nullptr) {
  7089. error(node, "#procedure may only be used within procedures");
  7090. o->type = t_untyped_string;
  7091. o->value = exact_value_string(str_lit(""));
  7092. } else {
  7093. o->type = t_untyped_string;
  7094. o->value = exact_value_string(c->proc_name);
  7095. }
  7096. } else if (name == "caller_location") {
  7097. init_core_source_code_location(c->checker);
  7098. error(node, "#caller_location may only be used as a default argument parameter");
  7099. o->type = t_source_code_location;
  7100. o->mode = Addressing_Value;
  7101. } else {
  7102. if (name == "location") {
  7103. init_core_source_code_location(c->checker);
  7104. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  7105. o->type = t_source_code_location;
  7106. o->mode = Addressing_Value;
  7107. } else if (
  7108. name == "assert" ||
  7109. name == "defined" ||
  7110. name == "config" ||
  7111. name == "load" ||
  7112. name == "load_hash" ||
  7113. name == "load_directory" ||
  7114. name == "load_or"
  7115. ) {
  7116. error(node, "'#%.*s' must be used as a call", LIT(name));
  7117. o->type = t_invalid;
  7118. o->mode = Addressing_Invalid;
  7119. } else {
  7120. error(node, "Unknown directive: #%.*s", LIT(name));
  7121. o->type = t_invalid;
  7122. o->mode = Addressing_Invalid;
  7123. }
  7124. }
  7125. return kind;
  7126. }
  7127. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7128. ExprKind kind = Expr_Expr;
  7129. Operand cond = {Addressing_Invalid};
  7130. ast_node(te, TernaryIfExpr, node);
  7131. check_expr(c, &cond, te->cond);
  7132. node->viral_state_flags |= te->cond->viral_state_flags;
  7133. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7134. error(te->cond, "Non-boolean condition in ternary if expression");
  7135. }
  7136. Operand x = {Addressing_Invalid};
  7137. Operand y = {Addressing_Invalid};
  7138. check_expr_or_type(c, &x, te->x, type_hint);
  7139. node->viral_state_flags |= te->x->viral_state_flags;
  7140. if (te->y != nullptr) {
  7141. Type *th = type_hint;
  7142. if (type_hint == nullptr && is_type_typed(x.type)) {
  7143. th = x.type;
  7144. }
  7145. check_expr_or_type(c, &y, te->y, th);
  7146. node->viral_state_flags |= te->y->viral_state_flags;
  7147. } else {
  7148. error(node, "A ternary expression must have an else clause");
  7149. return kind;
  7150. }
  7151. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7152. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7153. gbString type_string = expr_to_string(type_expr);
  7154. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7155. gb_string_free(type_string);
  7156. return kind;
  7157. }
  7158. if (x.type == nullptr || x.type == t_invalid ||
  7159. y.type == nullptr || y.type == t_invalid) {
  7160. return kind;
  7161. }
  7162. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7163. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7164. if (x.mode == Addressing_Invalid) {
  7165. return kind;
  7166. }
  7167. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7168. if (y.mode == Addressing_Invalid) {
  7169. x.mode = Addressing_Invalid;
  7170. return kind;
  7171. }
  7172. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7173. // x: union{f32} = f32(123) if cond else nil
  7174. if (type_hint && !is_type_any(type_hint)) {
  7175. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7176. check_cast(c, &x, type_hint);
  7177. check_cast(c, &y, type_hint);
  7178. }
  7179. }
  7180. if (!ternary_compare_types(x.type, y.type)) {
  7181. gbString its = type_to_string(x.type);
  7182. gbString ets = type_to_string(y.type);
  7183. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7184. gb_string_free(ets);
  7185. gb_string_free(its);
  7186. return kind;
  7187. }
  7188. o->type = x.type;
  7189. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  7190. o->type = y.type;
  7191. }
  7192. o->mode = Addressing_Value;
  7193. o->expr = node;
  7194. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7195. if (check_cast_internal(c, &x, type_hint) &&
  7196. check_cast_internal(c, &y, type_hint)) {
  7197. convert_to_typed(c, o, type_hint);
  7198. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7199. o->type = type_hint;
  7200. }
  7201. }
  7202. return kind;
  7203. }
  7204. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7205. ExprKind kind = Expr_Expr;
  7206. Operand cond = {};
  7207. ast_node(te, TernaryWhenExpr, node);
  7208. check_expr(c, &cond, te->cond);
  7209. node->viral_state_flags |= te->cond->viral_state_flags;
  7210. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7211. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7212. return kind;
  7213. }
  7214. if (cond.value.value_bool) {
  7215. check_expr_or_type(c, o, te->x, type_hint);
  7216. node->viral_state_flags |= te->x->viral_state_flags;
  7217. } else {
  7218. if (te->y != nullptr) {
  7219. check_expr_or_type(c, o, te->y, type_hint);
  7220. node->viral_state_flags |= te->y->viral_state_flags;
  7221. } else {
  7222. error(node, "A ternary when expression must have an else clause");
  7223. return kind;
  7224. }
  7225. }
  7226. return kind;
  7227. }
  7228. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7229. ast_node(oe, OrElseExpr, node);
  7230. String name = oe->token.string;
  7231. Ast *arg = oe->x;
  7232. Ast *default_value = oe->y;
  7233. Operand x = {};
  7234. Operand y = {};
  7235. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7236. if (is_load_directive_call(arg)) {
  7237. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7238. // Allow for chaining of '#load(path) or_else #load(path)'
  7239. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  7240. bool y_is_diverging = false;
  7241. check_expr_base(c, &y, default_value, x.type);
  7242. switch (y.mode) {
  7243. case Addressing_NoValue:
  7244. if (is_diverging_expr(y.expr)) {
  7245. // Allow
  7246. y.mode = Addressing_Value;
  7247. y_is_diverging = true;
  7248. } else {
  7249. error_operand_no_value(&y);
  7250. y.mode = Addressing_Invalid;
  7251. }
  7252. break;
  7253. case Addressing_Type:
  7254. error_operand_not_expression(&y);
  7255. y.mode = Addressing_Invalid;
  7256. break;
  7257. }
  7258. if (y.mode == Addressing_Invalid) {
  7259. o->mode = Addressing_Value;
  7260. o->type = t_invalid;
  7261. o->expr = node;
  7262. return Expr_Expr;
  7263. }
  7264. if (!y_is_diverging) {
  7265. check_assignment(c, &y, x.type, name);
  7266. if (y.mode != Addressing_Constant) {
  7267. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7268. }
  7269. }
  7270. }
  7271. if (res == LoadDirective_Success) {
  7272. *o = x;
  7273. } else {
  7274. *o = y;
  7275. }
  7276. o->expr = node;
  7277. return Expr_Expr;
  7278. }
  7279. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7280. if (x.mode == Addressing_Invalid) {
  7281. o->mode = Addressing_Value;
  7282. o->type = t_invalid;
  7283. o->expr = node;
  7284. return Expr_Expr;
  7285. }
  7286. bool y_is_diverging = false;
  7287. check_expr_base(c, &y, default_value, x.type);
  7288. switch (y.mode) {
  7289. case Addressing_NoValue:
  7290. if (is_diverging_expr(y.expr)) {
  7291. // Allow
  7292. y.mode = Addressing_Value;
  7293. y_is_diverging = true;
  7294. } else {
  7295. error_operand_no_value(&y);
  7296. y.mode = Addressing_Invalid;
  7297. }
  7298. break;
  7299. case Addressing_Type:
  7300. error_operand_not_expression(&y);
  7301. y.mode = Addressing_Invalid;
  7302. break;
  7303. }
  7304. if (y.mode == Addressing_Invalid) {
  7305. o->mode = Addressing_Value;
  7306. o->type = t_invalid;
  7307. o->expr = node;
  7308. return Expr_Expr;
  7309. }
  7310. Type *left_type = nullptr;
  7311. Type *right_type = nullptr;
  7312. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7313. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7314. if (left_type != nullptr) {
  7315. if (!y_is_diverging) {
  7316. check_assignment(c, &y, left_type, name);
  7317. }
  7318. } else {
  7319. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7320. }
  7321. if (left_type == nullptr) {
  7322. left_type = t_invalid;
  7323. }
  7324. o->mode = Addressing_Value;
  7325. o->type = left_type;
  7326. o->expr = node;
  7327. return Expr_Expr;
  7328. }
  7329. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7330. ast_node(re, OrReturnExpr, node);
  7331. String name = re->token.string;
  7332. Operand x = {};
  7333. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  7334. if (x.mode == Addressing_Invalid) {
  7335. o->mode = Addressing_Value;
  7336. o->type = t_invalid;
  7337. o->expr = node;
  7338. return Expr_Expr;
  7339. }
  7340. Type *left_type = nullptr;
  7341. Type *right_type = nullptr;
  7342. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7343. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  7344. if (right_type == nullptr) {
  7345. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7346. } else {
  7347. Type *proc_type = base_type(c->curr_proc_sig);
  7348. GB_ASSERT(proc_type->kind == Type_Proc);
  7349. Type *result_type = proc_type->Proc.results;
  7350. if (result_type == nullptr) {
  7351. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  7352. } else {
  7353. GB_ASSERT(result_type->kind == Type_Tuple);
  7354. auto const &vars = result_type->Tuple.variables;
  7355. Type *end_type = vars[vars.count-1]->type;
  7356. if (vars.count > 1) {
  7357. if (!proc_type->Proc.has_named_results) {
  7358. 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));
  7359. }
  7360. }
  7361. Operand rhs = {};
  7362. rhs.type = right_type;
  7363. rhs.mode = Addressing_Value;
  7364. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  7365. // NOTE(bill): allow implicit conversion between boolean types
  7366. // within 'or_return' to improve the experience using third-party code
  7367. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  7368. // TODO(bill): better error message
  7369. gbString a = type_to_string(right_type);
  7370. gbString b = type_to_string(end_type);
  7371. gbString ret_type = type_to_string(result_type);
  7372. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  7373. if (vars.count == 1) {
  7374. error_line("\tProcedure return value type: %s\n", ret_type);
  7375. } else {
  7376. error_line("\tProcedure return value types: (%s)\n", ret_type);
  7377. }
  7378. gb_string_free(ret_type);
  7379. gb_string_free(b);
  7380. gb_string_free(a);
  7381. }
  7382. }
  7383. }
  7384. o->expr = node;
  7385. o->type = left_type;
  7386. if (left_type != nullptr) {
  7387. o->mode = Addressing_Value;
  7388. } else {
  7389. o->mode = Addressing_NoValue;
  7390. }
  7391. if (c->curr_proc_sig == nullptr) {
  7392. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7393. }
  7394. if (c->in_defer) {
  7395. error(node, "'or_return' cannot be used within a defer statement");
  7396. }
  7397. return Expr_Expr;
  7398. }
  7399. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7400. ast_node(be, OrBranchExpr, node);
  7401. String name = be->token.string;
  7402. Operand x = {};
  7403. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  7404. if (x.mode == Addressing_Invalid) {
  7405. o->mode = Addressing_Value;
  7406. o->type = t_invalid;
  7407. o->expr = node;
  7408. return Expr_Expr;
  7409. }
  7410. Type *left_type = nullptr;
  7411. Type *right_type = nullptr;
  7412. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7413. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  7414. if (right_type == nullptr) {
  7415. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7416. } else {
  7417. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  7418. // okay
  7419. } else {
  7420. gbString s = type_to_string(right_type);
  7421. error(node, "'%.*s' requires a boolean or nil-able type, got %s", s);
  7422. gb_string_free(s);
  7423. }
  7424. }
  7425. o->expr = node;
  7426. o->type = left_type;
  7427. if (left_type != nullptr) {
  7428. o->mode = Addressing_Value;
  7429. } else {
  7430. o->mode = Addressing_NoValue;
  7431. }
  7432. if (c->curr_proc_sig == nullptr) {
  7433. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7434. }
  7435. Ast *label = be->label;
  7436. switch (be->token.kind) {
  7437. case Token_or_break:
  7438. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  7439. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  7440. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  7441. }
  7442. break;
  7443. case Token_or_continue:
  7444. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  7445. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  7446. }
  7447. break;
  7448. }
  7449. if (label != nullptr) {
  7450. if (label->kind != Ast_Ident) {
  7451. error(label, "A branch statement's label name must be an identifier");
  7452. return Expr_Expr;
  7453. }
  7454. Ast *ident = label;
  7455. String name = ident->Ident.token.string;
  7456. Operand o = {};
  7457. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  7458. if (e == nullptr) {
  7459. error(ident, "Undeclared label name: %.*s", LIT(name));
  7460. return Expr_Expr;
  7461. }
  7462. add_entity_use(c, ident, e);
  7463. if (e->kind != Entity_Label) {
  7464. error(ident, "'%.*s' is not a label", LIT(name));
  7465. return Expr_Expr;
  7466. }
  7467. Ast *parent = e->Label.parent;
  7468. GB_ASSERT(parent != nullptr);
  7469. switch (parent->kind) {
  7470. case Ast_BlockStmt:
  7471. case Ast_IfStmt:
  7472. case Ast_SwitchStmt:
  7473. if (be->token.kind != Token_or_break) {
  7474. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  7475. }
  7476. break;
  7477. case Ast_RangeStmt:
  7478. case Ast_ForStmt:
  7479. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  7480. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  7481. }
  7482. break;
  7483. }
  7484. }
  7485. return Expr_Expr;
  7486. }
  7487. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  7488. Type *bt = base_type(type);
  7489. StringSet fields_visited = {};
  7490. defer (string_set_destroy(&fields_visited));
  7491. StringMap<String> fields_visited_through_raw_union = {};
  7492. defer (string_map_destroy(&fields_visited_through_raw_union));
  7493. String assignment_str = str_lit("structure literal");
  7494. if (bt->kind == Type_BitField) {
  7495. assignment_str = str_lit("bit_field literal");
  7496. }
  7497. for (Ast *elem : elems) {
  7498. if (elem->kind != Ast_FieldValue) {
  7499. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7500. continue;
  7501. }
  7502. ast_node(fv, FieldValue, elem);
  7503. Ast *ident = fv->field;
  7504. if (ident->kind == Ast_ImplicitSelectorExpr) {
  7505. gbString expr_str = expr_to_string(ident);
  7506. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  7507. gb_string_free(expr_str);
  7508. ident = ident->ImplicitSelectorExpr.selector;
  7509. }
  7510. if (ident->kind != Ast_Ident) {
  7511. gbString expr_str = expr_to_string(ident);
  7512. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  7513. gb_string_free(expr_str);
  7514. continue;
  7515. }
  7516. String name = ident->Ident.token.string;
  7517. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7518. bool is_unknown = sel.entity == nullptr;
  7519. if (is_unknown) {
  7520. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  7521. continue;
  7522. }
  7523. Entity *field = nullptr;
  7524. if (bt->kind == Type_Struct) {
  7525. field = bt->Struct.fields[sel.index[0]];
  7526. } else if (bt->kind == Type_BitField) {
  7527. field = bt->BitField.fields[sel.index[0]];
  7528. } else {
  7529. GB_PANIC("Unknown type");
  7530. }
  7531. add_entity_use(c, ident, field);
  7532. if (string_set_update(&fields_visited, name)) {
  7533. if (sel.index.count > 1) {
  7534. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7535. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7536. } else {
  7537. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  7538. }
  7539. } else {
  7540. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  7541. }
  7542. continue;
  7543. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7544. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7545. continue;
  7546. }
  7547. if (sel.indirect) {
  7548. 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));
  7549. continue;
  7550. }
  7551. if (sel.index.count > 1) {
  7552. GB_ASSERT(bt->kind == Type_Struct);
  7553. if (is_constant) {
  7554. Type *ft = type;
  7555. for (i32 index : sel.index) {
  7556. Type *bt = base_type(ft);
  7557. switch (bt->kind) {
  7558. case Type_Struct:
  7559. if (bt->Struct.is_raw_union) {
  7560. is_constant = false;
  7561. break;
  7562. }
  7563. ft = bt->Struct.fields[index]->type;
  7564. break;
  7565. case Type_Array:
  7566. ft = bt->Array.elem;
  7567. break;
  7568. default:
  7569. GB_PANIC("invalid type: %s", type_to_string(ft));
  7570. break;
  7571. }
  7572. }
  7573. if (is_constant &&
  7574. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  7575. is_constant = false;
  7576. }
  7577. }
  7578. Type *nested_ft = bt;
  7579. for (i32 index : sel.index) {
  7580. Type *bt = base_type(nested_ft);
  7581. switch (bt->kind) {
  7582. case Type_Struct:
  7583. if (bt->Struct.is_raw_union) {
  7584. for (Entity *re : bt->Struct.fields) {
  7585. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  7586. }
  7587. }
  7588. nested_ft = bt->Struct.fields[index]->type;
  7589. break;
  7590. case Type_Array:
  7591. nested_ft = bt->Array.elem;
  7592. break;
  7593. default:
  7594. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  7595. break;
  7596. }
  7597. }
  7598. field = sel.entity;
  7599. }
  7600. Operand o = {};
  7601. check_expr_or_type(c, &o, fv->value, field->type);
  7602. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7603. is_constant = false;
  7604. }
  7605. if (is_constant) {
  7606. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7607. }
  7608. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  7609. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  7610. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  7611. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  7612. }
  7613. check_assignment(c, &o, field->type, assignment_str);
  7614. c->bit_field_bit_size = prev_bit_field_bit_size;
  7615. }
  7616. }
  7617. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  7618. type_expr = unparen_expr(type_expr);
  7619. if (type_expr == nullptr) {
  7620. return false;
  7621. }
  7622. // [?]Type
  7623. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  7624. Ast *count = type_expr->ArrayType.count;
  7625. if (count->kind == Ast_UnaryExpr &&
  7626. count->UnaryExpr.op.kind == Token_Question) {
  7627. return true;
  7628. }
  7629. }
  7630. return false;
  7631. }
  7632. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7633. ExprKind kind = Expr_Expr;
  7634. ast_node(cl, CompoundLit, node);
  7635. Type *type = type_hint;
  7636. if (type != nullptr && is_type_untyped(type)) {
  7637. type = nullptr;
  7638. }
  7639. bool is_to_be_determined_array_count = false;
  7640. bool is_constant = true;
  7641. Ast *type_expr = cl->type;
  7642. bool used_type_hint_expr = false;
  7643. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  7644. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  7645. type_expr = clone_ast(c->type_hint_expr);
  7646. used_type_hint_expr = true;
  7647. }
  7648. }
  7649. if (type_expr != nullptr) {
  7650. type = nullptr;
  7651. // [?]Type
  7652. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  7653. Ast *count = type_expr->ArrayType.count;
  7654. if (count->kind == Ast_UnaryExpr &&
  7655. count->UnaryExpr.op.kind == Token_Question) {
  7656. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  7657. is_to_be_determined_array_count = true;
  7658. }
  7659. if (cl->elems.count > 0) {
  7660. if (type_expr->ArrayType.tag != nullptr) {
  7661. Ast *tag = type_expr->ArrayType.tag;
  7662. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7663. String name = tag->BasicDirective.name.string;
  7664. if (name == "soa") {
  7665. error(node, "#soa arrays are not supported for compound literals");
  7666. return kind;
  7667. }
  7668. }
  7669. }
  7670. }
  7671. if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  7672. if (cl->elems.count > 0) {
  7673. Ast *tag = type_expr->DynamicArrayType.tag;
  7674. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7675. String name = tag->BasicDirective.name.string;
  7676. if (name == "soa") {
  7677. error(node, "#soa arrays are not supported for compound literals");
  7678. return kind;
  7679. }
  7680. }
  7681. }
  7682. if (type == nullptr) {
  7683. type = check_type(c, type_expr);
  7684. }
  7685. }
  7686. if (type == nullptr) {
  7687. error(node, "Missing type in compound literal");
  7688. return kind;
  7689. }
  7690. Type *t = base_type(type);
  7691. if (is_type_polymorphic(t)) {
  7692. gbString str = type_to_string(type);
  7693. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  7694. o->expr = node;
  7695. o->type = type;
  7696. gb_string_free(str);
  7697. return kind;
  7698. }
  7699. switch (t->kind) {
  7700. case Type_Struct: {
  7701. if (cl->elems.count == 0) {
  7702. break; // NOTE(bill): No need to init
  7703. }
  7704. if (t->Struct.is_raw_union) {
  7705. if (cl->elems.count > 0) {
  7706. // NOTE: unions cannot be constant
  7707. is_constant = false;
  7708. if (cl->elems[0]->kind != Ast_FieldValue) {
  7709. gbString type_str = type_to_string(type);
  7710. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  7711. gb_string_free(type_str);
  7712. } else {
  7713. if (cl->elems.count != 1) {
  7714. gbString type_str = type_to_string(type);
  7715. 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);
  7716. gb_string_free(type_str);
  7717. } else {
  7718. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7719. }
  7720. }
  7721. }
  7722. break;
  7723. }
  7724. isize field_count = t->Struct.fields.count;
  7725. isize min_field_count = t->Struct.fields.count;
  7726. for (isize i = min_field_count-1; i >= 0; i--) {
  7727. Entity *e = t->Struct.fields[i];
  7728. GB_ASSERT(e->kind == Entity_Variable);
  7729. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  7730. min_field_count--;
  7731. } else {
  7732. break;
  7733. }
  7734. }
  7735. if (cl->elems[0]->kind == Ast_FieldValue) {
  7736. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7737. } else {
  7738. bool seen_field_value = false;
  7739. for_array(index, cl->elems) {
  7740. Entity *field = nullptr;
  7741. Ast *elem = cl->elems[index];
  7742. if (elem->kind == Ast_FieldValue) {
  7743. seen_field_value = true;
  7744. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7745. continue;
  7746. } else if (seen_field_value) {
  7747. error(elem, "Value elements cannot be used after a 'field = value'");
  7748. continue;
  7749. }
  7750. if (index >= field_count) {
  7751. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7752. break;
  7753. }
  7754. if (field == nullptr) {
  7755. field = t->Struct.fields[index];
  7756. }
  7757. Operand o = {};
  7758. check_expr_or_type(c, &o, elem, field->type);
  7759. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7760. is_constant = false;
  7761. }
  7762. if (is_constant) {
  7763. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7764. }
  7765. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7766. }
  7767. if (cl->elems.count < field_count) {
  7768. if (min_field_count < field_count) {
  7769. if (cl->elems.count < min_field_count) {
  7770. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  7771. }
  7772. } else {
  7773. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7774. }
  7775. }
  7776. }
  7777. break;
  7778. }
  7779. case Type_Slice:
  7780. case Type_Array:
  7781. case Type_DynamicArray:
  7782. case Type_SimdVector:
  7783. case Type_Matrix:
  7784. {
  7785. Type *elem_type = nullptr;
  7786. String context_name = {};
  7787. i64 max_type_count = -1;
  7788. if (t->kind == Type_Slice) {
  7789. elem_type = t->Slice.elem;
  7790. context_name = str_lit("slice literal");
  7791. } else if (t->kind == Type_Array) {
  7792. elem_type = t->Array.elem;
  7793. context_name = str_lit("array literal");
  7794. if (!is_to_be_determined_array_count) {
  7795. max_type_count = t->Array.count;
  7796. }
  7797. } else if (t->kind == Type_DynamicArray) {
  7798. elem_type = t->DynamicArray.elem;
  7799. context_name = str_lit("dynamic array literal");
  7800. is_constant = false;
  7801. if (!build_context.no_dynamic_literals) {
  7802. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  7803. add_package_dependency(c, "runtime", "__dynamic_array_append");
  7804. }
  7805. } else if (t->kind == Type_SimdVector) {
  7806. elem_type = t->SimdVector.elem;
  7807. context_name = str_lit("simd vector literal");
  7808. max_type_count = t->SimdVector.count;
  7809. } else if (t->kind == Type_Matrix) {
  7810. elem_type = t->Matrix.elem;
  7811. context_name = str_lit("matrix literal");
  7812. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  7813. } else {
  7814. GB_PANIC("unreachable");
  7815. }
  7816. i64 max = 0;
  7817. Type *bet = base_type(elem_type);
  7818. if (!elem_type_can_be_constant(bet)) {
  7819. is_constant = false;
  7820. }
  7821. if (bet == t_invalid) {
  7822. break;
  7823. }
  7824. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7825. RangeCache rc = range_cache_make(heap_allocator());
  7826. defer (range_cache_destroy(&rc));
  7827. for (Ast *elem : cl->elems) {
  7828. if (elem->kind != Ast_FieldValue) {
  7829. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7830. continue;
  7831. }
  7832. ast_node(fv, FieldValue, elem);
  7833. if (is_ast_range(fv->field)) {
  7834. Token op = fv->field->BinaryExpr.op;
  7835. Operand x = {};
  7836. Operand y = {};
  7837. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  7838. if (!ok) {
  7839. continue;
  7840. }
  7841. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  7842. error(x.expr, "Expected a constant integer as an array field");
  7843. continue;
  7844. }
  7845. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  7846. error(y.expr, "Expected a constant integer as an array field");
  7847. continue;
  7848. }
  7849. i64 lo = exact_value_to_i64(x.value);
  7850. i64 hi = exact_value_to_i64(y.value);
  7851. i64 max_index = hi;
  7852. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  7853. hi -= 1;
  7854. } else { // .. (inclusive)
  7855. max_index += 1;
  7856. }
  7857. bool new_range = range_cache_add_range(&rc, lo, hi);
  7858. if (!new_range) {
  7859. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  7860. continue;
  7861. }
  7862. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  7863. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  7864. continue;
  7865. }
  7866. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  7867. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  7868. continue;
  7869. }
  7870. if (max < hi) {
  7871. max = max_index;
  7872. }
  7873. Operand operand = {};
  7874. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7875. check_assignment(c, &operand, elem_type, context_name);
  7876. is_constant = is_constant && operand.mode == Addressing_Constant;
  7877. } else {
  7878. Operand op_index = {};
  7879. check_expr(c, &op_index, fv->field);
  7880. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  7881. error(elem, "Expected a constant integer as an array field");
  7882. continue;
  7883. }
  7884. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  7885. i64 index = exact_value_to_i64(op_index.value);
  7886. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  7887. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  7888. continue;
  7889. }
  7890. bool new_index = range_cache_add_index(&rc, index);
  7891. if (!new_index) {
  7892. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  7893. continue;
  7894. }
  7895. if (max < index+1) {
  7896. max = index+1;
  7897. }
  7898. Operand operand = {};
  7899. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7900. check_assignment(c, &operand, elem_type, context_name);
  7901. is_constant = is_constant && operand.mode == Addressing_Constant;
  7902. }
  7903. }
  7904. cl->max_count = max;
  7905. } else {
  7906. isize index = 0;
  7907. for (; index < cl->elems.count; index++) {
  7908. Ast *e = cl->elems[index];
  7909. if (e == nullptr) {
  7910. error(node, "Invalid literal element");
  7911. continue;
  7912. }
  7913. if (e->kind == Ast_FieldValue) {
  7914. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7915. continue;
  7916. }
  7917. if (0 <= max_type_count && max_type_count <= index) {
  7918. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  7919. }
  7920. Operand operand = {};
  7921. check_expr_with_type_hint(c, &operand, e, elem_type);
  7922. check_assignment(c, &operand, elem_type, context_name);
  7923. is_constant = is_constant && operand.mode == Addressing_Constant;
  7924. }
  7925. if (max < index) {
  7926. max = index;
  7927. }
  7928. }
  7929. if (t->kind == Type_Array) {
  7930. if (is_to_be_determined_array_count) {
  7931. t->Array.count = max;
  7932. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7933. if (0 < max && max < t->Array.count) {
  7934. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  7935. }
  7936. }
  7937. }
  7938. if (t->kind == Type_SimdVector) {
  7939. if (!is_constant) {
  7940. // error(node, "Expected all constant elements for a simd vector");
  7941. }
  7942. }
  7943. if (t->kind == Type_DynamicArray) {
  7944. if (build_context.no_dynamic_literals && cl->elems.count) {
  7945. error(node, "Compound literals of dynamic types have been disabled");
  7946. }
  7947. }
  7948. if (t->kind == Type_Matrix) {
  7949. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7950. if (0 < max && max < max_type_count) {
  7951. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  7952. }
  7953. }
  7954. }
  7955. break;
  7956. }
  7957. case Type_EnumeratedArray:
  7958. {
  7959. Type *elem_type = t->EnumeratedArray.elem;
  7960. Type *index_type = t->EnumeratedArray.index;
  7961. String context_name = str_lit("enumerated array literal");
  7962. i64 max_type_count = t->EnumeratedArray.count;
  7963. gbString index_type_str = type_to_string(index_type);
  7964. defer (gb_string_free(index_type_str));
  7965. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  7966. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  7967. String total_lo_string = {};
  7968. String total_hi_string = {};
  7969. GB_ASSERT(is_type_enum(index_type));
  7970. {
  7971. Type *bt = base_type(index_type);
  7972. GB_ASSERT(bt->kind == Type_Enum);
  7973. for (Entity *f : bt->Enum.fields) {
  7974. if (f->kind != Entity_Constant) {
  7975. continue;
  7976. }
  7977. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  7978. total_lo_string = f->token.string;
  7979. }
  7980. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  7981. total_hi_string = f->token.string;
  7982. }
  7983. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  7984. break;
  7985. }
  7986. }
  7987. }
  7988. i64 max = 0;
  7989. Type *bet = base_type(elem_type);
  7990. if (!elem_type_can_be_constant(bet)) {
  7991. is_constant = false;
  7992. }
  7993. if (bet == t_invalid) {
  7994. break;
  7995. }
  7996. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  7997. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  7998. defer (map_destroy(&seen));
  7999. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8000. RangeCache rc = range_cache_make(heap_allocator());
  8001. defer (range_cache_destroy(&rc));
  8002. for (Ast *elem : cl->elems) {
  8003. if (elem->kind != Ast_FieldValue) {
  8004. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8005. continue;
  8006. }
  8007. ast_node(fv, FieldValue, elem);
  8008. if (is_ast_range(fv->field)) {
  8009. Token op = fv->field->BinaryExpr.op;
  8010. Operand x = {};
  8011. Operand y = {};
  8012. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8013. if (!ok) {
  8014. continue;
  8015. }
  8016. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8017. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8018. continue;
  8019. }
  8020. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8021. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8022. continue;
  8023. }
  8024. i64 lo = exact_value_to_i64(x.value);
  8025. i64 hi = exact_value_to_i64(y.value);
  8026. i64 max_index = hi;
  8027. if (op.kind == Token_RangeHalf) {
  8028. hi -= 1;
  8029. }
  8030. bool new_range = range_cache_add_range(&rc, lo, hi);
  8031. if (!new_range) {
  8032. gbString lo_str = expr_to_string(x.expr);
  8033. gbString hi_str = expr_to_string(y.expr);
  8034. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8035. gb_string_free(hi_str);
  8036. gb_string_free(lo_str);
  8037. continue;
  8038. }
  8039. // NOTE(bill): These are sanity checks for invalid enum values
  8040. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8041. gbString lo_str = expr_to_string(x.expr);
  8042. 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));
  8043. gb_string_free(lo_str);
  8044. continue;
  8045. }
  8046. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8047. gbString hi_str = expr_to_string(y.expr);
  8048. 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));
  8049. gb_string_free(hi_str);
  8050. continue;
  8051. }
  8052. if (max < hi) {
  8053. max = max_index;
  8054. }
  8055. Operand operand = {};
  8056. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8057. check_assignment(c, &operand, elem_type, context_name);
  8058. is_constant = is_constant && operand.mode == Addressing_Constant;
  8059. TokenKind upper_op = Token_LtEq;
  8060. if (op.kind == Token_RangeHalf) {
  8061. upper_op = Token_Lt;
  8062. }
  8063. add_to_seen_map(c, &seen, upper_op, x, x, y);
  8064. } else {
  8065. Operand op_index = {};
  8066. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8067. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8068. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8069. continue;
  8070. }
  8071. i64 index = exact_value_to_i64(op_index.value);
  8072. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8073. gbString idx_str = expr_to_string(op_index.expr);
  8074. 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));
  8075. gb_string_free(idx_str);
  8076. continue;
  8077. }
  8078. bool new_index = range_cache_add_index(&rc, index);
  8079. if (!new_index) {
  8080. gbString idx_str = expr_to_string(op_index.expr);
  8081. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8082. gb_string_free(idx_str);
  8083. continue;
  8084. }
  8085. if (max < index+1) {
  8086. max = index+1;
  8087. }
  8088. Operand operand = {};
  8089. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8090. check_assignment(c, &operand, elem_type, context_name);
  8091. is_constant = is_constant && operand.mode == Addressing_Constant;
  8092. add_to_seen_map(c, &seen, op_index);
  8093. }
  8094. }
  8095. cl->max_count = max;
  8096. } else {
  8097. isize index = 0;
  8098. for (; index < cl->elems.count; index++) {
  8099. Ast *e = cl->elems[index];
  8100. if (e == nullptr) {
  8101. error(node, "Invalid literal element");
  8102. continue;
  8103. }
  8104. if (e->kind == Ast_FieldValue) {
  8105. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8106. continue;
  8107. }
  8108. if (0 <= max_type_count && max_type_count <= index) {
  8109. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8110. }
  8111. Operand operand = {};
  8112. check_expr_with_type_hint(c, &operand, e, elem_type);
  8113. check_assignment(c, &operand, elem_type, context_name);
  8114. is_constant = is_constant && operand.mode == Addressing_Constant;
  8115. }
  8116. if (max < index) {
  8117. max = index;
  8118. }
  8119. }
  8120. bool was_error = false;
  8121. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8122. if (0 < max && max < t->EnumeratedArray.count) {
  8123. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  8124. was_error = true;
  8125. } else {
  8126. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  8127. was_error = true;
  8128. }
  8129. }
  8130. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  8131. if (cl->elems.count > 0 && !was_error && !is_partial) {
  8132. TEMPORARY_ALLOCATOR_GUARD();
  8133. Type *et = base_type(index_type);
  8134. GB_ASSERT(et->kind == Type_Enum);
  8135. auto fields = et->Enum.fields;
  8136. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  8137. for (Entity *f : fields) {
  8138. if (f->kind != Entity_Constant) {
  8139. continue;
  8140. }
  8141. ExactValue v = f->Constant.value;
  8142. auto found = map_get(&seen, hash_exact_value(v));
  8143. if (!found) {
  8144. array_add(&unhandled, f);
  8145. }
  8146. }
  8147. if (unhandled.count > 0) {
  8148. ERROR_BLOCK();
  8149. if (unhandled.count == 1) {
  8150. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  8151. } else {
  8152. error(node, "Unhandled enumerated array cases:");
  8153. for_array(i, unhandled) {
  8154. Entity *f = unhandled[i];
  8155. error_line("\t%.*s\n", LIT(f->token.string));
  8156. }
  8157. }
  8158. if (!build_context.terse_errors) {
  8159. error_line("\n");
  8160. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  8161. }
  8162. }
  8163. }
  8164. break;
  8165. }
  8166. case Type_Basic: {
  8167. if (!is_type_any(t)) {
  8168. if (cl->elems.count != 0) {
  8169. gbString s = type_to_string(t);
  8170. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  8171. gb_string_free(s);
  8172. is_constant = false;
  8173. }
  8174. break;
  8175. }
  8176. if (cl->elems.count == 0) {
  8177. break; // NOTE(bill): No need to init
  8178. }
  8179. { // Checker values
  8180. Type *field_types[2] = {t_rawptr, t_typeid};
  8181. isize field_count = 2;
  8182. if (cl->elems[0]->kind == Ast_FieldValue) {
  8183. bool fields_visited[2] = {};
  8184. for_array(i, cl->elems) {
  8185. Ast *elem = cl->elems[i];
  8186. if (elem->kind != Ast_FieldValue) {
  8187. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8188. continue;
  8189. }
  8190. ast_node(fv, FieldValue, elem);
  8191. if (fv->field->kind != Ast_Ident) {
  8192. gbString expr_str = expr_to_string(fv->field);
  8193. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  8194. gb_string_free(expr_str);
  8195. continue;
  8196. }
  8197. String name = fv->field->Ident.token.string;
  8198. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8199. if (sel.entity == nullptr) {
  8200. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  8201. continue;
  8202. }
  8203. isize index = sel.index[0];
  8204. if (fields_visited[index]) {
  8205. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  8206. continue;
  8207. }
  8208. fields_visited[index] = true;
  8209. check_expr(c, o, fv->value);
  8210. // NOTE(bill): 'any' literals can never be constant
  8211. is_constant = false;
  8212. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8213. }
  8214. } else {
  8215. for_array(index, cl->elems) {
  8216. Ast *elem = cl->elems[index];
  8217. if (elem->kind == Ast_FieldValue) {
  8218. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8219. continue;
  8220. }
  8221. check_expr(c, o, elem);
  8222. if (index >= field_count) {
  8223. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  8224. break;
  8225. }
  8226. // NOTE(bill): 'any' literals can never be constant
  8227. is_constant = false;
  8228. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8229. }
  8230. if (cl->elems.count < field_count) {
  8231. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  8232. }
  8233. }
  8234. }
  8235. break;
  8236. }
  8237. case Type_Map: {
  8238. if (cl->elems.count == 0) {
  8239. break;
  8240. }
  8241. is_constant = false;
  8242. { // Checker values
  8243. bool key_is_typeid = is_type_typeid(t->Map.key);
  8244. bool value_is_typeid = is_type_typeid(t->Map.value);
  8245. for (Ast *elem : cl->elems) {
  8246. if (elem->kind != Ast_FieldValue) {
  8247. error(elem, "Only 'field = value' elements are allowed in a map literal");
  8248. continue;
  8249. }
  8250. ast_node(fv, FieldValue, elem);
  8251. if (key_is_typeid) {
  8252. check_expr_or_type(c, o, fv->field, t->Map.key);
  8253. } else {
  8254. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  8255. }
  8256. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  8257. if (o->mode == Addressing_Invalid) {
  8258. continue;
  8259. }
  8260. if (value_is_typeid) {
  8261. check_expr_or_type(c, o, fv->value, t->Map.value);
  8262. } else {
  8263. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  8264. }
  8265. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  8266. }
  8267. }
  8268. if (build_context.no_dynamic_literals && cl->elems.count) {
  8269. error(node, "Compound literals of dynamic types have been disabled");
  8270. } else {
  8271. add_map_reserve_dependencies(c);
  8272. add_map_set_dependencies(c);
  8273. }
  8274. break;
  8275. }
  8276. case Type_BitSet: {
  8277. if (cl->elems.count == 0) {
  8278. break; // NOTE(bill): No need to init
  8279. }
  8280. Type *et = base_type(t->BitSet.elem);
  8281. isize field_count = 0;
  8282. if (et->kind == Type_Enum) {
  8283. field_count = et->Enum.fields.count;
  8284. }
  8285. if (cl->elems[0]->kind == Ast_FieldValue) {
  8286. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  8287. is_constant = false;
  8288. } else {
  8289. for (Ast *elem : cl->elems) {
  8290. if (elem->kind == Ast_FieldValue) {
  8291. error(elem, "'field = value' in a bit_set a literal is not allowed");
  8292. continue;
  8293. }
  8294. check_expr_with_type_hint(c, o, elem, et);
  8295. if (is_constant) {
  8296. is_constant = o->mode == Addressing_Constant;
  8297. }
  8298. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  8299. if (o->mode == Addressing_Constant) {
  8300. i64 lower = t->BitSet.lower;
  8301. i64 upper = t->BitSet.upper;
  8302. i64 v = exact_value_to_i64(o->value);
  8303. if (lower <= v && v <= upper) {
  8304. // okay
  8305. } else {
  8306. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  8307. continue;
  8308. }
  8309. }
  8310. }
  8311. }
  8312. break;
  8313. }
  8314. case Type_BitField: {
  8315. if (cl->elems.count == 0) {
  8316. break; // NOTE(bill): No need to init
  8317. }
  8318. is_constant = false;
  8319. if (cl->elems[0]->kind != Ast_FieldValue) {
  8320. gbString type_str = type_to_string(type);
  8321. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  8322. gb_string_free(type_str);
  8323. } else {
  8324. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8325. }
  8326. break;
  8327. }
  8328. default: {
  8329. if (cl->elems.count == 0) {
  8330. break; // NOTE(bill): No need to init
  8331. }
  8332. gbString str = type_to_string(type);
  8333. error(node, "Invalid compound literal type '%s'", str);
  8334. gb_string_free(str);
  8335. return kind;
  8336. }
  8337. }
  8338. if (is_constant) {
  8339. o->mode = Addressing_Constant;
  8340. if (is_type_bit_set(type)) {
  8341. // NOTE(bill): Encode as an integer
  8342. Type *bt = base_type(type);
  8343. BigInt bits = {};
  8344. BigInt one = {};
  8345. big_int_from_u64(&one, 1);
  8346. for (Ast *e : cl->elems) {
  8347. GB_ASSERT(e->kind != Ast_FieldValue);
  8348. TypeAndValue tav = e->tav;
  8349. if (tav.mode != Addressing_Constant) {
  8350. continue;
  8351. }
  8352. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  8353. i64 v = big_int_to_i64(&tav.value.value_integer);
  8354. i64 lower = bt->BitSet.lower;
  8355. u64 index = cast(u64)(v-lower);
  8356. BigInt bit = {};
  8357. big_int_from_u64(&bit, index);
  8358. big_int_shl(&bit, &one, &bit);
  8359. big_int_or(&bits, &bits, &bit);
  8360. }
  8361. o->value.kind = ExactValue_Integer;
  8362. o->value.value_integer = bits;
  8363. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  8364. ExactValue value = exact_value_compound(node);
  8365. Type *bt = core_type(type);
  8366. if (bt->kind == Type_Basic) {
  8367. if (bt->Basic.flags & BasicFlag_Boolean) {
  8368. value = exact_value_bool(false);
  8369. } else if (bt->Basic.flags & BasicFlag_Integer) {
  8370. value = exact_value_i64(0);
  8371. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  8372. value = exact_value_i64(0);
  8373. } else if (bt->Basic.flags & BasicFlag_Float) {
  8374. value = exact_value_float(0);
  8375. } else if (bt->Basic.flags & BasicFlag_Complex) {
  8376. value = exact_value_complex(0, 0);
  8377. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  8378. value = exact_value_quaternion(0, 0, 0, 0);
  8379. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  8380. value = exact_value_pointer(0);
  8381. } else if (bt->Basic.flags & BasicFlag_String) {
  8382. String empty_string = {};
  8383. value = exact_value_string(empty_string);
  8384. } else if (bt->Basic.flags & BasicFlag_Rune) {
  8385. value = exact_value_i64(0);
  8386. }
  8387. }
  8388. o->value = value;
  8389. } else {
  8390. o->value = exact_value_compound(node);
  8391. }
  8392. } else {
  8393. o->mode = Addressing_Value;
  8394. }
  8395. o->type = type;
  8396. return kind;
  8397. }
  8398. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8399. ExprKind kind = Expr_Expr;
  8400. ast_node(ta, TypeAssertion, node);
  8401. check_expr(c, o, ta->expr);
  8402. node->viral_state_flags |= ta->expr->viral_state_flags;
  8403. if (o->mode == Addressing_Invalid) {
  8404. o->expr = node;
  8405. return kind;
  8406. }
  8407. if (o->mode == Addressing_Constant) {
  8408. gbString expr_str = expr_to_string(o->expr);
  8409. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  8410. gb_string_free(expr_str);
  8411. o->mode = Addressing_Invalid;
  8412. o->expr = node;
  8413. return kind;
  8414. }
  8415. if (is_type_untyped(o->type)) {
  8416. gbString expr_str = expr_to_string(o->expr);
  8417. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  8418. gb_string_free(expr_str);
  8419. o->mode = Addressing_Invalid;
  8420. o->expr = node;
  8421. return kind;
  8422. }
  8423. Type *src = type_deref(o->type);
  8424. Type *bsrc = base_type(src);
  8425. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  8426. if (!is_type_union(src)) {
  8427. gbString str = type_to_string(o->type);
  8428. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  8429. gb_string_free(str);
  8430. o->mode = Addressing_Invalid;
  8431. o->expr = node;
  8432. return kind;
  8433. }
  8434. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  8435. bool allowed = false;
  8436. for (Type *vt : bsrc->Union.variants) {
  8437. if (are_types_identical(vt, type_hint)) {
  8438. allowed = true;
  8439. add_type_info_type(c, vt);
  8440. break;
  8441. }
  8442. }
  8443. if (allowed) {
  8444. add_type_info_type(c, o->type);
  8445. o->type = type_hint;
  8446. o->mode = Addressing_OptionalOk;
  8447. return kind;
  8448. }
  8449. }
  8450. if (bsrc->Union.variants.count != 1) {
  8451. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  8452. o->mode = Addressing_Invalid;
  8453. o->expr = node;
  8454. return kind;
  8455. }
  8456. add_type_info_type(c, o->type);
  8457. add_type_info_type(c, bsrc->Union.variants[0]);
  8458. o->type = bsrc->Union.variants[0];
  8459. o->mode = Addressing_OptionalOk;
  8460. } else {
  8461. Type *t = check_type(c, ta->type);
  8462. Type *dst = t;
  8463. if (is_type_union(src)) {
  8464. bool ok = false;
  8465. for (Type *vt : bsrc->Union.variants) {
  8466. if (are_types_identical(vt, dst)) {
  8467. ok = true;
  8468. break;
  8469. }
  8470. }
  8471. if (!ok) {
  8472. gbString expr_str = expr_to_string(o->expr);
  8473. gbString dst_type_str = type_to_string(t);
  8474. defer (gb_string_free(expr_str));
  8475. defer (gb_string_free(dst_type_str));
  8476. if (bsrc->Union.variants.count == 0) {
  8477. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  8478. } else {
  8479. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  8480. }
  8481. o->mode = Addressing_Invalid;
  8482. o->expr = node;
  8483. return kind;
  8484. }
  8485. add_type_info_type(c, o->type);
  8486. add_type_info_type(c, t);
  8487. o->type = t;
  8488. o->mode = Addressing_OptionalOk;
  8489. } else if (is_type_any(src)) {
  8490. o->type = t;
  8491. o->mode = Addressing_OptionalOk;
  8492. add_type_info_type(c, o->type);
  8493. add_type_info_type(c, t);
  8494. } else {
  8495. gbString str = type_to_string(o->type);
  8496. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  8497. gb_string_free(str);
  8498. o->mode = Addressing_Invalid;
  8499. o->expr = node;
  8500. return kind;
  8501. }
  8502. }
  8503. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  8504. add_package_dependency(c, "runtime", "type_assertion_check");
  8505. add_package_dependency(c, "runtime", "type_assertion_check2");
  8506. }
  8507. return kind;
  8508. }
  8509. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8510. ast_node(se, SelectorCallExpr, node);
  8511. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  8512. // COM APIs is a great example of where this kind of thing is extremely useful
  8513. // General idea:
  8514. //
  8515. // x->y(123) == x.y(x, 123)
  8516. //
  8517. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  8518. // Just regenerating a new AST aids things
  8519. //
  8520. // TODO(bill): Is this a good hack or not?
  8521. //
  8522. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  8523. if (se->modified_call) {
  8524. // Prevent double evaluation
  8525. o->expr = node;
  8526. o->type = node->tav.type;
  8527. o->value = node->tav.value;
  8528. o->mode = node->tav.mode;
  8529. return Expr_Expr;
  8530. }
  8531. bool allow_arrow_right_selector_expr;
  8532. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8533. c->allow_arrow_right_selector_expr = true;
  8534. Operand x = {};
  8535. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  8536. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8537. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  8538. o->mode = Addressing_Invalid;
  8539. o->type = t_invalid;
  8540. o->expr = node;
  8541. return kind;
  8542. }
  8543. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  8544. gbString type_str = type_to_string(x.type);
  8545. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  8546. gb_string_free(type_str);
  8547. o->mode = Addressing_Invalid;
  8548. o->type = t_invalid;
  8549. o->expr = node;
  8550. return Expr_Stmt;
  8551. }
  8552. ast_node(ce, CallExpr, se->call);
  8553. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  8554. Ast *first_arg = x.expr->SelectorExpr.expr;
  8555. GB_ASSERT(first_arg != nullptr);
  8556. Entity *e = entity_of_node(se->expr);
  8557. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  8558. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  8559. }
  8560. if (e->kind != Entity_ProcGroup) {
  8561. Type *pt = base_type(x.type);
  8562. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  8563. Type *first_type = nullptr;
  8564. String first_arg_name = {};
  8565. if (pt->Proc.param_count > 0) {
  8566. Entity *f = pt->Proc.params->Tuple.variables[0];
  8567. first_type = f->type;
  8568. first_arg_name = f->token.string;
  8569. }
  8570. if (first_arg_name.len == 0) {
  8571. first_arg_name = str_lit("_");
  8572. }
  8573. if (first_type == nullptr) {
  8574. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  8575. o->mode = Addressing_Invalid;
  8576. o->type = t_invalid;
  8577. o->expr = node;
  8578. return Expr_Stmt;
  8579. }
  8580. Operand y = {};
  8581. y.mode = first_arg->tav.mode;
  8582. y.type = first_arg->tav.type;
  8583. y.value = first_arg->tav.value;
  8584. if (check_is_assignable_to(c, &y, first_type)) {
  8585. // Do nothing, it's valid
  8586. } else {
  8587. Operand z = y;
  8588. z.type = type_deref(y.type);
  8589. if (check_is_assignable_to(c, &z, first_type)) {
  8590. // NOTE(bill): AST GENERATION HACK!
  8591. Token op = {Token_Pointer};
  8592. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  8593. } else if (y.mode == Addressing_Variable) {
  8594. Operand w = y;
  8595. w.type = alloc_type_pointer(y.type);
  8596. if (check_is_assignable_to(c, &w, first_type)) {
  8597. // NOTE(bill): AST GENERATION HACK!
  8598. Token op = {Token_And};
  8599. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  8600. }
  8601. }
  8602. }
  8603. if (ce->args.count > 0) {
  8604. bool fail = false;
  8605. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  8606. for (Ast *arg : ce->args) {
  8607. bool mix = false;
  8608. if (first_is_field_value) {
  8609. mix = arg->kind != Ast_FieldValue;
  8610. } else {
  8611. mix = arg->kind == Ast_FieldValue;
  8612. }
  8613. if (mix) {
  8614. fail = true;
  8615. break;
  8616. }
  8617. }
  8618. if (!fail && first_is_field_value) {
  8619. Token op = {Token_Eq};
  8620. AstFile *f = first_arg->file();
  8621. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  8622. }
  8623. }
  8624. }
  8625. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  8626. modified_args[0] = first_arg;
  8627. slice_copy(&modified_args, ce->args, 1);
  8628. ce->args = modified_args;
  8629. se->modified_call = true;
  8630. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8631. c->allow_arrow_right_selector_expr = true;
  8632. check_expr_base(c, o, se->call, type_hint);
  8633. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8634. o->expr = node;
  8635. return Expr_Expr;
  8636. }
  8637. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8638. ExprKind kind = Expr_Expr;
  8639. ast_node(ie, IndexExpr, node);
  8640. check_expr(c, o, ie->expr);
  8641. node->viral_state_flags |= ie->expr->viral_state_flags;
  8642. if (o->mode == Addressing_Invalid) {
  8643. o->expr = node;
  8644. return kind;
  8645. }
  8646. Type *t = base_type(type_deref(o->type));
  8647. bool is_ptr = is_type_pointer(o->type);
  8648. bool is_const = o->mode == Addressing_Constant;
  8649. if (is_type_map(t)) {
  8650. Operand key = {};
  8651. if (is_type_typeid(t->Map.key)) {
  8652. check_expr_or_type(c, &key, ie->index, t->Map.key);
  8653. } else {
  8654. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  8655. }
  8656. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  8657. if (key.mode == Addressing_Invalid) {
  8658. o->mode = Addressing_Invalid;
  8659. o->expr = node;
  8660. return kind;
  8661. }
  8662. o->mode = Addressing_MapIndex;
  8663. o->type = t->Map.value;
  8664. o->expr = node;
  8665. add_map_get_dependencies(c);
  8666. add_map_set_dependencies(c);
  8667. return Expr_Expr;
  8668. }
  8669. i64 max_count = -1;
  8670. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  8671. if (is_const) {
  8672. if (is_type_array(t)) {
  8673. // Okay
  8674. } else if (is_type_slice(t)) {
  8675. // Okay
  8676. } else if (is_type_enumerated_array(t)) {
  8677. // Okay
  8678. } else if (is_type_string(t)) {
  8679. // Okay
  8680. } else if (is_type_relative_multi_pointer(t)) {
  8681. // Okay
  8682. } else if (is_type_matrix(t)) {
  8683. // Okay
  8684. } else {
  8685. valid = false;
  8686. }
  8687. }
  8688. if (!valid) {
  8689. gbString str = expr_to_string(o->expr);
  8690. gbString type_str = type_to_string(o->type);
  8691. defer (gb_string_free(str));
  8692. defer (gb_string_free(type_str));
  8693. if (is_const) {
  8694. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  8695. } else {
  8696. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  8697. }
  8698. o->mode = Addressing_Invalid;
  8699. o->expr = node;
  8700. return kind;
  8701. }
  8702. if (ie->index == nullptr) {
  8703. gbString str = expr_to_string(o->expr);
  8704. error(o->expr, "Missing index for '%s'", str);
  8705. gb_string_free(str);
  8706. o->mode = Addressing_Invalid;
  8707. o->expr = node;
  8708. return kind;
  8709. }
  8710. Type *index_type_hint = nullptr;
  8711. if (is_type_enumerated_array(t)) {
  8712. Type *bt = base_type(t);
  8713. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  8714. index_type_hint = bt->EnumeratedArray.index;
  8715. }
  8716. i64 index = 0;
  8717. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  8718. if (is_const) {
  8719. if (index < 0) {
  8720. gbString str = expr_to_string(o->expr);
  8721. error(o->expr, "Cannot index a constant '%s'", str);
  8722. if (!build_context.terse_errors) {
  8723. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8724. }
  8725. gb_string_free(str);
  8726. o->mode = Addressing_Invalid;
  8727. o->expr = node;
  8728. return kind;
  8729. } else if (ok) {
  8730. ExactValue value = type_and_value_of_expr(ie->expr).value;
  8731. o->mode = Addressing_Constant;
  8732. bool success = false;
  8733. bool finish = false;
  8734. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  8735. if (!success) {
  8736. gbString str = expr_to_string(o->expr);
  8737. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  8738. if (!build_context.terse_errors) {
  8739. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8740. }
  8741. gb_string_free(str);
  8742. o->mode = Addressing_Invalid;
  8743. o->expr = node;
  8744. return kind;
  8745. }
  8746. }
  8747. }
  8748. if (type_hint != nullptr && is_type_matrix(t)) {
  8749. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  8750. // if a type hint exists
  8751. }
  8752. return kind;
  8753. }
  8754. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8755. ExprKind kind = Expr_Stmt;
  8756. ast_node(se, SliceExpr, node);
  8757. check_expr(c, o, se->expr);
  8758. node->viral_state_flags |= se->expr->viral_state_flags;
  8759. if (o->mode == Addressing_Invalid) {
  8760. o->mode = Addressing_Invalid;
  8761. o->expr = node;
  8762. return kind;
  8763. }
  8764. bool valid = false;
  8765. i64 max_count = -1;
  8766. Type *t = base_type(type_deref(o->type));
  8767. switch (t->kind) {
  8768. case Type_Basic:
  8769. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  8770. valid = true;
  8771. if (o->mode == Addressing_Constant) {
  8772. max_count = o->value.value_string.len;
  8773. }
  8774. o->type = type_deref(o->type);
  8775. }
  8776. break;
  8777. case Type_Array:
  8778. valid = true;
  8779. max_count = t->Array.count;
  8780. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  8781. gbString str = expr_to_string(node);
  8782. error(node, "Cannot slice array '%s', value is not addressable", str);
  8783. gb_string_free(str);
  8784. o->mode = Addressing_Invalid;
  8785. o->expr = node;
  8786. return kind;
  8787. }
  8788. o->type = alloc_type_slice(t->Array.elem);
  8789. break;
  8790. case Type_MultiPointer:
  8791. valid = true;
  8792. o->type = type_deref(o->type);
  8793. break;
  8794. case Type_Slice:
  8795. valid = true;
  8796. o->type = type_deref(o->type);
  8797. break;
  8798. case Type_DynamicArray:
  8799. valid = true;
  8800. o->type = alloc_type_slice(t->DynamicArray.elem);
  8801. break;
  8802. case Type_Struct:
  8803. if (is_type_soa_struct(t)) {
  8804. valid = true;
  8805. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  8806. }
  8807. break;
  8808. case Type_RelativeMultiPointer:
  8809. valid = true;
  8810. o->type = type_deref(o->type);
  8811. break;
  8812. case Type_EnumeratedArray:
  8813. {
  8814. gbString str = expr_to_string(o->expr);
  8815. gbString type_str = type_to_string(o->type);
  8816. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  8817. gb_string_free(type_str);
  8818. gb_string_free(str);
  8819. o->mode = Addressing_Invalid;
  8820. o->expr = node;
  8821. return kind;
  8822. }
  8823. break;
  8824. }
  8825. if (!valid) {
  8826. gbString str = expr_to_string(o->expr);
  8827. gbString type_str = type_to_string(o->type);
  8828. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  8829. gb_string_free(type_str);
  8830. gb_string_free(str);
  8831. o->mode = Addressing_Invalid;
  8832. o->expr = node;
  8833. return kind;
  8834. }
  8835. if (se->low == nullptr && se->high != nullptr) {
  8836. // It is okay to continue as it will assume the 1st index is zero
  8837. }
  8838. i64 indices[2] = {};
  8839. Ast *nodes[2] = {se->low, se->high};
  8840. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8841. i64 index = max_count;
  8842. if (nodes[i] != nullptr) {
  8843. i64 capacity = -1;
  8844. if (max_count >= 0) {
  8845. capacity = max_count;
  8846. }
  8847. i64 j = 0;
  8848. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  8849. index = j;
  8850. }
  8851. node->viral_state_flags |= nodes[i]->viral_state_flags;
  8852. } else if (i == 0) {
  8853. index = 0;
  8854. }
  8855. indices[i] = index;
  8856. }
  8857. for (isize i = 0; i < gb_count_of(indices); i++) {
  8858. i64 a = indices[i];
  8859. for (isize j = i+1; j < gb_count_of(indices); j++) {
  8860. i64 b = indices[j];
  8861. if (a > b && b >= 0) {
  8862. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  8863. }
  8864. }
  8865. }
  8866. if (max_count < 0) {
  8867. if (o->mode == Addressing_Constant) {
  8868. gbString s = expr_to_string(se->expr);
  8869. error(se->expr, "Cannot slice constant value '%s'", s);
  8870. gb_string_free(s);
  8871. }
  8872. }
  8873. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  8874. /*
  8875. x[:] -> [^]T
  8876. x[i:] -> [^]T
  8877. x[:n] -> []T
  8878. x[i:n] -> []T
  8879. */
  8880. o->type = alloc_type_slice(t->MultiPointer.elem);
  8881. } else if (t->kind == Type_RelativeMultiPointer && se->high != nullptr) {
  8882. /*
  8883. x[:] -> [^]T
  8884. x[i:] -> [^]T
  8885. x[:n] -> []T
  8886. x[i:n] -> []T
  8887. */
  8888. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  8889. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  8890. o->type = alloc_type_slice(pointer_type->MultiPointer.elem);
  8891. }
  8892. o->mode = Addressing_Value;
  8893. if (is_type_string(t) && max_count >= 0) {
  8894. bool all_constant = true;
  8895. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8896. if (nodes[i] != nullptr) {
  8897. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  8898. if (tav.mode != Addressing_Constant) {
  8899. all_constant = false;
  8900. break;
  8901. }
  8902. }
  8903. }
  8904. if (!all_constant) {
  8905. gbString str = expr_to_string(o->expr);
  8906. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  8907. if (!build_context.terse_errors) {
  8908. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8909. }
  8910. gb_string_free(str);
  8911. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  8912. o->expr = node;
  8913. return kind;
  8914. }
  8915. String s = {};
  8916. if (o->value.kind == ExactValue_String) {
  8917. s = o->value.value_string;
  8918. }
  8919. o->mode = Addressing_Constant;
  8920. o->type = t;
  8921. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  8922. }
  8923. return kind;
  8924. }
  8925. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8926. u32 prev_state_flags = c->state_flags;
  8927. defer (c->state_flags = prev_state_flags);
  8928. if (node->state_flags != 0) {
  8929. u32 in = node->state_flags;
  8930. u32 out = c->state_flags;
  8931. if (in & StateFlag_no_bounds_check) {
  8932. out |= StateFlag_no_bounds_check;
  8933. out &= ~StateFlag_bounds_check;
  8934. } else if (in & StateFlag_bounds_check) {
  8935. out |= StateFlag_bounds_check;
  8936. out &= ~StateFlag_no_bounds_check;
  8937. }
  8938. if (in & StateFlag_no_type_assert) {
  8939. out |= StateFlag_no_type_assert;
  8940. out &= ~StateFlag_type_assert;
  8941. } else if (in & StateFlag_type_assert) {
  8942. out |= StateFlag_type_assert;
  8943. out &= ~StateFlag_no_type_assert;
  8944. }
  8945. c->state_flags = out;
  8946. }
  8947. ExprKind kind = Expr_Stmt;
  8948. o->mode = Addressing_Invalid;
  8949. o->type = t_invalid;
  8950. o->value = {ExactValue_Invalid};
  8951. switch (node->kind) {
  8952. default:
  8953. return kind;
  8954. case_ast_node(be, BadExpr, node)
  8955. return kind;
  8956. case_end;
  8957. case_ast_node(i, Implicit, node)
  8958. switch (i->kind) {
  8959. case Token_context:
  8960. {
  8961. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  8962. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  8963. return kind;
  8964. }
  8965. if (unparen_expr(c->assignment_lhs_hint) == node) {
  8966. c->scope->flags |= ScopeFlag_ContextDefined;
  8967. }
  8968. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  8969. error(node, "'context' has not been defined within this scope");
  8970. // Continue with value
  8971. }
  8972. init_core_context(c->checker);
  8973. o->mode = Addressing_Context;
  8974. o->type = t_context;
  8975. }
  8976. break;
  8977. default:
  8978. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  8979. return kind;
  8980. }
  8981. case_end;
  8982. case_ast_node(i, Ident, node);
  8983. check_ident(c, o, node, nullptr, type_hint, false);
  8984. case_end;
  8985. case_ast_node(u, Uninit, node);
  8986. o->mode = Addressing_Value;
  8987. o->type = t_untyped_uninit;
  8988. error(node, "Use of --- outside of variable declaration");
  8989. case_end;
  8990. case_ast_node(bl, BasicLit, node);
  8991. Type *t = t_invalid;
  8992. switch (node->tav.value.kind) {
  8993. case ExactValue_String: t = t_untyped_string; break;
  8994. case ExactValue_Float: t = t_untyped_float; break;
  8995. case ExactValue_Complex: t = t_untyped_complex; break;
  8996. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  8997. case ExactValue_Integer:
  8998. t = t_untyped_integer;
  8999. if (bl->token.kind == Token_Rune) {
  9000. t = t_untyped_rune;
  9001. }
  9002. break;
  9003. default:
  9004. GB_PANIC("Unhandled value type for basic literal");
  9005. break;
  9006. }
  9007. o->mode = Addressing_Constant;
  9008. o->type = t;
  9009. o->value = node->tav.value;
  9010. case_end;
  9011. case_ast_node(bd, BasicDirective, node);
  9012. kind = check_basic_directive_expr(c, o, node, type_hint);
  9013. case_end;
  9014. case_ast_node(pg, ProcGroup, node);
  9015. error(node, "Illegal use of a procedure group");
  9016. o->mode = Addressing_Invalid;
  9017. case_end;
  9018. case_ast_node(pl, ProcLit, node);
  9019. CheckerContext ctx = *c;
  9020. DeclInfo *decl = nullptr;
  9021. Type *type = alloc_type(Type_Proc);
  9022. check_open_scope(&ctx, pl->type);
  9023. {
  9024. decl = make_decl_info(ctx.scope, ctx.decl);
  9025. decl->proc_lit = node;
  9026. ctx.decl = decl;
  9027. defer (ctx.decl = ctx.decl->parent);
  9028. if (pl->tags != 0) {
  9029. error(node, "A procedure literal cannot have tags");
  9030. pl->tags = 0; // TODO(bill): Should I zero this?!
  9031. }
  9032. check_procedure_type(&ctx, type, pl->type);
  9033. if (!is_type_proc(type)) {
  9034. gbString str = expr_to_string(node);
  9035. error(node, "Invalid procedure literal '%s'", str);
  9036. gb_string_free(str);
  9037. check_close_scope(&ctx);
  9038. return kind;
  9039. }
  9040. if (pl->body == nullptr) {
  9041. error(node, "A procedure literal must have a body");
  9042. return kind;
  9043. }
  9044. pl->decl = decl;
  9045. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  9046. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  9047. array_add(&ctx.checker->nested_proc_lits, decl);
  9048. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  9049. }
  9050. check_close_scope(&ctx);
  9051. o->mode = Addressing_Value;
  9052. o->type = type;
  9053. case_end;
  9054. case_ast_node(te, TernaryIfExpr, node);
  9055. kind = check_ternary_if_expr(c, o, node, type_hint);
  9056. case_end;
  9057. case_ast_node(te, TernaryWhenExpr, node);
  9058. kind = check_ternary_when_expr(c, o, node, type_hint);
  9059. case_end;
  9060. case_ast_node(oe, OrElseExpr, node);
  9061. return check_or_else_expr(c, o, node, type_hint);
  9062. case_end;
  9063. case_ast_node(re, OrReturnExpr, node);
  9064. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  9065. return check_or_return_expr(c, o, node, type_hint);
  9066. case_end;
  9067. case_ast_node(re, OrBranchExpr, node);
  9068. return check_or_branch_expr(c, o, node, type_hint);
  9069. case_end;
  9070. case_ast_node(cl, CompoundLit, node);
  9071. kind = check_compound_literal(c, o, node, type_hint);
  9072. case_end;
  9073. case_ast_node(pe, ParenExpr, node);
  9074. kind = check_expr_base(c, o, pe->expr, type_hint);
  9075. node->viral_state_flags |= pe->expr->viral_state_flags;
  9076. o->expr = node;
  9077. case_end;
  9078. case_ast_node(te, TagExpr, node);
  9079. String name = te->name.string;
  9080. error(node, "Unknown tag expression, #%.*s", LIT(name));
  9081. if (te->expr) {
  9082. kind = check_expr_base(c, o, te->expr, type_hint);
  9083. node->viral_state_flags |= te->expr->viral_state_flags;
  9084. }
  9085. o->expr = node;
  9086. case_end;
  9087. case_ast_node(ta, TypeAssertion, node);
  9088. kind = check_type_assertion(c, o, node, type_hint);
  9089. case_end;
  9090. case_ast_node(tc, TypeCast, node);
  9091. check_expr_or_type(c, o, tc->type);
  9092. if (o->mode != Addressing_Type) {
  9093. gbString str = expr_to_string(tc->type);
  9094. error(tc->type, "Expected a type, got %s", str);
  9095. gb_string_free(str);
  9096. o->mode = Addressing_Invalid;
  9097. }
  9098. if (o->mode == Addressing_Invalid) {
  9099. o->expr = node;
  9100. return kind;
  9101. }
  9102. Type *type = o->type;
  9103. check_expr_base(c, o, tc->expr, type);
  9104. node->viral_state_flags |= tc->expr->viral_state_flags;
  9105. if (o->mode != Addressing_Invalid) {
  9106. switch (tc->token.kind) {
  9107. case Token_transmute:
  9108. check_transmute(c, node, o, type);
  9109. break;
  9110. case Token_cast:
  9111. check_cast(c, o, type);
  9112. break;
  9113. default:
  9114. error(node, "Invalid AST: Invalid casting expression");
  9115. o->mode = Addressing_Invalid;
  9116. break;
  9117. }
  9118. }
  9119. return Expr_Expr;
  9120. case_end;
  9121. case_ast_node(ac, AutoCast, node);
  9122. check_expr_base(c, o, ac->expr, type_hint);
  9123. node->viral_state_flags |= ac->expr->viral_state_flags;
  9124. if (o->mode == Addressing_Invalid) {
  9125. o->expr = node;
  9126. return kind;
  9127. }
  9128. if (type_hint) {
  9129. check_cast(c, o, type_hint);
  9130. }
  9131. o->expr = node;
  9132. return Expr_Expr;
  9133. case_end;
  9134. case_ast_node(ue, UnaryExpr, node);
  9135. Type *th = type_hint;
  9136. if (ue->op.kind == Token_And) {
  9137. th = type_deref(th);
  9138. }
  9139. check_expr_base(c, o, ue->expr, th);
  9140. node->viral_state_flags |= ue->expr->viral_state_flags;
  9141. if (o->mode != Addressing_Invalid) {
  9142. check_unary_expr(c, o, ue->op, node);
  9143. }
  9144. o->expr = node;
  9145. return Expr_Expr;
  9146. case_end;
  9147. case_ast_node(be, BinaryExpr, node);
  9148. check_binary_expr(c, o, node, type_hint, true);
  9149. if (o->mode == Addressing_Invalid) {
  9150. o->expr = node;
  9151. return kind;
  9152. }
  9153. case_end;
  9154. case_ast_node(se, SelectorExpr, node);
  9155. check_selector(c, o, node, type_hint);
  9156. node->viral_state_flags |= se->expr->viral_state_flags;
  9157. case_end;
  9158. case_ast_node(se, SelectorCallExpr, node);
  9159. return check_selector_call_expr(c, o, node, type_hint);
  9160. case_end;
  9161. case_ast_node(ise, ImplicitSelectorExpr, node);
  9162. return check_implicit_selector_expr(c, o, node, type_hint);
  9163. case_end;
  9164. case_ast_node(ie, IndexExpr, node);
  9165. kind = check_index_expr(c, o, node, type_hint);
  9166. case_end;
  9167. case_ast_node(se, SliceExpr, node);
  9168. kind = check_slice_expr(c, o, node, type_hint);
  9169. case_end;
  9170. case_ast_node(mie, MatrixIndexExpr, node);
  9171. check_matrix_index_expr(c, o, node, type_hint);
  9172. o->expr = node;
  9173. return Expr_Expr;
  9174. case_end;
  9175. case_ast_node(ce, CallExpr, node);
  9176. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  9177. case_end;
  9178. case_ast_node(de, DerefExpr, node);
  9179. check_expr_or_type(c, o, de->expr);
  9180. node->viral_state_flags |= de->expr->viral_state_flags;
  9181. if (o->mode == Addressing_Invalid) {
  9182. o->mode = Addressing_Invalid;
  9183. o->expr = node;
  9184. return kind;
  9185. } else {
  9186. Type *t = base_type(o->type);
  9187. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  9188. o->mode = Addressing_Variable;
  9189. o->type = t->Pointer.elem;
  9190. } else if (t->kind == Type_SoaPointer) {
  9191. o->mode = Addressing_SoaVariable;
  9192. o->type = type_deref(t);
  9193. } else if (t->kind == Type_RelativePointer) {
  9194. if (o->mode != Addressing_Variable) {
  9195. gbString str = expr_to_string(o->expr);
  9196. gbString typ = type_to_string(o->type);
  9197. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  9198. gb_string_free(typ);
  9199. gb_string_free(str);
  9200. }
  9201. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  9202. add_type_info_type(c, o->type);
  9203. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  9204. GB_ASSERT(ptr_type->kind == Type_Pointer);
  9205. o->mode = Addressing_Variable;
  9206. o->type = ptr_type->Pointer.elem;
  9207. } else {
  9208. gbString str = expr_to_string(o->expr);
  9209. gbString typ = type_to_string(o->type);
  9210. ERROR_BLOCK();
  9211. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  9212. if (o->type && is_type_multi_pointer(o->type)) {
  9213. if (!build_context.terse_errors) {
  9214. error_line("\tDid you mean '%s[0]'?\n", str);
  9215. }
  9216. }
  9217. gb_string_free(typ);
  9218. gb_string_free(str);
  9219. o->mode = Addressing_Invalid;
  9220. o->expr = node;
  9221. return kind;
  9222. }
  9223. }
  9224. case_end;
  9225. case_ast_node(ia, InlineAsmExpr, node);
  9226. if (c->curr_proc_decl == nullptr) {
  9227. error(node, "Inline asm expressions are only allowed within a procedure body");
  9228. }
  9229. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  9230. Type *return_type = nullptr;
  9231. for_array(i, ia->param_types) {
  9232. param_types[i] = check_type(c, ia->param_types[i]);
  9233. }
  9234. if (ia->return_type != nullptr) {
  9235. return_type = check_type(c, ia->return_type);
  9236. }
  9237. Operand x = {};
  9238. check_expr(c, &x, ia->asm_string);
  9239. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9240. error(x.expr, "Expected a constant string for the inline asm main parameter");
  9241. }
  9242. check_expr(c, &x, ia->constraints_string);
  9243. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9244. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  9245. }
  9246. Scope *scope = create_scope(c->info, c->scope);
  9247. scope->flags |= ScopeFlag_Proc;
  9248. Type *params = alloc_type_tuple();
  9249. Type *results = alloc_type_tuple();
  9250. if (param_types.count != 0) {
  9251. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  9252. for_array(i, param_types) {
  9253. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  9254. }
  9255. }
  9256. if (return_type != nullptr) {
  9257. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  9258. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  9259. }
  9260. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  9261. o->type = pt;
  9262. o->mode = Addressing_Value;
  9263. o->expr = node;
  9264. return Expr_Expr;
  9265. case_end;
  9266. case Ast_TypeidType:
  9267. case Ast_PolyType:
  9268. case Ast_ProcType:
  9269. case Ast_PointerType:
  9270. case Ast_MultiPointerType:
  9271. case Ast_ArrayType:
  9272. case Ast_DynamicArrayType:
  9273. case Ast_StructType:
  9274. case Ast_UnionType:
  9275. case Ast_EnumType:
  9276. case Ast_MapType:
  9277. case Ast_BitSetType:
  9278. case Ast_MatrixType:
  9279. case Ast_RelativeType:
  9280. o->mode = Addressing_Type;
  9281. o->type = check_type(c, node);
  9282. break;
  9283. }
  9284. kind = Expr_Expr;
  9285. o->expr = node;
  9286. return kind;
  9287. }
  9288. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9289. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  9290. if (o->type != nullptr && core_type(o->type) == nullptr) {
  9291. o->type = t_invalid;
  9292. gbString xs = expr_to_string(o->expr);
  9293. if (o->mode == Addressing_Type) {
  9294. error(o->expr, "Invalid type usage '%s'", xs);
  9295. } else {
  9296. error(o->expr, "Invalid expression '%s'", xs);
  9297. }
  9298. gb_string_free(xs);
  9299. }
  9300. if (o->type != nullptr && is_type_untyped(o->type)) {
  9301. add_untyped(c, node, o->mode, o->type, o->value);
  9302. }
  9303. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  9304. add_type_and_value(c, node, o->mode, o->type, o->value);
  9305. return kind;
  9306. }
  9307. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  9308. check_expr_base(c, o, e, nullptr);
  9309. switch (o->mode) {
  9310. default:
  9311. return; // NOTE(bill): Valid
  9312. case Addressing_NoValue:
  9313. error_operand_no_value(o);
  9314. break;
  9315. }
  9316. o->mode = Addressing_Invalid;
  9317. }
  9318. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  9319. check_expr_base(c, o, e, nullptr);
  9320. switch (o->mode) {
  9321. default:
  9322. return; // NOTE(bill): Valid
  9323. case Addressing_NoValue:
  9324. error_operand_no_value(o);
  9325. break;
  9326. case Addressing_Type:
  9327. error_operand_not_expression(o);
  9328. break;
  9329. }
  9330. o->mode = Addressing_Invalid;
  9331. }
  9332. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9333. check_expr_base(c, o, e, type_hint);
  9334. switch (o->mode) {
  9335. default:
  9336. return; // NOTE(bill): Valid
  9337. case Addressing_NoValue:
  9338. error_operand_no_value(o);
  9339. break;
  9340. case Addressing_Type:
  9341. error_operand_not_expression(o);
  9342. break;
  9343. }
  9344. o->mode = Addressing_Invalid;
  9345. }
  9346. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  9347. if (o->mode == Addressing_Value) {
  9348. // NOTE(bill): Tuples are not first class thus never named
  9349. if (o->type->kind == Type_Tuple) {
  9350. isize count = o->type->Tuple.variables.count;
  9351. error(o->expr,
  9352. "%td-valued expression found where single value expected", count);
  9353. o->mode = Addressing_Invalid;
  9354. GB_ASSERT(count != 1);
  9355. }
  9356. }
  9357. }
  9358. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  9359. check_multi_expr(c, o, e);
  9360. check_not_tuple(c, o);
  9361. }
  9362. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9363. check_expr_base(c, o, e, type_hint);
  9364. check_not_tuple(c, o);
  9365. error_operand_no_value(o);
  9366. }
  9367. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  9368. switch (v.kind) {
  9369. case ExactValue_Invalid:
  9370. return true;
  9371. case ExactValue_Bool:
  9372. return !v.value_bool;
  9373. case ExactValue_String:
  9374. return v.value_string.len == 0;
  9375. case ExactValue_Integer:
  9376. return big_int_is_zero(&v.value_integer);
  9377. case ExactValue_Float:
  9378. return v.value_float == 0.0;
  9379. case ExactValue_Complex:
  9380. if (v.value_complex) {
  9381. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  9382. }
  9383. return true;
  9384. case ExactValue_Quaternion:
  9385. if (v.value_quaternion) {
  9386. return v.value_quaternion->real == 0.0 &&
  9387. v.value_quaternion->imag == 0.0 &&
  9388. v.value_quaternion->jmag == 0.0 &&
  9389. v.value_quaternion->kmag == 0.0;
  9390. }
  9391. return true;
  9392. case ExactValue_Pointer:
  9393. return v.value_pointer == 0;
  9394. case ExactValue_Compound:
  9395. if (v.value_compound == nullptr) {
  9396. return true;
  9397. } else {
  9398. ast_node(cl, CompoundLit, v.value_compound);
  9399. if (cl->elems.count == 0) {
  9400. return true;
  9401. } else {
  9402. for (Ast *elem : cl->elems) {
  9403. if (elem->tav.mode != Addressing_Constant) {
  9404. return false;
  9405. }
  9406. if (!is_exact_value_zero(elem->tav.value)) {
  9407. return false;
  9408. }
  9409. }
  9410. return true;
  9411. }
  9412. }
  9413. case ExactValue_Procedure:
  9414. return v.value_procedure == nullptr;
  9415. case ExactValue_Typeid:
  9416. return v.value_typeid == nullptr;
  9417. }
  9418. return true;
  9419. }
  9420. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  9421. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  9422. for_array(i, params) {
  9423. if (i > 0) {
  9424. str = gb_string_appendc(str, ", ");
  9425. }
  9426. str = write_expr_to_string(str, params[i], false);
  9427. }
  9428. return str;
  9429. }
  9430. gb_internal gbString string_append_string(gbString str, String string) {
  9431. if (string.len > 0) {
  9432. return gb_string_append_length(str, &string[0], string.len);
  9433. }
  9434. return str;
  9435. }
  9436. gb_internal gbString string_append_token(gbString str, Token token) {
  9437. str = string_append_string(str, token.string);
  9438. return str;
  9439. }
  9440. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  9441. if (node == nullptr)
  9442. return str;
  9443. if (is_ast_stmt(node)) {
  9444. GB_ASSERT("stmt passed to write_expr_to_string");
  9445. }
  9446. switch (node->kind) {
  9447. default:
  9448. str = gb_string_appendc(str, "(BadExpr)");
  9449. break;
  9450. case_ast_node(i, Ident, node);
  9451. str = string_append_token(str, i->token);
  9452. case_end;
  9453. case_ast_node(i, Implicit, node);
  9454. str = string_append_token(str, *i);
  9455. case_end;
  9456. case_ast_node(bl, BasicLit, node);
  9457. str = string_append_token(str, bl->token);
  9458. case_end;
  9459. case_ast_node(bd, BasicDirective, node);
  9460. str = gb_string_append_rune(str, '#');
  9461. str = string_append_string(str, bd->name.string);
  9462. case_end;
  9463. case_ast_node(ud, Uninit, node);
  9464. str = gb_string_appendc(str, "---");
  9465. case_end;
  9466. case_ast_node(pg, ProcGroup, node);
  9467. str = gb_string_appendc(str, "proc{");
  9468. for_array(i, pg->args) {
  9469. if (i > 0) str = gb_string_appendc(str, ", ");
  9470. str = write_expr_to_string(str, pg->args[i], shorthand);
  9471. }
  9472. str = gb_string_append_rune(str, '}');
  9473. case_end;
  9474. case_ast_node(pl, ProcLit, node);
  9475. str = write_expr_to_string(str, pl->type, shorthand);
  9476. if (pl->body) {
  9477. str = gb_string_appendc(str, " {...}");
  9478. } else {
  9479. str = gb_string_appendc(str, " ---");
  9480. }
  9481. case_end;
  9482. case_ast_node(cl, CompoundLit, node);
  9483. str = write_expr_to_string(str, cl->type, shorthand);
  9484. str = gb_string_append_rune(str, '{');
  9485. if (shorthand) {
  9486. str = gb_string_appendc(str, "...");
  9487. } else {
  9488. for_array(i, cl->elems) {
  9489. if (i > 0) str = gb_string_appendc(str, ", ");
  9490. str = write_expr_to_string(str, cl->elems[i], shorthand);
  9491. }
  9492. }
  9493. str = gb_string_append_rune(str, '}');
  9494. case_end;
  9495. case_ast_node(te, TagExpr, node);
  9496. str = gb_string_append_rune(str, '#');
  9497. str = string_append_token(str, te->name);
  9498. str = write_expr_to_string(str, te->expr, shorthand);
  9499. case_end;
  9500. case_ast_node(ue, UnaryExpr, node);
  9501. str = string_append_token(str, ue->op);
  9502. str = write_expr_to_string(str, ue->expr, shorthand);
  9503. case_end;
  9504. case_ast_node(de, DerefExpr, node);
  9505. str = write_expr_to_string(str, de->expr, shorthand);
  9506. str = gb_string_append_rune(str, '^');
  9507. case_end;
  9508. case_ast_node(be, BinaryExpr, node);
  9509. str = write_expr_to_string(str, be->left, shorthand);
  9510. str = gb_string_append_rune(str, ' ');
  9511. str = string_append_token(str, be->op);
  9512. str = gb_string_append_rune(str, ' ');
  9513. str = write_expr_to_string(str, be->right, shorthand);
  9514. case_end;
  9515. case_ast_node(te, TernaryIfExpr, node);
  9516. TokenPos x = ast_token(te->x).pos;
  9517. TokenPos cond = ast_token(te->cond).pos;
  9518. if (x < cond) {
  9519. str = write_expr_to_string(str, te->x, shorthand);
  9520. str = gb_string_appendc(str, " if ");
  9521. str = write_expr_to_string(str, te->cond, shorthand);
  9522. str = gb_string_appendc(str, " else ");
  9523. str = write_expr_to_string(str, te->y, shorthand);
  9524. } else {
  9525. str = write_expr_to_string(str, te->cond, shorthand);
  9526. str = gb_string_appendc(str, " ? ");
  9527. str = write_expr_to_string(str, te->x, shorthand);
  9528. str = gb_string_appendc(str, " : ");
  9529. str = write_expr_to_string(str, te->y, shorthand);
  9530. }
  9531. case_end;
  9532. case_ast_node(te, TernaryWhenExpr, node);
  9533. str = write_expr_to_string(str, te->x, shorthand);
  9534. str = gb_string_appendc(str, " when ");
  9535. str = write_expr_to_string(str, te->cond, shorthand);
  9536. str = gb_string_appendc(str, " else ");
  9537. str = write_expr_to_string(str, te->y, shorthand);
  9538. case_end;
  9539. case_ast_node(oe, OrElseExpr, node);
  9540. str = write_expr_to_string(str, oe->x, shorthand);
  9541. str = gb_string_appendc(str, " or_else ");
  9542. str = write_expr_to_string(str, oe->y, shorthand);
  9543. case_end;
  9544. case_ast_node(oe, OrReturnExpr, node);
  9545. str = write_expr_to_string(str, oe->expr, shorthand);
  9546. str = gb_string_appendc(str, " or_return");
  9547. case_end;
  9548. case_ast_node(oe, OrBranchExpr, node);
  9549. str = write_expr_to_string(str, oe->expr, shorthand);
  9550. str = gb_string_append_rune(str, ' ');
  9551. str = string_append_token(str, oe->token);
  9552. if (oe->label) {
  9553. str = gb_string_append_rune(str, ' ');
  9554. str = write_expr_to_string(str, oe->label, shorthand);
  9555. }
  9556. case_end;
  9557. case_ast_node(pe, ParenExpr, node);
  9558. str = gb_string_append_rune(str, '(');
  9559. str = write_expr_to_string(str, pe->expr, shorthand);
  9560. str = gb_string_append_rune(str, ')');
  9561. case_end;
  9562. case_ast_node(se, SelectorExpr, node);
  9563. str = write_expr_to_string(str, se->expr, shorthand);
  9564. str = string_append_token(str, se->token);
  9565. str = write_expr_to_string(str, se->selector, shorthand);
  9566. case_end;
  9567. case_ast_node(se, ImplicitSelectorExpr, node);
  9568. str = gb_string_append_rune(str, '.');
  9569. str = write_expr_to_string(str, se->selector, shorthand);
  9570. case_end;
  9571. case_ast_node(se, SelectorCallExpr, node);
  9572. str = write_expr_to_string(str, se->expr, shorthand);
  9573. str = gb_string_appendc(str, "(");
  9574. ast_node(ce, CallExpr, se->call);
  9575. isize start = se->modified_call ? 1 : 0;
  9576. for (isize i = start; i < ce->args.count; i++) {
  9577. Ast *arg = ce->args[i];
  9578. if (i > start) {
  9579. str = gb_string_appendc(str, ", ");
  9580. }
  9581. str = write_expr_to_string(str, arg, shorthand);
  9582. }
  9583. str = gb_string_appendc(str, ")");
  9584. case_end;
  9585. case_ast_node(ta, TypeAssertion, node);
  9586. str = write_expr_to_string(str, ta->expr, shorthand);
  9587. if (ta->type != nullptr &&
  9588. ta->type->kind == Ast_UnaryExpr &&
  9589. ta->type->UnaryExpr.op.kind == Token_Question) {
  9590. str = gb_string_appendc(str, ".?");
  9591. } else {
  9592. str = gb_string_appendc(str, ".(");
  9593. str = write_expr_to_string(str, ta->type, shorthand);
  9594. str = gb_string_append_rune(str, ')');
  9595. }
  9596. case_end;
  9597. case_ast_node(tc, TypeCast, node);
  9598. str = string_append_token(str, tc->token);
  9599. str = gb_string_append_rune(str, '(');
  9600. str = write_expr_to_string(str, tc->type, shorthand);
  9601. str = gb_string_append_rune(str, ')');
  9602. str = write_expr_to_string(str, tc->expr, shorthand);
  9603. case_end;
  9604. case_ast_node(ac, AutoCast, node);
  9605. str = string_append_token(str, ac->token);
  9606. str = gb_string_append_rune(str, ' ');
  9607. str = write_expr_to_string(str, ac->expr, shorthand);
  9608. case_end;
  9609. case_ast_node(ie, IndexExpr, node);
  9610. str = write_expr_to_string(str, ie->expr, shorthand);
  9611. str = gb_string_append_rune(str, '[');
  9612. str = write_expr_to_string(str, ie->index, shorthand);
  9613. str = gb_string_append_rune(str, ']');
  9614. case_end;
  9615. case_ast_node(se, SliceExpr, node);
  9616. str = write_expr_to_string(str, se->expr, shorthand);
  9617. str = gb_string_append_rune(str, '[');
  9618. str = write_expr_to_string(str, se->low, shorthand);
  9619. str = string_append_token(str, se->interval);
  9620. str = write_expr_to_string(str, se->high, shorthand);
  9621. str = gb_string_append_rune(str, ']');
  9622. case_end;
  9623. case_ast_node(mie, MatrixIndexExpr, node);
  9624. str = write_expr_to_string(str, mie->expr, shorthand);
  9625. str = gb_string_append_rune(str, '[');
  9626. str = write_expr_to_string(str, mie->row_index, shorthand);
  9627. str = gb_string_appendc(str, ", ");
  9628. str = write_expr_to_string(str, mie->column_index, shorthand);
  9629. str = gb_string_append_rune(str, ']');
  9630. case_end;
  9631. case_ast_node(e, Ellipsis, node);
  9632. str = gb_string_appendc(str, "..");
  9633. str = write_expr_to_string(str, e->expr, shorthand);
  9634. case_end;
  9635. case_ast_node(fv, FieldValue, node);
  9636. str = write_expr_to_string(str, fv->field, shorthand);
  9637. str = gb_string_appendc(str, " = ");
  9638. str = write_expr_to_string(str, fv->value, shorthand);
  9639. case_end;
  9640. case_ast_node(fv, EnumFieldValue, node);
  9641. str = write_expr_to_string(str, fv->name, shorthand);
  9642. if (fv->value) {
  9643. str = gb_string_appendc(str, " = ");
  9644. str = write_expr_to_string(str, fv->value, shorthand);
  9645. }
  9646. case_end;
  9647. case_ast_node(ht, HelperType, node);
  9648. str = gb_string_appendc(str, "#type ");
  9649. str = write_expr_to_string(str, ht->type, shorthand);
  9650. case_end;
  9651. case_ast_node(ht, DistinctType, node);
  9652. str = gb_string_appendc(str, "distinct ");
  9653. str = write_expr_to_string(str, ht->type, shorthand);
  9654. case_end;
  9655. case_ast_node(pt, PolyType, node);
  9656. str = gb_string_append_rune(str, '$');
  9657. str = write_expr_to_string(str, pt->type, shorthand);
  9658. if (pt->specialization != nullptr) {
  9659. str = gb_string_append_rune(str, '/');
  9660. str = write_expr_to_string(str, pt->specialization, shorthand);
  9661. }
  9662. case_end;
  9663. case_ast_node(pt, PointerType, node);
  9664. str = gb_string_append_rune(str, '^');
  9665. str = write_expr_to_string(str, pt->type, shorthand);
  9666. case_end;
  9667. case_ast_node(pt, MultiPointerType, node);
  9668. str = gb_string_appendc(str, "[^]");
  9669. str = write_expr_to_string(str, pt->type, shorthand);
  9670. case_end;
  9671. case_ast_node(at, ArrayType, node);
  9672. str = gb_string_append_rune(str, '[');
  9673. if (at->count != nullptr &&
  9674. at->count->kind == Ast_UnaryExpr &&
  9675. at->count->UnaryExpr.op.kind == Token_Question) {
  9676. str = gb_string_appendc(str, "?");
  9677. } else {
  9678. str = write_expr_to_string(str, at->count, shorthand);
  9679. }
  9680. str = gb_string_append_rune(str, ']');
  9681. str = write_expr_to_string(str, at->elem, shorthand);
  9682. case_end;
  9683. case_ast_node(at, DynamicArrayType, node);
  9684. str = gb_string_appendc(str, "[dynamic]");
  9685. str = write_expr_to_string(str, at->elem, shorthand);
  9686. case_end;
  9687. case_ast_node(bs, BitSetType, node);
  9688. str = gb_string_appendc(str, "bit_set[");
  9689. str = write_expr_to_string(str, bs->elem, shorthand);
  9690. str = gb_string_appendc(str, "]");
  9691. case_end;
  9692. case_ast_node(mt, MapType, node);
  9693. str = gb_string_appendc(str, "map[");
  9694. str = write_expr_to_string(str, mt->key, shorthand);
  9695. str = gb_string_append_rune(str, ']');
  9696. str = write_expr_to_string(str, mt->value, shorthand);
  9697. case_end;
  9698. case_ast_node(mt, MatrixType, node);
  9699. str = gb_string_appendc(str, "matrix[");
  9700. str = write_expr_to_string(str, mt->row_count, shorthand);
  9701. str = gb_string_appendc(str, ", ");
  9702. str = write_expr_to_string(str, mt->column_count, shorthand);
  9703. str = gb_string_append_rune(str, ']');
  9704. str = write_expr_to_string(str, mt->elem, shorthand);
  9705. case_end;
  9706. case_ast_node(f, Field, node);
  9707. if (f->flags&FieldFlag_using) {
  9708. str = gb_string_appendc(str, "using ");
  9709. }
  9710. if (f->flags&FieldFlag_no_alias) {
  9711. str = gb_string_appendc(str, "#no_alias ");
  9712. }
  9713. if (f->flags&FieldFlag_c_vararg) {
  9714. str = gb_string_appendc(str, "#c_vararg ");
  9715. }
  9716. if (f->flags&FieldFlag_any_int) {
  9717. str = gb_string_appendc(str, "#any_int ");
  9718. }
  9719. if (f->flags&FieldFlag_const) {
  9720. str = gb_string_appendc(str, "#const ");
  9721. }
  9722. if (f->flags&FieldFlag_subtype) {
  9723. str = gb_string_appendc(str, "#subtype ");
  9724. }
  9725. for_array(i, f->names) {
  9726. Ast *name = f->names[i];
  9727. if (i > 0) str = gb_string_appendc(str, ", ");
  9728. str = write_expr_to_string(str, name, shorthand);
  9729. }
  9730. if (f->names.count > 0) {
  9731. if (f->type == nullptr && f->default_value != nullptr) {
  9732. str = gb_string_append_rune(str, ' ');
  9733. }
  9734. str = gb_string_appendc(str, ":");
  9735. }
  9736. if (f->type != nullptr) {
  9737. str = gb_string_append_rune(str, ' ');
  9738. str = write_expr_to_string(str, f->type, shorthand);
  9739. }
  9740. if (f->default_value != nullptr) {
  9741. if (f->type != nullptr) {
  9742. str = gb_string_append_rune(str, ' ');
  9743. }
  9744. str = gb_string_appendc(str, "= ");
  9745. str = write_expr_to_string(str, f->default_value, shorthand);
  9746. }
  9747. case_end;
  9748. case_ast_node(f, FieldList, node);
  9749. bool has_name = false;
  9750. for_array(i, f->list) {
  9751. ast_node(field, Field, f->list[i]);
  9752. if (field->names.count > 1) {
  9753. has_name = true;
  9754. break;
  9755. }
  9756. if (field->names.count == 0) {
  9757. continue;
  9758. }
  9759. if (!is_blank_ident(field->names[0])) {
  9760. has_name = true;
  9761. break;
  9762. }
  9763. }
  9764. for_array(i, f->list) {
  9765. if (i > 0) str = gb_string_appendc(str, ", ");
  9766. if (has_name) {
  9767. str = write_expr_to_string(str, f->list[i], shorthand);
  9768. } else {
  9769. ast_node(field, Field, f->list[i]);
  9770. if (field->flags&FieldFlag_using) {
  9771. str = gb_string_appendc(str, "using ");
  9772. }
  9773. if (field->flags&FieldFlag_no_alias) {
  9774. str = gb_string_appendc(str, "#no_alias ");
  9775. }
  9776. if (field->flags&FieldFlag_c_vararg) {
  9777. str = gb_string_appendc(str, "#c_vararg ");
  9778. }
  9779. str = write_expr_to_string(str, field->type, shorthand);
  9780. }
  9781. }
  9782. case_end;
  9783. case_ast_node(ce, CallExpr, node);
  9784. switch (ce->inlining) {
  9785. case ProcInlining_inline:
  9786. str = gb_string_appendc(str, "#force_inline ");
  9787. break;
  9788. case ProcInlining_no_inline:
  9789. str = gb_string_appendc(str, "#force_no_inline ");
  9790. break;
  9791. }
  9792. str = write_expr_to_string(str, ce->proc, shorthand);
  9793. str = gb_string_appendc(str, "(");
  9794. isize idx0 = cast(isize)ce->was_selector;
  9795. for (isize i = idx0; i < ce->args.count; i++) {
  9796. Ast *arg = ce->args[i];
  9797. if (i > idx0) {
  9798. str = gb_string_appendc(str, ", ");
  9799. }
  9800. str = write_expr_to_string(str, arg, shorthand);
  9801. }
  9802. str = gb_string_appendc(str, ")");
  9803. case_end;
  9804. case_ast_node(tt, TypeidType, node);
  9805. str = gb_string_appendc(str, "typeid");
  9806. if (tt->specialization) {
  9807. str = gb_string_appendc(str, "/");
  9808. str = write_expr_to_string(str, tt->specialization, shorthand);
  9809. }
  9810. case_end;
  9811. case_ast_node(pt, ProcType, node);
  9812. str = gb_string_appendc(str, "proc(");
  9813. str = write_expr_to_string(str, pt->params, shorthand);
  9814. str = gb_string_appendc(str, ")");
  9815. if (pt->results != nullptr) {
  9816. str = gb_string_appendc(str, " -> ");
  9817. bool parens_needed = false;
  9818. if (pt->results && pt->results->kind == Ast_FieldList) {
  9819. for (Ast *field : pt->results->FieldList.list) {
  9820. ast_node(f, Field, field);
  9821. if (f->names.count != 0) {
  9822. parens_needed = true;
  9823. break;
  9824. }
  9825. }
  9826. }
  9827. if (parens_needed) {
  9828. str = gb_string_append_rune(str, '(');
  9829. }
  9830. str = write_expr_to_string(str, pt->results, shorthand);
  9831. if (parens_needed) {
  9832. str = gb_string_append_rune(str, ')');
  9833. }
  9834. }
  9835. case_end;
  9836. case_ast_node(st, StructType, node);
  9837. str = gb_string_appendc(str, "struct ");
  9838. if (st->polymorphic_params) {
  9839. str = gb_string_append_rune(str, '(');
  9840. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9841. str = gb_string_appendc(str, ") ");
  9842. }
  9843. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  9844. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  9845. if (st->align) {
  9846. str = gb_string_appendc(str, "#align ");
  9847. str = write_expr_to_string(str, st->align, shorthand);
  9848. str = gb_string_append_rune(str, ' ');
  9849. }
  9850. str = gb_string_append_rune(str, '{');
  9851. if (shorthand) {
  9852. str = gb_string_appendc(str, "...");
  9853. } else {
  9854. str = write_struct_fields_to_string(str, st->fields);
  9855. }
  9856. str = gb_string_append_rune(str, '}');
  9857. case_end;
  9858. case_ast_node(st, UnionType, node);
  9859. str = gb_string_appendc(str, "union ");
  9860. if (st->polymorphic_params) {
  9861. str = gb_string_append_rune(str, '(');
  9862. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9863. str = gb_string_appendc(str, ") ");
  9864. }
  9865. switch (st->kind) {
  9866. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  9867. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  9868. }
  9869. if (st->align) {
  9870. str = gb_string_appendc(str, "#align ");
  9871. str = write_expr_to_string(str, st->align, shorthand);
  9872. str = gb_string_append_rune(str, ' ');
  9873. }
  9874. str = gb_string_append_rune(str, '{');
  9875. if (shorthand) {
  9876. str = gb_string_appendc(str, "...");
  9877. } else {
  9878. str = write_struct_fields_to_string(str, st->variants);
  9879. }
  9880. str = gb_string_append_rune(str, '}');
  9881. case_end;
  9882. case_ast_node(et, EnumType, node);
  9883. str = gb_string_appendc(str, "enum ");
  9884. if (et->base_type != nullptr) {
  9885. str = write_expr_to_string(str, et->base_type, shorthand);
  9886. str = gb_string_append_rune(str, ' ');
  9887. }
  9888. str = gb_string_append_rune(str, '{');
  9889. if (shorthand) {
  9890. str = gb_string_appendc(str, "...");
  9891. } else {
  9892. for_array(i, et->fields) {
  9893. if (i > 0) {
  9894. str = gb_string_appendc(str, ", ");
  9895. }
  9896. str = write_expr_to_string(str, et->fields[i], shorthand);
  9897. }
  9898. }
  9899. str = gb_string_append_rune(str, '}');
  9900. case_end;
  9901. case_ast_node(rt, RelativeType, node);
  9902. str = write_expr_to_string(str, rt->tag, shorthand);
  9903. str = gb_string_appendc(str, "" );
  9904. str = write_expr_to_string(str, rt->type, shorthand);
  9905. case_end;
  9906. case_ast_node(f, BitFieldField, node);
  9907. str = write_expr_to_string(str, f->name, shorthand);
  9908. str = gb_string_appendc(str, ": ");
  9909. str = write_expr_to_string(str, f->type, shorthand);
  9910. str = gb_string_appendc(str, " | ");
  9911. str = write_expr_to_string(str, f->bit_size, shorthand);
  9912. case_end;
  9913. case_ast_node(bf, BitFieldType, node);
  9914. str = gb_string_appendc(str, "bit_field ");
  9915. if (!shorthand) {
  9916. str = write_expr_to_string(str, bf->backing_type, shorthand);
  9917. }
  9918. str = gb_string_appendc(str, " {");
  9919. if (shorthand) {
  9920. str = gb_string_appendc(str, "...");
  9921. } else {
  9922. for_array(i, bf->fields) {
  9923. if (i > 0) {
  9924. str = gb_string_appendc(str, ", ");
  9925. }
  9926. str = write_expr_to_string(str, bf->fields[i], false);
  9927. }
  9928. }
  9929. str = gb_string_appendc(str, "}");
  9930. case_end;
  9931. case_ast_node(ia, InlineAsmExpr, node);
  9932. str = gb_string_appendc(str, "asm(");
  9933. for_array(i, ia->param_types) {
  9934. if (i > 0) {
  9935. str = gb_string_appendc(str, ", ");
  9936. }
  9937. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  9938. }
  9939. str = gb_string_appendc(str, ")");
  9940. if (ia->return_type != nullptr) {
  9941. str = gb_string_appendc(str, " -> ");
  9942. str = write_expr_to_string(str, ia->return_type, shorthand);
  9943. }
  9944. if (ia->has_side_effects) {
  9945. str = gb_string_appendc(str, " #side_effects");
  9946. }
  9947. if (ia->is_align_stack) {
  9948. str = gb_string_appendc(str, " #stack_align");
  9949. }
  9950. if (ia->dialect) {
  9951. str = gb_string_appendc(str, " #");
  9952. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  9953. }
  9954. str = gb_string_appendc(str, " {");
  9955. if (shorthand) {
  9956. str = gb_string_appendc(str, "...");
  9957. } else {
  9958. str = write_expr_to_string(str, ia->asm_string, shorthand);
  9959. str = gb_string_appendc(str, ", ");
  9960. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  9961. }
  9962. str = gb_string_appendc(str, "}");
  9963. case_end;
  9964. }
  9965. return str;
  9966. }
  9967. gb_internal gbString expr_to_string(Ast *expression) {
  9968. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  9969. }
  9970. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  9971. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  9972. }
  9973. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  9974. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  9975. }