check_expr.cpp 336 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615
  1. enum CallArgumentError {
  2. CallArgumentError_None,
  3. CallArgumentError_NoneProcedureType,
  4. CallArgumentError_WrongTypes,
  5. CallArgumentError_NonVariadicExpand,
  6. CallArgumentError_VariadicTuple,
  7. CallArgumentError_MultipleVariadicExpand,
  8. CallArgumentError_AmbiguousPolymorphicVariadic,
  9. CallArgumentError_ArgumentCount,
  10. CallArgumentError_TooFewArguments,
  11. CallArgumentError_TooManyArguments,
  12. CallArgumentError_InvalidFieldValue,
  13. CallArgumentError_ParameterNotFound,
  14. CallArgumentError_ParameterMissing,
  15. CallArgumentError_DuplicateParameter,
  16. CallArgumentError_NoneConstantParameter,
  17. CallArgumentError_OutOfOrderParameters,
  18. CallArgumentError_MAX,
  19. };
  20. gb_global char const *CallArgumentError_strings[CallArgumentError_MAX] = {
  21. "None",
  22. "NoneProcedureType",
  23. "WrongTypes",
  24. "NonVariadicExpand",
  25. "VariadicTuple",
  26. "MultipleVariadicExpand",
  27. "AmbiguousPolymorphicVariadic",
  28. "ArgumentCount",
  29. "TooFewArguments",
  30. "TooManyArguments",
  31. "InvalidFieldValue",
  32. "ParameterNotFound",
  33. "ParameterMissing",
  34. "DuplicateParameter",
  35. "NoneConstantParameter",
  36. "OutOfOrderParameters",
  37. };
  38. enum struct CallArgumentErrorMode {
  39. NoErrors,
  40. ShowErrors,
  41. };
  42. struct CallArgumentData {
  43. Entity *gen_entity;
  44. i64 score;
  45. Type * result_type;
  46. };
  47. struct PolyProcData {
  48. Entity * gen_entity;
  49. ProcInfo *proc_info;
  50. };
  51. struct ValidIndexAndScore {
  52. isize index;
  53. i64 score;
  54. };
  55. gb_internal int valid_index_and_score_cmp(void const *a, void const *b) {
  56. i64 si = (cast(ValidIndexAndScore const *)a)->score;
  57. i64 sj = (cast(ValidIndexAndScore const *)b)->score;
  58. return sj < si ? -1 : sj > si;
  59. }
  60. gb_internal void check_expr (CheckerContext *c, Operand *operand, Ast *expression);
  61. gb_internal void check_multi_expr (CheckerContext *c, Operand *operand, Ast *expression);
  62. gb_internal void check_multi_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression);
  63. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint);
  64. gb_internal void check_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  65. gb_internal ExprKind check_expr_base (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  66. gb_internal void check_expr_with_type_hint (CheckerContext *c, Operand *o, Ast *e, Type *t);
  67. gb_internal Type * check_type (CheckerContext *c, Ast *expression);
  68. gb_internal Type * check_type_expr (CheckerContext *c, Ast *expression, Type *named_type);
  69. gb_internal Type * make_optional_ok_type (Type *value, bool typed=true);
  70. gb_internal Entity * check_selector (CheckerContext *c, Operand *operand, Ast *node, Type *type_hint);
  71. gb_internal Entity * check_ident (CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name);
  72. gb_internal void check_not_tuple (CheckerContext *c, Operand *operand);
  73. gb_internal void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
  74. gb_internal gbString expr_to_string (Ast *expression);
  75. gb_internal gbString expr_to_string (Ast *expression, gbAllocator allocator);
  76. gb_internal void update_untyped_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
  77. gb_internal bool check_is_terminating (Ast *node, String const &label);
  78. gb_internal bool check_has_break (Ast *stmt, String const &label, bool implicit);
  79. gb_internal void check_stmt (CheckerContext *c, Ast *node, u32 flags);
  80. gb_internal void check_stmt_list (CheckerContext *c, Slice<Ast *> const &stmts, u32 flags);
  81. gb_internal void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
  82. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
  83. gb_internal bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> const *operands = nullptr);
  84. gb_internal void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
  85. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  86. gb_internal void check_union_type (CheckerContext *c, Type *union_type, Ast *node, Array<Operand> *poly_operands,
  87. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  88. gb_internal Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  89. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0);
  90. gb_internal void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
  91. gb_internal Type *make_soa_struct_fixed(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem, i64 count, Type *generic_type);
  92. gb_internal Type *make_soa_struct_slice(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  93. gb_internal Type *make_soa_struct_dynamic_array(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  94. gb_internal bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint);
  95. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand=true);
  96. gb_internal void check_or_else_right_type(CheckerContext *c, Ast *expr, String const &name, Type *right_type);
  97. gb_internal void check_or_else_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  98. gb_internal void check_or_else_expr_no_value_error(CheckerContext *c, String const &name, Operand const &x, Type *type_hint);
  99. gb_internal void check_or_return_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  100. gb_internal bool is_diverging_expr(Ast *expr);
  101. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_);
  102. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr);
  103. gb_internal Entity *find_polymorphic_record_entity(GenTypesData *found_gen_types, isize param_count, Array<Operand> const &ordered_operands);
  104. gb_internal bool complete_soa_type(Checker *checker, Type *t, bool wait_to_finish);
  105. enum LoadDirectiveResult {
  106. LoadDirective_Success = 0,
  107. LoadDirective_Error = 1,
  108. LoadDirective_NotFound = 2,
  109. };
  110. gb_internal bool is_load_directive_call(Ast *call) {
  111. call = unparen_expr(call);
  112. if (call->kind != Ast_CallExpr) {
  113. return false;
  114. }
  115. ast_node(ce, CallExpr, call);
  116. if (ce->proc->kind != Ast_BasicDirective) {
  117. return false;
  118. }
  119. ast_node(bd, BasicDirective, ce->proc);
  120. String name = bd->name.string;
  121. return name == "load";
  122. }
  123. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  124. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  125. auto results = did_you_mean_results(d);
  126. if (results.count != 0) {
  127. error_line("\tSuggestion: Did you mean?\n");
  128. for (auto const &result : results) {
  129. String const &target = result.target;
  130. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  131. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  132. }
  133. }
  134. }
  135. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  136. if (e->kind != Entity_TypeName) {
  137. return;
  138. }
  139. if (e->TypeName.objc_metadata == nullptr) {
  140. return;
  141. }
  142. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  143. Type *t = base_type(e->type);
  144. GB_ASSERT(t->kind == Type_Struct);
  145. if (is_type) {
  146. for (auto const &entry : objc_metadata->type_entries) {
  147. string_set_add(set, entry.name);
  148. }
  149. } else {
  150. for (auto const &entry : objc_metadata->value_entries) {
  151. string_set_add(set, entry.name);
  152. }
  153. }
  154. for (Entity *f : t->Struct.fields) {
  155. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  156. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  157. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  158. }
  159. }
  160. }
  161. }
  162. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  163. if (build_context.terse_errors) { return; }
  164. ERROR_BLOCK();
  165. GB_ASSERT(e->kind == Entity_TypeName);
  166. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  167. auto *objc_metadata = e->TypeName.objc_metadata;
  168. MUTEX_GUARD(objc_metadata->mutex);
  169. StringSet set = {};
  170. defer (string_set_destroy(&set));
  171. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  172. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  173. defer (did_you_mean_destroy(&d));
  174. for (String const &target : set) {
  175. did_you_mean_append(&d, target);
  176. }
  177. check_did_you_mean_print(&d, prefix);
  178. }
  179. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  180. if (build_context.terse_errors) { return; }
  181. ERROR_BLOCK();
  182. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  183. defer (did_you_mean_destroy(&d));
  184. for (Entity *e : fields) {
  185. did_you_mean_append(&d, e->token.string);
  186. }
  187. check_did_you_mean_print(&d, prefix);
  188. }
  189. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  190. if (build_context.terse_errors) { return; }
  191. ERROR_BLOCK();
  192. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  193. defer (did_you_mean_destroy(&d));
  194. for (Entity *e : fields) {
  195. did_you_mean_append(&d, e->token.string);
  196. }
  197. check_did_you_mean_print(&d, prefix);
  198. }
  199. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  200. if (build_context.terse_errors) { return; }
  201. ERROR_BLOCK();
  202. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  203. defer (did_you_mean_destroy(&d));
  204. rw_mutex_shared_lock(&scope->mutex);
  205. for (auto const &entry : scope->elements) {
  206. Entity *e = entry.value;
  207. did_you_mean_append(&d, e->token.string);
  208. }
  209. rw_mutex_shared_unlock(&scope->mutex);
  210. check_did_you_mean_print(&d, prefix);
  211. }
  212. gb_internal Entity *entity_from_expr(Ast *expr) {
  213. expr = unparen_expr(expr);
  214. switch (expr->kind) {
  215. case Ast_Ident:
  216. return expr->Ident.entity;
  217. case Ast_SelectorExpr:
  218. return entity_from_expr(expr->SelectorExpr.selector);
  219. }
  220. return nullptr;
  221. }
  222. gb_internal void error_operand_not_expression(Operand *o) {
  223. if (o->mode == Addressing_Type) {
  224. gbString err = expr_to_string(o->expr);
  225. error(o->expr, "'%s' is not an expression but a type", err);
  226. gb_string_free(err);
  227. o->mode = Addressing_Invalid;
  228. }
  229. }
  230. gb_internal void error_operand_no_value(Operand *o) {
  231. if (o->mode == Addressing_NoValue) {
  232. gbString err = expr_to_string(o->expr);
  233. Ast *x = unparen_expr(o->expr);
  234. if (x->kind == Ast_CallExpr) {
  235. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  236. } else {
  237. error(o->expr, "'%s' used as a value", err);
  238. }
  239. gb_string_free(err);
  240. o->mode = Addressing_Invalid;
  241. }
  242. }
  243. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  244. if (build_context.dynamic_map_calls) {
  245. add_package_dependency(c, "runtime", "__dynamic_map_get");
  246. } else {
  247. add_package_dependency(c, "runtime", "map_desired_position");
  248. add_package_dependency(c, "runtime", "map_probe_distance");
  249. }
  250. }
  251. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  252. init_core_source_code_location(c->checker);
  253. if (t_map_set_proc == nullptr) {
  254. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  255. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  256. }
  257. if (build_context.dynamic_map_calls) {
  258. add_package_dependency(c, "runtime", "__dynamic_map_set");
  259. } else {
  260. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  261. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  262. }
  263. }
  264. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  265. init_core_source_code_location(c->checker);
  266. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  267. }
  268. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  269. Scope *s = c->scope;
  270. check_collect_entities(c, nodes);
  271. for (auto const &entry : s->elements) {
  272. Entity *e = entry.value;
  273. switch (e->kind) {
  274. case Entity_Constant:
  275. case Entity_TypeName:
  276. case Entity_Procedure:
  277. break;
  278. default:
  279. continue;
  280. }
  281. DeclInfo *d = decl_info_of_entity(e);
  282. if (d != nullptr) {
  283. check_entity_decl(c, e, d, nullptr);
  284. }
  285. }
  286. }
  287. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  288. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  289. ///////////////////////////////////////////////////////////////////////////////
  290. // //
  291. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  292. // //
  293. ///////////////////////////////////////////////////////////////////////////////
  294. CheckerInfo *info = old_c->info;
  295. if (base_entity == nullptr) {
  296. return false;
  297. }
  298. if (!is_type_proc(base_entity->type)) {
  299. return false;
  300. }
  301. if (base_entity->flags & EntityFlag_Disabled) {
  302. return false;
  303. }
  304. String name = base_entity->token.string;
  305. Type *src = base_type(base_entity->type);
  306. Type *dst = nullptr;
  307. if (type != nullptr) {
  308. dst = base_type(type);
  309. }
  310. if (param_operands == nullptr) {
  311. GB_ASSERT(dst != nullptr);
  312. }
  313. if (param_operands != nullptr) {
  314. GB_ASSERT(dst == nullptr);
  315. }
  316. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  317. return false;
  318. }
  319. if (dst != nullptr) {
  320. if (dst->Proc.is_polymorphic) {
  321. return false;
  322. }
  323. if (dst->Proc.param_count != src->Proc.param_count ||
  324. dst->Proc.result_count != src->Proc.result_count) {
  325. return false;
  326. }
  327. }
  328. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  329. if (old_decl == nullptr) {
  330. return false;
  331. }
  332. gbAllocator a = heap_allocator();
  333. Array<Operand> operands = {};
  334. if (param_operands) {
  335. operands = *param_operands;
  336. } else {
  337. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  338. for (isize i = 0; i < dst->Proc.param_count; i++) {
  339. Entity *param = dst->Proc.params->Tuple.variables[i];
  340. Operand o = {Addressing_Value};
  341. o.type = param->type;
  342. array_add(&operands, o);
  343. }
  344. }
  345. defer (if (param_operands == nullptr) {
  346. array_free(&operands);
  347. });
  348. CheckerContext nctx = *old_c;
  349. Scope *scope = create_scope(info, base_entity->scope);
  350. scope->flags |= ScopeFlag_Proc;
  351. nctx.scope = scope;
  352. nctx.allow_polymorphic_types = true;
  353. if (nctx.polymorphic_scope == nullptr) {
  354. nctx.polymorphic_scope = scope;
  355. }
  356. auto *pt = &src->Proc;
  357. // NOTE(bill): This is slightly memory leaking if the type already exists
  358. // Maybe it's better to check with the previous types first?
  359. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  360. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  361. if (!success) {
  362. return false;
  363. }
  364. GenProcsData *gen_procs = nullptr;
  365. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  366. GB_ASSERT(base_entity->kind == Entity_Procedure);
  367. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  368. gen_procs = base_entity->Procedure.gen_procs;
  369. if (gen_procs) {
  370. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  371. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  372. for (Entity *other : gen_procs->procs) {
  373. Type *pt = base_type(other->type);
  374. if (are_types_identical(pt, final_proc_type)) {
  375. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  376. if (poly_proc_data) {
  377. poly_proc_data->gen_entity = other;
  378. }
  379. return true;
  380. }
  381. }
  382. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  383. } else {
  384. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  385. gen_procs->procs.allocator = heap_allocator();
  386. base_entity->Procedure.gen_procs = gen_procs;
  387. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  388. }
  389. {
  390. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  391. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  392. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  393. nctx.no_polymorphic_errors = false;
  394. // NOTE(bill): Reset scope from the failed procedure type
  395. scope_reset(scope);
  396. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  397. Ast *cloned_proc_type_node = clone_ast(pt->node);
  398. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  399. if (!success) {
  400. return false;
  401. }
  402. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  403. for (Entity *other : gen_procs->procs) {
  404. Type *pt = base_type(other->type);
  405. if (are_types_identical(pt, final_proc_type)) {
  406. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  407. if (poly_proc_data) {
  408. poly_proc_data->gen_entity = other;
  409. }
  410. DeclInfo *decl = other->decl_info;
  411. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  412. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  413. proc_info->file = other->file;
  414. proc_info->token = other->token;
  415. proc_info->decl = decl;
  416. proc_info->type = other->type;
  417. proc_info->body = decl->proc_lit->ProcLit.body;
  418. proc_info->tags = other->Procedure.tags;;
  419. proc_info->generated_from_polymorphic = true;
  420. proc_info->poly_def_node = poly_def_node;
  421. check_procedure_later(nctx.checker, proc_info);
  422. }
  423. return true;
  424. }
  425. }
  426. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  427. }
  428. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  429. ast_node(pl, ProcLit, proc_lit);
  430. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  431. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  432. final_proc_type->Proc.is_poly_specialized = true;
  433. final_proc_type->Proc.is_polymorphic = true;
  434. final_proc_type->Proc.variadic = src->Proc.variadic;
  435. final_proc_type->Proc.require_results = src->Proc.require_results;
  436. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  437. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  438. final_proc_type->Proc.diverging = src->Proc.diverging;
  439. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  440. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  441. for (isize i = 0; i < operands.count; i++) {
  442. Operand o = operands[i];
  443. if (final_proc_type == o.type ||
  444. base_entity->type == o.type) {
  445. // NOTE(bill): Cycle
  446. final_proc_type->Proc.is_poly_specialized = false;
  447. break;
  448. }
  449. }
  450. u64 tags = base_entity->Procedure.tags;
  451. Ast *ident = clone_ast(base_entity->identifier);
  452. Token token = ident->Ident.token;
  453. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  454. d->gen_proc_type = final_proc_type;
  455. d->type_expr = pl->type;
  456. d->proc_lit = proc_lit;
  457. d->proc_checked_state = ProcCheckedState_Unchecked;
  458. d->defer_use_checked = false;
  459. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  460. entity->identifier = ident;
  461. add_entity_and_decl_info(&nctx, ident, entity, d);
  462. // NOTE(bill): Set the scope afterwards as this is not real overloading
  463. entity->scope = scope->parent;
  464. entity->file = base_entity->file;
  465. entity->pkg = base_entity->pkg;
  466. entity->flags = 0;
  467. d->entity = entity;
  468. AstFile *file = nullptr;
  469. {
  470. Scope *s = entity->scope;
  471. while (s != nullptr && s->file == nullptr) {
  472. file = s->file;
  473. s = s->parent;
  474. }
  475. }
  476. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  477. array_add(&gen_procs->procs, entity);
  478. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  479. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  480. proc_info->file = file;
  481. proc_info->token = token;
  482. proc_info->decl = d;
  483. proc_info->type = final_proc_type;
  484. proc_info->body = pl->body;
  485. proc_info->tags = tags;
  486. proc_info->generated_from_polymorphic = true;
  487. proc_info->poly_def_node = poly_def_node;
  488. if (poly_proc_data) {
  489. poly_proc_data->gen_entity = entity;
  490. poly_proc_data->proc_info = proc_info;
  491. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  492. }
  493. // NOTE(bill): Check the newly generated procedure body
  494. check_procedure_later(nctx.checker, proc_info);
  495. return true;
  496. }
  497. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  498. if (operand->expr == nullptr) return false;
  499. Entity *base_entity = entity_of_node(operand->expr);
  500. if (base_entity == nullptr) return false;
  501. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  502. }
  503. 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) {
  504. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  505. }
  506. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  507. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  508. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  509. #define MAXIMUM_TYPE_DISTANCE 10
  510. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming) {
  511. if (c == nullptr) {
  512. GB_ASSERT(operand->mode == Addressing_Value);
  513. GB_ASSERT(is_type_typed(operand->type));
  514. }
  515. if (operand->mode == Addressing_Invalid ||
  516. type == t_invalid) {
  517. return -1;
  518. }
  519. if (operand->mode == Addressing_Builtin) {
  520. return -1;
  521. }
  522. if (operand->mode == Addressing_Type) {
  523. if (is_type_typeid(type)) {
  524. if (is_type_polymorphic(operand->type)) {
  525. return -1;
  526. }
  527. add_type_info_type(c, operand->type);
  528. return 4;
  529. }
  530. return -1;
  531. }
  532. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  533. return -1;
  534. }
  535. Type *s = operand->type;
  536. if (are_types_identical(s, type)) {
  537. return 0;
  538. }
  539. Type *src = base_type(s);
  540. Type *dst = base_type(type);
  541. if (is_type_untyped_uninit(src)) {
  542. return 1;
  543. }
  544. if (is_type_untyped_nil(src)) {
  545. if (type_has_nil(dst)) {
  546. return 1;
  547. }
  548. return -1;
  549. }
  550. if (is_type_untyped(src)) {
  551. if (is_type_any(dst)) {
  552. // NOTE(bill): Anything can cast to 'Any'
  553. add_type_info_type(c, s);
  554. return MAXIMUM_TYPE_DISTANCE;
  555. }
  556. if (dst->kind == Type_Basic) {
  557. if (operand->mode == Addressing_Constant) {
  558. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  559. if (is_type_typed(dst) && src->kind == Type_Basic) {
  560. switch (src->Basic.kind) {
  561. case Basic_UntypedBool:
  562. if (is_type_boolean(dst)) {
  563. return 1;
  564. }
  565. break;
  566. case Basic_UntypedRune:
  567. if (is_type_integer(dst) || is_type_rune(dst)) {
  568. return 1;
  569. }
  570. break;
  571. case Basic_UntypedInteger:
  572. if (is_type_integer(dst) || is_type_rune(dst)) {
  573. return 1;
  574. }
  575. break;
  576. case Basic_UntypedString:
  577. if (is_type_string(dst)) {
  578. return 1;
  579. }
  580. break;
  581. case Basic_UntypedFloat:
  582. if (is_type_float(dst)) {
  583. return 1;
  584. }
  585. break;
  586. case Basic_UntypedComplex:
  587. if (is_type_complex(dst)) {
  588. return 1;
  589. }
  590. if (is_type_quaternion(dst)) {
  591. return 2;
  592. }
  593. break;
  594. case Basic_UntypedQuaternion:
  595. if (is_type_quaternion(dst)) {
  596. return 1;
  597. }
  598. break;
  599. }
  600. }
  601. return 2;
  602. }
  603. return -1;
  604. }
  605. if (src->kind == Type_Basic) {
  606. Type *d = base_array_type(dst);
  607. i64 score = -1;
  608. switch (src->Basic.kind) {
  609. case Basic_UntypedBool:
  610. if (is_type_boolean(d)) {
  611. score = 1;
  612. }
  613. break;
  614. case Basic_UntypedRune:
  615. if (is_type_integer(d) || is_type_rune(d)) {
  616. score = 1;
  617. }
  618. break;
  619. case Basic_UntypedInteger:
  620. if (is_type_integer(d) || is_type_rune(d)) {
  621. score = 1;
  622. }
  623. break;
  624. case Basic_UntypedString:
  625. if (is_type_string(d)) {
  626. score = 1;
  627. }
  628. break;
  629. case Basic_UntypedFloat:
  630. if (is_type_float(d)) {
  631. score = 1;
  632. }
  633. break;
  634. case Basic_UntypedComplex:
  635. if (is_type_complex(d)) {
  636. score = 1;
  637. }
  638. if (is_type_quaternion(d)) {
  639. score = 2;
  640. }
  641. break;
  642. case Basic_UntypedQuaternion:
  643. if (is_type_quaternion(d)) {
  644. score = 1;
  645. }
  646. break;
  647. }
  648. if (score > 0) {
  649. if (is_type_typed(d)) {
  650. score += 1;
  651. }
  652. if (d != dst) {
  653. score += 6;
  654. }
  655. }
  656. return score;
  657. }
  658. }
  659. }
  660. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  661. if (c->in_enum_type) {
  662. return 3;
  663. }
  664. }
  665. {
  666. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  667. if (subtype_level > 0) {
  668. return 4 + subtype_level;
  669. }
  670. }
  671. // rawptr <- ^T
  672. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  673. return 5;
  674. }
  675. // rawptr <- [^]T
  676. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  677. return 5;
  678. }
  679. // ^T <- [^]T
  680. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  681. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  682. return 4;
  683. }
  684. }
  685. // [^]T <- ^T
  686. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  687. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  688. return 4;
  689. }
  690. }
  691. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  692. bool modify_type = !c->no_polymorphic_errors;
  693. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  694. return 2;
  695. }
  696. }
  697. if (is_type_union(dst)) {
  698. for (Type *vt : dst->Union.variants) {
  699. if (are_types_identical(vt, s)) {
  700. return 1;
  701. }
  702. }
  703. if (dst->Union.variants.count == 1) {
  704. Type *vt = dst->Union.variants[0];
  705. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  706. if (score >= 0) {
  707. return score+2;
  708. }
  709. } else if (is_type_untyped(src)) {
  710. i64 prev_lowest_score = -1;
  711. i64 lowest_score = -1;
  712. for (Type *vt : dst->Union.variants) {
  713. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  714. if (score >= 0) {
  715. if (lowest_score < 0) {
  716. lowest_score = score;
  717. } else {
  718. if (prev_lowest_score < 0) {
  719. prev_lowest_score = lowest_score;
  720. } else {
  721. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  722. }
  723. lowest_score = gb_min(lowest_score, score);
  724. }
  725. }
  726. }
  727. if (lowest_score >= 0) {
  728. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  729. return lowest_score+2;
  730. }
  731. }
  732. }
  733. }
  734. if (is_type_relative_pointer(dst)) {
  735. i64 score = check_distance_between_types(c, operand, dst->RelativePointer.pointer_type, allow_array_programming);
  736. if (score >= 0) {
  737. return score+2;
  738. }
  739. }
  740. if (is_type_relative_multi_pointer(dst)) {
  741. i64 score = check_distance_between_types(c, operand, dst->RelativeMultiPointer.pointer_type, allow_array_programming);
  742. if (score >= 0) {
  743. return score+2;
  744. }
  745. }
  746. if (is_type_proc(dst)) {
  747. if (are_types_identical(src, dst)) {
  748. return 3;
  749. }
  750. PolyProcData poly_proc_data = {};
  751. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  752. Entity *e = poly_proc_data.gen_entity;
  753. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  754. add_entity_use(c, operand->expr, e);
  755. return 4;
  756. }
  757. }
  758. if (is_type_complex_or_quaternion(dst)) {
  759. Type *elem = base_complex_elem_type(dst);
  760. if (are_types_identical(elem, base_type(src))) {
  761. return 5;
  762. }
  763. }
  764. if (allow_array_programming) {
  765. if (is_type_array(dst)) {
  766. Type *elem = base_array_type(dst);
  767. i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
  768. if (distance >= 0) {
  769. return distance + 6;
  770. }
  771. }
  772. if (is_type_simd_vector(dst)) {
  773. Type *dst_elem = base_array_type(dst);
  774. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  775. if (distance >= 0) {
  776. return distance + 6;
  777. }
  778. }
  779. }
  780. if (is_type_matrix(dst)) {
  781. if (are_types_identical(src, dst)) {
  782. return 5;
  783. }
  784. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  785. Type *dst_elem = base_array_type(dst);
  786. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  787. if (distance >= 0) {
  788. return distance + 7;
  789. }
  790. }
  791. }
  792. if (is_type_any(dst)) {
  793. if (!is_type_polymorphic(src)) {
  794. if (operand->mode == Addressing_Context && operand->type == t_context) {
  795. return -1;
  796. } else {
  797. // NOTE(bill): Anything can cast to 'Any'
  798. add_type_info_type(c, s);
  799. return MAXIMUM_TYPE_DISTANCE;
  800. }
  801. }
  802. }
  803. Ast *expr = unparen_expr(operand->expr);
  804. if (expr != nullptr) {
  805. if (expr->kind == Ast_AutoCast) {
  806. Operand x = *operand;
  807. x.expr = expr->AutoCast.expr;
  808. if (check_cast_internal(c, &x, type)) {
  809. return MAXIMUM_TYPE_DISTANCE;
  810. }
  811. }
  812. }
  813. return -1;
  814. }
  815. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  816. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  817. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  818. // TODO(bill): A decent score function
  819. i64 d = distance*distance; // x^2
  820. if (is_variadic && d >= 0) {
  821. d += distance + 1; // x^2 + x + 1
  822. }
  823. return gb_max(c - d, 0);
  824. }
  825. gb_internal bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_, bool is_variadic=false, bool allow_array_programming=true) {
  826. i64 score = 0;
  827. i64 distance = check_distance_between_types(c, operand, type, allow_array_programming);
  828. bool ok = distance >= 0;
  829. if (ok) {
  830. score = assign_score_function(distance, is_variadic);
  831. }
  832. if (score_) *score_ = score;
  833. return ok;
  834. }
  835. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming=true) {
  836. i64 score = 0;
  837. return check_is_assignable_to_with_score(c, operand, type, &score, /*is_variadic*/false, allow_array_programming);
  838. }
  839. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  840. Operand x = {};
  841. x.type = src;
  842. x.mode = Addressing_Value;
  843. return check_is_assignable_to(nullptr, &x, dst);
  844. }
  845. gb_internal AstPackage *get_package_of_type(Type *type) {
  846. for (;;) {
  847. if (type == nullptr) {
  848. return nullptr;
  849. }
  850. switch (type->kind) {
  851. case Type_Basic:
  852. return builtin_pkg;
  853. case Type_Named:
  854. if (type->Named.type_name != nullptr) {
  855. return type->Named.type_name->pkg;
  856. }
  857. return nullptr;
  858. case Type_Pointer:
  859. type = type->Pointer.elem;
  860. continue;
  861. case Type_Array:
  862. type = type->Array.elem;
  863. continue;
  864. case Type_Slice:
  865. type = type->Slice.elem;
  866. continue;
  867. case Type_DynamicArray:
  868. type = type->DynamicArray.elem;
  869. continue;
  870. case Type_RelativePointer:
  871. type = type->RelativePointer.pointer_type;
  872. continue;
  873. case Type_RelativeMultiPointer:
  874. type = type->RelativeMultiPointer.pointer_type;
  875. continue;
  876. }
  877. return nullptr;
  878. }
  879. }
  880. // NOTE(bill): 'content_name' is for debugging and error messages
  881. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  882. check_not_tuple(c, operand);
  883. if (operand->mode == Addressing_Invalid) {
  884. return;
  885. }
  886. if (is_type_untyped(operand->type)) {
  887. Type *target_type = type;
  888. if (type == nullptr || is_type_any(type)) {
  889. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  890. error(operand->expr, "Use of --- in %.*s", LIT(context_name));
  891. operand->mode = Addressing_Invalid;
  892. return;
  893. }
  894. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  895. error(operand->expr, "Use of untyped nil in %.*s", LIT(context_name));
  896. operand->mode = Addressing_Invalid;
  897. return;
  898. }
  899. target_type = default_type(operand->type);
  900. if (type != nullptr && !is_type_any(type)) {
  901. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  902. }
  903. add_type_info_type(c, type);
  904. add_type_info_type(c, target_type);
  905. }
  906. convert_to_typed(c, operand, target_type);
  907. if (operand->mode == Addressing_Invalid) {
  908. return;
  909. }
  910. }
  911. if (type == nullptr) {
  912. return;
  913. }
  914. if (operand->mode == Addressing_ProcGroup) {
  915. bool good = false;
  916. if (type != nullptr && is_type_proc(type)) {
  917. Array<Entity *> procs = proc_group_entities(c, *operand);
  918. // NOTE(bill): These should be done
  919. for (Entity *e : procs) {
  920. Type *t = base_type(e->type);
  921. if (t == t_invalid) {
  922. continue;
  923. }
  924. Operand x = {};
  925. x.mode = Addressing_Value;
  926. x.type = t;
  927. if (check_is_assignable_to(c, &x, type)) {
  928. add_entity_use(c, operand->expr, e);
  929. good = true;
  930. break;
  931. }
  932. }
  933. }
  934. if (!good) {
  935. gbString expr_str = expr_to_string(operand->expr);
  936. gbString op_type_str = type_to_string(operand->type);
  937. gbString type_str = type_to_string(type);
  938. defer (gb_string_free(type_str));
  939. defer (gb_string_free(op_type_str));
  940. defer (gb_string_free(expr_str));
  941. // TODO(bill): is this a good enough error message?
  942. error(operand->expr,
  943. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s",
  944. expr_str,
  945. op_type_str,
  946. LIT(context_name));
  947. operand->mode = Addressing_Invalid;
  948. }
  949. convert_to_typed(c, operand, type);
  950. return;
  951. }
  952. if (check_is_assignable_to(c, operand, type)) {
  953. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  954. add_type_info_type(c, operand->type);
  955. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  956. }
  957. } else {
  958. gbString expr_str = expr_to_string(operand->expr);
  959. gbString op_type_str = type_to_string(operand->type);
  960. gbString type_str = type_to_string(type);
  961. defer (gb_string_free(type_str));
  962. defer (gb_string_free(op_type_str));
  963. defer (gb_string_free(expr_str));
  964. switch (operand->mode) {
  965. case Addressing_Builtin:
  966. error(operand->expr,
  967. "Cannot assign built-in procedure '%s' in %.*s",
  968. expr_str,
  969. LIT(context_name));
  970. break;
  971. case Addressing_Type:
  972. if (is_type_polymorphic(operand->type)) {
  973. error(operand->expr,
  974. "Cannot assign '%s' which is a polymorphic type in %.*s",
  975. op_type_str,
  976. LIT(context_name));
  977. } else {
  978. error(operand->expr,
  979. "Cannot assign '%s' which is a type in %.*s",
  980. op_type_str,
  981. LIT(context_name));
  982. }
  983. break;
  984. default:
  985. // TODO(bill): is this a good enough error message?
  986. {
  987. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  988. gbString type_extra = gb_string_make(heap_allocator(), "");
  989. defer (gb_string_free(op_type_extra));
  990. defer (gb_string_free(type_extra));
  991. isize on = gb_string_length(op_type_str);
  992. isize tn = gb_string_length(type_str);
  993. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  994. AstPackage *op_pkg = get_package_of_type(operand->type);
  995. AstPackage *type_pkg = get_package_of_type(type);
  996. if (op_pkg != nullptr) {
  997. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  998. }
  999. if (type_pkg != nullptr) {
  1000. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  1001. }
  1002. }
  1003. ERROR_BLOCK();
  1004. error(operand->expr,
  1005. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s",
  1006. expr_str,
  1007. op_type_str, op_type_extra,
  1008. type_str, type_extra,
  1009. LIT(context_name));
  1010. check_assignment_error_suggestion(c, operand, type);
  1011. if (context_name == "procedure argument") {
  1012. Type *src = base_type(operand->type);
  1013. Type *dst = base_type(type);
  1014. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  1015. gbString a = expr_to_string(operand->expr);
  1016. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  1017. gb_string_free(a);
  1018. }
  1019. }
  1020. }
  1021. break;
  1022. }
  1023. operand->mode = Addressing_Invalid;
  1024. return;
  1025. }
  1026. }
  1027. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1028. Type *gt = *gt_;
  1029. GB_ASSERT(gt->kind == Type_Generic);
  1030. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1031. GB_ASSERT(e != nullptr);
  1032. if (e->kind == Entity_TypeName) {
  1033. *gt_ = nullptr;
  1034. *dst_count = source_count;
  1035. e->kind = Entity_Constant;
  1036. e->Constant.value = exact_value_i64(source_count);
  1037. e->type = t_untyped_integer;
  1038. return true;
  1039. } else if (e->kind == Entity_Constant) {
  1040. *gt_ = nullptr;
  1041. if (e->Constant.value.kind != ExactValue_Integer) {
  1042. return false;
  1043. }
  1044. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1045. if (count != source_count) {
  1046. return false;
  1047. }
  1048. *dst_count = source_count;
  1049. return true;
  1050. }
  1051. return false;
  1052. }
  1053. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1054. Operand o = {Addressing_Value};
  1055. o.type = source;
  1056. switch (poly->kind) {
  1057. case Type_Basic:
  1058. if (compound) return are_types_identical(poly, source);
  1059. return check_is_assignable_to(c, &o, poly);
  1060. case Type_Named: {
  1061. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1062. return true;
  1063. }
  1064. if (compound || !is_type_generic(poly)) {
  1065. return are_types_identical(poly, source);
  1066. }
  1067. return check_is_assignable_to(c, &o, poly);
  1068. }
  1069. case Type_Generic: {
  1070. if (poly->Generic.specialized != nullptr) {
  1071. Type *s = poly->Generic.specialized;
  1072. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1073. return false;
  1074. }
  1075. }
  1076. if (modify_type) {
  1077. Type *ds = default_type(source);
  1078. gb_memmove(poly, ds, gb_size_of(Type));
  1079. }
  1080. return true;
  1081. }
  1082. case Type_Pointer:
  1083. if (source->kind == Type_Pointer) {
  1084. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1085. if (level > 0) {
  1086. return true;
  1087. }
  1088. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1089. } else if (source->kind == Type_MultiPointer) {
  1090. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1091. if (level > 0) {
  1092. return true;
  1093. }
  1094. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1095. }
  1096. return false;
  1097. case Type_MultiPointer:
  1098. if (source->kind == Type_MultiPointer) {
  1099. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1100. if (level > 0) {
  1101. return true;
  1102. }
  1103. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1104. } else if (source->kind == Type_Pointer) {
  1105. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1106. if (level > 0) {
  1107. return true;
  1108. }
  1109. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1110. }
  1111. return false;
  1112. case Type_Array:
  1113. if (source->kind == Type_Array) {
  1114. if (poly->Array.generic_count != nullptr) {
  1115. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1116. return false;
  1117. }
  1118. }
  1119. if (poly->Array.count == source->Array.count) {
  1120. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1121. }
  1122. } else if (source->kind == Type_EnumeratedArray) {
  1123. if (poly->Array.generic_count != nullptr) {
  1124. Type *gt = poly->Array.generic_count;
  1125. GB_ASSERT(gt->kind == Type_Generic);
  1126. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1127. GB_ASSERT(e != nullptr);
  1128. if (e->kind == Entity_TypeName) {
  1129. Type *index = source->EnumeratedArray.index;
  1130. Type *it = base_type(index);
  1131. if (it->kind != Type_Enum) {
  1132. return false;
  1133. }
  1134. poly->kind = Type_EnumeratedArray;
  1135. poly->cached_size = -1;
  1136. poly->cached_align = -1;
  1137. poly->flags.exchange(source->flags);
  1138. poly->failure = false;
  1139. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1140. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1141. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1142. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1143. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1144. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1145. e->kind = Entity_TypeName;
  1146. e->TypeName.is_type_alias = true;
  1147. e->type = index;
  1148. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1149. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1150. }
  1151. }
  1152. }
  1153. }
  1154. return false;
  1155. case Type_EnumeratedArray:
  1156. if (source->kind == Type_EnumeratedArray) {
  1157. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1158. return false;
  1159. }
  1160. if (poly->EnumeratedArray.op) {
  1161. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1162. return false;
  1163. }
  1164. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1165. return false;
  1166. }
  1167. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1168. return false;
  1169. }
  1170. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1171. }
  1172. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1173. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1174. return index || elem;
  1175. }
  1176. return false;
  1177. case Type_DynamicArray:
  1178. if (source->kind == Type_DynamicArray) {
  1179. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1180. }
  1181. return false;
  1182. case Type_Slice:
  1183. if (source->kind == Type_Slice) {
  1184. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1185. }
  1186. return false;
  1187. case Type_Enum:
  1188. return false;
  1189. case Type_BitSet:
  1190. if (source->kind == Type_BitSet) {
  1191. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1192. return false;
  1193. }
  1194. if (poly->BitSet.underlying == nullptr) {
  1195. if (modify_type) {
  1196. poly->BitSet.underlying = source->BitSet.underlying;
  1197. }
  1198. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1199. return false;
  1200. }
  1201. return true;
  1202. }
  1203. return false;
  1204. case Type_Union:
  1205. if (source->kind == Type_Union) {
  1206. TypeUnion *x = &poly->Union;
  1207. TypeUnion *y = &source->Union;
  1208. if (x->variants.count != y->variants.count) {
  1209. return false;
  1210. }
  1211. for_array(i, x->variants) {
  1212. Type *a = x->variants[i];
  1213. Type *b = y->variants[i];
  1214. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1215. if (!ok) return false;
  1216. }
  1217. return true;
  1218. }
  1219. return false;
  1220. case Type_Struct:
  1221. if (source->kind == Type_Struct) {
  1222. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1223. poly->Struct.soa_kind != StructSoa_None) {
  1224. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1225. if (ok) switch (source->Struct.soa_kind) {
  1226. case StructSoa_None:
  1227. default:
  1228. GB_PANIC("Unhandled SOA Kind");
  1229. break;
  1230. case StructSoa_Fixed:
  1231. if (modify_type) {
  1232. Type *type = make_soa_struct_fixed(c, nullptr, poly->Struct.node, poly->Struct.soa_elem, poly->Struct.soa_count, nullptr);
  1233. gb_memmove(poly, type, gb_size_of(*type));
  1234. }
  1235. break;
  1236. case StructSoa_Slice:
  1237. if (modify_type) {
  1238. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1239. gb_memmove(poly, type, gb_size_of(*type));
  1240. }
  1241. break;
  1242. case StructSoa_Dynamic:
  1243. if (modify_type) {
  1244. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1245. gb_memmove(poly, type, gb_size_of(*type));
  1246. }
  1247. break;
  1248. }
  1249. return ok;
  1250. }
  1251. // NOTE(bill): Check for subtypes of
  1252. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1253. }
  1254. return false;
  1255. case Type_Tuple:
  1256. GB_PANIC("This should never happen");
  1257. return false;
  1258. case Type_Proc:
  1259. if (source->kind == Type_Proc) {
  1260. TypeProc *x = &poly->Proc;
  1261. TypeProc *y = &source->Proc;
  1262. if (x->calling_convention != y->calling_convention) {
  1263. return false;
  1264. }
  1265. if (x->c_vararg != y->c_vararg) {
  1266. return false;
  1267. }
  1268. if (x->variadic != y->variadic) {
  1269. return false;
  1270. }
  1271. if (x->param_count != y->param_count) {
  1272. return false;
  1273. }
  1274. if (x->result_count != y->result_count) {
  1275. return false;
  1276. }
  1277. for (isize i = 0; i < x->param_count; i++) {
  1278. Entity *a = x->params->Tuple.variables[i];
  1279. Entity *b = y->params->Tuple.variables[i];
  1280. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1281. if (!ok) return false;
  1282. }
  1283. for (isize i = 0; i < x->result_count; i++) {
  1284. Entity *a = x->results->Tuple.variables[i];
  1285. Entity *b = y->results->Tuple.variables[i];
  1286. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1287. if (!ok) return false;
  1288. }
  1289. return true;
  1290. }
  1291. return false;
  1292. case Type_Map:
  1293. if (source->kind == Type_Map) {
  1294. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1295. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1296. if (key || value) {
  1297. poly->Map.lookup_result_type = nullptr;
  1298. init_map_internal_types(poly);
  1299. return true;
  1300. }
  1301. }
  1302. return false;
  1303. case Type_Matrix:
  1304. if (source->kind == Type_Matrix) {
  1305. if (poly->Matrix.generic_row_count != nullptr) {
  1306. poly->Matrix.stride_in_bytes = 0;
  1307. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1308. return false;
  1309. }
  1310. }
  1311. if (poly->Matrix.generic_column_count != nullptr) {
  1312. poly->Matrix.stride_in_bytes = 0;
  1313. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1314. return false;
  1315. }
  1316. }
  1317. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1318. poly->Matrix.column_count == source->Matrix.column_count) {
  1319. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1320. }
  1321. }
  1322. return false;
  1323. case Type_SimdVector:
  1324. if (source->kind == Type_SimdVector) {
  1325. if (poly->SimdVector.generic_count != nullptr) {
  1326. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1327. return false;
  1328. }
  1329. }
  1330. if (poly->SimdVector.count == source->SimdVector.count) {
  1331. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1332. }
  1333. }
  1334. return false;
  1335. }
  1336. return false;
  1337. }
  1338. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1339. if (curr->state != EntityState_InProgress) {
  1340. return false;
  1341. }
  1342. for_array(i, *c->type_path) {
  1343. Entity *prev = c->type_path->data[i];
  1344. if (prev == curr) {
  1345. if (report) {
  1346. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1347. for (isize j = i; j < c->type_path->count; j++) {
  1348. Entity *curr = (*c->type_path)[j];
  1349. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1350. }
  1351. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1352. curr->type = t_invalid;
  1353. }
  1354. return true;
  1355. }
  1356. }
  1357. return false;
  1358. }
  1359. struct CIdentSuggestion {
  1360. String name;
  1361. String msg;
  1362. };
  1363. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1364. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1365. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1366. {str_lit("sizeof"), str_lit("'size_of'?")},
  1367. {str_lit("alignof"), str_lit("'align_of'?")},
  1368. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1369. {str_lit("_Bool"), str_lit("'bool'?")},
  1370. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1371. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1372. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1373. {str_lit("float"), str_lit("'f32'?")},
  1374. {str_lit("double"), str_lit("'f64'?")},
  1375. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1376. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1377. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1378. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1379. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1380. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1381. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1382. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1383. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1384. {str_lit("uint8_t"), str_lit("'u8'?")},
  1385. {str_lit("int8_t"), str_lit("'i8'?")},
  1386. {str_lit("uint16_t"), str_lit("'u16'?")},
  1387. {str_lit("int16_t"), str_lit("'i16'?")},
  1388. {str_lit("uint32_t"), str_lit("'u32'?")},
  1389. {str_lit("int32_t"), str_lit("'i32'?")},
  1390. {str_lit("uint64_t"), str_lit("'u64'?")},
  1391. {str_lit("int64_t"), str_lit("'i64'?")},
  1392. {str_lit("uint128_t"), str_lit("'u128'?")},
  1393. {str_lit("int128_t"), str_lit("'i128'?")},
  1394. {str_lit("float32"), str_lit("'f32'?")},
  1395. {str_lit("float64"), str_lit("'f64'?")},
  1396. {str_lit("float32_t"), str_lit("'f32'?")},
  1397. {str_lit("float64_t"), str_lit("'f64'?")},
  1398. };
  1399. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1400. GB_ASSERT(n->kind == Ast_Ident);
  1401. o->mode = Addressing_Invalid;
  1402. o->expr = n;
  1403. String name = n->Ident.token.string;
  1404. Entity *e = scope_lookup(c->scope, name);
  1405. if (e == nullptr) {
  1406. if (is_blank_ident(name)) {
  1407. error(n, "'_' cannot be used as a value");
  1408. } else {
  1409. ERROR_BLOCK();
  1410. error(n, "Undeclared name: %.*s", LIT(name));
  1411. // NOTE(bill): Loads of checks for C programmers
  1412. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1413. if (name == suggestion.name) {
  1414. error_line("\tSuggestion: Did you mean %.*s\n", LIT(suggestion.msg));
  1415. }
  1416. }
  1417. }
  1418. o->type = t_invalid;
  1419. o->mode = Addressing_Invalid;
  1420. if (named_type != nullptr) {
  1421. set_base_type(named_type, t_invalid);
  1422. }
  1423. return nullptr;
  1424. }
  1425. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1426. if (e->parent_proc_decl != nullptr &&
  1427. e->parent_proc_decl != c->curr_proc_decl) {
  1428. if (e->kind == Entity_Variable) {
  1429. if ((e->flags & EntityFlag_Static) == 0) {
  1430. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1431. return nullptr;
  1432. }
  1433. } else if (e->kind == Entity_Label) {
  1434. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1435. return nullptr;
  1436. }
  1437. }
  1438. if (e->kind == Entity_ProcGroup) {
  1439. auto *pge = &e->ProcGroup;
  1440. DeclInfo *d = decl_info_of_entity(e);
  1441. check_entity_decl(c, e, d, nullptr);
  1442. Array<Entity *> procs = pge->entities;
  1443. bool skip = false;
  1444. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1445. // NOTE(bill): These should be done
  1446. for (Entity *proc : procs) {
  1447. Type *t = base_type(proc->type);
  1448. if (t == t_invalid) {
  1449. continue;
  1450. }
  1451. Operand x = {};
  1452. x.mode = Addressing_Value;
  1453. x.type = t;
  1454. if (check_is_assignable_to(c, &x, type_hint)) {
  1455. e = proc;
  1456. add_entity_use(c, n, e);
  1457. skip = true;
  1458. break;
  1459. }
  1460. }
  1461. }
  1462. if (!skip) {
  1463. o->mode = Addressing_ProcGroup;
  1464. o->type = t_invalid;
  1465. o->proc_group = e;
  1466. return nullptr;
  1467. }
  1468. }
  1469. add_entity_use(c, n, e);
  1470. if (e->state == EntityState_Unresolved) {
  1471. check_entity_decl(c, e, nullptr, named_type);
  1472. }
  1473. if (e->type == nullptr) {
  1474. // TODO(bill): Which is correct? return or compiler_error?
  1475. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1476. return nullptr;
  1477. }
  1478. e->flags |= EntityFlag_Used;
  1479. Type *type = e->type;
  1480. o->type = type;
  1481. switch (e->kind) {
  1482. case Entity_Constant:
  1483. if (type == t_invalid) {
  1484. o->type = t_invalid;
  1485. return e;
  1486. }
  1487. o->value = e->Constant.value;
  1488. if (o->value.kind == ExactValue_Invalid) {
  1489. return e;
  1490. }
  1491. if (o->value.kind == ExactValue_Procedure) {
  1492. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1493. if (proc != nullptr) {
  1494. o->mode = Addressing_Value;
  1495. o->type = proc->type;
  1496. return proc;
  1497. }
  1498. }
  1499. o->mode = Addressing_Constant;
  1500. break;
  1501. case Entity_Variable:
  1502. e->flags |= EntityFlag_Used;
  1503. if (type == t_invalid) {
  1504. o->type = t_invalid;
  1505. return e;
  1506. }
  1507. o->mode = Addressing_Variable;
  1508. if (e->flags & EntityFlag_Value) {
  1509. o->mode = Addressing_Value;
  1510. }
  1511. break;
  1512. case Entity_Procedure:
  1513. o->mode = Addressing_Value;
  1514. o->value = exact_value_procedure(n);
  1515. break;
  1516. case Entity_Builtin:
  1517. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1518. o->mode = Addressing_Builtin;
  1519. break;
  1520. case Entity_TypeName:
  1521. o->mode = Addressing_Type;
  1522. if (check_cycle(c, e, true)) {
  1523. o->type = t_invalid;
  1524. }
  1525. if (o->type != nullptr && o->type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1526. o->type = base_type(o->type);
  1527. }
  1528. break;
  1529. case Entity_ImportName:
  1530. if (!allow_import_name) {
  1531. error(n, "Use of import '%.*s' not in selector", LIT(name));
  1532. }
  1533. return e;
  1534. case Entity_LibraryName:
  1535. if (!allow_import_name) {
  1536. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1537. }
  1538. return e;
  1539. case Entity_Label:
  1540. o->mode = Addressing_NoValue;
  1541. break;
  1542. case Entity_Nil:
  1543. o->mode = Addressing_Value;
  1544. break;
  1545. default:
  1546. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1547. break;
  1548. }
  1549. return e;
  1550. }
  1551. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1552. if (o->type == nullptr) {
  1553. gbString str = expr_to_string(o->expr);
  1554. error(o->expr, "Expression has no value '%s'", str);
  1555. gb_string_free(str);
  1556. return false;
  1557. }
  1558. Type *type = base_type(core_array_type(o->type));
  1559. gbString str = nullptr;
  1560. switch (op.kind) {
  1561. case Token_Add:
  1562. case Token_Sub:
  1563. if (!is_type_numeric(type)) {
  1564. str = expr_to_string(o->expr);
  1565. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1566. gb_string_free(str);
  1567. }
  1568. break;
  1569. case Token_Xor:
  1570. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1571. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1572. }
  1573. break;
  1574. case Token_Not:
  1575. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1576. ERROR_BLOCK();
  1577. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1578. if (is_type_integer(type)) {
  1579. str = expr_to_string(o->expr);
  1580. error_line("\tSuggestion: Did you mean to do one of the following?\n");
  1581. error_line("\t\t'%s == 0'?\n", str);
  1582. error_line("\t\tUse of the bitwise not operator '~'?\n");
  1583. gb_string_free(str);
  1584. }
  1585. } else {
  1586. o->type = t_untyped_bool;
  1587. }
  1588. break;
  1589. case Token_Mul:
  1590. {
  1591. ERROR_BLOCK();
  1592. error(op, "Operator '%.*s' is not a valid unary operator in Odin", LIT(op.string));
  1593. if (is_type_pointer(o->type)) {
  1594. str = expr_to_string(o->expr);
  1595. error_line("\tSuggestion: Did you mean '%s^'?\n", str);
  1596. o->type = type_deref(o->type);
  1597. } else if (is_type_multi_pointer(o->type)) {
  1598. str = expr_to_string(o->expr);
  1599. error_line("\tSuggestion: The value is a multi-pointer, did you mean '%s[0]'?\n", str);
  1600. o->type = type_deref(o->type, true);
  1601. }
  1602. }
  1603. break;
  1604. default:
  1605. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1606. return false;
  1607. }
  1608. return true;
  1609. }
  1610. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1611. Type *main_type = o->type;
  1612. Type *type = base_type(core_array_type(main_type));
  1613. Type *ct = core_type(type);
  1614. switch (op.kind) {
  1615. case Token_Sub:
  1616. case Token_SubEq:
  1617. if (is_type_bit_set(type)) {
  1618. return true;
  1619. } else if (!is_type_numeric(type)) {
  1620. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1621. return false;
  1622. }
  1623. break;
  1624. case Token_Quo:
  1625. case Token_QuoEq:
  1626. if (is_type_matrix(main_type)) {
  1627. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1628. return false;
  1629. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1630. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1631. return false;
  1632. }
  1633. /*fallthrough*/
  1634. case Token_Mul:
  1635. case Token_MulEq:
  1636. case Token_AddEq:
  1637. if (is_type_bit_set(type)) {
  1638. return true;
  1639. } else if (!is_type_numeric(type)) {
  1640. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1641. return false;
  1642. }
  1643. break;
  1644. case Token_Add:
  1645. if (is_type_string(type)) {
  1646. if (o->mode == Addressing_Constant) {
  1647. return true;
  1648. }
  1649. error(op, "String concatenation is only allowed with constant strings");
  1650. return false;
  1651. } else if (is_type_bit_set(type)) {
  1652. return true;
  1653. } else if (!is_type_numeric(type)) {
  1654. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1655. return false;
  1656. }
  1657. break;
  1658. case Token_And:
  1659. case Token_Or:
  1660. case Token_AndEq:
  1661. case Token_OrEq:
  1662. case Token_Xor:
  1663. case Token_XorEq:
  1664. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1665. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1666. return false;
  1667. }
  1668. break;
  1669. case Token_Mod:
  1670. case Token_ModMod:
  1671. case Token_ModEq:
  1672. case Token_ModModEq:
  1673. if (is_type_matrix(main_type)) {
  1674. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1675. return false;
  1676. }
  1677. if (!is_type_integer(type)) {
  1678. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1679. return false;
  1680. } else if (is_type_simd_vector(main_type)) {
  1681. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1682. return false;
  1683. }
  1684. break;
  1685. case Token_AndNot:
  1686. case Token_AndNotEq:
  1687. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1688. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1689. return false;
  1690. }
  1691. break;
  1692. case Token_CmpAnd:
  1693. case Token_CmpOr:
  1694. case Token_CmpAndEq:
  1695. case Token_CmpOrEq:
  1696. if (!is_type_boolean(type)) {
  1697. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1698. return false;
  1699. }
  1700. break;
  1701. default:
  1702. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1703. return false;
  1704. }
  1705. return true;
  1706. }
  1707. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1708. if (in_value.kind == ExactValue_Invalid) {
  1709. // NOTE(bill): There's already been an error
  1710. return true;
  1711. }
  1712. type = core_type(type);
  1713. if (type == t_invalid) {
  1714. return false;
  1715. } else if (is_type_boolean(type)) {
  1716. return in_value.kind == ExactValue_Bool;
  1717. } else if (is_type_string(type)) {
  1718. return in_value.kind == ExactValue_String;
  1719. } else if (is_type_integer(type) || is_type_rune(type)) {
  1720. if (in_value.kind == ExactValue_Bool) {
  1721. return false;
  1722. }
  1723. ExactValue v = exact_value_to_integer(in_value);
  1724. if (v.kind != ExactValue_Integer) {
  1725. return false;
  1726. }
  1727. if (out_value) *out_value = v;
  1728. if (is_type_untyped(type)) {
  1729. return true;
  1730. }
  1731. BigInt i = v.value_integer;
  1732. i64 byte_size = type_size_of(type);
  1733. BigInt umax = {};
  1734. BigInt imin = {};
  1735. BigInt imax = {};
  1736. if (c->bit_field_bit_size > 0) {
  1737. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1738. big_int_from_u64(&umax, 1);
  1739. big_int_from_i64(&imin, 1);
  1740. big_int_from_i64(&imax, 1);
  1741. BigInt bu = {};
  1742. BigInt bi = {};
  1743. big_int_from_i64(&bu, bit_size);
  1744. big_int_from_i64(&bi, bit_size-1);
  1745. big_int_shl_eq(&umax, &bu);
  1746. mp_decr(&umax);
  1747. big_int_shl_eq(&imin, &bi);
  1748. big_int_neg(&imin, &imin);
  1749. big_int_shl_eq(&imax, &bi);
  1750. mp_decr(&imax);
  1751. } else {
  1752. if (byte_size < 16) {
  1753. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1754. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1755. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1756. } else {
  1757. big_int_from_u64(&umax, 1);
  1758. big_int_from_i64(&imin, 1);
  1759. big_int_from_i64(&imax, 1);
  1760. BigInt bi128 = {};
  1761. BigInt bi127 = {};
  1762. big_int_from_i64(&bi128, 128);
  1763. big_int_from_i64(&bi127, 127);
  1764. big_int_shl_eq(&umax, &bi128);
  1765. mp_decr(&umax);
  1766. big_int_shl_eq(&imin, &bi127);
  1767. big_int_neg(&imin, &imin);
  1768. big_int_shl_eq(&imax, &bi127);
  1769. mp_decr(&imax);
  1770. }
  1771. }
  1772. switch (type->Basic.kind) {
  1773. case Basic_rune:
  1774. case Basic_i8:
  1775. case Basic_i16:
  1776. case Basic_i32:
  1777. case Basic_i64:
  1778. case Basic_i128:
  1779. case Basic_int:
  1780. case Basic_i16le:
  1781. case Basic_i32le:
  1782. case Basic_i64le:
  1783. case Basic_i128le:
  1784. case Basic_i16be:
  1785. case Basic_i32be:
  1786. case Basic_i64be:
  1787. case Basic_i128be:
  1788. {
  1789. // return imin <= i && i <= imax;
  1790. int a = big_int_cmp(&imin, &i);
  1791. int b = big_int_cmp(&i, &imax);
  1792. return (a <= 0) && (b <= 0);
  1793. }
  1794. case Basic_u8:
  1795. case Basic_u16:
  1796. case Basic_u32:
  1797. case Basic_u64:
  1798. case Basic_u128:
  1799. case Basic_uint:
  1800. case Basic_uintptr:
  1801. case Basic_u16le:
  1802. case Basic_u32le:
  1803. case Basic_u64le:
  1804. case Basic_u128le:
  1805. case Basic_u16be:
  1806. case Basic_u32be:
  1807. case Basic_u64be:
  1808. case Basic_u128be:
  1809. {
  1810. // return 0ull <= i && i <= umax;
  1811. int b = big_int_cmp(&i, &umax);
  1812. return !i.sign && (b <= 0);
  1813. }
  1814. case Basic_UntypedInteger:
  1815. return true;
  1816. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1817. }
  1818. } else if (is_type_float(type)) {
  1819. ExactValue v = exact_value_to_float(in_value);
  1820. if (v.kind != ExactValue_Float) {
  1821. return false;
  1822. }
  1823. if (out_value) *out_value = v;
  1824. switch (type->Basic.kind) {
  1825. case Basic_f16:
  1826. case Basic_f32:
  1827. case Basic_f64:
  1828. return true;
  1829. case Basic_f16le:
  1830. case Basic_f16be:
  1831. case Basic_f32le:
  1832. case Basic_f32be:
  1833. case Basic_f64le:
  1834. case Basic_f64be:
  1835. return true;
  1836. case Basic_UntypedFloat:
  1837. return true;
  1838. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1839. }
  1840. } else if (is_type_complex(type)) {
  1841. ExactValue v = exact_value_to_complex(in_value);
  1842. if (v.kind != ExactValue_Complex) {
  1843. return false;
  1844. }
  1845. switch (type->Basic.kind) {
  1846. case Basic_complex32:
  1847. case Basic_complex64:
  1848. case Basic_complex128: {
  1849. ExactValue real = exact_value_real(v);
  1850. ExactValue imag = exact_value_imag(v);
  1851. if (real.kind != ExactValue_Invalid &&
  1852. imag.kind != ExactValue_Invalid) {
  1853. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1854. return true;
  1855. }
  1856. break;
  1857. }
  1858. case Basic_UntypedComplex:
  1859. return true;
  1860. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1861. }
  1862. return false;
  1863. } else if (is_type_quaternion(type)) {
  1864. ExactValue v = exact_value_to_quaternion(in_value);
  1865. if (v.kind != ExactValue_Quaternion) {
  1866. return false;
  1867. }
  1868. switch (type->Basic.kind) {
  1869. case Basic_quaternion64:
  1870. case Basic_quaternion128:
  1871. case Basic_quaternion256: {
  1872. ExactValue real = exact_value_real(v);
  1873. ExactValue imag = exact_value_imag(v);
  1874. ExactValue jmag = exact_value_jmag(v);
  1875. ExactValue kmag = exact_value_kmag(v);
  1876. if (real.kind != ExactValue_Invalid &&
  1877. imag.kind != ExactValue_Invalid) {
  1878. 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));
  1879. return true;
  1880. }
  1881. break;
  1882. }
  1883. case Basic_UntypedComplex:
  1884. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  1885. return true;
  1886. case Basic_UntypedQuaternion:
  1887. return true;
  1888. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1889. }
  1890. return false;
  1891. } else if (is_type_pointer(type)) {
  1892. if (in_value.kind == ExactValue_Pointer) {
  1893. return true;
  1894. }
  1895. if (in_value.kind == ExactValue_Integer) {
  1896. return false;
  1897. // return true;
  1898. }
  1899. if (in_value.kind == ExactValue_String) {
  1900. return false;
  1901. }
  1902. if (out_value) *out_value = in_value;
  1903. } else if (is_type_bit_set(type)) {
  1904. if (in_value.kind == ExactValue_Integer) {
  1905. return true;
  1906. }
  1907. }
  1908. return false;
  1909. }
  1910. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  1911. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  1912. gbString b = type_to_string(type);
  1913. i64 sz = type_size_of(type);
  1914. i64 bit_size = 8*sz;
  1915. bool size_changed = false;
  1916. if (max_bit_size > 0) {
  1917. size_changed = (bit_size != max_bit_size);
  1918. bit_size = gb_min(bit_size, max_bit_size);
  1919. }
  1920. BigInt *bi = &o->value.value_integer;
  1921. if (is_type_unsigned(type)) {
  1922. if (big_int_is_neg(bi)) {
  1923. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  1924. } else {
  1925. BigInt one = big_int_make_u64(1);
  1926. BigInt max_size = big_int_make_u64(1);
  1927. BigInt bits = big_int_make_i64(bit_size);
  1928. big_int_shl_eq(&max_size, &bits);
  1929. big_int_sub_eq(&max_size, &one);
  1930. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1931. if (size_changed) {
  1932. 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));
  1933. } else {
  1934. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1935. }
  1936. }
  1937. } else {
  1938. BigInt zero = big_int_make_u64(0);
  1939. BigInt one = big_int_make_u64(1);
  1940. BigInt max_size = big_int_make_u64(1);
  1941. BigInt bits = big_int_make_i64(bit_size - 1);
  1942. big_int_shl_eq(&max_size, &bits);
  1943. String max_size_str = {};
  1944. if (big_int_is_neg(bi)) {
  1945. big_int_neg(&max_size, &max_size);
  1946. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1947. } else {
  1948. big_int_sub_eq(&max_size, &one);
  1949. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1950. }
  1951. if (size_changed) {
  1952. 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));
  1953. } else {
  1954. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1955. }
  1956. }
  1957. gb_string_free(b);
  1958. return true;
  1959. }
  1960. return false;
  1961. }
  1962. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  1963. gbString a = expr_to_string(o->expr);
  1964. gbString b = type_to_string(type);
  1965. defer(
  1966. gb_string_free(b);
  1967. gb_string_free(a);
  1968. );
  1969. Type *src = base_type(o->type);
  1970. Type *dst = base_type(type);
  1971. if (is_type_array(src) && is_type_slice(dst)) {
  1972. Type *s = src->Array.elem;
  1973. Type *d = dst->Slice.elem;
  1974. if (are_types_identical(s, d)) {
  1975. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1976. }
  1977. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  1978. Type *s = src->DynamicArray.elem;
  1979. Type *d = dst->Slice.elem;
  1980. if (are_types_identical(s, d)) {
  1981. error_line("\tSuggestion: the dynamic array expression may be sliced with %s[:]\n", a);
  1982. }
  1983. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  1984. error_line("\tSuggestion: the expression may be directly casted to type %s\n", b);
  1985. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1986. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1987. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable, \n");
  1988. error_line("\t whereas slices in general are assumed to be mutable.\n");
  1989. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  1990. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  1991. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  1992. return;
  1993. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  1994. gbString s = expr_to_string(c->type_hint_expr);
  1995. error_line("\tSuggestion: make sure that `%s` is attached to the compound literal directly\n", s);
  1996. gb_string_free(s);
  1997. } else if (is_type_pointer(type) &&
  1998. o->mode == Addressing_Variable &&
  1999. are_types_identical(type_deref(type), o->type)) {
  2000. gbString s = expr_to_string(o->expr);
  2001. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  2002. gb_string_free(s);
  2003. } else if (is_type_pointer(o->type) &&
  2004. are_types_identical(type_deref(o->type), type)) {
  2005. gbString s = expr_to_string(o->expr);
  2006. error_line("\tSuggestion: Did you mean `%s^`\n", s);
  2007. gb_string_free(s);
  2008. }
  2009. }
  2010. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  2011. gbString a = expr_to_string(o->expr);
  2012. gbString b = type_to_string(type);
  2013. defer(
  2014. gb_string_free(b);
  2015. gb_string_free(a);
  2016. );
  2017. Type *src = base_type(o->type);
  2018. Type *dst = base_type(type);
  2019. if (is_type_array(src) && is_type_slice(dst)) {
  2020. Type *s = src->Array.elem;
  2021. Type *d = dst->Slice.elem;
  2022. if (are_types_identical(s, d)) {
  2023. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2024. }
  2025. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  2026. if (is_type_uintptr(type)) {
  2027. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  2028. } else {
  2029. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  2030. i64 x = type_size_of(o->type);
  2031. i64 y = type_size_of(type);
  2032. if (x != y) {
  2033. 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);
  2034. }
  2035. }
  2036. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2037. if (is_type_uintptr(o->type)) {
  2038. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2039. } else {
  2040. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2041. }
  2042. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2043. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2044. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2045. return;
  2046. }
  2047. }
  2048. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2049. GB_ASSERT(o->mode == Addressing_Constant);
  2050. ExactValue out_value = o->value;
  2051. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2052. o->value = out_value;
  2053. return true;
  2054. } else {
  2055. o->value = out_value;
  2056. gbString a = expr_to_string(o->expr);
  2057. gbString b = type_to_string(type);
  2058. gbString c = type_to_string(o->type);
  2059. gbString s = exact_value_to_string(o->value);
  2060. defer(
  2061. gb_string_free(s);
  2062. gb_string_free(c);
  2063. gb_string_free(b);
  2064. gb_string_free(a);
  2065. o->mode = Addressing_Invalid;
  2066. );
  2067. ERROR_BLOCK();
  2068. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2069. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2070. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2071. } else {
  2072. i64 max_bit_size = 0;
  2073. if (ctx->bit_field_bit_size) {
  2074. max_bit_size = ctx->bit_field_bit_size;
  2075. }
  2076. if (are_types_identical(o->type, type)) {
  2077. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2078. } else {
  2079. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2080. }
  2081. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2082. }
  2083. } else {
  2084. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2085. check_assignment_error_suggestion(ctx, o, type);
  2086. }
  2087. return false;
  2088. }
  2089. }
  2090. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2091. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2092. if (o->expr->SelectorExpr.is_bit_field) {
  2093. return true;
  2094. }
  2095. }
  2096. if (o->mode == Addressing_OptionalOk) {
  2097. Ast *expr = unselector_expr(o->expr);
  2098. if (expr->kind != Ast_TypeAssertion) {
  2099. return true;
  2100. }
  2101. ast_node(ta, TypeAssertion, expr);
  2102. TypeAndValue tv = ta->expr->tav;
  2103. if (is_type_pointer(tv.type)) {
  2104. return false;
  2105. }
  2106. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2107. return false;
  2108. }
  2109. if (is_type_any(tv.type)) {
  2110. return false;
  2111. }
  2112. return true;
  2113. }
  2114. if (o->mode == Addressing_MapIndex) {
  2115. return false;
  2116. }
  2117. Ast *expr = unparen_expr(o->expr);
  2118. if (expr->kind == Ast_CompoundLit) {
  2119. return false;
  2120. }
  2121. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2122. }
  2123. gb_internal void check_old_for_or_switch_value_usage(Ast *expr) {
  2124. Entity *e = entity_of_node(expr);
  2125. if (e != nullptr && (e->flags & EntityFlag_OldForOrSwitchValue) != 0) {
  2126. GB_ASSERT(e->kind == Entity_Variable);
  2127. ERROR_BLOCK();
  2128. if ((e->flags & EntityFlag_ForValue) != 0) {
  2129. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2130. error(expr, "Assuming a for-in defined value is addressable as the iterable is passed by value has been disallowed.");
  2131. if (is_type_map(parent_type)) {
  2132. error_line("\tSuggestion: Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2133. } else {
  2134. error_line("\tSuggestion: Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2135. }
  2136. } else {
  2137. GB_ASSERT((e->flags & EntityFlag_SwitchValue) != 0);
  2138. error(expr, "Assuming a switch-in defined value is addressable as the iterable is passed by value has been disallowed.");
  2139. error_line("\tSuggestion: Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2140. }
  2141. }
  2142. }
  2143. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2144. switch (op.kind) {
  2145. case Token_And: { // Pointer address
  2146. if (check_is_not_addressable(c, o)) {
  2147. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2148. ast_node(ue, UnaryExpr, node);
  2149. gbString str = expr_to_string(ue->expr);
  2150. defer (gb_string_free(str));
  2151. Entity *e = entity_of_node(ue->expr);
  2152. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2153. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2154. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2155. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2156. } else {
  2157. switch (o->mode) {
  2158. case Addressing_Constant:
  2159. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2160. break;
  2161. case Addressing_SwizzleValue:
  2162. case Addressing_SwizzleVariable:
  2163. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2164. break;
  2165. default:
  2166. {
  2167. ERROR_BLOCK();
  2168. error(op, "Cannot take the pointer address of '%s'", str);
  2169. if (e != nullptr && (e->flags & EntityFlag_ForValue) != 0) {
  2170. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2171. if (parent_type != nullptr && is_type_string(parent_type)) {
  2172. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2173. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2174. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2175. } else {
  2176. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2177. }
  2178. }
  2179. if (e != nullptr && (e->flags & EntityFlag_SwitchValue) != 0) {
  2180. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2181. }
  2182. }
  2183. break;
  2184. }
  2185. }
  2186. }
  2187. o->mode = Addressing_Invalid;
  2188. return;
  2189. }
  2190. if (o->mode == Addressing_SoaVariable) {
  2191. ast_node(ue, UnaryExpr, node);
  2192. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2193. ast_node(ie, IndexExpr, ue->expr);
  2194. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2195. GB_ASSERT(is_type_soa_struct(soa_type));
  2196. o->type = alloc_type_soa_pointer(soa_type);
  2197. } else {
  2198. o->type = alloc_type_pointer(o->type);
  2199. }
  2200. } else {
  2201. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2202. ast_node(ue, UnaryExpr, node);
  2203. check_old_for_or_switch_value_usage(ue->expr);
  2204. }
  2205. o->type = alloc_type_pointer(o->type);
  2206. }
  2207. switch (o->mode) {
  2208. case Addressing_OptionalOk:
  2209. case Addressing_MapIndex:
  2210. o->mode = Addressing_OptionalOkPtr;
  2211. break;
  2212. default:
  2213. o->mode = Addressing_Value;
  2214. break;
  2215. }
  2216. return;
  2217. }
  2218. }
  2219. if (!check_unary_op(c, o, op)) {
  2220. o->mode = Addressing_Invalid;
  2221. return;
  2222. }
  2223. if (o->mode == Addressing_Constant) {
  2224. Type *type = base_type(o->type);
  2225. if (!is_type_constant_type(o->type)) {
  2226. gbString xt = type_to_string(o->type);
  2227. gbString err_str = expr_to_string(node);
  2228. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2229. gb_string_free(err_str);
  2230. gb_string_free(xt);
  2231. o->mode = Addressing_Invalid;
  2232. return;
  2233. }
  2234. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2235. gbString err_str = expr_to_string(node);
  2236. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2237. gb_string_free(err_str);
  2238. o->mode = Addressing_Invalid;
  2239. return;
  2240. }
  2241. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2242. gbString err_str = expr_to_string(node);
  2243. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2244. gb_string_free(err_str);
  2245. o->mode = Addressing_Invalid;
  2246. return;
  2247. }
  2248. i32 precision = 0;
  2249. if (is_type_typed(type)) {
  2250. precision = cast(i32)(8 * type_size_of(type));
  2251. }
  2252. bool is_unsigned = is_type_unsigned(type);
  2253. if (is_type_rune(type)) {
  2254. GB_ASSERT(!is_unsigned);
  2255. }
  2256. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2257. if (is_type_typed(type)) {
  2258. if (node != nullptr) {
  2259. o->expr = node;
  2260. }
  2261. check_is_expressible(c, o, type);
  2262. }
  2263. return;
  2264. }
  2265. o->mode = Addressing_Value;
  2266. }
  2267. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2268. if (t == nullptr) {
  2269. return;
  2270. }
  2271. t = base_type(t);
  2272. if (!is_type_comparable(t)) {
  2273. return;
  2274. }
  2275. switch (t->kind) {
  2276. case Type_Basic:
  2277. switch (t->Basic.kind) {
  2278. case Basic_complex32:
  2279. add_package_dependency(c, "runtime", "complex32_eq");
  2280. add_package_dependency(c, "runtime", "complex32_ne");
  2281. break;
  2282. case Basic_complex64:
  2283. add_package_dependency(c, "runtime", "complex64_eq");
  2284. add_package_dependency(c, "runtime", "complex64_ne");
  2285. break;
  2286. case Basic_complex128:
  2287. add_package_dependency(c, "runtime", "complex128_eq");
  2288. add_package_dependency(c, "runtime", "complex128_ne");
  2289. break;
  2290. case Basic_quaternion64:
  2291. add_package_dependency(c, "runtime", "quaternion64_eq");
  2292. add_package_dependency(c, "runtime", "quaternion64_ne");
  2293. break;
  2294. case Basic_quaternion128:
  2295. add_package_dependency(c, "runtime", "quaternion128_eq");
  2296. add_package_dependency(c, "runtime", "quaternion128_ne");
  2297. break;
  2298. case Basic_quaternion256:
  2299. add_package_dependency(c, "runtime", "quaternion256_eq");
  2300. add_package_dependency(c, "runtime", "quaternion256_ne");
  2301. break;
  2302. case Basic_cstring:
  2303. add_package_dependency(c, "runtime", "cstring_eq");
  2304. add_package_dependency(c, "runtime", "cstring_ne");
  2305. break;
  2306. case Basic_string:
  2307. add_package_dependency(c, "runtime", "string_eq");
  2308. add_package_dependency(c, "runtime", "string_ne");
  2309. break;
  2310. }
  2311. break;
  2312. case Type_Struct:
  2313. for (Entity *field : t->Struct.fields) {
  2314. add_comparison_procedures_for_fields(c, field->type);
  2315. }
  2316. break;
  2317. }
  2318. }
  2319. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2320. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2321. bool comp = are_types_identical(x->type, y->type);
  2322. switch (op) {
  2323. case Token_CmpEq: /* comp = comp; */ break;
  2324. case Token_NotEq: comp = !comp; break;
  2325. }
  2326. x->mode = Addressing_Constant;
  2327. x->type = t_untyped_bool;
  2328. x->value = exact_value_bool(comp);
  2329. return;
  2330. }
  2331. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2332. add_type_info_type(c, x->type);
  2333. add_type_info_type(c, y->type);
  2334. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2335. x->mode = Addressing_Value;
  2336. x->type = t_untyped_bool;
  2337. return;
  2338. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2339. add_type_info_type(c, x->type);
  2340. add_type_info_type(c, y->type);
  2341. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2342. x->mode = Addressing_Value;
  2343. x->type = t_untyped_bool;
  2344. return;
  2345. }
  2346. TEMPORARY_ALLOCATOR_GUARD();
  2347. gbString err_str = nullptr;
  2348. if (check_is_assignable_to(c, x, y->type) ||
  2349. check_is_assignable_to(c, y, x->type)) {
  2350. Type *err_type = x->type;
  2351. bool defined = false;
  2352. switch (op) {
  2353. case Token_CmpEq:
  2354. case Token_NotEq:
  2355. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2356. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2357. (is_operand_nil(*y) && type_has_nil(x->type));
  2358. break;
  2359. case Token_Lt:
  2360. case Token_Gt:
  2361. case Token_LtEq:
  2362. case Token_GtEq:
  2363. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2364. defined = true;
  2365. } else {
  2366. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2367. }
  2368. break;
  2369. }
  2370. if (!defined) {
  2371. gbString xs = type_to_string(x->type, temporary_allocator());
  2372. gbString ys = type_to_string(y->type, temporary_allocator());
  2373. err_str = gb_string_make(temporary_allocator(),
  2374. gb_bprintf("operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2375. );
  2376. } else {
  2377. Type *comparison_type = x->type;
  2378. if (x->type == err_type && is_operand_nil(*x)) {
  2379. comparison_type = y->type;
  2380. }
  2381. add_comparison_procedures_for_fields(c, comparison_type);
  2382. }
  2383. } else {
  2384. gbString xt, yt;
  2385. if (x->mode == Addressing_ProcGroup) {
  2386. xt = gb_string_make(temporary_allocator(), "procedure group");
  2387. } else {
  2388. xt = type_to_string(x->type);
  2389. }
  2390. if (y->mode == Addressing_ProcGroup) {
  2391. yt = gb_string_make(temporary_allocator(), "procedure group");
  2392. } else {
  2393. yt = type_to_string(y->type);
  2394. }
  2395. err_str = gb_string_make(temporary_allocator(), gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  2396. }
  2397. if (err_str != nullptr) {
  2398. error(node, "Cannot compare expression, %s", err_str);
  2399. x->type = t_untyped_bool;
  2400. } else {
  2401. if (x->mode == Addressing_Constant &&
  2402. y->mode == Addressing_Constant) {
  2403. if (is_type_constant_type(x->type)) {
  2404. if (is_type_bit_set(x->type)) {
  2405. switch (op) {
  2406. case Token_CmpEq:
  2407. case Token_NotEq:
  2408. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2409. break;
  2410. case Token_Lt:
  2411. case Token_LtEq:
  2412. {
  2413. ExactValue lhs = x->value;
  2414. ExactValue rhs = y->value;
  2415. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2416. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2417. if (op == Token_Lt) {
  2418. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2419. }
  2420. x->value = res;
  2421. break;
  2422. }
  2423. case Token_Gt:
  2424. case Token_GtEq:
  2425. {
  2426. ExactValue lhs = x->value;
  2427. ExactValue rhs = y->value;
  2428. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2429. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2430. if (op == Token_Gt) {
  2431. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2432. }
  2433. x->value = res;
  2434. break;
  2435. }
  2436. }
  2437. } else {
  2438. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2439. }
  2440. } else {
  2441. x->mode = Addressing_Value;
  2442. }
  2443. } else {
  2444. x->mode = Addressing_Value;
  2445. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2446. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2447. i64 size = 0;
  2448. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2449. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2450. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2451. switch (op) {
  2452. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2453. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2454. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2455. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2456. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2457. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2458. }
  2459. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2460. switch (op) {
  2461. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2462. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2463. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2464. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2465. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2466. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2467. }
  2468. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2469. switch (op) {
  2470. case Token_CmpEq:
  2471. switch (8*size) {
  2472. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2473. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2474. }
  2475. break;
  2476. case Token_NotEq:
  2477. switch (8*size) {
  2478. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2479. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2480. }
  2481. break;
  2482. }
  2483. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2484. switch (op) {
  2485. case Token_CmpEq:
  2486. switch (8*size) {
  2487. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2488. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2489. }
  2490. break;
  2491. case Token_NotEq:
  2492. switch (8*size) {
  2493. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2494. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2495. }
  2496. break;
  2497. }
  2498. }
  2499. }
  2500. x->type = t_untyped_bool;
  2501. }
  2502. }
  2503. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2504. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2505. ast_node(be, BinaryExpr, node);
  2506. ExactValue x_val = {};
  2507. if (x->mode == Addressing_Constant) {
  2508. x_val = exact_value_to_integer(x->value);
  2509. }
  2510. bool x_is_untyped = is_type_untyped(x->type);
  2511. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  2512. gbString err_str = expr_to_string(x->expr);
  2513. error(node, "Shifted operand '%s' must be an integer", err_str);
  2514. gb_string_free(err_str);
  2515. x->mode = Addressing_Invalid;
  2516. return;
  2517. }
  2518. if (is_type_unsigned(y->type)) {
  2519. } else if (is_type_untyped(y->type)) {
  2520. convert_to_typed(c, y, t_untyped_integer);
  2521. if (y->mode == Addressing_Invalid) {
  2522. x->mode = Addressing_Invalid;
  2523. return;
  2524. }
  2525. } else {
  2526. gbString err_str = expr_to_string(y->expr);
  2527. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2528. gb_string_free(err_str);
  2529. x->mode = Addressing_Invalid;
  2530. return;
  2531. }
  2532. if (x->mode == Addressing_Constant) {
  2533. if (y->mode == Addressing_Constant) {
  2534. ExactValue y_val = exact_value_to_integer(y->value);
  2535. if (y_val.kind != ExactValue_Integer) {
  2536. gbString err_str = expr_to_string(y->expr);
  2537. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2538. gb_string_free(err_str);
  2539. x->mode = Addressing_Invalid;
  2540. return;
  2541. }
  2542. BigInt max_shift = {};
  2543. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2544. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  2545. gbString err_str = expr_to_string(y->expr);
  2546. error(node, "Shift amount too large: '%s'", err_str);
  2547. gb_string_free(err_str);
  2548. x->mode = Addressing_Invalid;
  2549. return;
  2550. }
  2551. if (!is_type_integer(x->type)) {
  2552. // NOTE(bill): It could be an untyped float but still representable
  2553. // as an integer
  2554. x->type = t_untyped_integer;
  2555. }
  2556. x->expr = node;
  2557. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  2558. if (is_type_typed(x->type)) {
  2559. check_is_expressible(c, x, x->type);
  2560. }
  2561. return;
  2562. }
  2563. TokenPos pos = ast_token(x->expr).pos;
  2564. if (x_is_untyped) {
  2565. if (x->expr != nullptr) {
  2566. x->expr->tav.is_lhs = true;
  2567. }
  2568. x->mode = Addressing_Value;
  2569. if (type_hint) {
  2570. if (is_type_integer(type_hint)) {
  2571. x->type = type_hint;
  2572. } else {
  2573. gbString x_str = expr_to_string(x->expr);
  2574. gbString to_type = type_to_string(type_hint);
  2575. error(node, "Conversion of shifted operand '%s' to '%s' is not allowed", x_str, to_type);
  2576. gb_string_free(x_str);
  2577. gb_string_free(to_type);
  2578. x->mode = Addressing_Invalid;
  2579. }
  2580. } else if (!is_type_integer(x->type)) {
  2581. gbString x_str = expr_to_string(x->expr);
  2582. error(node, "Non-integer shifted operand '%s' is not allowed", x_str);
  2583. gb_string_free(x_str);
  2584. x->mode = Addressing_Invalid;
  2585. }
  2586. // x->value = x_val;
  2587. return;
  2588. }
  2589. }
  2590. if (y->mode == Addressing_Constant && big_int_is_neg(&y->value.value_integer)) {
  2591. gbString err_str = expr_to_string(y->expr);
  2592. error(node, "Shift amount cannot be negative: '%s'", err_str);
  2593. gb_string_free(err_str);
  2594. }
  2595. if (!is_type_integer(x->type)) {
  2596. gbString err_str = expr_to_string(x->expr);
  2597. error(node, "Shift operand '%s' must be an integer", err_str);
  2598. gb_string_free(err_str);
  2599. x->mode = Addressing_Invalid;
  2600. return;
  2601. }
  2602. if (is_type_untyped(y->type)) {
  2603. convert_to_typed(c, y, t_uint);
  2604. }
  2605. x->mode = Addressing_Value;
  2606. }
  2607. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2608. if (check_is_assignable_to(c, operand, y)) {
  2609. return true;
  2610. }
  2611. bool is_constant = operand->mode == Addressing_Constant;
  2612. Type *x = operand->type;
  2613. Type *src = core_type(x);
  2614. Type *dst = core_type(y);
  2615. if (are_types_identical(src, dst)) {
  2616. return true;
  2617. }
  2618. // if (is_type_tuple(src)) {
  2619. // Ast *expr = unparen_expr(operand->expr);
  2620. // if (expr && expr->kind == Ast_CallExpr) {
  2621. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2622. // ast_node(ce, CallExpr, expr);
  2623. // Type *pt = base_type(type_of_expr(ce->proc));
  2624. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2625. // if (pt->Proc.result_count > 0) {
  2626. // Operand op = *operand;
  2627. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2628. // bool ok = check_is_castable_to(c, &op, y);
  2629. // if (ok) {
  2630. // ce->optional_ok_one = true;
  2631. // }
  2632. // return ok;
  2633. // }
  2634. // }
  2635. // }
  2636. // }
  2637. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2638. if (is_type_u8_array(dst)) {
  2639. String s = operand->value.value_string;
  2640. return s.len == dst->Array.count;
  2641. }
  2642. if (is_type_rune_array(dst)) {
  2643. String s = operand->value.value_string;
  2644. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2645. }
  2646. }
  2647. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2648. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2649. return dst->Array.count == src->Array.count;
  2650. }
  2651. }
  2652. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2653. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2654. }
  2655. // Cast between booleans and integers
  2656. if (is_type_boolean(src) || is_type_integer(src)) {
  2657. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2658. return true;
  2659. }
  2660. }
  2661. // Cast between numbers
  2662. if (is_type_integer(src) || is_type_float(src)) {
  2663. if (is_type_integer(dst) || is_type_float(dst)) {
  2664. return true;
  2665. }
  2666. }
  2667. if (is_type_bit_field(src)) {
  2668. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2669. }
  2670. if (is_type_bit_field(dst)) {
  2671. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2672. }
  2673. if (is_type_integer(src) && is_type_rune(dst)) {
  2674. return true;
  2675. }
  2676. if (is_type_rune(src) && is_type_integer(dst)) {
  2677. return true;
  2678. }
  2679. if (is_type_complex(src) && is_type_complex(dst)) {
  2680. return true;
  2681. }
  2682. if (is_type_float(src) && is_type_complex(dst)) {
  2683. return true;
  2684. }
  2685. if (is_type_float(src) && is_type_quaternion(dst)) {
  2686. return true;
  2687. }
  2688. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2689. return true;
  2690. }
  2691. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2692. return true;
  2693. }
  2694. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2695. GB_ASSERT(src->kind == Type_Matrix);
  2696. GB_ASSERT(dst->kind == Type_Matrix);
  2697. Operand op = *operand;
  2698. op.type = src->Matrix.elem;
  2699. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2700. return false;
  2701. }
  2702. if (src->Matrix.row_count != src->Matrix.column_count) {
  2703. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2704. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2705. return src_count == dst_count;
  2706. }
  2707. return is_matrix_square(dst) && is_matrix_square(src);
  2708. }
  2709. // Cast between pointers
  2710. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2711. return true;
  2712. }
  2713. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2714. return true;
  2715. }
  2716. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2717. return true;
  2718. }
  2719. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2720. return true;
  2721. }
  2722. // uintptr <-> pointer
  2723. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2724. return true;
  2725. }
  2726. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2727. return true;
  2728. }
  2729. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2730. return true;
  2731. }
  2732. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2733. return true;
  2734. }
  2735. // []byte/[]u8 <-> string (not cstring)
  2736. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2737. return true;
  2738. }
  2739. // cstring -> string
  2740. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2741. if (operand->mode != Addressing_Constant) {
  2742. add_package_dependency(c, "runtime", "cstring_to_string");
  2743. }
  2744. return true;
  2745. }
  2746. // cstring -> ^u8
  2747. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2748. return !is_constant;
  2749. }
  2750. // cstring -> [^]u8
  2751. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2752. return !is_constant;
  2753. }
  2754. // cstring -> rawptr
  2755. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2756. return !is_constant;
  2757. }
  2758. // ^u8 -> cstring
  2759. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2760. return !is_constant;
  2761. }
  2762. // [^]u8 -> cstring
  2763. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2764. return !is_constant;
  2765. }
  2766. // rawptr -> cstring
  2767. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2768. return !is_constant;
  2769. }
  2770. // proc <-> proc
  2771. if (is_type_proc(src) && is_type_proc(dst)) {
  2772. if (is_type_polymorphic(dst)) {
  2773. if (is_type_polymorphic(src) &&
  2774. operand->mode == Addressing_Variable) {
  2775. return true;
  2776. }
  2777. return false;
  2778. }
  2779. return true;
  2780. }
  2781. // proc -> rawptr
  2782. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2783. return true;
  2784. }
  2785. // rawptr -> proc
  2786. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2787. return true;
  2788. }
  2789. if (is_type_array(dst)) {
  2790. Type *elem = base_array_type(dst);
  2791. if (check_is_castable_to(c, operand, elem)) {
  2792. return true;
  2793. }
  2794. }
  2795. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2796. if (src->SimdVector.count != dst->SimdVector.count) {
  2797. return false;
  2798. }
  2799. Type *elem_src = base_array_type(src);
  2800. Type *elem_dst = base_array_type(dst);
  2801. Operand x = {};
  2802. x.type = elem_src;
  2803. x.mode = Addressing_Value;
  2804. return check_is_castable_to(c, &x, elem_dst);
  2805. }
  2806. if (is_type_simd_vector(dst)) {
  2807. Type *elem = base_array_type(dst);
  2808. if (check_is_castable_to(c, operand, elem)) {
  2809. return true;
  2810. }
  2811. }
  2812. return false;
  2813. }
  2814. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2815. bool is_const_expr = x->mode == Addressing_Constant;
  2816. Type *bt = base_type(type);
  2817. if (is_const_expr && is_type_constant_type(bt)) {
  2818. if (core_type(bt)->kind == Type_Basic) {
  2819. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2820. return true;
  2821. } else if (check_is_castable_to(c, x, type)) {
  2822. if (is_type_pointer(type)) {
  2823. return true;
  2824. }
  2825. }
  2826. } else if (check_is_castable_to(c, x, type)) {
  2827. x->value = {};
  2828. x->mode = Addressing_Value;
  2829. return true;
  2830. }
  2831. } else if (check_is_castable_to(c, x, type)) {
  2832. if (x->mode != Addressing_Constant) {
  2833. x->mode = Addressing_Value;
  2834. } else if (is_type_slice(type) && is_type_string(x->type)) {
  2835. x->mode = Addressing_Value;
  2836. } else if (is_type_union(type)) {
  2837. x->mode = Addressing_Value;
  2838. }
  2839. if (x->mode == Addressing_Value) {
  2840. x->value = {};
  2841. }
  2842. return true;
  2843. }
  2844. return false;
  2845. }
  2846. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type) {
  2847. if (!is_operand_value(*x)) {
  2848. error(x->expr, "Only values can be casted");
  2849. x->mode = Addressing_Invalid;
  2850. return;
  2851. }
  2852. bool is_const_expr = x->mode == Addressing_Constant;
  2853. bool can_convert = check_cast_internal(c, x, type);
  2854. if (!can_convert) {
  2855. TEMPORARY_ALLOCATOR_GUARD();
  2856. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  2857. gbString to_type = type_to_string(type, temporary_allocator());
  2858. gbString from_type = type_to_string(x->type, temporary_allocator());
  2859. x->mode = Addressing_Invalid;
  2860. ERROR_BLOCK();
  2861. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  2862. if (is_const_expr) {
  2863. gbString val_str = exact_value_to_string(x->value);
  2864. if (is_type_float(x->type) && is_type_integer(type)) {
  2865. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  2866. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2867. x->mode = Addressing_Constant;
  2868. x->type = type;
  2869. } else {
  2870. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  2871. if (is_type_numeric(type)) {
  2872. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2873. x->mode = Addressing_Constant;
  2874. x->type = type;
  2875. }
  2876. }
  2877. gb_string_free(val_str);
  2878. }
  2879. check_cast_error_suggestion(c, x, type);
  2880. return;
  2881. }
  2882. if (is_type_untyped(x->type)) {
  2883. Type *final_type = type;
  2884. if (is_const_expr && !is_type_constant_type(type)) {
  2885. final_type = default_type(x->type);
  2886. }
  2887. update_untyped_expr_type(c, x->expr, final_type, true);
  2888. } else {
  2889. Type *src = core_type(x->type);
  2890. Type *dst = core_type(type);
  2891. if (src != dst) {
  2892. bool const REQUIRE = true;
  2893. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  2894. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  2895. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  2896. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  2897. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  2898. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  2899. } else if (src == t_f16 && is_type_float(dst)) {
  2900. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  2901. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  2902. } else if (is_type_float(dst) && dst == t_f16) {
  2903. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  2904. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  2905. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  2906. }
  2907. }
  2908. }
  2909. x->type = type;
  2910. }
  2911. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  2912. if (!is_operand_value(*o)) {
  2913. error(o->expr, "'transmute' can only be applied to values");
  2914. o->mode = Addressing_Invalid;
  2915. return false;
  2916. }
  2917. // if (o->mode == Addressing_Constant) {
  2918. // gbString expr_str = expr_to_string(o->expr);
  2919. // error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  2920. // gb_string_free(expr_str);
  2921. // o->mode = Addressing_Invalid;
  2922. // o->expr = node;
  2923. // return false;
  2924. // }
  2925. Type *src_t = o->type;
  2926. Type *dst_t = t;
  2927. Type *src_bt = base_type(src_t);
  2928. Type *dst_bt = base_type(dst_t);
  2929. if (is_type_untyped(src_t)) {
  2930. gbString expr_str = expr_to_string(o->expr);
  2931. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  2932. gb_string_free(expr_str);
  2933. o->mode = Addressing_Invalid;
  2934. o->expr = node;
  2935. return false;
  2936. }
  2937. if (dst_bt == nullptr || dst_bt == t_invalid) {
  2938. GB_ASSERT(global_error_collector.count != 0);
  2939. o->mode = Addressing_Invalid;
  2940. o->expr = node;
  2941. return false;
  2942. }
  2943. if (src_bt == nullptr || src_bt == t_invalid) {
  2944. // NOTE(bill): this should be an error
  2945. GB_ASSERT(global_error_collector.count != 0);
  2946. o->mode = Addressing_Value;
  2947. o->expr = node;
  2948. o->type = dst_t;
  2949. return true;
  2950. }
  2951. i64 srcz = type_size_of(src_t);
  2952. i64 dstz = type_size_of(dst_t);
  2953. if (srcz != dstz) {
  2954. gbString expr_str = expr_to_string(o->expr);
  2955. gbString type_str = type_to_string(dst_t);
  2956. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  2957. gb_string_free(type_str);
  2958. gb_string_free(expr_str);
  2959. o->mode = Addressing_Invalid;
  2960. o->expr = node;
  2961. return false;
  2962. }
  2963. o->expr = node;
  2964. o->type = dst_t;
  2965. if (o->mode == Addressing_Constant) {
  2966. if (are_types_identical(src_bt, dst_bt)) {
  2967. return true;
  2968. }
  2969. if (is_type_integer(src_t) && is_type_integer(dst_t)) {
  2970. if (types_have_same_internal_endian(src_t, dst_t)) {
  2971. ExactValue src_v = exact_value_to_integer(o->value);
  2972. GB_ASSERT(src_v.kind == ExactValue_Integer);
  2973. BigInt v = src_v.value_integer;
  2974. BigInt smax = {};
  2975. BigInt umax = {};
  2976. big_int_from_u64(&smax, 0);
  2977. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  2978. big_int_from_u64(&umax, 1);
  2979. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  2980. big_int_shl_eq(&umax, &sz_in_bits);
  2981. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  2982. if (big_int_cmp(&v, &smax) >= 0) {
  2983. big_int_sub_eq(&v, &umax);
  2984. }
  2985. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  2986. if (big_int_is_neg(&v)) {
  2987. big_int_add_eq(&v, &umax);
  2988. }
  2989. }
  2990. o->value.kind = ExactValue_Integer;
  2991. o->value.value_integer = v;
  2992. return true;
  2993. }
  2994. }
  2995. }
  2996. o->mode = Addressing_Value;
  2997. o->value = {};
  2998. return true;
  2999. }
  3000. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  3001. if (is_type_array(x->type) && !is_type_array(y->type)) {
  3002. if (check_is_assignable_to(c, y, x->type)) {
  3003. if (check_binary_op(c, x, op)) {
  3004. return true;
  3005. }
  3006. }
  3007. }
  3008. return false;
  3009. }
  3010. gb_internal bool is_ise_expr(Ast *node) {
  3011. node = unparen_expr(node);
  3012. return node->kind == Ast_ImplicitSelectorExpr;
  3013. }
  3014. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  3015. if (use_lhs_as_type_hint) { // RHS in this case
  3016. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  3017. }
  3018. return false;
  3019. }
  3020. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  3021. Type *xt = base_type(matrix);
  3022. if (type_hint != nullptr) {
  3023. Type *th = base_type(type_hint);
  3024. if (are_types_identical(th, xt)) {
  3025. return type_hint;
  3026. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  3027. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  3028. // ignore
  3029. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  3030. xt->Matrix.column_count == th->Matrix.column_count) {
  3031. return type_hint;
  3032. }
  3033. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  3034. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  3035. // ignore
  3036. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  3037. return type_hint;
  3038. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3039. return type_hint;
  3040. }
  3041. }
  3042. }
  3043. return matrix;
  3044. }
  3045. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3046. if (!check_binary_op(c, x, op)) {
  3047. x->mode = Addressing_Invalid;
  3048. return;
  3049. }
  3050. Type *xt = base_type(x->type);
  3051. Type *yt = base_type(y->type);
  3052. if (is_type_matrix(x->type)) {
  3053. GB_ASSERT(xt->kind == Type_Matrix);
  3054. if (op.kind == Token_Mul) {
  3055. if (yt->kind == Type_Matrix) {
  3056. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3057. goto matrix_error;
  3058. }
  3059. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3060. goto matrix_error;
  3061. }
  3062. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3063. goto matrix_error;
  3064. }
  3065. x->mode = Addressing_Value;
  3066. if (are_types_identical(xt, yt)) {
  3067. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3068. // prefer the named type
  3069. x->type = y->type;
  3070. }
  3071. } else {
  3072. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3073. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3074. }
  3075. goto matrix_success;
  3076. } else if (yt->kind == Type_Array) {
  3077. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3078. goto matrix_error;
  3079. }
  3080. if (xt->Matrix.column_count != yt->Array.count) {
  3081. goto matrix_error;
  3082. }
  3083. // Treat arrays as column vectors
  3084. x->mode = Addressing_Value;
  3085. if (xt->Matrix.row_count == yt->Array.count) {
  3086. x->type = y->type;
  3087. } else {
  3088. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3089. }
  3090. goto matrix_success;
  3091. }
  3092. }
  3093. if (!are_types_identical(xt, yt)) {
  3094. goto matrix_error;
  3095. }
  3096. x->mode = Addressing_Value;
  3097. x->type = xt;
  3098. goto matrix_success;
  3099. } else {
  3100. GB_ASSERT(!is_type_matrix(xt));
  3101. GB_ASSERT(is_type_matrix(yt));
  3102. if (op.kind == Token_Mul) {
  3103. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3104. if (xt->kind == Type_Array) {
  3105. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3106. goto matrix_error;
  3107. }
  3108. if (xt->Array.count != yt->Matrix.row_count) {
  3109. goto matrix_error;
  3110. }
  3111. // Treat arrays as row vectors
  3112. x->mode = Addressing_Value;
  3113. if (yt->Matrix.column_count == xt->Array.count) {
  3114. x->type = x->type;
  3115. } else {
  3116. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3117. }
  3118. goto matrix_success;
  3119. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3120. x->type = check_matrix_type_hint(y->type, type_hint);
  3121. return;
  3122. }
  3123. }
  3124. if (!are_types_identical(xt, yt)) {
  3125. goto matrix_error;
  3126. }
  3127. x->mode = Addressing_Value;
  3128. x->type = xt;
  3129. goto matrix_success;
  3130. }
  3131. matrix_success:
  3132. x->type = check_matrix_type_hint(x->type, type_hint);
  3133. return;
  3134. matrix_error:
  3135. gbString xts = type_to_string(x->type);
  3136. gbString yts = type_to_string(y->type);
  3137. gbString expr_str = expr_to_string(x->expr);
  3138. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3139. gb_string_free(expr_str);
  3140. gb_string_free(yts);
  3141. gb_string_free(xts);
  3142. x->type = t_invalid;
  3143. x->mode = Addressing_Invalid;
  3144. return;
  3145. }
  3146. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3147. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3148. Operand y_ = {}, *y = &y_;
  3149. ast_node(be, BinaryExpr, node);
  3150. defer({
  3151. node->viral_state_flags |= be->left->viral_state_flags;
  3152. node->viral_state_flags |= be->right->viral_state_flags;
  3153. });
  3154. Token op = be->op;
  3155. switch (op.kind) {
  3156. case Token_CmpEq:
  3157. case Token_NotEq: {
  3158. // NOTE(bill): Allow comparisons between types
  3159. if (is_ise_expr(be->left)) {
  3160. // Evalute the right before the left for an '.X' expression
  3161. check_expr_or_type(c, y, be->right, type_hint);
  3162. check_expr_or_type(c, x, be->left, y->type);
  3163. } else {
  3164. check_expr_or_type(c, x, be->left, type_hint);
  3165. check_expr_or_type(c, y, be->right, x->type);
  3166. }
  3167. bool xt = x->mode == Addressing_Type;
  3168. bool yt = y->mode == Addressing_Type;
  3169. // If only one is a type, this is an error
  3170. if (xt ^ yt) {
  3171. GB_ASSERT(xt != yt);
  3172. if (xt) {
  3173. if (!is_type_typeid(y->type)) {
  3174. error_operand_not_expression(x);
  3175. }
  3176. }
  3177. if (yt) {
  3178. if (!is_type_typeid(x->type)) {
  3179. error_operand_not_expression(y);
  3180. }
  3181. }
  3182. }
  3183. break;
  3184. }
  3185. case Token_in:
  3186. case Token_not_in:
  3187. {
  3188. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3189. check_expr(c, y, be->right);
  3190. Type *rhs_type = type_deref(y->type);
  3191. if (is_type_bit_set(rhs_type)) {
  3192. Type *elem = base_type(rhs_type)->BitSet.elem;
  3193. check_expr_with_type_hint(c, x, be->left, elem);
  3194. } else if (is_type_map(rhs_type)) {
  3195. Type *key = base_type(rhs_type)->Map.key;
  3196. check_expr_with_type_hint(c, x, be->left, key);
  3197. } else {
  3198. check_expr(c, x, be->left);
  3199. }
  3200. if (x->mode == Addressing_Invalid) {
  3201. return;
  3202. }
  3203. if (y->mode == Addressing_Invalid) {
  3204. x->mode = Addressing_Invalid;
  3205. x->expr = y->expr;
  3206. return;
  3207. }
  3208. if (is_type_map(rhs_type)) {
  3209. Type *yt = base_type(rhs_type);
  3210. if (op.kind == Token_in) {
  3211. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3212. } else {
  3213. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3214. }
  3215. add_map_get_dependencies(c);
  3216. } else if (is_type_bit_set(rhs_type)) {
  3217. Type *yt = base_type(rhs_type);
  3218. if (op.kind == Token_in) {
  3219. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3220. } else {
  3221. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3222. }
  3223. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3224. ExactValue k = exact_value_to_integer(x->value);
  3225. ExactValue v = exact_value_to_integer(y->value);
  3226. GB_ASSERT(k.kind == ExactValue_Integer);
  3227. GB_ASSERT(v.kind == ExactValue_Integer);
  3228. i64 key = big_int_to_i64(&k.value_integer);
  3229. i64 lower = yt->BitSet.lower;
  3230. i64 upper = yt->BitSet.upper;
  3231. if (lower <= key && key <= upper) {
  3232. i64 bit = 1ll<<key;
  3233. i64 bits = big_int_to_i64(&v.value_integer);
  3234. x->mode = Addressing_Constant;
  3235. x->type = t_untyped_bool;
  3236. if (op.kind == Token_in) {
  3237. x->value = exact_value_bool((bit & bits) != 0);
  3238. } else {
  3239. x->value = exact_value_bool((bit & bits) == 0);
  3240. }
  3241. x->expr = node;
  3242. return;
  3243. } else {
  3244. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3245. x->mode = Addressing_Invalid;
  3246. }
  3247. }
  3248. } else {
  3249. gbString t = type_to_string(y->type);
  3250. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3251. gb_string_free(t);
  3252. x->expr = node;
  3253. x->mode = Addressing_Invalid;
  3254. return;
  3255. }
  3256. if (x->mode != Addressing_Invalid) {
  3257. x->mode = Addressing_Value;
  3258. x->type = t_untyped_bool;
  3259. }
  3260. x->expr = node;
  3261. return;
  3262. }
  3263. default:
  3264. if (is_ise_expr(be->left)) {
  3265. // Evalute the right before the left for an '.X' expression
  3266. check_expr_or_type(c, y, be->right, type_hint);
  3267. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3268. check_expr_or_type(c, x, be->left, y->type);
  3269. } else {
  3270. check_expr_with_type_hint(c, x, be->left, type_hint);
  3271. }
  3272. } else {
  3273. check_expr_with_type_hint(c, x, be->left, type_hint);
  3274. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3275. check_expr_with_type_hint(c, y, be->right, x->type);
  3276. } else {
  3277. check_expr_with_type_hint(c, y, be->right, type_hint);
  3278. }
  3279. }
  3280. break;
  3281. }
  3282. if (x->mode == Addressing_Invalid) {
  3283. return;
  3284. }
  3285. if (y->mode == Addressing_Invalid) {
  3286. x->mode = Addressing_Invalid;
  3287. x->expr = y->expr;
  3288. return;
  3289. }
  3290. if (x->mode == Addressing_Builtin) {
  3291. x->mode = Addressing_Invalid;
  3292. error(x->expr, "built-in expression in binary expression");
  3293. return;
  3294. }
  3295. if (y->mode == Addressing_Builtin) {
  3296. x->mode = Addressing_Invalid;
  3297. error(y->expr, "built-in expression in binary expression");
  3298. return;
  3299. }
  3300. if (x->mode == Addressing_ProcGroup) {
  3301. x->mode = Addressing_Invalid;
  3302. if (x->proc_group != nullptr) {
  3303. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3304. } else {
  3305. error(x->expr, "procedure group used in binary expression");
  3306. }
  3307. return;
  3308. }
  3309. if (y->mode == Addressing_ProcGroup) {
  3310. x->mode = Addressing_Invalid;
  3311. if (x->proc_group != nullptr) {
  3312. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3313. } else {
  3314. error(y->expr, "procedure group used in binary expression");
  3315. }
  3316. return;
  3317. }
  3318. if (token_is_shift(op.kind)) {
  3319. check_shift(c, x, y, node, type_hint);
  3320. return;
  3321. }
  3322. switch (op.kind) {
  3323. case Token_Quo:
  3324. case Token_Mod:
  3325. case Token_ModMod:
  3326. case Token_QuoEq:
  3327. case Token_ModEq:
  3328. case Token_ModModEq:
  3329. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3330. is_type_float(x->type) && is_type_untyped(x->type)) {
  3331. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3332. gbString t = type_to_string(y->type);
  3333. if (x->value.kind != ExactValue_Invalid) {
  3334. gbString s = exact_value_to_string(x->value);
  3335. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3336. gb_string_free(s);
  3337. } else {
  3338. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3339. }
  3340. gb_string_free(t);
  3341. }
  3342. break;
  3343. }
  3344. convert_to_typed(c, x, y->type);
  3345. if (x->mode == Addressing_Invalid) {
  3346. return;
  3347. }
  3348. convert_to_typed(c, y, x->type);
  3349. if (y->mode == Addressing_Invalid) {
  3350. x->mode = Addressing_Invalid;
  3351. return;
  3352. }
  3353. if (token_is_comparison(op.kind)) {
  3354. check_comparison(c, node, x, y, op.kind);
  3355. return;
  3356. }
  3357. if (check_binary_array_expr(c, op, x, y)) {
  3358. x->mode = Addressing_Value;
  3359. x->type = x->type;
  3360. return;
  3361. }
  3362. if (check_binary_array_expr(c, op, y, x)) {
  3363. x->mode = Addressing_Value;
  3364. x->type = y->type;
  3365. return;
  3366. }
  3367. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3368. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3369. x->expr = node;
  3370. return;
  3371. }
  3372. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3373. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3374. // NOTE(bill, 2022-06-26)
  3375. // Allow any boolean types within `&&` and `||`
  3376. // This is an exception to all other binary expressions since the result
  3377. // of a comparison will always be an untyped boolean, and allowing
  3378. // any boolean between these two simplifies a lot of expressions
  3379. } else if (!are_types_identical(x->type, y->type)) {
  3380. if (x->type != t_invalid &&
  3381. y->type != t_invalid) {
  3382. gbString xt = type_to_string(x->type);
  3383. gbString yt = type_to_string(y->type);
  3384. gbString expr_str = expr_to_string(node);
  3385. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3386. gb_string_free(expr_str);
  3387. gb_string_free(yt);
  3388. gb_string_free(xt);
  3389. }
  3390. x->mode = Addressing_Invalid;
  3391. return;
  3392. }
  3393. if (!check_binary_op(c, x, op)) {
  3394. x->mode = Addressing_Invalid;
  3395. return;
  3396. }
  3397. switch (op.kind) {
  3398. case Token_Quo:
  3399. case Token_Mod:
  3400. case Token_ModMod:
  3401. case Token_QuoEq:
  3402. case Token_ModEq:
  3403. case Token_ModModEq:
  3404. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3405. y->mode == Addressing_Constant) {
  3406. bool fail = false;
  3407. switch (y->value.kind) {
  3408. case ExactValue_Integer:
  3409. if (big_int_is_zero(&y->value.value_integer)) {
  3410. fail = true;
  3411. }
  3412. break;
  3413. case ExactValue_Float:
  3414. if (y->value.value_float == 0.0) {
  3415. fail = true;
  3416. }
  3417. break;
  3418. }
  3419. if (fail) {
  3420. error(y->expr, "Division by zero not allowed");
  3421. x->mode = Addressing_Invalid;
  3422. return;
  3423. }
  3424. }
  3425. break;
  3426. case Token_CmpAnd:
  3427. case Token_CmpOr:
  3428. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3429. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3430. }
  3431. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3432. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3433. }
  3434. break;
  3435. }
  3436. if (x->mode == Addressing_Constant &&
  3437. y->mode == Addressing_Constant) {
  3438. ExactValue a = x->value;
  3439. ExactValue b = y->value;
  3440. if (!is_type_constant_type(x->type)) {
  3441. x->mode = Addressing_Value;
  3442. return;
  3443. }
  3444. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3445. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3446. }
  3447. if (is_type_bit_set(x->type)) {
  3448. switch (op.kind) {
  3449. case Token_Add: op.kind = Token_Or; break;
  3450. case Token_Sub: op.kind = Token_AndNot; break;
  3451. }
  3452. }
  3453. x->value = exact_binary_operator_value(op.kind, a, b);
  3454. if (is_type_typed(x->type)) {
  3455. if (node != nullptr) {
  3456. x->expr = node;
  3457. }
  3458. check_is_expressible(c, x, x->type);
  3459. }
  3460. return;
  3461. } else if (is_type_string(x->type)) {
  3462. error(node, "String concatenation is only allowed with constant strings");
  3463. x->mode = Addressing_Invalid;
  3464. return;
  3465. }
  3466. bool REQUIRE = true;
  3467. Type *bt = base_type(x->type);
  3468. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3469. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3470. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3471. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3472. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3473. }
  3474. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3475. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3476. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3477. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3478. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3479. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3480. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3481. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3482. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3483. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3484. }
  3485. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3486. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3487. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3488. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3489. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3490. case Basic_u128:
  3491. case Basic_i128:
  3492. if (is_arch_wasm()) {
  3493. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3494. }
  3495. break;
  3496. }
  3497. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3498. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3499. case Basic_u128:
  3500. case Basic_i128:
  3501. if (is_arch_wasm()) {
  3502. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3503. }
  3504. break;
  3505. }
  3506. }
  3507. x->mode = Addressing_Value;
  3508. }
  3509. gb_internal Operand make_operand_from_node(Ast *node) {
  3510. GB_ASSERT(node != nullptr);
  3511. Operand x = {};
  3512. x.expr = node;
  3513. x.mode = node->tav.mode;
  3514. x.type = node->tav.type;
  3515. x.value = node->tav.value;
  3516. return x;
  3517. }
  3518. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3519. GB_ASSERT(e != nullptr);
  3520. ExprInfo *old = check_get_expr_info(c, e);
  3521. if (old == nullptr) {
  3522. if (type != nullptr && type != t_invalid) {
  3523. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3524. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3525. if (e->kind == Ast_TernaryIfExpr) {
  3526. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3527. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3528. }
  3529. }
  3530. }
  3531. return;
  3532. }
  3533. switch (e->kind) {
  3534. case_ast_node(ue, UnaryExpr, e);
  3535. if (old->value.kind != ExactValue_Invalid) {
  3536. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3537. // They don't need to be updated as they will be updated later and
  3538. // checked at the end of general checking stage.
  3539. break;
  3540. }
  3541. update_untyped_expr_type(c, ue->expr, type, final);
  3542. case_end;
  3543. case_ast_node(be, BinaryExpr, e);
  3544. if (old->value.kind != ExactValue_Invalid) {
  3545. // See above note in UnaryExpr case
  3546. break;
  3547. }
  3548. if (token_is_comparison(be->op.kind)) {
  3549. // NOTE(bill): Do nothing as the types are fine
  3550. } else if (token_is_shift(be->op.kind)) {
  3551. update_untyped_expr_type(c, be->left, type, final);
  3552. } else {
  3553. update_untyped_expr_type(c, be->left, type, final);
  3554. update_untyped_expr_type(c, be->right, type, final);
  3555. }
  3556. case_end;
  3557. case_ast_node(te, TernaryIfExpr, e);
  3558. if (old->value.kind != ExactValue_Invalid) {
  3559. // See above note in UnaryExpr case
  3560. break;
  3561. }
  3562. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3563. // having an untyped value
  3564. Operand x = make_operand_from_node(te->x);
  3565. Operand y = make_operand_from_node(te->y);
  3566. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3567. update_untyped_expr_type(c, te->x, type, final);
  3568. }
  3569. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3570. update_untyped_expr_type(c, te->y, type, final);
  3571. }
  3572. case_end;
  3573. case_ast_node(te, TernaryWhenExpr, e);
  3574. if (old->value.kind != ExactValue_Invalid) {
  3575. // See above note in UnaryExpr case
  3576. break;
  3577. }
  3578. update_untyped_expr_type(c, te->x, type, final);
  3579. update_untyped_expr_type(c, te->y, type, final);
  3580. case_end;
  3581. case_ast_node(ore, OrReturnExpr, e);
  3582. if (old->value.kind != ExactValue_Invalid) {
  3583. // See above note in UnaryExpr case
  3584. break;
  3585. }
  3586. update_untyped_expr_type(c, ore->expr, type, final);
  3587. case_end;
  3588. case_ast_node(obe, OrBranchExpr, e);
  3589. if (old->value.kind != ExactValue_Invalid) {
  3590. // See above note in UnaryExpr case
  3591. break;
  3592. }
  3593. update_untyped_expr_type(c, obe->expr, type, final);
  3594. case_end;
  3595. case_ast_node(oee, OrElseExpr, e);
  3596. if (old->value.kind != ExactValue_Invalid) {
  3597. // See above note in UnaryExpr case
  3598. break;
  3599. }
  3600. update_untyped_expr_type(c, oee->x, type, final);
  3601. update_untyped_expr_type(c, oee->y, type, final);
  3602. case_end;
  3603. case_ast_node(pe, ParenExpr, e);
  3604. update_untyped_expr_type(c, pe->expr, type, final);
  3605. case_end;
  3606. }
  3607. if (!final && is_type_untyped(type)) {
  3608. old->type = base_type(type);
  3609. return;
  3610. }
  3611. // We need to remove it and then give it a new one
  3612. check_remove_expr_info(c, e);
  3613. if (old->is_lhs && !is_type_integer(type)) {
  3614. gbString expr_str = expr_to_string(e);
  3615. gbString type_str = type_to_string(type);
  3616. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3617. gb_string_free(type_str);
  3618. gb_string_free(expr_str);
  3619. return;
  3620. }
  3621. add_type_and_value(c, e, old->mode, type, old->value);
  3622. }
  3623. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3624. GB_ASSERT(e != nullptr);
  3625. ExprInfo *found = check_get_expr_info(c, e);
  3626. if (found) {
  3627. found->value = value;
  3628. }
  3629. }
  3630. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type, bool ignore_error_block=false) {
  3631. gbString expr_str = expr_to_string(operand->expr);
  3632. gbString type_str = type_to_string(target_type);
  3633. gbString from_type_str = type_to_string(operand->type);
  3634. char const *extra_text = "";
  3635. if (operand->mode == Addressing_Constant) {
  3636. if (big_int_is_zero(&operand->value.value_integer)) {
  3637. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3638. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3639. extra_text = " - Did you want 'nil'?";
  3640. }
  3641. }
  3642. }
  3643. if (!ignore_error_block) {
  3644. begin_error_block();
  3645. }
  3646. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3647. if (operand->value.kind == ExactValue_String) {
  3648. String key = operand->value.value_string;
  3649. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3650. Type *et = base_type(target_type);
  3651. check_did_you_mean_type(key, et->Enum.fields, ".");
  3652. }
  3653. }
  3654. gb_string_free(from_type_str);
  3655. gb_string_free(type_str);
  3656. gb_string_free(expr_str);
  3657. operand->mode = Addressing_Invalid;
  3658. if (!ignore_error_block) {
  3659. end_error_block();
  3660. }
  3661. }
  3662. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3663. Type *t = core_type(type);
  3664. if (is_type_boolean(t)) {
  3665. // v = exact_value_to_boolean(v);
  3666. } else if (is_type_float(t)) {
  3667. v = exact_value_to_float(v);
  3668. } else if (is_type_integer(t)) {
  3669. v = exact_value_to_integer(v);
  3670. } else if (is_type_pointer(t)) {
  3671. v = exact_value_to_integer(v);
  3672. } else if (is_type_complex(t)) {
  3673. v = exact_value_to_complex(v);
  3674. } else if (is_type_quaternion(t)) {
  3675. v = exact_value_to_quaternion(v);
  3676. }
  3677. return v;
  3678. }
  3679. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3680. GB_ASSERT_NOT_NULL(target_type);
  3681. if (operand->mode == Addressing_Invalid ||
  3682. operand->mode == Addressing_Type ||
  3683. is_type_typed(operand->type) ||
  3684. target_type == t_invalid) {
  3685. return;
  3686. }
  3687. if (is_type_untyped(target_type)) {
  3688. GB_ASSERT(operand->type->kind == Type_Basic);
  3689. GB_ASSERT(target_type->kind == Type_Basic);
  3690. BasicKind x_kind = operand->type->Basic.kind;
  3691. BasicKind y_kind = target_type->Basic.kind;
  3692. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3693. if (x_kind < y_kind) {
  3694. operand->type = target_type;
  3695. update_untyped_expr_type(c, operand->expr, target_type, false);
  3696. }
  3697. } else if (x_kind != y_kind) {
  3698. operand->mode = Addressing_Invalid;
  3699. convert_untyped_error(c, operand, target_type);
  3700. return;
  3701. }
  3702. return;
  3703. }
  3704. Type *t = base_type(target_type);
  3705. if (c->in_enum_type) {
  3706. t = core_type(target_type);
  3707. }
  3708. switch (t->kind) {
  3709. case Type_Basic:
  3710. if (operand->mode == Addressing_Constant) {
  3711. check_is_expressible(c, operand, t);
  3712. if (operand->mode == Addressing_Invalid) {
  3713. return;
  3714. }
  3715. update_untyped_expr_value(c, operand->expr, operand->value);
  3716. } else {
  3717. switch (operand->type->Basic.kind) {
  3718. case Basic_UntypedBool:
  3719. if (!is_type_boolean(target_type)) {
  3720. operand->mode = Addressing_Invalid;
  3721. convert_untyped_error(c, operand, target_type);
  3722. return;
  3723. }
  3724. break;
  3725. case Basic_UntypedInteger:
  3726. case Basic_UntypedFloat:
  3727. case Basic_UntypedComplex:
  3728. case Basic_UntypedQuaternion:
  3729. case Basic_UntypedRune:
  3730. if (!is_type_numeric(target_type)) {
  3731. operand->mode = Addressing_Invalid;
  3732. convert_untyped_error(c, operand, target_type);
  3733. return;
  3734. }
  3735. break;
  3736. case Basic_UntypedNil:
  3737. if (is_type_any(target_type)) {
  3738. // target_type = t_untyped_nil;
  3739. } else if (is_type_cstring(target_type)) {
  3740. // target_type = t_untyped_nil;
  3741. } else if (!type_has_nil(target_type)) {
  3742. operand->mode = Addressing_Invalid;
  3743. convert_untyped_error(c, operand, target_type);
  3744. return;
  3745. }
  3746. break;
  3747. }
  3748. }
  3749. break;
  3750. case Type_Array: {
  3751. Type *elem = base_array_type(t);
  3752. if (check_is_assignable_to(c, operand, elem)) {
  3753. operand->mode = Addressing_Value;
  3754. } else {
  3755. if (operand->value.kind == ExactValue_String) {
  3756. String s = operand->value.value_string;
  3757. if (is_type_u8_array(t)) {
  3758. if (s.len == t->Array.count) {
  3759. break;
  3760. }
  3761. } else if (is_type_rune_array(t)) {
  3762. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  3763. if (rune_count == t->Array.count) {
  3764. break;
  3765. }
  3766. }
  3767. }
  3768. operand->mode = Addressing_Invalid;
  3769. convert_untyped_error(c, operand, target_type);
  3770. return;
  3771. }
  3772. break;
  3773. }
  3774. case Type_Matrix: {
  3775. Type *elem = base_array_type(t);
  3776. if (check_is_assignable_to(c, operand, elem)) {
  3777. if (t->Matrix.row_count != t->Matrix.column_count) {
  3778. operand->mode = Addressing_Invalid;
  3779. ERROR_BLOCK();
  3780. convert_untyped_error(c, operand, target_type, true);
  3781. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  3782. return;
  3783. } else {
  3784. operand->mode = Addressing_Value;
  3785. }
  3786. } else {
  3787. operand->mode = Addressing_Invalid;
  3788. convert_untyped_error(c, operand, target_type);
  3789. return;
  3790. }
  3791. break;
  3792. }
  3793. case Type_Union:
  3794. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  3795. TEMPORARY_ALLOCATOR_GUARD();
  3796. isize count = t->Union.variants.count;
  3797. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  3798. isize valid_count = 0;
  3799. isize first_success_index = -1;
  3800. for_array(i, t->Union.variants) {
  3801. Type *vt = t->Union.variants[i];
  3802. i64 score = 0;
  3803. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  3804. valids[valid_count].index = i;
  3805. valids[valid_count].score = score;
  3806. valid_count += 1;
  3807. if (first_success_index < 0) {
  3808. first_success_index = i;
  3809. }
  3810. }
  3811. }
  3812. if (valid_count > 1) {
  3813. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  3814. i64 best_score = valids[0].score;
  3815. for (isize i = 1; i < valid_count; i++) {
  3816. auto v = valids[i];
  3817. if (best_score > v.score) {
  3818. valid_count = i;
  3819. break;
  3820. }
  3821. best_score = v.score;
  3822. }
  3823. first_success_index = valids[0].index;
  3824. }
  3825. gbString type_str = type_to_string(target_type);
  3826. defer (gb_string_free(type_str));
  3827. if (valid_count == 1) {
  3828. operand->mode = Addressing_Value;
  3829. operand->type = t->Union.variants[first_success_index];
  3830. target_type = t->Union.variants[first_success_index];
  3831. break;
  3832. } else if (valid_count > 1) {
  3833. ERROR_BLOCK();
  3834. GB_ASSERT(first_success_index >= 0);
  3835. operand->mode = Addressing_Invalid;
  3836. convert_untyped_error(c, operand, target_type, true);
  3837. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  3838. i32 j = 0;
  3839. for (i32 i = 0; i < valid_count; i++) {
  3840. ValidIndexAndScore valid = valids[i];
  3841. if (j > 0 && valid_count > 2) error_line(", ");
  3842. if (j == valid_count-1) {
  3843. if (valid_count == 2) error_line(" ");
  3844. error_line("or ");
  3845. }
  3846. gbString str = type_to_string(t->Union.variants[valid.index]);
  3847. error_line("'%s'", str);
  3848. gb_string_free(str);
  3849. j++;
  3850. }
  3851. error_line("\n\n");
  3852. return;
  3853. } else if (is_type_untyped_uninit(operand->type)) {
  3854. target_type = t_untyped_uninit;
  3855. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  3856. ERROR_BLOCK();
  3857. operand->mode = Addressing_Invalid;
  3858. convert_untyped_error(c, operand, target_type, true);
  3859. if (count > 0) {
  3860. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  3861. error_line("\t");
  3862. for (i32 i = 0; i < count; i++) {
  3863. Type *v = t->Union.variants[i];
  3864. if (i > 0 && count > 2) error_line(", ");
  3865. if (i == count-1) {
  3866. if (count == 2) error_line(" ");
  3867. if (count > 1) {
  3868. error_line("or ");
  3869. }
  3870. }
  3871. gbString str = type_to_string(v);
  3872. error_line("'%s'", str);
  3873. gb_string_free(str);
  3874. }
  3875. error_line("\n\n");
  3876. }
  3877. return;
  3878. }
  3879. }
  3880. /* fallthrough */
  3881. default:
  3882. if (is_type_untyped_uninit(operand->type)) {
  3883. target_type = t_untyped_uninit;
  3884. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  3885. target_type = t_untyped_nil;
  3886. } else {
  3887. operand->mode = Addressing_Invalid;
  3888. convert_untyped_error(c, operand, target_type);
  3889. return;
  3890. }
  3891. break;
  3892. }
  3893. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  3894. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  3895. } else {
  3896. target_type = default_type(operand->type);
  3897. }
  3898. }
  3899. update_untyped_expr_type(c, operand->expr, target_type, true);
  3900. operand->type = target_type;
  3901. }
  3902. 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) {
  3903. Operand operand = {Addressing_Invalid};
  3904. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  3905. if (operand.mode == Addressing_Invalid) {
  3906. if (value) *value = 0;
  3907. return false;
  3908. }
  3909. Type *index_type = t_int;
  3910. if (type_hint != nullptr) {
  3911. index_type = type_hint;
  3912. }
  3913. convert_to_typed(c, &operand, index_type);
  3914. if (operand.mode == Addressing_Invalid) {
  3915. if (value) *value = 0;
  3916. return false;
  3917. }
  3918. if (type_hint != nullptr) {
  3919. if (!check_is_assignable_to(c, &operand, type_hint)) {
  3920. gbString expr_str = expr_to_string(operand.expr);
  3921. gbString index_type_str = type_to_string(type_hint);
  3922. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  3923. gb_string_free(index_type_str);
  3924. gb_string_free(expr_str);
  3925. if (value) *value = 0;
  3926. return false;
  3927. }
  3928. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  3929. gbString expr_str = expr_to_string(operand.expr);
  3930. gbString type_str = type_to_string(operand.type);
  3931. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  3932. gb_string_free(type_str);
  3933. gb_string_free(expr_str);
  3934. if (value) *value = 0;
  3935. return false;
  3936. }
  3937. if (operand.mode == Addressing_Constant &&
  3938. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  3939. BigInt i = exact_value_to_integer(operand.value).value_integer;
  3940. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  3941. TEMPORARY_ALLOCATOR_GUARD();
  3942. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3943. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3944. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  3945. if (value) *value = 0;
  3946. return false;
  3947. }
  3948. if (max_count >= 0) {
  3949. if (is_type_enum(index_type)) {
  3950. Type *bt = base_type(index_type);
  3951. GB_ASSERT(bt->kind == Type_Enum);
  3952. ExactValue const &lo = *bt->Enum.min_value;
  3953. ExactValue const &hi = *bt->Enum.max_value;
  3954. String lo_str = {};
  3955. String hi_str = {};
  3956. if (bt->Enum.fields.count > 0) {
  3957. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  3958. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  3959. lo_str = bt->Enum.fields[lo_idx]->token.string;
  3960. hi_str = bt->Enum.fields[hi_idx]->token.string;
  3961. }
  3962. bool out_of_bounds = false;
  3963. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  3964. out_of_bounds = true;
  3965. }
  3966. if (out_of_bounds) {
  3967. gbString expr_str = expr_to_string(operand.expr);
  3968. if (lo_str.len > 0) {
  3969. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  3970. } else {
  3971. gbString index_type_str = type_to_string(index_type);
  3972. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  3973. gb_string_free(index_type_str);
  3974. }
  3975. gb_string_free(expr_str);
  3976. return false;
  3977. }
  3978. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  3979. return true;
  3980. } else { // NOTE(bill): Do array bound checking
  3981. i64 v = -1;
  3982. if (i.used <= 1) {
  3983. v = big_int_to_i64(&i);
  3984. }
  3985. if (value) *value = v;
  3986. bool out_of_bounds = false;
  3987. if (v < 0) {
  3988. out_of_bounds = true;
  3989. } else if (open_range) {
  3990. out_of_bounds = v > max_count;
  3991. } else {
  3992. out_of_bounds = v >= max_count;
  3993. }
  3994. if (out_of_bounds) {
  3995. TEMPORARY_ALLOCATOR_GUARD();
  3996. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3997. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3998. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  3999. return false;
  4000. }
  4001. return true;
  4002. }
  4003. } else {
  4004. if (value) *value = exact_value_to_i64(operand.value);
  4005. return true;
  4006. }
  4007. }
  4008. // NOTE(bill): It's alright :D
  4009. if (value) *value = -1;
  4010. return true;
  4011. }
  4012. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  4013. if (value.kind == ExactValue_String) {
  4014. GB_ASSERT(0 <= index && index < value.value_string.len);
  4015. u8 val = value.value_string[index];
  4016. if (success_) *success_ = true;
  4017. if (finish_) *finish_ = true;
  4018. return exact_value_u64(val);
  4019. }
  4020. if (value.kind != ExactValue_Compound) {
  4021. if (success_) *success_ = true;
  4022. if (finish_) *finish_ = true;
  4023. return value;
  4024. }
  4025. Ast *node = value.value_compound;
  4026. switch (node->kind) {
  4027. case_ast_node(cl, CompoundLit, node);
  4028. if (cl->elems.count == 0) {
  4029. if (success_) *success_ = true;
  4030. if (finish_) *finish_ = true;
  4031. return empty_exact_value;
  4032. }
  4033. if (cl->elems[0]->kind == Ast_FieldValue) {
  4034. if (is_type_struct(node->tav.type)) {
  4035. bool found = false;
  4036. for (Ast *elem : cl->elems) {
  4037. if (elem->kind != Ast_FieldValue) {
  4038. continue;
  4039. }
  4040. ast_node(fv, FieldValue, elem);
  4041. String name = fv->field->Ident.token.string;
  4042. Selection sub_sel = lookup_field(node->tav.type, name, false);
  4043. defer (array_free(&sub_sel.index));
  4044. if (sub_sel.index.count > 0 &&
  4045. sub_sel.index[0] == index) {
  4046. value = fv->value->tav.value;
  4047. found = true;
  4048. break;
  4049. }
  4050. }
  4051. if (!found) {
  4052. // Use the zero value if it is not found
  4053. value = {};
  4054. }
  4055. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4056. for (Ast *elem : cl->elems) {
  4057. if (elem->kind != Ast_FieldValue) {
  4058. continue;
  4059. }
  4060. ast_node(fv, FieldValue, elem);
  4061. if (is_ast_range(fv->field)) {
  4062. ast_node(ie, BinaryExpr, fv->field);
  4063. TypeAndValue lo_tav = ie->left->tav;
  4064. TypeAndValue hi_tav = ie->right->tav;
  4065. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4066. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4067. TokenKind op = ie->op.kind;
  4068. i64 lo = exact_value_to_i64(lo_tav.value);
  4069. i64 hi = exact_value_to_i64(hi_tav.value);
  4070. i64 corrected_index = index;
  4071. if (is_type_enumerated_array(node->tav.type)) {
  4072. Type *bt = base_type(node->tav.type);
  4073. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4074. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4075. }
  4076. if (op != Token_RangeHalf) {
  4077. if (lo <= corrected_index && corrected_index <= hi) {
  4078. TypeAndValue tav = fv->value->tav;
  4079. if (success_) *success_ = true;
  4080. if (finish_) *finish_ = false;
  4081. return tav.value;
  4082. }
  4083. } else {
  4084. if (lo <= corrected_index && corrected_index < hi) {
  4085. TypeAndValue tav = fv->value->tav;
  4086. if (success_) *success_ = true;
  4087. if (finish_) *finish_ = false;
  4088. return tav.value;
  4089. }
  4090. }
  4091. } else {
  4092. TypeAndValue index_tav = fv->field->tav;
  4093. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4094. ExactValue index_value = index_tav.value;
  4095. if (is_type_enumerated_array(node->tav.type)) {
  4096. Type *bt = base_type(node->tav.type);
  4097. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4098. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4099. }
  4100. i64 field_index = exact_value_to_i64(index_value);
  4101. if (index == field_index) {
  4102. TypeAndValue tav = fv->value->tav;
  4103. if (success_) *success_ = true;
  4104. if (finish_) *finish_ = false;
  4105. return tav.value;;
  4106. }
  4107. }
  4108. }
  4109. }
  4110. } else {
  4111. i32 count = (i32)cl->elems.count;
  4112. if (count < index) {
  4113. if (success_) *success_ = false;
  4114. if (finish_) *finish_ = true;
  4115. return empty_exact_value;
  4116. }
  4117. if (cl->elems.count <= index) {
  4118. if (success_) *success_ = false;
  4119. if (finish_) *finish_ = false;
  4120. return value;
  4121. }
  4122. TypeAndValue tav = cl->elems[index]->tav;
  4123. if (tav.mode == Addressing_Constant) {
  4124. if (success_) *success_ = true;
  4125. if (finish_) *finish_ = false;
  4126. return tav.value;
  4127. } else {
  4128. GB_ASSERT(is_type_untyped_nil(tav.type));
  4129. if (success_) *success_ = true;
  4130. if (finish_) *finish_ = false;
  4131. return tav.value;
  4132. }
  4133. }
  4134. case_end;
  4135. default:
  4136. if (success_) *success_ = true;
  4137. if (finish_) *finish_ = true;
  4138. return empty_exact_value;
  4139. }
  4140. if (finish_) *finish_ = false;
  4141. return value;
  4142. }
  4143. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4144. if (operand->mode != Addressing_Constant) {
  4145. if (success_) *success_ = false;
  4146. return empty_exact_value;
  4147. }
  4148. if (sel.indirect) {
  4149. if (success_) *success_ = false;
  4150. return empty_exact_value;
  4151. }
  4152. if (sel.index.count == 0) {
  4153. if (success_) *success_ = false;
  4154. return empty_exact_value;
  4155. }
  4156. ExactValue value = operand->value;
  4157. if (value.kind == ExactValue_Compound) {
  4158. while (sel.index.count > 0) {
  4159. i32 index = sel.index[0];
  4160. sel = sub_selection(sel, 1);
  4161. bool finish = false;
  4162. value = get_constant_field_single(c, value, index, success_, &finish);
  4163. if (finish) {
  4164. return value;
  4165. }
  4166. }
  4167. if (success_) *success_ = true;
  4168. return value;
  4169. } else if (value.kind == ExactValue_Quaternion) {
  4170. // @QuaternionLayout
  4171. Quaternion256 q = *value.value_quaternion;
  4172. GB_ASSERT(sel.index.count == 1);
  4173. switch (sel.index[0]) {
  4174. case 3: // w
  4175. if (success_) *success_ = true;
  4176. return exact_value_float(q.real);
  4177. case 0: // x
  4178. if (success_) *success_ = true;
  4179. return exact_value_float(q.imag);
  4180. case 1: // y
  4181. if (success_) *success_ = true;
  4182. return exact_value_float(q.jmag);
  4183. case 2: // z
  4184. if (success_) *success_ = true;
  4185. return exact_value_float(q.kmag);
  4186. }
  4187. if (success_) *success_ = false;
  4188. return empty_exact_value;
  4189. } else if (value.kind == ExactValue_Complex) {
  4190. // @QuaternionLayout
  4191. Complex128 c = *value.value_complex;
  4192. GB_ASSERT(sel.index.count == 1);
  4193. switch (sel.index[0]) {
  4194. case 0: // real
  4195. if (success_) *success_ = true;
  4196. return exact_value_float(c.real);
  4197. case 1: // imag
  4198. if (success_) *success_ = true;
  4199. return exact_value_float(c.imag);
  4200. }
  4201. if (success_) *success_ = false;
  4202. return empty_exact_value;
  4203. }
  4204. if (success_) *success_ = true;
  4205. return empty_exact_value;
  4206. }
  4207. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4208. Type *array_type = base_type(type_deref(original_type));
  4209. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4210. if (array_type->kind == Type_SimdVector) {
  4211. Type *elem_type = array_type->SimdVector.elem;
  4212. return alloc_type_simd_vector(new_count, elem_type);
  4213. }
  4214. Type *elem_type = array_type->Array.elem;
  4215. Type *swizzle_array_type = nullptr;
  4216. Type *bth = base_type(type_deref(type_hint));
  4217. if (bth != nullptr && bth->kind == Type_Array &&
  4218. bth->Array.count == new_count &&
  4219. are_types_identical(bth->Array.elem, elem_type)) {
  4220. swizzle_array_type = type_hint;
  4221. } else {
  4222. i64 max_count = array_type->Array.count;
  4223. if (new_count == max_count) {
  4224. swizzle_array_type = original_type;
  4225. } else {
  4226. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4227. }
  4228. }
  4229. return swizzle_array_type;
  4230. }
  4231. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4232. bool is_declared = entity != nullptr;
  4233. if (is_declared) {
  4234. if (entity->kind == Entity_Builtin) {
  4235. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4236. // This means that we should just ignore the found result through it
  4237. *allow_builtin = entity->scope == import_scope ||
  4238. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4239. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4240. is_declared = false;
  4241. }
  4242. }
  4243. return is_declared;
  4244. }
  4245. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4246. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4247. if (node->kind == Ast_Ident) {
  4248. String name = node->Ident.token.string;
  4249. return scope_lookup(c->scope, name);
  4250. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4251. ast_node(se, SelectorExpr, node);
  4252. if (se->token.kind == Token_ArrowRight) {
  4253. return nullptr;
  4254. }
  4255. Ast *op_expr = se->expr;
  4256. Ast *selector = unparen_expr(se->selector);
  4257. if (selector == nullptr) {
  4258. return nullptr;
  4259. }
  4260. if (selector->kind != Ast_Ident) {
  4261. return nullptr;
  4262. }
  4263. Entity *entity = nullptr;
  4264. Entity *expr_entity = nullptr;
  4265. bool check_op_expr = true;
  4266. if (op_expr->kind == Ast_Ident) {
  4267. String op_name = op_expr->Ident.token.string;
  4268. Entity *e = scope_lookup(c->scope, op_name);
  4269. if (e == nullptr) {
  4270. return nullptr;
  4271. }
  4272. add_entity_use(c, op_expr, e);
  4273. expr_entity = e;
  4274. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4275. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4276. // It pretty much needs to be in this order and this way
  4277. // If you can clean this up, please do but be really careful
  4278. String import_name = op_name;
  4279. Scope *import_scope = e->ImportName.scope;
  4280. String entity_name = selector->Ident.token.string;
  4281. check_op_expr = false;
  4282. entity = scope_lookup_current(import_scope, entity_name);
  4283. bool allow_builtin = false;
  4284. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4285. return nullptr;
  4286. }
  4287. check_entity_decl(c, entity, nullptr, nullptr);
  4288. if (entity->kind == Entity_ProcGroup) {
  4289. return entity;
  4290. }
  4291. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4292. }
  4293. }
  4294. Operand operand = {};
  4295. if (check_op_expr) {
  4296. check_expr_base(c, &operand, op_expr, nullptr);
  4297. if (operand.mode == Addressing_Invalid) {
  4298. return nullptr;
  4299. }
  4300. }
  4301. if (entity == nullptr && selector->kind == Ast_Ident) {
  4302. String field_name = selector->Ident.token.string;
  4303. if (is_type_dynamic_array(type_deref(operand.type))) {
  4304. init_mem_allocator(c->checker);
  4305. }
  4306. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4307. entity = sel.entity;
  4308. }
  4309. if (entity != nullptr) {
  4310. return entity;
  4311. }
  4312. }
  4313. return nullptr;
  4314. }
  4315. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4316. ast_node(se, SelectorExpr, node);
  4317. bool check_op_expr = true;
  4318. Entity *expr_entity = nullptr;
  4319. Entity *entity = nullptr;
  4320. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4321. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4322. ERROR_BLOCK();
  4323. error(node, "Illegal use of -> selector shorthand outside of a call");
  4324. gbString x = expr_to_string(se->expr);
  4325. gbString y = expr_to_string(se->selector);
  4326. error_line("\tSuggestion: Did you mean '%s.%s'?\n", x, y);
  4327. gb_string_free(y);
  4328. gb_string_free(x);
  4329. // TODO(bill): Should this terminate here or propagate onwards?
  4330. // operand->mode = Addressing_Invalid;
  4331. // operand->expr = node;
  4332. // return nullptr;
  4333. }
  4334. operand->expr = node;
  4335. Ast *op_expr = se->expr;
  4336. Ast *selector = unparen_expr(se->selector);
  4337. if (selector == nullptr) {
  4338. operand->mode = Addressing_Invalid;
  4339. operand->expr = node;
  4340. return nullptr;
  4341. }
  4342. if (selector->kind != Ast_Ident) {
  4343. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4344. operand->mode = Addressing_Invalid;
  4345. operand->expr = node;
  4346. return nullptr;
  4347. }
  4348. if (op_expr->kind == Ast_Ident) {
  4349. String op_name = op_expr->Ident.token.string;
  4350. Entity *e = scope_lookup(c->scope, op_name);
  4351. add_entity_use(c, op_expr, e);
  4352. expr_entity = e;
  4353. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4354. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4355. // It pretty much needs to be in this order and this way
  4356. // If you can clean this up, please do but be really careful
  4357. String import_name = op_name;
  4358. Scope *import_scope = e->ImportName.scope;
  4359. String entity_name = selector->Ident.token.string;
  4360. check_op_expr = false;
  4361. entity = scope_lookup_current(import_scope, entity_name);
  4362. bool allow_builtin = false;
  4363. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4364. ERROR_BLOCK();
  4365. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4366. operand->mode = Addressing_Invalid;
  4367. operand->expr = node;
  4368. check_did_you_mean_scope(entity_name, import_scope);
  4369. return nullptr;
  4370. }
  4371. check_entity_decl(c, entity, nullptr, nullptr);
  4372. if (entity->kind == Entity_ProcGroup) {
  4373. operand->mode = Addressing_ProcGroup;
  4374. operand->proc_group = entity;
  4375. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4376. return entity;
  4377. }
  4378. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4379. if (!is_entity_exported(entity, allow_builtin)) {
  4380. gbString sel_str = expr_to_string(selector);
  4381. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4382. gb_string_free(sel_str);
  4383. // NOTE(bill): make the state valid still, even if it's "invalid"
  4384. // operand->mode = Addressing_Invalid;
  4385. // operand->expr = node;
  4386. // return nullptr;
  4387. }
  4388. if (entity->kind == Entity_ProcGroup) {
  4389. Array<Entity *> procs = entity->ProcGroup.entities;
  4390. bool skip = false;
  4391. for (Entity *p : procs) {
  4392. Type *t = base_type(p->type);
  4393. if (t == t_invalid) {
  4394. continue;
  4395. }
  4396. Operand x = {};
  4397. x.mode = Addressing_Value;
  4398. x.type = t;
  4399. if (type_hint != nullptr) {
  4400. if (check_is_assignable_to(c, &x, type_hint)) {
  4401. entity = p;
  4402. skip = true;
  4403. break;
  4404. }
  4405. }
  4406. }
  4407. if (!skip) {
  4408. GB_ASSERT(entity != nullptr);
  4409. operand->mode = Addressing_ProcGroup;
  4410. operand->type = t_invalid;
  4411. operand->expr = node;
  4412. operand->proc_group = entity;
  4413. return entity;
  4414. }
  4415. }
  4416. }
  4417. }
  4418. if (check_op_expr) {
  4419. check_expr_base(c, operand, op_expr, nullptr);
  4420. if (operand->mode == Addressing_Invalid) {
  4421. operand->mode = Addressing_Invalid;
  4422. operand->expr = node;
  4423. return nullptr;
  4424. }
  4425. }
  4426. if (operand->type && is_type_soa_struct(type_deref(operand->type))) {
  4427. complete_soa_type(c->checker, type_deref(operand->type), false);
  4428. }
  4429. if (entity == nullptr && selector->kind == Ast_Ident) {
  4430. String field_name = selector->Ident.token.string;
  4431. Type *t = type_deref(operand->type);
  4432. if (t == nullptr) {
  4433. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4434. } else if (is_type_dynamic_array(t)) {
  4435. init_mem_allocator(c->checker);
  4436. }
  4437. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4438. entity = sel.entity;
  4439. // NOTE(bill): Add type info needed for fields like 'names'
  4440. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4441. add_type_info_type(c, operand->type);
  4442. }
  4443. if (is_type_enum(operand->type)) {
  4444. add_type_info_type(c, operand->type);
  4445. }
  4446. }
  4447. if (entity == nullptr && selector->kind == Ast_Ident && (is_type_array(type_deref(operand->type)) || is_type_simd_vector(type_deref(operand->type)))) {
  4448. String field_name = selector->Ident.token.string;
  4449. if (1 < field_name.len && field_name.len <= 4) {
  4450. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4451. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4452. bool found_xyzw = false;
  4453. bool found_rgba = false;
  4454. for (isize i = 0; i < field_name.len; i++) {
  4455. bool valid = false;
  4456. for (isize j = 0; j < 4; j++) {
  4457. if (field_name.text[i] == swizzles_xyzw[j]) {
  4458. found_xyzw = true;
  4459. valid = true;
  4460. break;
  4461. }
  4462. if (field_name.text[i] == swizzles_rgba[j]) {
  4463. found_rgba = true;
  4464. valid = true;
  4465. break;
  4466. }
  4467. }
  4468. if (!valid) {
  4469. goto end_of_array_selector_swizzle;
  4470. }
  4471. }
  4472. u8 *swizzles = nullptr;
  4473. u8 index_count = cast(u8)field_name.len;
  4474. if (found_xyzw && found_rgba) {
  4475. gbString op_str = expr_to_string(op_expr);
  4476. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4477. gb_string_free(op_str);
  4478. operand->mode = Addressing_Invalid;
  4479. operand->expr = node;
  4480. return nullptr;
  4481. }
  4482. u8 indices = 0;
  4483. if (found_xyzw) {
  4484. swizzles = swizzles_xyzw;
  4485. } else if (found_rgba) {
  4486. swizzles = swizzles_rgba;
  4487. }
  4488. for (isize i = 0; i < field_name.len; i++) {
  4489. for (isize j = 0; j < 4; j++) {
  4490. if (field_name.text[i] == swizzles[j]) {
  4491. indices |= cast(u8)(j)<<(i*2);
  4492. break;
  4493. }
  4494. }
  4495. }
  4496. Type *original_type = operand->type;
  4497. Type *array_type = base_type(type_deref(original_type));
  4498. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4499. i64 array_count = get_array_type_count(array_type);
  4500. for (u8 i = 0; i < index_count; i++) {
  4501. u8 idx = indices>>(i*2) & 3;
  4502. if (idx >= array_count) {
  4503. char c = 0;
  4504. if (found_xyzw) {
  4505. c = swizzles_xyzw[idx];
  4506. } else if (found_rgba) {
  4507. c = swizzles_rgba[idx];
  4508. } else {
  4509. GB_PANIC("unknown swizzle kind");
  4510. }
  4511. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4512. break;
  4513. }
  4514. }
  4515. se->swizzle_count = index_count;
  4516. se->swizzle_indices = indices;
  4517. AddressingMode prev_mode = operand->mode;
  4518. operand->mode = Addressing_SwizzleValue;
  4519. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4520. operand->expr = node;
  4521. switch (prev_mode) {
  4522. case Addressing_Variable:
  4523. case Addressing_SoaVariable:
  4524. case Addressing_SwizzleVariable:
  4525. operand->mode = Addressing_SwizzleVariable;
  4526. break;
  4527. }
  4528. if (array_type->kind == Type_SimdVector) {
  4529. operand->mode = Addressing_Value;
  4530. }
  4531. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4532. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4533. return swizzle_entity;
  4534. }
  4535. end_of_array_selector_swizzle:;
  4536. }
  4537. if (entity == nullptr) {
  4538. gbString op_str = expr_to_string(op_expr);
  4539. gbString type_str = type_to_string_shorthand(operand->type);
  4540. gbString sel_str = expr_to_string(selector);
  4541. if (operand->mode == Addressing_Type) {
  4542. if (is_type_polymorphic(operand->type, true)) {
  4543. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4544. } else {
  4545. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4546. }
  4547. } else {
  4548. ERROR_BLOCK();
  4549. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4550. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4551. String const &name = selector->Ident.token.string;
  4552. Type *bt = base_type(operand->type);
  4553. if (operand->type->kind == Type_Named &&
  4554. operand->type->Named.type_name &&
  4555. operand->type->Named.type_name->kind == Entity_TypeName &&
  4556. operand->type->Named.type_name->TypeName.objc_metadata) {
  4557. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4558. } else if (bt->kind == Type_Struct) {
  4559. check_did_you_mean_type(name, bt->Struct.fields);
  4560. } else if (bt->kind == Type_Enum) {
  4561. check_did_you_mean_type(name, bt->Enum.fields);
  4562. }
  4563. }
  4564. }
  4565. gb_string_free(sel_str);
  4566. gb_string_free(type_str);
  4567. gb_string_free(op_str);
  4568. operand->mode = Addressing_Invalid;
  4569. operand->expr = node;
  4570. return nullptr;
  4571. }
  4572. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4573. bool success = false;
  4574. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4575. if (success) {
  4576. operand->mode = Addressing_Constant;
  4577. operand->expr = node;
  4578. operand->value = field_value;
  4579. operand->type = entity->type;
  4580. add_entity_use(c, selector, entity);
  4581. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4582. return entity;
  4583. }
  4584. gbString op_str = expr_to_string(op_expr);
  4585. gbString type_str = type_to_string_shorthand(operand->type);
  4586. gbString sel_str = expr_to_string(selector);
  4587. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4588. gb_string_free(sel_str);
  4589. gb_string_free(type_str);
  4590. gb_string_free(op_str);
  4591. operand->mode = Addressing_Invalid;
  4592. operand->expr = node;
  4593. return nullptr;
  4594. }
  4595. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4596. bool success = false;
  4597. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4598. if (success) {
  4599. operand->mode = Addressing_Constant;
  4600. operand->expr = node;
  4601. operand->value = field_value;
  4602. operand->type = entity->type;
  4603. add_entity_use(c, selector, entity);
  4604. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4605. return entity;
  4606. }
  4607. gbString op_str = expr_to_string(op_expr);
  4608. gbString type_str = type_to_string_shorthand(operand->type);
  4609. gbString sel_str = expr_to_string(selector);
  4610. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4611. gb_string_free(sel_str);
  4612. gb_string_free(type_str);
  4613. gb_string_free(op_str);
  4614. operand->mode = Addressing_Invalid;
  4615. operand->expr = node;
  4616. return nullptr;
  4617. }
  4618. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4619. gbString op_str = expr_to_string(op_expr);
  4620. gbString type_str = type_to_string_shorthand(operand->type);
  4621. gbString sel_str = expr_to_string(selector);
  4622. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4623. gb_string_free(sel_str);
  4624. gb_string_free(type_str);
  4625. gb_string_free(op_str);
  4626. operand->mode = Addressing_Invalid;
  4627. operand->expr = node;
  4628. return nullptr;
  4629. }
  4630. add_entity_use(c, selector, entity);
  4631. operand->type = entity->type;
  4632. operand->expr = node;
  4633. if (entity->flags & EntityFlag_BitFieldField) {
  4634. add_package_dependency(c, "runtime", "__write_bits");
  4635. add_package_dependency(c, "runtime", "__read_bits");
  4636. }
  4637. switch (entity->kind) {
  4638. case Entity_Constant:
  4639. operand->value = entity->Constant.value;
  4640. operand->mode = Addressing_Constant;
  4641. if (operand->value.kind == ExactValue_Procedure) {
  4642. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4643. if (proc != nullptr) {
  4644. operand->mode = Addressing_Value;
  4645. operand->type = proc->type;
  4646. }
  4647. }
  4648. break;
  4649. case Entity_Variable:
  4650. if (sel.is_bit_field) {
  4651. se->is_bit_field = true;
  4652. }
  4653. if (sel.indirect) {
  4654. operand->mode = Addressing_Variable;
  4655. } else if (operand->mode == Addressing_Context) {
  4656. // Do nothing
  4657. } else if (operand->mode == Addressing_MapIndex) {
  4658. operand->mode = Addressing_Value;
  4659. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4660. operand->mode = Addressing_SoaVariable;
  4661. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4662. operand->mode = Addressing_Value;
  4663. } else if (operand->mode == Addressing_SoaVariable) {
  4664. operand->mode = Addressing_Variable;
  4665. } else if (operand->mode != Addressing_Value) {
  4666. operand->mode = Addressing_Variable;
  4667. } else {
  4668. operand->mode = Addressing_Value;
  4669. }
  4670. break;
  4671. case Entity_TypeName:
  4672. operand->mode = Addressing_Type;
  4673. break;
  4674. case Entity_Procedure:
  4675. operand->mode = Addressing_Value;
  4676. operand->value = exact_value_procedure(node);
  4677. break;
  4678. case Entity_Builtin:
  4679. operand->mode = Addressing_Builtin;
  4680. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  4681. break;
  4682. case Entity_ProcGroup:
  4683. operand->mode = Addressing_ProcGroup;
  4684. operand->proc_group = entity;
  4685. break;
  4686. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  4687. case Entity_Nil:
  4688. operand->mode = Addressing_Value;
  4689. break;
  4690. }
  4691. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4692. return entity;
  4693. }
  4694. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  4695. ptr = base_type(ptr);
  4696. if (is_type_pointer(ptr)) {
  4697. if (is_type_rawptr(ptr)) {
  4698. return false;
  4699. }
  4700. if (elem) *elem = ptr->Pointer.elem;
  4701. return true;
  4702. }
  4703. return false;
  4704. }
  4705. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  4706. elem = core_type(elem);
  4707. if (is_type_internally_pointer_like(elem)) {
  4708. return true;
  4709. }
  4710. if (elem->kind == Type_BitSet) {
  4711. elem = bit_set_to_int(elem);
  4712. }
  4713. if (elem->kind != Type_Basic) {
  4714. return false;
  4715. }
  4716. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  4717. }
  4718. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  4719. switch (node->kind) {
  4720. case_ast_node(i, Ident, node);
  4721. String name = i->token.string;
  4722. if (nested) {
  4723. Entity *e = scope_lookup_current(s, name);
  4724. if (e != nullptr) {
  4725. if (out_scope) *out_scope = e->scope;
  4726. return true;
  4727. }
  4728. } else {
  4729. Entity *e = scope_lookup(s, name);
  4730. if (e != nullptr) {
  4731. if (out_scope) *out_scope = e->scope;
  4732. return true;
  4733. }
  4734. }
  4735. case_end;
  4736. case_ast_node(se, SelectorExpr, node);
  4737. Ast *lhs = se->expr;
  4738. Ast *rhs = se->selector;
  4739. Scope *lhs_scope = nullptr;
  4740. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  4741. return check_identifier_exists(lhs_scope, rhs, true);
  4742. }
  4743. case_end;
  4744. }
  4745. return false;
  4746. }
  4747. gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) {
  4748. if (o.type && is_type_no_copy(o.type)) {
  4749. Ast *expr = unparen_expr(o.expr);
  4750. if (expr && o.mode != Addressing_Constant) {
  4751. if (expr->kind == Ast_CallExpr) {
  4752. // Okay
  4753. } else {
  4754. error(o.expr, "Invalid use of #no_copy value in %.*s", LIT(context));
  4755. return true;
  4756. }
  4757. }
  4758. }
  4759. return false;
  4760. }
  4761. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  4762. bool optional_ok = false;
  4763. isize tuple_index = 0;
  4764. for (Ast *rhs_expr : rhs) {
  4765. CheckerContext c_ = *ctx;
  4766. CheckerContext *c = &c_;
  4767. Operand o = {};
  4768. Type *type_hint = nullptr;
  4769. if (tuple_index < lhs.count) {
  4770. type_hint = lhs[tuple_index].type;
  4771. }
  4772. check_expr_base(c, &o, rhs_expr, type_hint);
  4773. if (o.mode == Addressing_NoValue) {
  4774. error_operand_no_value(&o);
  4775. o.mode = Addressing_Invalid;
  4776. }
  4777. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4778. if (lhs.count == 2 && rhs.count == 1 &&
  4779. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4780. Ast *expr = unparen_expr(o.expr);
  4781. Operand val0 = o;
  4782. Operand val1 = o;
  4783. val0.mode = Addressing_Value;
  4784. val1.mode = Addressing_Value;
  4785. val1.type = t_untyped_bool;
  4786. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4787. if (expr->kind == Ast_TypeAssertion &&
  4788. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4789. // NOTE(bill): Used only for optimizations in the backend
  4790. if (is_blank_ident(lhs[0].expr)) {
  4791. expr->TypeAssertion.ignores[0] = true;
  4792. }
  4793. if (is_blank_ident(lhs[1].expr)) {
  4794. expr->TypeAssertion.ignores[1] = true;
  4795. }
  4796. }
  4797. array_add(operands, val0);
  4798. array_add(operands, val1);
  4799. optional_ok = true;
  4800. tuple_index += 2;
  4801. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  4802. Type *tuple = o.type;
  4803. GB_ASSERT(tuple->Tuple.variables.count == 2);
  4804. Ast *expr = unparen_expr(o.expr);
  4805. if (expr->kind == Ast_CallExpr) {
  4806. expr->CallExpr.optional_ok_one = true;
  4807. }
  4808. Operand val = o;
  4809. val.type = tuple->Tuple.variables[0]->type;
  4810. val.mode = Addressing_Value;
  4811. array_add(operands, val);
  4812. tuple_index += tuple->Tuple.variables.count;
  4813. } else {
  4814. array_add(operands, o);
  4815. tuple_index += 1;
  4816. }
  4817. } else {
  4818. TypeTuple *tuple = &o.type->Tuple;
  4819. for (Entity *e : tuple->variables) {
  4820. o.type = e->type;
  4821. array_add(operands, o);
  4822. check_no_copy_assignment(o, str_lit("assignment"));
  4823. }
  4824. tuple_index += tuple->variables.count;
  4825. }
  4826. }
  4827. return optional_ok;
  4828. }
  4829. typedef u32 UnpackFlags;
  4830. enum UnpackFlag : u32 {
  4831. UnpackFlag_None = 0,
  4832. UnpackFlag_AllowOk = 1<<0,
  4833. UnpackFlag_IsVariadic = 1<<1,
  4834. UnpackFlag_AllowUndef = 1<<2,
  4835. };
  4836. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags) {
  4837. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  4838. if (lhs == nullptr || c->decl == nullptr) {
  4839. return tuple_count;
  4840. }
  4841. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  4842. Entity *e = lhs[tuple_index + j];
  4843. if (e == nullptr) {
  4844. continue;
  4845. }
  4846. DeclInfo *decl = decl_info_of_entity(e);
  4847. if (decl == nullptr) {
  4848. continue;
  4849. }
  4850. rw_mutex_shared_lock(&decl->deps_mutex);
  4851. rw_mutex_lock(&c->decl->deps_mutex);
  4852. for (Entity *dep : decl->deps) {
  4853. ptr_set_add(&c->decl->deps, dep);
  4854. }
  4855. rw_mutex_unlock(&c->decl->deps_mutex);
  4856. rw_mutex_shared_unlock(&decl->deps_mutex);
  4857. }
  4858. return tuple_count;
  4859. };
  4860. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  4861. bool is_variadic = (flags & UnpackFlag_IsVariadic) != 0;
  4862. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  4863. bool optional_ok = false;
  4864. isize tuple_index = 0;
  4865. for (Ast *rhs : rhs_arguments) {
  4866. if (rhs->kind == Ast_FieldValue) {
  4867. error(rhs, "Invalid use of 'field = value'");
  4868. rhs = rhs->FieldValue.value;
  4869. }
  4870. CheckerContext c_ = *ctx;
  4871. CheckerContext *c = &c_;
  4872. Operand o = {};
  4873. Type *type_hint = nullptr;
  4874. if (lhs != nullptr && tuple_index < lhs_count) {
  4875. // NOTE(bill): override DeclInfo for dependency
  4876. Entity *e = lhs[tuple_index];
  4877. if (e != nullptr) {
  4878. type_hint = e->type;
  4879. if (e->flags & EntityFlag_Ellipsis) {
  4880. GB_ASSERT(is_type_slice(e->type));
  4881. GB_ASSERT(e->type->kind == Type_Slice);
  4882. type_hint = e->type->Slice.elem;
  4883. }
  4884. }
  4885. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  4886. // NOTE(bill): override DeclInfo for dependency
  4887. Entity *e = lhs[lhs_count-1];
  4888. if (e != nullptr) {
  4889. type_hint = e->type;
  4890. if (e->flags & EntityFlag_Ellipsis) {
  4891. GB_ASSERT(is_type_slice(e->type));
  4892. GB_ASSERT(e->type->kind == Type_Slice);
  4893. type_hint = e->type->Slice.elem;
  4894. }
  4895. }
  4896. }
  4897. Ast *rhs_expr = unparen_expr(rhs);
  4898. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  4899. // NOTE(bill): Just handle this very specific logic here
  4900. o.type = t_untyped_uninit;
  4901. o.mode = Addressing_Value;
  4902. o.expr = rhs;
  4903. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  4904. } else {
  4905. check_expr_base(c, &o, rhs, type_hint);
  4906. }
  4907. if (o.mode == Addressing_NoValue) {
  4908. error_operand_no_value(&o);
  4909. o.mode = Addressing_Invalid;
  4910. }
  4911. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4912. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  4913. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4914. Ast *expr = unparen_expr(o.expr);
  4915. Operand val0 = o;
  4916. Operand val1 = o;
  4917. val0.mode = Addressing_Value;
  4918. val1.mode = Addressing_Value;
  4919. val1.type = t_untyped_bool;
  4920. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4921. if (expr->kind == Ast_TypeAssertion &&
  4922. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4923. // NOTE(bill): Used only for optimizations in the backend
  4924. if (is_blank_ident(lhs[0]->token)) {
  4925. expr->TypeAssertion.ignores[0] = true;
  4926. }
  4927. if (is_blank_ident(lhs[1]->token)) {
  4928. expr->TypeAssertion.ignores[1] = true;
  4929. }
  4930. }
  4931. array_add(operands, val0);
  4932. array_add(operands, val1);
  4933. optional_ok = true;
  4934. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  4935. } else {
  4936. array_add(operands, o);
  4937. tuple_index += 1;
  4938. }
  4939. } else {
  4940. TypeTuple *tuple = &o.type->Tuple;
  4941. for (Entity *e : tuple->variables) {
  4942. o.type = e->type;
  4943. array_add(operands, o);
  4944. }
  4945. isize count = tuple->variables.count;
  4946. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  4947. }
  4948. }
  4949. return optional_ok;
  4950. }
  4951. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  4952. GB_ASSERT(pt != nullptr);
  4953. GB_ASSERT(pt->kind == Type_Proc);
  4954. isize param_count = 0;
  4955. isize param_count_excluding_defaults = 0;
  4956. bool variadic = pt->Proc.variadic;
  4957. TypeTuple *param_tuple = nullptr;
  4958. if (pt->Proc.params != nullptr) {
  4959. param_tuple = &pt->Proc.params->Tuple;
  4960. param_count = param_tuple->variables.count;
  4961. if (variadic) {
  4962. for (isize i = param_count-1; i >= 0; i--) {
  4963. Entity *e = param_tuple->variables[i];
  4964. if (e->kind == Entity_TypeName) {
  4965. break;
  4966. }
  4967. if (e->kind == Entity_Variable) {
  4968. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4969. param_count--;
  4970. continue;
  4971. }
  4972. }
  4973. break;
  4974. }
  4975. param_count--;
  4976. }
  4977. }
  4978. param_count_excluding_defaults = param_count;
  4979. if (param_tuple != nullptr) {
  4980. for (isize i = param_count-1; i >= 0; i--) {
  4981. Entity *e = param_tuple->variables[i];
  4982. if (e->kind == Entity_TypeName) {
  4983. break;
  4984. }
  4985. if (e->kind == Entity_Variable) {
  4986. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4987. param_count_excluding_defaults--;
  4988. continue;
  4989. }
  4990. }
  4991. break;
  4992. }
  4993. }
  4994. if (param_count_) *param_count_ = param_count;
  4995. return param_count_excluding_defaults;
  4996. }
  4997. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  4998. isize param_count = pt->param_count;
  4999. for (isize i = 0; i < param_count; i++) {
  5000. Entity *e = pt->params->Tuple.variables[i];
  5001. String name = e->token.string;
  5002. if (is_blank_ident(name)) {
  5003. continue;
  5004. }
  5005. if (name == parameter_name) {
  5006. return i;
  5007. }
  5008. }
  5009. return -1;
  5010. }
  5011. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  5012. type = base_type(type);
  5013. GB_ASSERT(type->kind == Type_Proc);
  5014. return lookup_procedure_parameter(&type->Proc, parameter_name);
  5015. }
  5016. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  5017. Entity *entity, Type *proc_type,
  5018. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  5019. CallArgumentErrorMode show_error_mode,
  5020. CallArgumentData *data) {
  5021. TEMPORARY_ALLOCATOR_GUARD();
  5022. CallArgumentError err = CallArgumentError_None;
  5023. ast_node(ce, CallExpr, call);
  5024. GB_ASSERT(is_type_proc(proc_type));
  5025. proc_type = base_type(proc_type);
  5026. TypeProc *pt = &proc_type->Proc;
  5027. isize param_count = 0;
  5028. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  5029. bool variadic = pt->variadic;
  5030. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5031. i64 score = 0;
  5032. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  5033. Type *final_proc_type = proc_type;
  5034. Entity *gen_entity = nullptr;
  5035. if (vari_expand && !variadic) {
  5036. if (show_error) {
  5037. error(ce->ellipsis,
  5038. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  5039. LIT(ce->proc->Ident.token.string));
  5040. }
  5041. err = CallArgumentError_NonVariadicExpand;
  5042. } else if (vari_expand && pt->c_vararg) {
  5043. if (show_error) {
  5044. error(ce->ellipsis,
  5045. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  5046. LIT(ce->proc->Ident.token.string));
  5047. }
  5048. err = CallArgumentError_NonVariadicExpand;
  5049. }
  5050. GB_ASSERT(ce->split_args);
  5051. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  5052. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  5053. defer ({
  5054. for (Operand const &o : ordered_operands) {
  5055. if (o.expr != nullptr) {
  5056. call->viral_state_flags |= o.expr->viral_state_flags;
  5057. }
  5058. }
  5059. });
  5060. isize positional_operand_count = positional_operands.count;
  5061. if (variadic) {
  5062. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5063. } else if (positional_operand_count > pt->param_count) {
  5064. err = CallArgumentError_TooManyArguments;
  5065. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5066. if (show_error) {
  5067. gbString proc_str = expr_to_string(ce->proc);
  5068. defer (gb_string_free(proc_str));
  5069. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5070. }
  5071. return err;
  5072. }
  5073. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5074. for (isize i = 0; i < positional_operand_count; i++) {
  5075. ordered_operands[i] = positional_operands[i];
  5076. visited[i] = true;
  5077. }
  5078. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5079. bool named_variadic_param = false;
  5080. if (named_operands.count != 0) {
  5081. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5082. for_array(i, ce->split_args->named) {
  5083. Ast *arg = ce->split_args->named[i];
  5084. Operand operand = named_operands[i];
  5085. ast_node(fv, FieldValue, arg);
  5086. if (fv->field->kind != Ast_Ident) {
  5087. if (show_error) {
  5088. gbString expr_str = expr_to_string(fv->field);
  5089. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5090. gb_string_free(expr_str);
  5091. }
  5092. err = CallArgumentError_InvalidFieldValue;
  5093. continue;
  5094. }
  5095. String name = fv->field->Ident.token.string;
  5096. isize param_index = lookup_procedure_parameter(pt, name);
  5097. if (param_index < 0) {
  5098. if (show_error) {
  5099. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5100. }
  5101. err = CallArgumentError_ParameterNotFound;
  5102. continue;
  5103. }
  5104. if (pt->variadic && param_index == pt->variadic_index) {
  5105. named_variadic_param = true;
  5106. }
  5107. if (visited[param_index]) {
  5108. if (show_error) {
  5109. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5110. }
  5111. err = CallArgumentError_DuplicateParameter;
  5112. continue;
  5113. }
  5114. visited[param_index] = true;
  5115. ordered_operands[param_index] = operand;
  5116. }
  5117. }
  5118. isize dummy_argument_count = 0;
  5119. bool actually_variadic = false;
  5120. if (variadic) {
  5121. if (visited[pt->variadic_index] &&
  5122. positional_operand_count < positional_operands.count) {
  5123. if (show_error) {
  5124. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5125. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5126. }
  5127. err = CallArgumentError_DuplicateParameter;
  5128. } else if (!visited[pt->variadic_index]) {
  5129. visited[pt->variadic_index] = true;
  5130. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5131. if (vari_expand) {
  5132. if (variadic_operands.count == 0) {
  5133. error(call, "'..' in the wrong position");
  5134. } else {
  5135. GB_ASSERT(variadic_operands.count != 0);
  5136. *variadic_operand = variadic_operands[0];
  5137. variadic_operand->type = default_type(variadic_operand->type);
  5138. actually_variadic = true;
  5139. }
  5140. } else {
  5141. AstFile *f = call->file();
  5142. // HACK(bill): this is an awful hack
  5143. Operand o = {};
  5144. o.mode = Addressing_Value;
  5145. o.expr = ast_ident(f, make_token_ident("nil"));
  5146. o.expr->Ident.token.pos = ast_token(call).pos;
  5147. if (variadic_operands.count != 0) {
  5148. actually_variadic = true;
  5149. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5150. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5151. o.type = vt->type;
  5152. } else {
  5153. dummy_argument_count += 1;
  5154. o.type = t_untyped_nil;
  5155. }
  5156. *variadic_operand = o;
  5157. }
  5158. }
  5159. }
  5160. for (Operand const &o : ordered_operands) {
  5161. if (o.mode != Addressing_Invalid) {
  5162. check_no_copy_assignment(o, str_lit("procedure call expression"));
  5163. }
  5164. }
  5165. for (isize i = 0; i < pt->param_count; i++) {
  5166. if (!visited[i]) {
  5167. Entity *e = pt->params->Tuple.variables[i];
  5168. if (e->kind == Entity_Variable) {
  5169. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5170. ordered_operands[i].mode = Addressing_Value;
  5171. ordered_operands[i].type = e->type;
  5172. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5173. dummy_argument_count += 1;
  5174. score += assign_score_function(1);
  5175. continue;
  5176. }
  5177. }
  5178. if (show_error) {
  5179. if (e->kind == Entity_TypeName) {
  5180. error(call, "Type parameter '%.*s' is missing in procedure call",
  5181. LIT(e->token.string));
  5182. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5183. // Ignore
  5184. } else {
  5185. gbString str = type_to_string(e->type);
  5186. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5187. LIT(e->token.string), str);
  5188. gb_string_free(str);
  5189. }
  5190. }
  5191. err = CallArgumentError_ParameterMissing;
  5192. }
  5193. }
  5194. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5195. bool allow_array_programming = !(e && (e->flags & EntityFlag_NoBroadcast));
  5196. i64 s = 0;
  5197. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic, allow_array_programming)) {
  5198. bool ok = false;
  5199. if (e && (e->flags & EntityFlag_AnyInt)) {
  5200. if (is_type_integer(param_type)) {
  5201. ok = check_is_castable_to(c, o, param_type);
  5202. }
  5203. }
  5204. if (!allow_array_programming && check_is_assignable_to_with_score(c, o, param_type, nullptr, param_is_variadic, !allow_array_programming)) {
  5205. if (show_error) {
  5206. error(o->expr, "'#no_broadcast' disallows automatic broadcasting a value across all elements of an array-like type in a procedure argument");
  5207. }
  5208. }
  5209. if (ok) {
  5210. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5211. } else {
  5212. if (show_error) {
  5213. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5214. }
  5215. err = CallArgumentError_WrongTypes;
  5216. }
  5217. } else if (show_error) {
  5218. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5219. }
  5220. if (e && e->flags & EntityFlag_ConstInput) {
  5221. if (o->mode != Addressing_Constant) {
  5222. if (show_error) {
  5223. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5224. }
  5225. err = CallArgumentError_NoneConstantParameter;
  5226. }
  5227. }
  5228. if (!err && is_type_any(param_type)) {
  5229. add_type_info_type(c, o->type);
  5230. }
  5231. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5232. add_type_info_type(c, o->type);
  5233. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5234. } else if (show_error && is_type_untyped(o->type)) {
  5235. update_untyped_expr_type(c, o->expr, param_type, true);
  5236. }
  5237. return s;
  5238. };
  5239. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5240. err = CallArgumentError_None;
  5241. if (variadic) {
  5242. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5243. Type *t = pt->params->Tuple.variables[0]->type;
  5244. if (is_type_polymorphic(t)) {
  5245. if (show_error) {
  5246. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5247. }
  5248. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5249. }
  5250. }
  5251. } else {
  5252. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5253. PolyProcData poly_proc_data = {};
  5254. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5255. gen_entity = poly_proc_data.gen_entity;
  5256. Type *gept = base_type(gen_entity->type);
  5257. GB_ASSERT(is_type_proc(gept));
  5258. final_proc_type = gen_entity->type;
  5259. pt = &gept->Proc;
  5260. } else {
  5261. err = CallArgumentError_WrongTypes;
  5262. }
  5263. }
  5264. for (isize i = 0; i < pt->param_count; i++) {
  5265. Operand *o = &ordered_operands[i];
  5266. if (o->mode == Addressing_Invalid) {
  5267. continue;
  5268. }
  5269. Entity *e = pt->params->Tuple.variables[i];
  5270. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5271. if (e->kind == Entity_TypeName) {
  5272. GB_ASSERT(pt->is_polymorphic);
  5273. if (o->mode != Addressing_Type) {
  5274. if (show_error) {
  5275. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5276. }
  5277. err = CallArgumentError_WrongTypes;
  5278. }
  5279. if (are_types_identical(e->type, o->type)) {
  5280. score += assign_score_function(1);
  5281. } else {
  5282. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5283. }
  5284. continue;
  5285. }
  5286. if (param_is_variadic) {
  5287. continue;
  5288. }
  5289. score += eval_param_and_score(c, o, e->type, err, false, e, show_error);
  5290. }
  5291. }
  5292. if (variadic) {
  5293. Entity *var_entity = pt->params->Tuple.variables[pt->variadic_index];
  5294. Type *slice = var_entity->type;
  5295. GB_ASSERT(is_type_slice(slice));
  5296. Type *elem = base_type(slice)->Slice.elem;
  5297. Type *t = elem;
  5298. if (is_type_polymorphic(t)) {
  5299. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5300. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5301. }
  5302. for_array(operand_index, variadic_operands) {
  5303. Operand *o = &variadic_operands[operand_index];
  5304. if (vari_expand) {
  5305. t = slice;
  5306. if (operand_index > 0) {
  5307. if (show_error) {
  5308. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5309. }
  5310. if (data) {
  5311. data->score = score;
  5312. data->result_type = final_proc_type->Proc.results;
  5313. data->gen_entity = gen_entity;
  5314. }
  5315. return CallArgumentError_MultipleVariadicExpand;
  5316. }
  5317. }
  5318. score += eval_param_and_score(c, o, t, err, true, var_entity, show_error);
  5319. }
  5320. }
  5321. if (data) {
  5322. data->score = score;
  5323. data->result_type = final_proc_type->Proc.results;
  5324. data->gen_entity = gen_entity;
  5325. Ast *proc_lit = nullptr;
  5326. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5327. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5328. if (vp && vp->kind == Ast_ProcLit) {
  5329. proc_lit = vp;
  5330. }
  5331. }
  5332. if (proc_lit == nullptr) {
  5333. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5334. }
  5335. }
  5336. return err;
  5337. }
  5338. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5339. GB_ASSERT(ce != nullptr);
  5340. if (ce->args.count == 0) {
  5341. return false;
  5342. }
  5343. return ce->args[0]->kind == Ast_FieldValue;
  5344. }
  5345. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  5346. Entity **lhs = nullptr;
  5347. isize lhs_count = -1;
  5348. if (proc_type == nullptr) {
  5349. return nullptr;
  5350. }
  5351. GB_ASSERT(is_type_proc(proc_type));
  5352. TypeProc *pt = &base_type(proc_type)->Proc;
  5353. *is_variadic = pt->variadic;
  5354. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5355. if (pt->params != nullptr) {
  5356. lhs = pt->params->Tuple.variables.data;
  5357. lhs_count = pt->params->Tuple.variables.count;
  5358. }
  5359. } else {
  5360. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5361. if (pt->params == nullptr) {
  5362. lhs_count = 0;
  5363. } else {
  5364. lhs_count = pt->params->Tuple.variables.count;
  5365. }
  5366. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5367. for (isize i = 0; i < lhs_count; i++) {
  5368. Entity *e = pt->params->Tuple.variables[i];
  5369. if (!is_type_polymorphic(e->type)) {
  5370. lhs[i] = e;
  5371. }
  5372. }
  5373. }
  5374. if (lhs_count_) *lhs_count_ = lhs_count;
  5375. return lhs;
  5376. }
  5377. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5378. if (clauses != nullptr) {
  5379. for (Ast *clause : *clauses) {
  5380. Operand o = {};
  5381. check_expr(ctx, &o, clause);
  5382. if (o.mode != Addressing_Constant) {
  5383. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5384. if (print_err && call_expr) error(call_expr, "at caller location");
  5385. return false;
  5386. } else if (o.value.kind != ExactValue_Bool) {
  5387. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5388. if (print_err && call_expr) error(call_expr, "at caller location");
  5389. return false;
  5390. } else if (!o.value.value_bool) {
  5391. if (print_err) {
  5392. ERROR_BLOCK();
  5393. gbString str = expr_to_string(clause);
  5394. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5395. gb_string_free(str);
  5396. if (scope != nullptr) {
  5397. isize print_count = 0;
  5398. for (auto const &entry : scope->elements) {
  5399. Entity *e = entry.value;
  5400. switch (e->kind) {
  5401. case Entity_TypeName: {
  5402. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5403. gbString str = type_to_string(e->type);
  5404. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5405. gb_string_free(str);
  5406. print_count += 1;
  5407. break;
  5408. }
  5409. case Entity_Constant: {
  5410. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5411. gbString str = exact_value_to_string(e->Constant.value);
  5412. if (is_type_untyped(e->type)) {
  5413. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5414. } else {
  5415. gbString t = type_to_string(e->type);
  5416. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5417. gb_string_free(t);
  5418. }
  5419. gb_string_free(str);
  5420. print_count += 1;
  5421. break;
  5422. }
  5423. }
  5424. }
  5425. }
  5426. if (call_expr) {
  5427. TokenPos pos = ast_token(call_expr).pos;
  5428. error_line("%s at caller location\n", token_pos_to_string(pos));
  5429. }
  5430. }
  5431. return false;
  5432. }
  5433. if (ast_file_vet_style(ctx->file)) {
  5434. Ast *c = unparen_expr(clause);
  5435. if (c->kind == Ast_BinaryExpr && c->BinaryExpr.op.kind == Token_CmpAnd) {
  5436. ERROR_BLOCK();
  5437. error(c, "Prefer to separate 'where' clauses with a comma rather than '&&'");
  5438. gbString x = expr_to_string(c->BinaryExpr.left);
  5439. gbString y = expr_to_string(c->BinaryExpr.right);
  5440. error_line("\tSuggestion: '%s, %s'\n", x, y);
  5441. gb_string_free(y);
  5442. gb_string_free(x);
  5443. }
  5444. }
  5445. }
  5446. }
  5447. return true;
  5448. }
  5449. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5450. bool success = true;
  5451. type = base_type(type);
  5452. if (named_args.count > 0) {
  5453. TypeProc *pt = nullptr;
  5454. if (is_type_proc(type)) {
  5455. pt = &type->Proc;
  5456. }
  5457. for_array(i, named_args) {
  5458. Ast *arg = named_args[i];
  5459. if (arg->kind != Ast_FieldValue) {
  5460. if (show_error) {
  5461. error(arg, "Expected a 'field = value'");
  5462. }
  5463. return false;
  5464. }
  5465. ast_node(fv, FieldValue, arg);
  5466. if (fv->field->kind != Ast_Ident) {
  5467. if (show_error) {
  5468. gbString expr_str = expr_to_string(fv->field);
  5469. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5470. gb_string_free(expr_str);
  5471. }
  5472. success = false;
  5473. continue;
  5474. }
  5475. String key = fv->field->Ident.token.string;
  5476. Ast *value = fv->value;
  5477. Type *type_hint = nullptr;
  5478. if (pt) {
  5479. isize param_index = lookup_procedure_parameter(pt, key);
  5480. if (param_index < 0) {
  5481. if (show_error) {
  5482. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5483. }
  5484. success = false;
  5485. continue;
  5486. }
  5487. Entity *e = pt->params->Tuple.variables[param_index];
  5488. if (!is_type_polymorphic(e->type)) {
  5489. type_hint = e->type;
  5490. }
  5491. }
  5492. Operand o = {};
  5493. check_expr_with_type_hint(c, &o, value, type_hint);
  5494. if (o.mode == Addressing_Invalid) {
  5495. success = false;
  5496. }
  5497. array_add(named_operands, o);
  5498. }
  5499. }
  5500. return success;
  5501. }
  5502. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5503. Entity *e, Type *proc_type,
  5504. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5505. CallArgumentErrorMode show_error_mode,
  5506. CallArgumentData *data) {
  5507. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5508. Ast *ident = operand->expr;
  5509. while (ident->kind == Ast_SelectorExpr) {
  5510. Ast *s = ident->SelectorExpr.selector;
  5511. ident = s;
  5512. }
  5513. if (e == nullptr) {
  5514. e = entity_of_node(ident);
  5515. if (e != nullptr) {
  5516. proc_type = e->type;
  5517. }
  5518. }
  5519. GB_ASSERT(proc_type != nullptr);
  5520. proc_type = base_type(proc_type);
  5521. GB_ASSERT(proc_type->kind == Type_Proc);
  5522. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5523. if (return_on_failure && err != CallArgumentError_None) {
  5524. return false;
  5525. }
  5526. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5527. if (!return_on_failure && entity_to_use != nullptr) {
  5528. add_entity_use(c, ident, entity_to_use);
  5529. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5530. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5531. }
  5532. if (data->gen_entity != nullptr) {
  5533. Entity *e = data->gen_entity;
  5534. DeclInfo *decl = data->gen_entity->decl_info;
  5535. CheckerContext ctx = *c;
  5536. ctx.scope = decl->scope;
  5537. ctx.decl = decl;
  5538. ctx.proc_name = e->token.string;
  5539. ctx.curr_proc_decl = decl;
  5540. ctx.curr_proc_sig = e->type;
  5541. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5542. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5543. if (return_on_failure) {
  5544. if (!ok) {
  5545. return false;
  5546. }
  5547. } else {
  5548. decl->where_clauses_evaluated = true;
  5549. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5550. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5551. }
  5552. if (is_type_proc(data->gen_entity->type)) {
  5553. Type *t = base_type(entity_to_use->type);
  5554. data->result_type = t->Proc.results;
  5555. }
  5556. }
  5557. }
  5558. return true;
  5559. }
  5560. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5561. ast_node(ce, CallExpr, call);
  5562. GB_ASSERT(ce->split_args != nullptr);
  5563. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5564. Slice<Ast *> const &named_args = ce->split_args->named;
  5565. CallArgumentData data = {};
  5566. data.result_type = t_invalid;
  5567. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5568. auto procs = proc_group_entities_cloned(c, *operand);
  5569. if (procs.count > 1) {
  5570. isize max_arg_count = positional_args.count + named_args.count;
  5571. for (Ast *arg : positional_args) {
  5572. // NOTE(bill): The only thing that may have multiple values
  5573. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5574. arg = strip_or_return_expr(arg);
  5575. if (arg && arg->kind == Ast_CallExpr) {
  5576. max_arg_count = ISIZE_MAX;
  5577. break;
  5578. }
  5579. }
  5580. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5581. // NOTE(bill): The only thing that may have multiple values
  5582. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5583. if (arg->kind == Ast_FieldValue) {
  5584. arg = strip_or_return_expr(arg->FieldValue.value);
  5585. if (arg && arg->kind == Ast_CallExpr) {
  5586. max_arg_count = ISIZE_MAX;
  5587. break;
  5588. }
  5589. }
  5590. }
  5591. // ignore named arguments first
  5592. for (Ast *arg : named_args) {
  5593. if (arg->kind != Ast_FieldValue) {
  5594. continue;
  5595. }
  5596. ast_node(fv, FieldValue, arg);
  5597. if (fv->field->kind != Ast_Ident) {
  5598. continue;
  5599. }
  5600. String key = fv->field->Ident.token.string;
  5601. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5602. Type *t = procs[proc_index]->type;
  5603. if (is_type_proc(t)) {
  5604. isize param_index = lookup_procedure_parameter(t, key);
  5605. if (param_index < 0) {
  5606. array_unordered_remove(&procs, proc_index);
  5607. }
  5608. }
  5609. }
  5610. }
  5611. if (procs.count == 0) {
  5612. // if any of the named arguments are wrong, the `procs` will be empty
  5613. // just start from scratch
  5614. array_free(&procs);
  5615. procs = proc_group_entities_cloned(c, *operand);
  5616. }
  5617. // filter by positional argument length
  5618. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5619. Entity *proc = procs[proc_index];
  5620. Type *pt = base_type(proc->type);
  5621. if (!(pt != nullptr && is_type_proc(pt))) {
  5622. proc_index++;
  5623. continue;
  5624. }
  5625. isize param_count = 0;
  5626. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5627. if (param_count_excluding_defaults > max_arg_count) {
  5628. array_unordered_remove(&procs, proc_index);
  5629. continue;
  5630. }
  5631. proc_index++;
  5632. }
  5633. }
  5634. Entity **lhs = nullptr;
  5635. isize lhs_count = -1;
  5636. bool is_variadic = false;
  5637. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5638. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5639. defer (array_free(&positional_operands));
  5640. defer (array_free(&named_operands));
  5641. if (procs.count == 1) {
  5642. Entity *e = procs[0];
  5643. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  5644. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5645. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5646. check_call_arguments_single(c, call, operand,
  5647. e, e->type,
  5648. positional_operands, named_operands,
  5649. CallArgumentErrorMode::ShowErrors,
  5650. &data);
  5651. }
  5652. return data;
  5653. }
  5654. {
  5655. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  5656. // where the same positional parameter has the same type value (and ellipsis)
  5657. isize proc_arg_count = -1;
  5658. for (Entity *p : procs) {
  5659. Type *pt = base_type(p->type);
  5660. if (pt != nullptr && is_type_proc(pt)) {
  5661. if (proc_arg_count < 0) {
  5662. proc_arg_count = pt->Proc.param_count;
  5663. } else {
  5664. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  5665. }
  5666. }
  5667. }
  5668. if (proc_arg_count >= 0) {
  5669. lhs_count = proc_arg_count;
  5670. if (lhs_count > 0) {
  5671. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  5672. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  5673. Entity *e = nullptr;
  5674. for (Entity *p : procs) {
  5675. Type *pt = base_type(p->type);
  5676. if (!(pt != nullptr && is_type_proc(pt))) {
  5677. continue;
  5678. }
  5679. if (e == nullptr) {
  5680. e = pt->Proc.params->Tuple.variables[param_index];
  5681. } else {
  5682. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  5683. if (e == f) {
  5684. continue;
  5685. }
  5686. if (are_types_identical(e->type, f->type)) {
  5687. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  5688. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  5689. if (ee == fe) {
  5690. continue;
  5691. }
  5692. }
  5693. // NOTE(bill): Entities are not close enough to be used
  5694. e = nullptr;
  5695. break;
  5696. }
  5697. }
  5698. lhs[param_index] = e;
  5699. }
  5700. }
  5701. }
  5702. }
  5703. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5704. for_array(i, named_args) {
  5705. Ast *arg = named_args[i];
  5706. if (arg->kind != Ast_FieldValue) {
  5707. error(arg, "Expected a 'field = value'");
  5708. return data;
  5709. }
  5710. ast_node(fv, FieldValue, arg);
  5711. if (fv->field->kind != Ast_Ident) {
  5712. gbString expr_str = expr_to_string(fv->field);
  5713. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5714. gb_string_free(expr_str);
  5715. return data;
  5716. }
  5717. String key = fv->field->Ident.token.string;
  5718. Ast *value = fv->value;
  5719. Type *type_hint = nullptr;
  5720. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  5721. Entity *e = lhs[lhs_idx];
  5722. if (e != nullptr && e->token.string == key &&
  5723. !is_type_polymorphic(e->type)) {
  5724. type_hint = e->type;
  5725. break;
  5726. }
  5727. }
  5728. Operand o = {};
  5729. check_expr_with_type_hint(c, &o, value, type_hint);
  5730. array_add(&named_operands, o);
  5731. }
  5732. gb_free(heap_allocator(), lhs);
  5733. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  5734. defer (array_free(&valids));
  5735. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  5736. defer (array_free(&proc_entities));
  5737. for (Entity *proc : procs) {
  5738. array_add(&proc_entities, proc);
  5739. }
  5740. int max_matched_features = 0;
  5741. gbString expr_name = expr_to_string(operand->expr);
  5742. defer (gb_string_free(expr_name));
  5743. for_array(i, procs) {
  5744. Entity *p = procs[i];
  5745. if (p->flags & EntityFlag_Disabled) {
  5746. continue;
  5747. }
  5748. Type *pt = base_type(p->type);
  5749. if (pt != nullptr && is_type_proc(pt)) {
  5750. CallArgumentData data = {};
  5751. CheckerContext ctx = *c;
  5752. ctx.no_polymorphic_errors = true;
  5753. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  5754. ctx.hide_polymorphic_errors = true;
  5755. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  5756. p, pt,
  5757. positional_operands, named_operands,
  5758. CallArgumentErrorMode::NoErrors,
  5759. &data);
  5760. if (!is_a_candidate) {
  5761. continue;
  5762. }
  5763. isize index = i;
  5764. ValidIndexAndScore item = {};
  5765. item.score = data.score;
  5766. if (data.gen_entity != nullptr) {
  5767. array_add(&proc_entities, data.gen_entity);
  5768. index = proc_entities.count-1;
  5769. // prefer non-polymorphic procedures over polymorphic
  5770. item.score += assign_score_function(1);
  5771. }
  5772. max_matched_features = gb_max(max_matched_features, matched_target_features(&pt->Proc));
  5773. item.index = index;
  5774. array_add(&valids, item);
  5775. }
  5776. }
  5777. if (max_matched_features > 0) {
  5778. for_array(i, valids) {
  5779. Entity *p = procs[valids[i].index];
  5780. Type *t = base_type(p->type);
  5781. GB_ASSERT(t->kind == Type_Proc);
  5782. int matched = matched_target_features(&t->Proc);
  5783. valids[i].score += assign_score_function(max_matched_features-matched);
  5784. }
  5785. }
  5786. if (valids.count > 1) {
  5787. array_sort(valids, valid_index_and_score_cmp);
  5788. i64 best_score = valids[0].score;
  5789. Entity *best_entity = proc_entities[valids[0].index];
  5790. GB_ASSERT(best_entity != nullptr);
  5791. for (isize i = 1; i < valids.count; i++) {
  5792. if (best_score > valids[i].score) {
  5793. valids.count = i;
  5794. break;
  5795. }
  5796. if (best_entity == proc_entities[valids[i].index]) {
  5797. valids.count = i;
  5798. break;
  5799. }
  5800. }
  5801. }
  5802. auto print_argument_types = [&]() {
  5803. error_line("\tGiven argument types: (");
  5804. isize i = 0;
  5805. for (Operand const &o : positional_operands) {
  5806. if (i++ > 0) error_line(", ");
  5807. gbString type = type_to_string(o.type);
  5808. defer (gb_string_free(type));
  5809. error_line("%s", type);
  5810. }
  5811. for (Operand const &o : named_operands) {
  5812. if (i++ > 0) error_line(", ");
  5813. gbString type = type_to_string(o.type);
  5814. defer (gb_string_free(type));
  5815. if (i < ce->split_args->named.count) {
  5816. Ast *named_field = ce->split_args->named[i];
  5817. ast_node(fv, FieldValue, named_field);
  5818. gbString field = expr_to_string(fv->field);
  5819. defer (gb_string_free(field));
  5820. error_line("%s = %s", field, type);
  5821. } else {
  5822. error_line("%s", type);
  5823. }
  5824. }
  5825. error_line(")\n");
  5826. };
  5827. if (valids.count == 0) {
  5828. ERROR_BLOCK();
  5829. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  5830. if (positional_operands.count == 0 && named_operands.count == 0) {
  5831. error_line("\tNo given arguments\n");
  5832. } else {
  5833. print_argument_types();
  5834. }
  5835. if (procs.count == 0) {
  5836. procs = proc_group_entities_cloned(c, *operand);
  5837. }
  5838. if (procs.count > 0) {
  5839. error_line("Did you mean to use one of the following:\n");
  5840. }
  5841. isize max_name_length = 0;
  5842. isize max_type_length = 0;
  5843. for (Entity *proc : procs) {
  5844. Type *t = base_type(proc->type);
  5845. if (t == t_invalid) continue;
  5846. String prefix = {};
  5847. String prefix_sep = {};
  5848. if (proc->pkg) {
  5849. prefix = proc->pkg->name;
  5850. prefix_sep = str_lit(".");
  5851. }
  5852. String name = proc->token.string;
  5853. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  5854. gbString pt;
  5855. if (t->Proc.node != nullptr) {
  5856. pt = expr_to_string(t->Proc.node);
  5857. } else {
  5858. pt = type_to_string(t);
  5859. }
  5860. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  5861. gb_string_free(pt);
  5862. }
  5863. isize max_spaces = gb_max(max_name_length, max_type_length);
  5864. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  5865. for (isize i = 0; i < max_spaces; i++) {
  5866. spaces[i] = ' ';
  5867. }
  5868. spaces[max_spaces] = 0;
  5869. for (Entity *proc : procs) {
  5870. TokenPos pos = proc->token.pos;
  5871. Type *t = base_type(proc->type);
  5872. if (t == t_invalid) continue;
  5873. GB_ASSERT(t->kind == Type_Proc);
  5874. gbString pt;
  5875. defer (gb_string_free(pt));
  5876. if (t->Proc.node != nullptr) {
  5877. pt = expr_to_string(t->Proc.node);
  5878. } else {
  5879. pt = type_to_string(t);
  5880. }
  5881. String prefix = {};
  5882. String prefix_sep = {};
  5883. if (proc->pkg) {
  5884. prefix = proc->pkg->name;
  5885. prefix_sep = str_lit(".");
  5886. }
  5887. String name = proc->token.string;
  5888. isize len = prefix.len + prefix_sep.len + name.len;
  5889. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  5890. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  5891. char const *sep = "::";
  5892. if (proc->kind == Entity_Variable) {
  5893. sep = ":=";
  5894. }
  5895. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  5896. LIT(prefix), LIT(prefix_sep), LIT(name),
  5897. name_padding, spaces,
  5898. sep,
  5899. pt,
  5900. type_padding, spaces,
  5901. token_pos_to_string(pos)
  5902. );
  5903. }
  5904. if (procs.count > 0) {
  5905. error_line("\n");
  5906. }
  5907. data.result_type = t_invalid;
  5908. } else if (valids.count > 1) {
  5909. ERROR_BLOCK();
  5910. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  5911. if (positional_operands.count == 0 && named_operands.count == 0) {
  5912. error_line("\tNo given arguments\n");
  5913. } else {
  5914. print_argument_types();
  5915. }
  5916. for (auto const &valid : valids) {
  5917. Entity *proc = proc_entities[valid.index];
  5918. GB_ASSERT(proc != nullptr);
  5919. TokenPos pos = proc->token.pos;
  5920. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  5921. gbString pt = nullptr;
  5922. defer (gb_string_free(pt));
  5923. if (t->Proc.node != nullptr) {
  5924. pt = expr_to_string(t->Proc.node);
  5925. } else {
  5926. pt = type_to_string(t);
  5927. }
  5928. String name = proc->token.string;
  5929. char const *sep = "::";
  5930. if (proc->kind == Entity_Variable) {
  5931. sep = ":=";
  5932. }
  5933. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  5934. if (proc->decl_info->proc_lit != nullptr) {
  5935. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  5936. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  5937. if (pl->where_token.kind != Token_Invalid) {
  5938. error_line("\n\t\twhere ");
  5939. for_array(j, pl->where_clauses) {
  5940. Ast *clause = pl->where_clauses[j];
  5941. if (j != 0) {
  5942. error_line("\t\t ");
  5943. }
  5944. gbString str = expr_to_string(clause);
  5945. error_line("%s", str);
  5946. gb_string_free(str);
  5947. if (j != pl->where_clauses.count-1) {
  5948. error_line(",");
  5949. }
  5950. }
  5951. error_line("\n\t");
  5952. }
  5953. }
  5954. error_line("at %s\n", token_pos_to_string(pos));
  5955. }
  5956. data.result_type = t_invalid;
  5957. } else {
  5958. GB_ASSERT(valids.count == 1);
  5959. Ast *ident = operand->expr;
  5960. while (ident->kind == Ast_SelectorExpr) {
  5961. Ast *s = ident->SelectorExpr.selector;
  5962. ident = s;
  5963. }
  5964. Entity *e = proc_entities[valids[0].index];
  5965. GB_ASSERT(e != nullptr);
  5966. Array<Operand> named_operands = {};
  5967. check_call_arguments_single(c, call, operand,
  5968. e, e->type,
  5969. positional_operands, named_operands,
  5970. CallArgumentErrorMode::ShowErrors,
  5971. &data);
  5972. return data;
  5973. }
  5974. return data;
  5975. }
  5976. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  5977. Type *proc_type = nullptr;
  5978. CallArgumentData data = {};
  5979. data.result_type = t_invalid;
  5980. proc_type = base_type(operand->type);
  5981. TypeProc *pt = nullptr;
  5982. if (proc_type) {
  5983. pt = &proc_type->Proc;
  5984. }
  5985. TEMPORARY_ALLOCATOR_GUARD();
  5986. ast_node(ce, CallExpr, call);
  5987. bool any_failure = false;
  5988. // Split positional and named args into separate arrays/slices
  5989. Slice<Ast *> positional_args = {};
  5990. Slice<Ast *> named_args = {};
  5991. if (ce->split_args == nullptr) {
  5992. positional_args = ce->args;
  5993. for (isize i = 0; i < ce->args.count; i++) {
  5994. Ast *arg = ce->args.data[i];
  5995. if (arg->kind == Ast_FieldValue) {
  5996. positional_args.count = i;
  5997. break;
  5998. }
  5999. }
  6000. named_args = slice(ce->args, positional_args.count, ce->args.count);
  6001. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  6002. split_args->positional = positional_args;
  6003. split_args->named = named_args;
  6004. ce->split_args = split_args;
  6005. } else {
  6006. positional_args = ce->split_args->positional;
  6007. named_args = ce->split_args->named;
  6008. }
  6009. if (operand->mode == Addressing_ProcGroup) {
  6010. return check_call_arguments_proc_group(c, operand, call);
  6011. }
  6012. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  6013. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6014. defer (array_free(&positional_operands));
  6015. defer (array_free(&named_operands));
  6016. if (positional_args.count > 0) {
  6017. isize lhs_count = -1;
  6018. bool is_variadic = false;
  6019. Entity **lhs = nullptr;
  6020. if (pt != nullptr) {
  6021. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  6022. }
  6023. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  6024. }
  6025. if (named_args.count > 0) {
  6026. for_array(i, named_args) {
  6027. Ast *arg = named_args[i];
  6028. if (arg->kind != Ast_FieldValue) {
  6029. error(arg, "Expected a 'field = value'");
  6030. return data;
  6031. }
  6032. ast_node(fv, FieldValue, arg);
  6033. if (fv->field->kind != Ast_Ident) {
  6034. gbString expr_str = expr_to_string(fv->field);
  6035. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6036. any_failure = true;
  6037. gb_string_free(expr_str);
  6038. continue;
  6039. }
  6040. String key = fv->field->Ident.token.string;
  6041. Ast *value = fv->value;
  6042. isize param_index = lookup_procedure_parameter(pt, key);
  6043. Type *type_hint = nullptr;
  6044. if (param_index >= 0) {
  6045. Entity *e = pt->params->Tuple.variables[param_index];
  6046. type_hint = e->type;
  6047. }
  6048. Operand o = {};
  6049. check_expr_with_type_hint(c, &o, value, type_hint);
  6050. if (o.mode == Addressing_Invalid) {
  6051. any_failure = true;
  6052. }
  6053. array_add(&named_operands, o);
  6054. }
  6055. }
  6056. if (!any_failure) {
  6057. check_call_arguments_single(c, call, operand,
  6058. nullptr, proc_type,
  6059. positional_operands, named_operands,
  6060. CallArgumentErrorMode::ShowErrors,
  6061. &data);
  6062. } else if (pt) {
  6063. data.result_type = pt->results;
  6064. }
  6065. return data;
  6066. }
  6067. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6068. if (!is_type_polymorphic_record(t)) {
  6069. return -1;
  6070. }
  6071. TypeTuple *params = get_record_polymorphic_params(t);
  6072. if (params == nullptr) {
  6073. return -1;
  6074. }
  6075. for_array(i, params->variables) {
  6076. Entity *e = params->variables[i];
  6077. String name = e->token.string;
  6078. if (is_blank_ident(name)) {
  6079. continue;
  6080. }
  6081. if (name == parameter_name) {
  6082. return i;
  6083. }
  6084. }
  6085. return -1;
  6086. }
  6087. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6088. ast_node(ce, CallExpr, call);
  6089. Type *original_type = operand->type;
  6090. GB_ASSERT(is_type_polymorphic_record(original_type));
  6091. bool show_error = true;
  6092. Array<Operand> operands = {};
  6093. defer (array_free(&operands));
  6094. bool named_fields = false;
  6095. {
  6096. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6097. auto prev_type_path = c->type_path;
  6098. c->type_path = new_checker_type_path();
  6099. defer ({
  6100. destroy_checker_type_path(c->type_path);
  6101. c->type_path = prev_type_path;
  6102. });
  6103. if (is_call_expr_field_value(ce)) {
  6104. named_fields = true;
  6105. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6106. for_array(i, ce->args) {
  6107. Ast *arg = ce->args[i];
  6108. ast_node(fv, FieldValue, arg);
  6109. if (fv->field->kind == Ast_Ident) {
  6110. String name = fv->field->Ident.token.string;
  6111. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6112. if (index >= 0) {
  6113. TypeTuple *params = get_record_polymorphic_params(original_type);
  6114. Entity *e = params->variables[index];
  6115. if (e->kind == Entity_Constant) {
  6116. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6117. continue;
  6118. }
  6119. }
  6120. }
  6121. check_expr_or_type(c, &operands[i], fv->value);
  6122. }
  6123. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6124. if (vari_expand) {
  6125. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6126. }
  6127. } else {
  6128. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6129. Entity **lhs = nullptr;
  6130. isize lhs_count = -1;
  6131. TypeTuple *params = get_record_polymorphic_params(original_type);
  6132. if (params != nullptr) {
  6133. lhs = params->variables.data;
  6134. lhs_count = params->variables.count;
  6135. }
  6136. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6137. }
  6138. }
  6139. CallArgumentError err = CallArgumentError_None;
  6140. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6141. isize param_count = tuple->variables.count;
  6142. isize minimum_param_count = param_count;
  6143. for (; minimum_param_count > 0; minimum_param_count--) {
  6144. Entity *e = tuple->variables[minimum_param_count-1];
  6145. if (e->kind != Entity_Constant) {
  6146. break;
  6147. }
  6148. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6149. break;
  6150. }
  6151. }
  6152. Array<Operand> ordered_operands = operands;
  6153. if (!named_fields) {
  6154. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6155. array_copy(&ordered_operands, operands, 0);
  6156. } else {
  6157. TEMPORARY_ALLOCATOR_GUARD();
  6158. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6159. // LEAK(bill)
  6160. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6161. for_array(i, ce->args) {
  6162. Ast *arg = ce->args[i];
  6163. ast_node(fv, FieldValue, arg);
  6164. if (fv->field->kind != Ast_Ident) {
  6165. if (show_error) {
  6166. gbString expr_str = expr_to_string(fv->field);
  6167. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6168. gb_string_free(expr_str);
  6169. }
  6170. err = CallArgumentError_InvalidFieldValue;
  6171. continue;
  6172. }
  6173. String name = fv->field->Ident.token.string;
  6174. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6175. if (index < 0) {
  6176. if (show_error) {
  6177. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6178. }
  6179. err = CallArgumentError_ParameterNotFound;
  6180. continue;
  6181. }
  6182. if (visited[index]) {
  6183. if (show_error) {
  6184. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6185. }
  6186. err = CallArgumentError_DuplicateParameter;
  6187. continue;
  6188. }
  6189. visited[index] = true;
  6190. ordered_operands[index] = operands[i];
  6191. }
  6192. for (isize i = 0; i < param_count; i++) {
  6193. if (!visited[i]) {
  6194. Entity *e = tuple->variables[i];
  6195. if (is_blank_ident(e->token)) {
  6196. continue;
  6197. }
  6198. if (show_error) {
  6199. if (e->kind == Entity_TypeName) {
  6200. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6201. LIT(e->token.string));
  6202. } else {
  6203. gbString str = type_to_string(e->type);
  6204. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6205. LIT(e->token.string), str);
  6206. gb_string_free(str);
  6207. }
  6208. }
  6209. err = CallArgumentError_ParameterMissing;
  6210. }
  6211. }
  6212. }
  6213. if (err != 0) {
  6214. operand->mode = Addressing_Invalid;
  6215. return err;
  6216. }
  6217. while (ordered_operands.count > 0) {
  6218. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6219. break;
  6220. }
  6221. array_pop(&ordered_operands);
  6222. }
  6223. if (minimum_param_count != param_count) {
  6224. if (param_count < ordered_operands.count) {
  6225. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6226. err = CallArgumentError_TooManyArguments;
  6227. } else if (minimum_param_count > ordered_operands.count) {
  6228. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6229. err = CallArgumentError_TooFewArguments;
  6230. }
  6231. } else {
  6232. if (param_count < ordered_operands.count) {
  6233. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6234. err = CallArgumentError_TooManyArguments;
  6235. } else if (param_count > ordered_operands.count) {
  6236. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6237. err = CallArgumentError_TooFewArguments;
  6238. }
  6239. }
  6240. if (err != 0) {
  6241. return err;
  6242. }
  6243. if (minimum_param_count != param_count) {
  6244. array_resize(&ordered_operands, param_count);
  6245. isize missing_count = 0;
  6246. // NOTE(bill): Replace missing operands with the default values (if possible)
  6247. for_array(i, ordered_operands) {
  6248. Operand *o = &ordered_operands[i];
  6249. if (o->expr == nullptr) {
  6250. Entity *e = tuple->variables[i];
  6251. if (e->kind == Entity_Constant) {
  6252. missing_count += 1;
  6253. o->mode = Addressing_Constant;
  6254. o->type = default_type(e->type);
  6255. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6256. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6257. o->value = e->Constant.param_value.value;
  6258. }
  6259. } else if (e->kind == Entity_TypeName) {
  6260. missing_count += 1;
  6261. o->mode = Addressing_Type;
  6262. o->type = e->type;
  6263. o->expr = e->identifier;
  6264. }
  6265. }
  6266. }
  6267. }
  6268. isize oo_count = gb_min(param_count, ordered_operands.count);
  6269. i64 score = 0;
  6270. for (isize i = 0; i < oo_count; i++) {
  6271. Entity *e = tuple->variables[i];
  6272. Operand *o = &ordered_operands[i];
  6273. if (o->mode == Addressing_Invalid) {
  6274. continue;
  6275. }
  6276. if (e->kind == Entity_TypeName) {
  6277. if (o->mode != Addressing_Type) {
  6278. if (show_error) {
  6279. gbString expr = expr_to_string(o->expr);
  6280. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6281. gb_string_free(expr);
  6282. }
  6283. err = CallArgumentError_WrongTypes;
  6284. }
  6285. if (are_types_identical(e->type, o->type)) {
  6286. score += assign_score_function(1);
  6287. } else {
  6288. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6289. }
  6290. } else {
  6291. i64 s = 0;
  6292. if (o->type->kind == Type_Generic) {
  6293. // Polymorphic name!
  6294. score += assign_score_function(1);
  6295. continue;
  6296. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6297. if (show_error) {
  6298. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6299. }
  6300. err = CallArgumentError_WrongTypes;
  6301. }
  6302. o->type = e->type;
  6303. if (o->mode != Addressing_Constant) {
  6304. bool valid = false;
  6305. if (is_type_proc(o->type)) {
  6306. Entity *proc_entity = entity_from_expr(o->expr);
  6307. valid = proc_entity != nullptr;
  6308. }
  6309. if (!valid) {
  6310. if (show_error) {
  6311. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6312. }
  6313. err = CallArgumentError_NoneConstantParameter;
  6314. }
  6315. }
  6316. score += s;
  6317. }
  6318. // NOTE(bill): Add type info the parameters
  6319. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6320. // add_type_info_type(c, o->type);
  6321. }
  6322. if (show_error && err) {
  6323. return err;
  6324. }
  6325. {
  6326. GenTypesData *found_gen_types = ensure_polymorphic_record_entity_has_gen_types(c, original_type);
  6327. mutex_lock(&found_gen_types->mutex);
  6328. defer (mutex_unlock(&found_gen_types->mutex));
  6329. Entity *found_entity = find_polymorphic_record_entity(found_gen_types, param_count, ordered_operands);
  6330. if (found_entity) {
  6331. operand->mode = Addressing_Type;
  6332. operand->type = found_entity->type;
  6333. return err;
  6334. }
  6335. CheckerContext ctx = *c;
  6336. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6337. ctx.scope = polymorphic_record_parent_scope(original_type);
  6338. GB_ASSERT(ctx.scope != nullptr);
  6339. Type *bt = base_type(original_type);
  6340. String generated_name = make_string_c(expr_to_string(call));
  6341. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6342. if (bt->kind == Type_Struct) {
  6343. Ast *node = clone_ast(bt->Struct.node);
  6344. Type *struct_type = alloc_type_struct();
  6345. struct_type->Struct.node = node;
  6346. struct_type->Struct.polymorphic_parent = original_type;
  6347. set_base_type(named_type, struct_type);
  6348. check_open_scope(&ctx, node);
  6349. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6350. check_close_scope(&ctx);
  6351. } else if (bt->kind == Type_Union) {
  6352. Ast *node = clone_ast(bt->Union.node);
  6353. Type *union_type = alloc_type_union();
  6354. union_type->Union.node = node;
  6355. union_type->Union.polymorphic_parent = original_type;
  6356. set_base_type(named_type, union_type);
  6357. check_open_scope(&ctx, node);
  6358. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6359. check_close_scope(&ctx);
  6360. } else {
  6361. GB_PANIC("Unsupported parametric polymorphic record type");
  6362. }
  6363. bt = base_type(named_type);
  6364. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6365. GB_ASSERT(original_type->kind == Type_Named);
  6366. Entity *e = original_type->Named.type_name;
  6367. GB_ASSERT(e->kind == Entity_TypeName);
  6368. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6369. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6370. Type *params = nullptr;
  6371. switch (bt->kind) {
  6372. case Type_Struct: params = bt->Struct.polymorphic_params; break;
  6373. case Type_Union: params = bt->Union.polymorphic_params; break;
  6374. }
  6375. if (params != nullptr) for_array(i, params->Tuple.variables) {
  6376. Entity *v = params->Tuple.variables[i];
  6377. String name = v->token.string;
  6378. if (i > 0) {
  6379. s = gb_string_append_fmt(s, ", ");
  6380. }
  6381. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6382. if (v->kind == Entity_TypeName) {
  6383. if (v->type->kind != Type_Generic) {
  6384. s = gb_string_append_fmt(s, "=");
  6385. s = write_type_to_string(s, v->type, false);
  6386. }
  6387. } else if (v->kind == Entity_Constant) {
  6388. s = gb_string_append_fmt(s, "=");
  6389. s = write_exact_value_to_string(s, v->Constant.value);
  6390. }
  6391. }
  6392. s = gb_string_append_fmt(s, ")");
  6393. String new_name = make_string_c(s);
  6394. named_type->Named.name = new_name;
  6395. if (named_type->Named.type_name) {
  6396. named_type->Named.type_name->token.string = new_name;
  6397. }
  6398. }
  6399. operand->mode = Addressing_Type;
  6400. operand->type = named_type;
  6401. }
  6402. return err;
  6403. }
  6404. // returns true on success
  6405. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6406. bool success = true;
  6407. if (args.count > 0) {
  6408. if (allow_mixed) {
  6409. bool was_named = false;
  6410. for (Ast *arg : args) {
  6411. if (was_named && arg->kind != Ast_FieldValue) {
  6412. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6413. success = false;
  6414. break;
  6415. }
  6416. was_named = was_named || arg->kind == Ast_FieldValue;
  6417. }
  6418. } else {
  6419. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6420. for (Ast *arg : args) {
  6421. bool mix = false;
  6422. if (first_is_field_value) {
  6423. mix = arg->kind != Ast_FieldValue;
  6424. } else {
  6425. mix = arg->kind == Ast_FieldValue;
  6426. }
  6427. if (mix) {
  6428. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6429. success = false;
  6430. }
  6431. }
  6432. }
  6433. }
  6434. return success;
  6435. }
  6436. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6437. operand->mode = Addressing_Invalid; \
  6438. operand->expr = call; \
  6439. return Expr_Stmt; \
  6440. }
  6441. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6442. if (proc != nullptr &&
  6443. proc->kind == Ast_BasicDirective) {
  6444. ast_node(bd, BasicDirective, proc);
  6445. String name = bd->name.string;
  6446. if (
  6447. name == "location" ||
  6448. name == "assert" ||
  6449. name == "panic" ||
  6450. name == "defined" ||
  6451. name == "config" ||
  6452. name == "load" ||
  6453. name == "load_directory" ||
  6454. name == "load_hash"
  6455. ) {
  6456. operand->mode = Addressing_Builtin;
  6457. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6458. operand->expr = proc;
  6459. operand->type = t_invalid;
  6460. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6461. } else {
  6462. error(proc, "Unknown directive: #%.*s", LIT(name));
  6463. operand->expr = proc;
  6464. operand->type = t_invalid;
  6465. operand->mode = Addressing_Invalid;
  6466. return Expr_Expr;
  6467. }
  6468. if (inlining != ProcInlining_none) {
  6469. error(call, "Inlining operators are not allowed on built-in procedures");
  6470. }
  6471. } else {
  6472. if (proc != nullptr) {
  6473. check_expr_or_type(c, operand, proc);
  6474. } else {
  6475. GB_ASSERT(operand->expr != nullptr);
  6476. }
  6477. }
  6478. if (operand->mode == Addressing_Invalid) {
  6479. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6480. for (Ast *arg : args) {
  6481. if (arg->kind == Ast_FieldValue) {
  6482. arg = arg->FieldValue.value;
  6483. }
  6484. check_expr_base(c, operand, arg, nullptr);
  6485. }
  6486. operand->mode = Addressing_Invalid;
  6487. operand->expr = call;
  6488. return Expr_Stmt;
  6489. }
  6490. if (operand->mode == Addressing_Type) {
  6491. Type *t = operand->type;
  6492. if (is_type_polymorphic_record(t)) {
  6493. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6494. if (!is_type_named(t)) {
  6495. gbString s = expr_to_string(operand->expr);
  6496. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6497. gb_string_free(s);
  6498. operand->mode = Addressing_Invalid;
  6499. operand->type = t_invalid;;
  6500. return Expr_Expr;
  6501. }
  6502. auto err = check_polymorphic_record_type(c, operand, call);
  6503. if (err == 0) {
  6504. Ast *ident = operand->expr;
  6505. while (ident->kind == Ast_SelectorExpr) {
  6506. Ast *s = ident->SelectorExpr.selector;
  6507. ident = s;
  6508. }
  6509. Type *ot = operand->type;
  6510. GB_ASSERT(ot->kind == Type_Named);
  6511. Entity *e = ot->Named.type_name;
  6512. add_entity_use(c, ident, e);
  6513. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6514. } else {
  6515. operand->mode = Addressing_Invalid;
  6516. operand->type = t_invalid;
  6517. }
  6518. } else {
  6519. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6520. operand->mode = Addressing_Invalid;
  6521. isize arg_count = args.count;
  6522. switch (arg_count) {
  6523. case 0:
  6524. {
  6525. gbString str = type_to_string(t);
  6526. error(call, "Missing argument in conversion to '%s'", str);
  6527. gb_string_free(str);
  6528. } break;
  6529. default:
  6530. {
  6531. gbString str = type_to_string(t);
  6532. error(call, "Too many arguments in conversion to '%s'", str);
  6533. gb_string_free(str);
  6534. } break;
  6535. case 1: {
  6536. Ast *arg = args[0];
  6537. if (arg->kind == Ast_FieldValue) {
  6538. error(call, "'field = value' cannot be used in a type conversion");
  6539. arg = arg->FieldValue.value;
  6540. // NOTE(bill): Carry on the cast regardless
  6541. }
  6542. check_expr_with_type_hint(c, operand, arg, t);
  6543. if (operand->mode != Addressing_Invalid) {
  6544. if (is_type_polymorphic(t)) {
  6545. error(call, "A polymorphic type cannot be used in a type conversion");
  6546. } else {
  6547. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  6548. // as it assumes it is determining the type
  6549. check_cast(c, operand, t);
  6550. }
  6551. }
  6552. operand->type = t;
  6553. operand->expr = call;
  6554. if (operand->mode != Addressing_Invalid) {
  6555. update_untyped_expr_type(c, arg, t, false);
  6556. }
  6557. break;
  6558. }
  6559. }
  6560. }
  6561. return Expr_Expr;
  6562. }
  6563. if (operand->mode == Addressing_Builtin) {
  6564. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  6565. i32 id = operand->builtin_id;
  6566. Entity *e = entity_of_node(operand->expr);
  6567. if (e != nullptr && e->token.string == "expand_to_tuple") {
  6568. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  6569. }
  6570. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  6571. operand->mode = Addressing_Invalid;
  6572. operand->type = t_invalid;
  6573. }
  6574. operand->expr = call;
  6575. return builtin_procs[id].kind;
  6576. }
  6577. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  6578. Entity *initial_entity = entity_of_node(operand->expr);
  6579. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  6580. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  6581. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  6582. if (c->decl) {
  6583. c->decl->defer_used += 1;
  6584. }
  6585. }
  6586. add_entity_use(c, operand->expr, initial_entity);
  6587. if (initial_entity->Procedure.entry_point_only) {
  6588. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  6589. // Okay
  6590. } else {
  6591. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  6592. }
  6593. }
  6594. }
  6595. if (operand->mode != Addressing_ProcGroup) {
  6596. Type *proc_type = base_type(operand->type);
  6597. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  6598. bool valid_mode = is_operand_value(*operand);
  6599. if (!valid_type || !valid_mode) {
  6600. Ast *e = operand->expr;
  6601. gbString str = expr_to_string(e);
  6602. gbString type_str = type_to_string(operand->type);
  6603. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  6604. gb_string_free(type_str);
  6605. gb_string_free(str);
  6606. operand->mode = Addressing_Invalid;
  6607. operand->expr = call;
  6608. return Expr_Stmt;
  6609. }
  6610. }
  6611. CallArgumentData data = check_call_arguments(c, operand, call);
  6612. Type *result_type = data.result_type;
  6613. gb_zero_item(operand);
  6614. operand->expr = call;
  6615. if (result_type == t_invalid) {
  6616. operand->mode = Addressing_Invalid;
  6617. operand->type = t_invalid;
  6618. return Expr_Stmt;
  6619. }
  6620. Type *pt = base_type(operand->type);
  6621. if (pt == nullptr) {
  6622. pt = t_invalid;
  6623. }
  6624. if (pt == t_invalid) {
  6625. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6626. pt = type_of_expr(operand->expr->CallExpr.proc);
  6627. }
  6628. if (pt == t_invalid && data.gen_entity) {
  6629. pt = data.gen_entity->type;
  6630. }
  6631. }
  6632. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  6633. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  6634. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  6635. }
  6636. }
  6637. if (result_type == nullptr) {
  6638. operand->mode = Addressing_NoValue;
  6639. } else {
  6640. GB_ASSERT(is_type_tuple(result_type));
  6641. isize count = result_type->Tuple.variables.count;
  6642. switch (count) {
  6643. case 0:
  6644. operand->mode = Addressing_NoValue;
  6645. break;
  6646. case 1:
  6647. operand->mode = Addressing_Value;
  6648. operand->type = result_type->Tuple.variables[0]->type;
  6649. break;
  6650. default:
  6651. operand->mode = Addressing_Value;
  6652. operand->type = result_type;
  6653. break;
  6654. }
  6655. }
  6656. bool is_call_inlined = false;
  6657. switch (inlining) {
  6658. case ProcInlining_inline:
  6659. is_call_inlined = true;
  6660. if (proc != nullptr) {
  6661. Entity *e = entity_from_expr(proc);
  6662. if (e != nullptr && e->kind == Entity_Procedure) {
  6663. DeclInfo *decl = e->decl_info;
  6664. if (decl->proc_lit) {
  6665. ast_node(pl, ProcLit, decl->proc_lit);
  6666. if (pl->inlining == ProcInlining_no_inline) {
  6667. error(call, "'#force_inline' cannot be applied to a procedure that has be marked as '#force_no_inline'");
  6668. }
  6669. }
  6670. }
  6671. }
  6672. break;
  6673. case ProcInlining_no_inline:
  6674. break;
  6675. case ProcInlining_none:
  6676. if (proc != nullptr) {
  6677. Entity *e = entity_from_expr(proc);
  6678. if (e != nullptr && e->kind == Entity_Procedure) {
  6679. DeclInfo *decl = e->decl_info;
  6680. if (decl->proc_lit) {
  6681. ast_node(pl, ProcLit, decl->proc_lit);
  6682. if (pl->inlining == ProcInlining_inline) {
  6683. is_call_inlined = true;
  6684. }
  6685. }
  6686. }
  6687. }
  6688. }
  6689. {
  6690. String invalid;
  6691. if (pt->kind == Type_Proc && pt->Proc.require_target_feature.len != 0) {
  6692. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.require_target_feature, &invalid)) {
  6693. error(call, "Called procedure requires target feature '%.*s' which is invalid for the build target", LIT(invalid));
  6694. } else if (!check_target_feature_is_enabled(pt->Proc.require_target_feature, &invalid)) {
  6695. error(call, "Calling this procedure requires target feature '%.*s' to be enabled", LIT(invalid));
  6696. }
  6697. }
  6698. if (pt->kind == Type_Proc && pt->Proc.enable_target_feature.len != 0) {
  6699. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.enable_target_feature, &invalid)) {
  6700. error(call, "Called procedure enables target feature '%.*s' which is invalid for the build target", LIT(invalid));
  6701. }
  6702. // NOTE: Due to restrictions in LLVM you can not inline calls with a superset of features.
  6703. if (is_call_inlined) {
  6704. GB_ASSERT(c->curr_proc_decl);
  6705. GB_ASSERT(c->curr_proc_decl->entity);
  6706. GB_ASSERT(c->curr_proc_decl->entity->type->kind == Type_Proc);
  6707. String scope_features = c->curr_proc_decl->entity->type->Proc.enable_target_feature;
  6708. if (!check_target_feature_is_superset_of(scope_features, pt->Proc.enable_target_feature, &invalid)) {
  6709. error(call, "Inlined procedure enables target feature '%.*s', this requires the calling procedure to at least enable the same feature", LIT(invalid));
  6710. }
  6711. }
  6712. }
  6713. }
  6714. operand->expr = call;
  6715. {
  6716. Type *type = nullptr;
  6717. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6718. type = type_of_expr(operand->expr->CallExpr.proc);
  6719. }
  6720. if (type == nullptr) {
  6721. type = pt;
  6722. }
  6723. type = base_type(type);
  6724. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  6725. operand->mode = Addressing_OptionalOk;
  6726. operand->type = type->Proc.results->Tuple.variables[0]->type;
  6727. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6728. operand->expr->CallExpr.optional_ok_one = true;
  6729. }
  6730. }
  6731. }
  6732. return Expr_Expr;
  6733. }
  6734. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  6735. check_expr_base(c, o, e, t);
  6736. check_not_tuple(c, o);
  6737. char const *err_str = nullptr;
  6738. switch (o->mode) {
  6739. case Addressing_NoValue:
  6740. err_str = "used as a value";
  6741. break;
  6742. case Addressing_Type:
  6743. if (t == nullptr || !is_type_typeid(t)) {
  6744. err_str = "is not an expression but a type, in this context it is ambiguous";
  6745. }
  6746. break;
  6747. case Addressing_Builtin:
  6748. err_str = "must be called";
  6749. break;
  6750. }
  6751. if (err_str != nullptr) {
  6752. gbString str = expr_to_string(e);
  6753. error(e, "'%s' %s", str, err_str);
  6754. gb_string_free(str);
  6755. o->mode = Addressing_Invalid;
  6756. }
  6757. }
  6758. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  6759. switch (t->kind) {
  6760. case Type_Basic:
  6761. if (t->Basic.kind == Basic_string) {
  6762. if (o->mode == Addressing_Constant) {
  6763. *max_count = o->value.value_string.len;
  6764. }
  6765. if (o->mode != Addressing_Constant) {
  6766. o->mode = Addressing_Value;
  6767. }
  6768. o->type = t_u8;
  6769. return true;
  6770. } else if (t->Basic.kind == Basic_UntypedString) {
  6771. if (o->mode == Addressing_Constant) {
  6772. *max_count = o->value.value_string.len;
  6773. o->type = t_u8;
  6774. return true;
  6775. }
  6776. return false;
  6777. }
  6778. break;
  6779. case Type_MultiPointer:
  6780. o->type = t->MultiPointer.elem;
  6781. if (o->mode != Addressing_Constant) {
  6782. o->mode = Addressing_Variable;
  6783. }
  6784. return true;
  6785. case Type_Array:
  6786. *max_count = t->Array.count;
  6787. if (indirection) {
  6788. o->mode = Addressing_Variable;
  6789. } else if (o->mode != Addressing_Variable &&
  6790. o->mode != Addressing_Constant) {
  6791. o->mode = Addressing_Value;
  6792. }
  6793. o->type = t->Array.elem;
  6794. return true;
  6795. case Type_EnumeratedArray:
  6796. *max_count = t->EnumeratedArray.count;
  6797. if (indirection) {
  6798. o->mode = Addressing_Variable;
  6799. } else if (o->mode != Addressing_Variable &&
  6800. o->mode != Addressing_Constant) {
  6801. o->mode = Addressing_Value;
  6802. }
  6803. o->type = t->EnumeratedArray.elem;
  6804. return true;
  6805. case Type_Matrix:
  6806. *max_count = t->Matrix.column_count;
  6807. if (indirection) {
  6808. o->mode = Addressing_Variable;
  6809. } else if (o->mode != Addressing_Variable) {
  6810. o->mode = Addressing_Value;
  6811. }
  6812. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  6813. return true;
  6814. case Type_Slice:
  6815. o->type = t->Slice.elem;
  6816. if (o->mode != Addressing_Constant) {
  6817. o->mode = Addressing_Variable;
  6818. }
  6819. return true;
  6820. case Type_RelativeMultiPointer:
  6821. {
  6822. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  6823. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  6824. o->type = pointer_type->MultiPointer.elem;
  6825. if (o->mode != Addressing_Constant) {
  6826. o->mode = Addressing_Variable;
  6827. }
  6828. }
  6829. return true;
  6830. case Type_DynamicArray:
  6831. o->type = t->DynamicArray.elem;
  6832. if (o->mode != Addressing_Constant) {
  6833. o->mode = Addressing_Variable;
  6834. }
  6835. return true;
  6836. case Type_Struct:
  6837. if (t->Struct.soa_kind != StructSoa_None) {
  6838. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6839. *max_count = t->Struct.soa_count;
  6840. }
  6841. o->type = t->Struct.soa_elem;
  6842. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  6843. o->mode = Addressing_SoaVariable;
  6844. } else {
  6845. o->mode = Addressing_Value;
  6846. }
  6847. return true;
  6848. }
  6849. return false;
  6850. }
  6851. if (is_type_pointer(original_type) && indirection) {
  6852. Type *ptr = base_type(original_type);
  6853. if (ptr->kind == Type_Pointer && o->mode == Addressing_SoaVariable) {
  6854. o->type = ptr->Pointer.elem;
  6855. o->mode = Addressing_Value;
  6856. return true;
  6857. }
  6858. }
  6859. return false;
  6860. }
  6861. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  6862. if (is_type_untyped_uninit(x)) {
  6863. return true;
  6864. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  6865. return true;
  6866. } else if (is_type_untyped_uninit(y)) {
  6867. return true;
  6868. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  6869. return true;
  6870. }
  6871. return are_types_identical(x, y);
  6872. }
  6873. 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) {
  6874. if (!is_ast_range(node)) {
  6875. return false;
  6876. }
  6877. ast_node(ie, BinaryExpr, node);
  6878. check_expr_with_type_hint(c, x, ie->left, type_hint);
  6879. if (x->mode == Addressing_Invalid) {
  6880. return false;
  6881. }
  6882. check_expr_with_type_hint(c, y, ie->right, type_hint);
  6883. if (y->mode == Addressing_Invalid) {
  6884. return false;
  6885. }
  6886. convert_to_typed(c, x, y->type);
  6887. if (x->mode == Addressing_Invalid) {
  6888. return false;
  6889. }
  6890. convert_to_typed(c, y, x->type);
  6891. if (y->mode == Addressing_Invalid) {
  6892. return false;
  6893. }
  6894. convert_to_typed(c, x, default_type(y->type));
  6895. if (x->mode == Addressing_Invalid) {
  6896. return false;
  6897. }
  6898. convert_to_typed(c, y, default_type(x->type));
  6899. if (y->mode == Addressing_Invalid) {
  6900. return false;
  6901. }
  6902. if (!are_types_identical(x->type, y->type)) {
  6903. if (x->type != t_invalid &&
  6904. y->type != t_invalid) {
  6905. gbString xt = type_to_string(x->type);
  6906. gbString yt = type_to_string(y->type);
  6907. gbString expr_str = expr_to_string(x->expr);
  6908. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  6909. gb_string_free(expr_str);
  6910. gb_string_free(yt);
  6911. gb_string_free(xt);
  6912. }
  6913. return false;
  6914. }
  6915. Type *type = x->type;
  6916. if (is_for_loop) {
  6917. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  6918. error(ie->op, "Only numerical types are allowed within interval expressions");
  6919. return false;
  6920. }
  6921. } else {
  6922. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  6923. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  6924. return false;
  6925. }
  6926. }
  6927. if (x->mode == Addressing_Constant &&
  6928. y->mode == Addressing_Constant) {
  6929. ExactValue a = x->value;
  6930. ExactValue b = y->value;
  6931. GB_ASSERT(are_types_identical(x->type, y->type));
  6932. TokenKind op = Token_Lt;
  6933. switch (ie->op.kind) {
  6934. case Token_Ellipsis: op = Token_LtEq; break; // ..
  6935. case Token_RangeFull: op = Token_LtEq; break; // ..=
  6936. case Token_RangeHalf: op = Token_Lt; break; // ..<
  6937. default: error(ie->op, "Invalid range operator"); break;
  6938. }
  6939. bool ok = compare_exact_values(op, a, b);
  6940. if (!ok) {
  6941. // TODO(bill): Better error message
  6942. error(ie->op, "Invalid interval range");
  6943. return false;
  6944. }
  6945. ExactValue inline_for_depth = exact_value_sub(b, a);
  6946. if (ie->op.kind != Token_RangeHalf) {
  6947. inline_for_depth = exact_value_increment_one(inline_for_depth);
  6948. }
  6949. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  6950. } else if (inline_for_depth_ != nullptr) {
  6951. error(ie->op, "Interval expressions must be constant");
  6952. return false;
  6953. }
  6954. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  6955. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  6956. return true;
  6957. }
  6958. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  6959. if (is_operand_nil(*o)) {
  6960. return true;
  6961. }
  6962. Ast *expr = unparen_expr(o->expr);
  6963. if (expr != nullptr) {
  6964. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  6965. if (e != nullptr && e->kind == Entity_Procedure) {
  6966. return true;
  6967. }
  6968. if (expr->kind == Ast_ProcLit) {
  6969. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  6970. return true;
  6971. }
  6972. }
  6973. return o->mode == Addressing_Constant;
  6974. }
  6975. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  6976. if (is_type_enum(th)) {
  6977. Type *enum_type = base_type(th);
  6978. GB_ASSERT(enum_type->kind == Type_Enum);
  6979. String name = ise->selector->Ident.token.string;
  6980. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  6981. if (e == nullptr) {
  6982. return false;
  6983. }
  6984. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  6985. GB_ASSERT(e->kind == Entity_Constant);
  6986. o->value = e->Constant.value;
  6987. o->mode = Addressing_Constant;
  6988. o->type = e->type;
  6989. return true;
  6990. }
  6991. if (is_type_union(th)) {
  6992. TEMPORARY_ALLOCATOR_GUARD();
  6993. Type *union_type = base_type(th);
  6994. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  6995. for (Type *vt : union_type->Union.variants) {
  6996. Operand x = {};
  6997. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  6998. array_add(&operands, x);
  6999. }
  7000. }
  7001. if (operands.count == 1) {
  7002. *o = operands[0];
  7003. return true;
  7004. }
  7005. }
  7006. return false;
  7007. }
  7008. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7009. ast_node(ise, ImplicitSelectorExpr, node);
  7010. o->type = t_invalid;
  7011. o->expr = node;
  7012. o->mode = Addressing_Invalid;
  7013. Type *th = type_hint;
  7014. if (th == nullptr) {
  7015. gbString str = expr_to_string(node);
  7016. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  7017. gb_string_free(str);
  7018. return Expr_Expr;
  7019. }
  7020. o->type = th;
  7021. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  7022. if (!ok) {
  7023. String name = ise->selector->Ident.token.string;
  7024. if (is_type_enum(th)) {
  7025. ERROR_BLOCK();
  7026. Type *bt = base_type(th);
  7027. GB_ASSERT(bt->kind == Type_Enum);
  7028. gbString typ = type_to_string(th);
  7029. defer (gb_string_free(typ));
  7030. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  7031. check_did_you_mean_type(name, bt->Enum.fields);
  7032. } else {
  7033. gbString typ = type_to_string(th);
  7034. gbString str = expr_to_string(node);
  7035. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  7036. gb_string_free(str);
  7037. gb_string_free(typ);
  7038. }
  7039. }
  7040. o->expr = node;
  7041. return Expr_Expr;
  7042. }
  7043. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  7044. switch (x->mode) {
  7045. case Addressing_MapIndex:
  7046. case Addressing_OptionalOk:
  7047. case Addressing_OptionalOkPtr:
  7048. if (val_type_) *val_type_ = x->type;
  7049. break;
  7050. default:
  7051. if (ok_type_) *ok_type_ = x->type;
  7052. return;
  7053. }
  7054. Ast *expr = unparen_expr(x->expr);
  7055. if (expr->kind == Ast_CallExpr) {
  7056. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  7057. if (is_type_proc(pt)) {
  7058. Type *tuple = pt->Proc.results;
  7059. if (pt->Proc.result_count >= 2) {
  7060. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7061. }
  7062. if (change_operand) {
  7063. expr->CallExpr.optional_ok_one = false;
  7064. x->type = tuple;
  7065. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7066. }
  7067. return;
  7068. }
  7069. }
  7070. Type *tuple = make_optional_ok_type(x->type);
  7071. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7072. if (change_operand) {
  7073. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7074. x->type = tuple;
  7075. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  7076. }
  7077. }
  7078. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7079. ast_node(ie, MatrixIndexExpr, node);
  7080. check_expr(c, o, ie->expr);
  7081. node->viral_state_flags |= ie->expr->viral_state_flags;
  7082. if (o->mode == Addressing_Invalid) {
  7083. o->expr = node;
  7084. return;
  7085. }
  7086. Type *t = base_type(type_deref(o->type));
  7087. bool is_ptr = is_type_pointer(o->type);
  7088. bool is_const = o->mode == Addressing_Constant;
  7089. if (t->kind != Type_Matrix) {
  7090. gbString str = expr_to_string(o->expr);
  7091. gbString type_str = type_to_string(o->type);
  7092. defer (gb_string_free(str));
  7093. defer (gb_string_free(type_str));
  7094. if (is_const) {
  7095. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  7096. } else {
  7097. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  7098. }
  7099. o->mode = Addressing_Invalid;
  7100. o->expr = node;
  7101. return;
  7102. }
  7103. o->type = t->Matrix.elem;
  7104. if (is_ptr) {
  7105. o->mode = Addressing_Variable;
  7106. } else if (o->mode != Addressing_Variable) {
  7107. o->mode = Addressing_Value;
  7108. }
  7109. if (ie->row_index == nullptr) {
  7110. gbString str = expr_to_string(o->expr);
  7111. error(o->expr, "Missing row index for '%s'", str);
  7112. gb_string_free(str);
  7113. o->mode = Addressing_Invalid;
  7114. o->expr = node;
  7115. return;
  7116. }
  7117. if (ie->column_index == nullptr) {
  7118. gbString str = expr_to_string(o->expr);
  7119. error(o->expr, "Missing column index for '%s'", str);
  7120. gb_string_free(str);
  7121. o->mode = Addressing_Invalid;
  7122. o->expr = node;
  7123. return;
  7124. }
  7125. i64 row_count = t->Matrix.row_count;
  7126. i64 column_count = t->Matrix.column_count;
  7127. i64 row_index = 0;
  7128. i64 column_index = 0;
  7129. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7130. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7131. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7132. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7133. }
  7134. gb_unused(row_ok);
  7135. gb_unused(column_ok);
  7136. }
  7137. struct TypeAndToken {
  7138. Type *type;
  7139. Token token;
  7140. };
  7141. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7142. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7143. if (operand.mode != Addressing_Constant) {
  7144. return;
  7145. }
  7146. if (operand.value.kind == ExactValue_Invalid) {
  7147. return;
  7148. }
  7149. uintptr key = hash_exact_value(operand.value);
  7150. GB_ASSERT(key != 0);
  7151. isize count = multi_map_count(seen, key);
  7152. if (count) {
  7153. TEMPORARY_ALLOCATOR_GUARD();
  7154. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  7155. multi_map_get_all(seen, key, taps);
  7156. for (isize i = 0; i < count; i++) {
  7157. TypeAndToken tap = taps[i];
  7158. Operand to = {};
  7159. to.mode = Addressing_Value;
  7160. to.type = tap.type;
  7161. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7162. continue;
  7163. }
  7164. TokenPos pos = tap.token.pos;
  7165. if (use_expr) {
  7166. gbString expr_str = expr_to_string(operand.expr);
  7167. error(operand.expr,
  7168. "Duplicate case '%s'\n"
  7169. "\tprevious case at %s",
  7170. expr_str,
  7171. token_pos_to_string(pos));
  7172. gb_string_free(expr_str);
  7173. } else {
  7174. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7175. }
  7176. return;
  7177. }
  7178. }
  7179. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7180. multi_map_insert(seen, key, tap);
  7181. }
  7182. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7183. if (is_type_enum(x.type)) {
  7184. // TODO(bill): Fix this logic so it's fast!!!
  7185. i64 v0 = exact_value_to_i64(lhs.value);
  7186. i64 v1 = exact_value_to_i64(rhs.value);
  7187. Operand v = {};
  7188. v.mode = Addressing_Constant;
  7189. v.type = x.type;
  7190. v.expr = x.expr;
  7191. Type *bt = base_type(x.type);
  7192. GB_ASSERT(bt->kind == Type_Enum);
  7193. for (i64 vi = v0; vi <= v1; vi++) {
  7194. if (upper_op != Token_LtEq && vi == v1) {
  7195. break;
  7196. }
  7197. v.value = exact_value_i64(vi);
  7198. add_constant_switch_case(ctx, seen, v);
  7199. }
  7200. } else {
  7201. add_constant_switch_case(ctx, seen, lhs);
  7202. if (upper_op == Token_LtEq) {
  7203. add_constant_switch_case(ctx, seen, rhs);
  7204. }
  7205. }
  7206. }
  7207. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7208. add_constant_switch_case(ctx, seen, x);
  7209. }
  7210. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7211. ast_node(bd, BasicDirective, node);
  7212. ExprKind kind = Expr_Expr;
  7213. o->mode = Addressing_Constant;
  7214. String name = bd->name.string;
  7215. if (name == "file") {
  7216. String file = get_file_path_string(bd->token.pos.file_id);
  7217. if (build_context.obfuscate_source_code_locations) {
  7218. file = obfuscate_string(file, "F");
  7219. }
  7220. o->type = t_untyped_string;
  7221. o->value = exact_value_string(file);
  7222. } else if (name == "line") {
  7223. i32 line = bd->token.pos.line;
  7224. if (build_context.obfuscate_source_code_locations) {
  7225. line = obfuscate_i32(line);
  7226. }
  7227. o->type = t_untyped_integer;
  7228. o->value = exact_value_i64(line);
  7229. } else if (name == "procedure") {
  7230. if (c->curr_proc_decl == nullptr) {
  7231. error(node, "#procedure may only be used within procedures");
  7232. o->type = t_untyped_string;
  7233. o->value = exact_value_string(str_lit(""));
  7234. } else {
  7235. String p = c->proc_name;
  7236. if (build_context.obfuscate_source_code_locations) {
  7237. p = obfuscate_string(p, "P");
  7238. }
  7239. o->type = t_untyped_string;
  7240. o->value = exact_value_string(p);
  7241. }
  7242. } else if (name == "caller_location") {
  7243. init_core_source_code_location(c->checker);
  7244. error(node, "#caller_location may only be used as a default argument parameter");
  7245. o->type = t_source_code_location;
  7246. o->mode = Addressing_Value;
  7247. } else {
  7248. if (name == "location") {
  7249. init_core_source_code_location(c->checker);
  7250. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  7251. o->type = t_source_code_location;
  7252. o->mode = Addressing_Value;
  7253. } else if (
  7254. name == "assert" ||
  7255. name == "defined" ||
  7256. name == "config" ||
  7257. name == "load" ||
  7258. name == "load_hash" ||
  7259. name == "load_directory" ||
  7260. name == "load_or"
  7261. ) {
  7262. error(node, "'#%.*s' must be used as a call", LIT(name));
  7263. o->type = t_invalid;
  7264. o->mode = Addressing_Invalid;
  7265. } else {
  7266. error(node, "Unknown directive: #%.*s", LIT(name));
  7267. o->type = t_invalid;
  7268. o->mode = Addressing_Invalid;
  7269. }
  7270. }
  7271. return kind;
  7272. }
  7273. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7274. ExprKind kind = Expr_Expr;
  7275. Operand cond = {Addressing_Invalid};
  7276. ast_node(te, TernaryIfExpr, node);
  7277. check_expr(c, &cond, te->cond);
  7278. node->viral_state_flags |= te->cond->viral_state_flags;
  7279. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7280. error(te->cond, "Non-boolean condition in ternary if expression");
  7281. }
  7282. Operand x = {Addressing_Invalid};
  7283. Operand y = {Addressing_Invalid};
  7284. check_expr_or_type(c, &x, te->x, type_hint);
  7285. node->viral_state_flags |= te->x->viral_state_flags;
  7286. if (te->y != nullptr) {
  7287. Type *th = type_hint;
  7288. if (type_hint == nullptr && is_type_typed(x.type)) {
  7289. th = x.type;
  7290. }
  7291. check_expr_or_type(c, &y, te->y, th);
  7292. node->viral_state_flags |= te->y->viral_state_flags;
  7293. } else {
  7294. error(node, "A ternary expression must have an else clause");
  7295. return kind;
  7296. }
  7297. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7298. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7299. gbString type_string = expr_to_string(type_expr);
  7300. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7301. gb_string_free(type_string);
  7302. return kind;
  7303. }
  7304. if (x.type == nullptr || x.type == t_invalid ||
  7305. y.type == nullptr || y.type == t_invalid) {
  7306. return kind;
  7307. }
  7308. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7309. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7310. if (x.mode == Addressing_Invalid) {
  7311. return kind;
  7312. }
  7313. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7314. if (y.mode == Addressing_Invalid) {
  7315. x.mode = Addressing_Invalid;
  7316. return kind;
  7317. }
  7318. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7319. // x: union{f32} = f32(123) if cond else nil
  7320. if (type_hint && !is_type_any(type_hint)) {
  7321. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7322. check_cast(c, &x, type_hint);
  7323. check_cast(c, &y, type_hint);
  7324. }
  7325. }
  7326. if (!ternary_compare_types(x.type, y.type)) {
  7327. gbString its = type_to_string(x.type);
  7328. gbString ets = type_to_string(y.type);
  7329. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7330. gb_string_free(ets);
  7331. gb_string_free(its);
  7332. return kind;
  7333. }
  7334. o->type = x.type;
  7335. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  7336. o->type = y.type;
  7337. }
  7338. o->mode = Addressing_Value;
  7339. o->expr = node;
  7340. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7341. if (check_cast_internal(c, &x, type_hint) &&
  7342. check_cast_internal(c, &y, type_hint)) {
  7343. convert_to_typed(c, o, type_hint);
  7344. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7345. o->type = type_hint;
  7346. }
  7347. }
  7348. return kind;
  7349. }
  7350. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7351. ExprKind kind = Expr_Expr;
  7352. Operand cond = {};
  7353. ast_node(te, TernaryWhenExpr, node);
  7354. check_expr(c, &cond, te->cond);
  7355. node->viral_state_flags |= te->cond->viral_state_flags;
  7356. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7357. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7358. return kind;
  7359. }
  7360. if (cond.value.value_bool) {
  7361. check_expr_or_type(c, o, te->x, type_hint);
  7362. node->viral_state_flags |= te->x->viral_state_flags;
  7363. } else {
  7364. if (te->y != nullptr) {
  7365. check_expr_or_type(c, o, te->y, type_hint);
  7366. node->viral_state_flags |= te->y->viral_state_flags;
  7367. } else {
  7368. error(node, "A ternary when expression must have an else clause");
  7369. return kind;
  7370. }
  7371. }
  7372. return kind;
  7373. }
  7374. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7375. ast_node(oe, OrElseExpr, node);
  7376. String name = oe->token.string;
  7377. Ast *arg = oe->x;
  7378. Ast *default_value = oe->y;
  7379. Operand x = {};
  7380. Operand y = {};
  7381. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7382. if (is_load_directive_call(arg)) {
  7383. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7384. // Allow for chaining of '#load(path) or_else #load(path)'
  7385. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  7386. bool y_is_diverging = false;
  7387. check_expr_base(c, &y, default_value, x.type);
  7388. switch (y.mode) {
  7389. case Addressing_NoValue:
  7390. if (is_diverging_expr(y.expr)) {
  7391. // Allow
  7392. y.mode = Addressing_Value;
  7393. y_is_diverging = true;
  7394. } else {
  7395. error_operand_no_value(&y);
  7396. y.mode = Addressing_Invalid;
  7397. }
  7398. break;
  7399. case Addressing_Type:
  7400. error_operand_not_expression(&y);
  7401. y.mode = Addressing_Invalid;
  7402. break;
  7403. }
  7404. if (y.mode == Addressing_Invalid) {
  7405. o->mode = Addressing_Value;
  7406. o->type = t_invalid;
  7407. o->expr = node;
  7408. return Expr_Expr;
  7409. }
  7410. if (!y_is_diverging) {
  7411. check_assignment(c, &y, x.type, name);
  7412. if (y.mode != Addressing_Constant) {
  7413. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7414. }
  7415. }
  7416. }
  7417. if (res == LoadDirective_Success) {
  7418. *o = x;
  7419. } else {
  7420. *o = y;
  7421. }
  7422. o->expr = node;
  7423. return Expr_Expr;
  7424. }
  7425. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7426. if (x.mode == Addressing_Invalid) {
  7427. o->mode = Addressing_Value;
  7428. o->type = t_invalid;
  7429. o->expr = node;
  7430. return Expr_Expr;
  7431. }
  7432. bool y_is_diverging = false;
  7433. check_expr_base(c, &y, default_value, x.type);
  7434. switch (y.mode) {
  7435. case Addressing_NoValue:
  7436. if (is_diverging_expr(y.expr)) {
  7437. // Allow
  7438. y.mode = Addressing_Value;
  7439. y_is_diverging = true;
  7440. } else {
  7441. error_operand_no_value(&y);
  7442. y.mode = Addressing_Invalid;
  7443. }
  7444. break;
  7445. case Addressing_Type:
  7446. error_operand_not_expression(&y);
  7447. y.mode = Addressing_Invalid;
  7448. break;
  7449. }
  7450. if (y.mode == Addressing_Invalid) {
  7451. o->mode = Addressing_Value;
  7452. o->type = t_invalid;
  7453. o->expr = node;
  7454. return Expr_Expr;
  7455. }
  7456. Type *left_type = nullptr;
  7457. Type *right_type = nullptr;
  7458. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7459. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7460. if (left_type != nullptr) {
  7461. if (!y_is_diverging) {
  7462. check_assignment(c, &y, left_type, name);
  7463. }
  7464. } else {
  7465. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7466. }
  7467. if (left_type == nullptr) {
  7468. left_type = t_invalid;
  7469. }
  7470. o->mode = Addressing_Value;
  7471. o->type = left_type;
  7472. o->expr = node;
  7473. return Expr_Expr;
  7474. }
  7475. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7476. ast_node(re, OrReturnExpr, node);
  7477. String name = re->token.string;
  7478. Operand x = {};
  7479. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  7480. if (x.mode == Addressing_Invalid) {
  7481. o->mode = Addressing_Value;
  7482. o->type = t_invalid;
  7483. o->expr = node;
  7484. return Expr_Expr;
  7485. }
  7486. Type *left_type = nullptr;
  7487. Type *right_type = nullptr;
  7488. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7489. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  7490. if (right_type == nullptr) {
  7491. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7492. } else {
  7493. Type *proc_type = base_type(c->curr_proc_sig);
  7494. GB_ASSERT(proc_type->kind == Type_Proc);
  7495. Type *result_type = proc_type->Proc.results;
  7496. if (result_type == nullptr) {
  7497. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  7498. } else {
  7499. GB_ASSERT(result_type->kind == Type_Tuple);
  7500. auto const &vars = result_type->Tuple.variables;
  7501. Type *end_type = vars[vars.count-1]->type;
  7502. if (vars.count > 1) {
  7503. if (!proc_type->Proc.has_named_results) {
  7504. 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));
  7505. }
  7506. }
  7507. Operand rhs = {};
  7508. rhs.type = right_type;
  7509. rhs.mode = Addressing_Value;
  7510. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  7511. // NOTE(bill): allow implicit conversion between boolean types
  7512. // within 'or_return' to improve the experience using third-party code
  7513. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  7514. ERROR_BLOCK();
  7515. // TODO(bill): better error message
  7516. gbString a = type_to_string(right_type);
  7517. gbString b = type_to_string(end_type);
  7518. gbString ret_type = type_to_string(result_type);
  7519. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  7520. if (vars.count == 1) {
  7521. error_line("\tProcedure return value type: %s\n", ret_type);
  7522. } else {
  7523. error_line("\tProcedure return value types: (%s)\n", ret_type);
  7524. }
  7525. gb_string_free(ret_type);
  7526. gb_string_free(b);
  7527. gb_string_free(a);
  7528. }
  7529. }
  7530. }
  7531. o->expr = node;
  7532. o->type = left_type;
  7533. if (left_type != nullptr) {
  7534. o->mode = Addressing_Value;
  7535. } else {
  7536. o->mode = Addressing_NoValue;
  7537. }
  7538. if (c->curr_proc_sig == nullptr) {
  7539. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7540. }
  7541. if (c->in_defer) {
  7542. error(node, "'or_return' cannot be used within a defer statement");
  7543. }
  7544. return Expr_Expr;
  7545. }
  7546. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7547. ast_node(be, OrBranchExpr, node);
  7548. String name = be->token.string;
  7549. Operand x = {};
  7550. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  7551. if (x.mode == Addressing_Invalid) {
  7552. o->mode = Addressing_Value;
  7553. o->type = t_invalid;
  7554. o->expr = node;
  7555. return Expr_Expr;
  7556. }
  7557. Type *left_type = nullptr;
  7558. Type *right_type = nullptr;
  7559. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7560. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  7561. if (right_type == nullptr) {
  7562. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7563. } else {
  7564. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  7565. // okay
  7566. } else {
  7567. gbString s = type_to_string(right_type);
  7568. error(node, "'%.*s' requires a boolean or nil-able type, got %s", s);
  7569. gb_string_free(s);
  7570. }
  7571. }
  7572. o->expr = node;
  7573. o->type = left_type;
  7574. if (left_type != nullptr) {
  7575. o->mode = Addressing_Value;
  7576. } else {
  7577. o->mode = Addressing_NoValue;
  7578. }
  7579. if (c->curr_proc_sig == nullptr) {
  7580. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7581. }
  7582. Ast *label = be->label;
  7583. switch (be->token.kind) {
  7584. case Token_or_break:
  7585. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  7586. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  7587. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  7588. }
  7589. break;
  7590. case Token_or_continue:
  7591. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  7592. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  7593. }
  7594. break;
  7595. }
  7596. if (label != nullptr) {
  7597. if (label->kind != Ast_Ident) {
  7598. error(label, "A branch statement's label name must be an identifier");
  7599. return Expr_Expr;
  7600. }
  7601. Ast *ident = label;
  7602. String name = ident->Ident.token.string;
  7603. Operand o = {};
  7604. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  7605. if (e == nullptr) {
  7606. error(ident, "Undeclared label name: %.*s", LIT(name));
  7607. return Expr_Expr;
  7608. }
  7609. add_entity_use(c, ident, e);
  7610. if (e->kind != Entity_Label) {
  7611. error(ident, "'%.*s' is not a label", LIT(name));
  7612. return Expr_Expr;
  7613. }
  7614. Ast *parent = e->Label.parent;
  7615. GB_ASSERT(parent != nullptr);
  7616. switch (parent->kind) {
  7617. case Ast_BlockStmt:
  7618. case Ast_IfStmt:
  7619. case Ast_SwitchStmt:
  7620. if (be->token.kind != Token_or_break) {
  7621. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  7622. }
  7623. break;
  7624. case Ast_RangeStmt:
  7625. case Ast_ForStmt:
  7626. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  7627. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  7628. }
  7629. break;
  7630. }
  7631. }
  7632. return Expr_Expr;
  7633. }
  7634. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  7635. Type *bt = base_type(type);
  7636. StringSet fields_visited = {};
  7637. defer (string_set_destroy(&fields_visited));
  7638. StringMap<String> fields_visited_through_raw_union = {};
  7639. defer (string_map_destroy(&fields_visited_through_raw_union));
  7640. String assignment_str = str_lit("structure literal");
  7641. if (bt->kind == Type_BitField) {
  7642. assignment_str = str_lit("bit_field literal");
  7643. }
  7644. for (Ast *elem : elems) {
  7645. if (elem->kind != Ast_FieldValue) {
  7646. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7647. continue;
  7648. }
  7649. ast_node(fv, FieldValue, elem);
  7650. Ast *ident = fv->field;
  7651. if (ident->kind == Ast_ImplicitSelectorExpr) {
  7652. gbString expr_str = expr_to_string(ident);
  7653. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  7654. gb_string_free(expr_str);
  7655. ident = ident->ImplicitSelectorExpr.selector;
  7656. }
  7657. if (ident->kind != Ast_Ident) {
  7658. gbString expr_str = expr_to_string(ident);
  7659. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  7660. gb_string_free(expr_str);
  7661. continue;
  7662. }
  7663. String name = ident->Ident.token.string;
  7664. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7665. bool is_unknown = sel.entity == nullptr;
  7666. if (is_unknown) {
  7667. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  7668. continue;
  7669. }
  7670. Entity *field = nullptr;
  7671. if (bt->kind == Type_Struct) {
  7672. field = bt->Struct.fields[sel.index[0]];
  7673. } else if (bt->kind == Type_BitField) {
  7674. field = bt->BitField.fields[sel.index[0]];
  7675. } else {
  7676. GB_PANIC("Unknown type");
  7677. }
  7678. add_entity_use(c, ident, field);
  7679. if (string_set_update(&fields_visited, name)) {
  7680. if (sel.index.count > 1) {
  7681. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7682. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7683. } else {
  7684. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  7685. }
  7686. } else {
  7687. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  7688. }
  7689. continue;
  7690. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7691. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7692. continue;
  7693. }
  7694. if (sel.indirect) {
  7695. 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));
  7696. continue;
  7697. }
  7698. if (sel.index.count > 1) {
  7699. GB_ASSERT(bt->kind == Type_Struct);
  7700. if (is_constant) {
  7701. Type *ft = type;
  7702. for (i32 index : sel.index) {
  7703. Type *bt = base_type(ft);
  7704. switch (bt->kind) {
  7705. case Type_Struct:
  7706. if (bt->Struct.is_raw_union) {
  7707. is_constant = false;
  7708. break;
  7709. }
  7710. ft = bt->Struct.fields[index]->type;
  7711. break;
  7712. case Type_Array:
  7713. ft = bt->Array.elem;
  7714. break;
  7715. default:
  7716. GB_PANIC("invalid type: %s", type_to_string(ft));
  7717. break;
  7718. }
  7719. }
  7720. if (is_constant &&
  7721. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  7722. is_constant = false;
  7723. }
  7724. }
  7725. Type *nested_ft = bt;
  7726. for (i32 index : sel.index) {
  7727. Type *bt = base_type(nested_ft);
  7728. switch (bt->kind) {
  7729. case Type_Struct:
  7730. if (bt->Struct.is_raw_union) {
  7731. for (Entity *re : bt->Struct.fields) {
  7732. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  7733. }
  7734. }
  7735. nested_ft = bt->Struct.fields[index]->type;
  7736. break;
  7737. case Type_Array:
  7738. nested_ft = bt->Array.elem;
  7739. break;
  7740. default:
  7741. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  7742. break;
  7743. }
  7744. }
  7745. field = sel.entity;
  7746. }
  7747. Operand o = {};
  7748. check_expr_or_type(c, &o, fv->value, field->type);
  7749. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7750. is_constant = false;
  7751. }
  7752. if (is_constant) {
  7753. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7754. }
  7755. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  7756. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  7757. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  7758. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  7759. }
  7760. check_assignment(c, &o, field->type, assignment_str);
  7761. c->bit_field_bit_size = prev_bit_field_bit_size;
  7762. }
  7763. }
  7764. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  7765. type_expr = unparen_expr(type_expr);
  7766. if (type_expr == nullptr) {
  7767. return false;
  7768. }
  7769. // [?]Type
  7770. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  7771. Ast *count = type_expr->ArrayType.count;
  7772. if (count->kind == Ast_UnaryExpr &&
  7773. count->UnaryExpr.op.kind == Token_Question) {
  7774. return true;
  7775. }
  7776. }
  7777. return false;
  7778. }
  7779. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7780. ExprKind kind = Expr_Expr;
  7781. ast_node(cl, CompoundLit, node);
  7782. Type *type = type_hint;
  7783. if (type != nullptr && is_type_untyped(type)) {
  7784. type = nullptr;
  7785. }
  7786. bool is_to_be_determined_array_count = false;
  7787. bool is_constant = true;
  7788. Ast *type_expr = cl->type;
  7789. bool used_type_hint_expr = false;
  7790. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  7791. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  7792. type_expr = clone_ast(c->type_hint_expr);
  7793. used_type_hint_expr = true;
  7794. }
  7795. }
  7796. if (type_expr != nullptr) {
  7797. type = nullptr;
  7798. // [?]Type
  7799. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  7800. Ast *count = type_expr->ArrayType.count;
  7801. if (count->kind == Ast_UnaryExpr &&
  7802. count->UnaryExpr.op.kind == Token_Question) {
  7803. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  7804. is_to_be_determined_array_count = true;
  7805. }
  7806. if (cl->elems.count > 0) {
  7807. if (type_expr->ArrayType.tag != nullptr) {
  7808. Ast *tag = type_expr->ArrayType.tag;
  7809. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7810. String name = tag->BasicDirective.name.string;
  7811. if (name == "soa") {
  7812. error(node, "#soa arrays are not supported for compound literals");
  7813. return kind;
  7814. }
  7815. }
  7816. }
  7817. }
  7818. if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  7819. if (cl->elems.count > 0) {
  7820. Ast *tag = type_expr->DynamicArrayType.tag;
  7821. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7822. String name = tag->BasicDirective.name.string;
  7823. if (name == "soa") {
  7824. error(node, "#soa arrays are not supported for compound literals");
  7825. return kind;
  7826. }
  7827. }
  7828. }
  7829. if (type == nullptr) {
  7830. type = check_type(c, type_expr);
  7831. }
  7832. }
  7833. if (type == nullptr) {
  7834. error(node, "Missing type in compound literal");
  7835. return kind;
  7836. }
  7837. Type *t = base_type(type);
  7838. if (is_type_polymorphic(t)) {
  7839. gbString str = type_to_string(type);
  7840. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  7841. o->expr = node;
  7842. o->type = type;
  7843. gb_string_free(str);
  7844. return kind;
  7845. }
  7846. switch (t->kind) {
  7847. case Type_Struct: {
  7848. if (cl->elems.count == 0) {
  7849. break; // NOTE(bill): No need to init
  7850. }
  7851. if (t->Struct.is_raw_union) {
  7852. if (cl->elems.count > 0) {
  7853. // NOTE: unions cannot be constant
  7854. is_constant = false;
  7855. if (cl->elems[0]->kind != Ast_FieldValue) {
  7856. gbString type_str = type_to_string(type);
  7857. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  7858. gb_string_free(type_str);
  7859. } else {
  7860. if (cl->elems.count != 1) {
  7861. gbString type_str = type_to_string(type);
  7862. 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);
  7863. gb_string_free(type_str);
  7864. } else {
  7865. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7866. }
  7867. }
  7868. }
  7869. break;
  7870. }
  7871. wait_signal_until_available(&t->Struct.fields_wait_signal);
  7872. isize field_count = t->Struct.fields.count;
  7873. isize min_field_count = t->Struct.fields.count;
  7874. for (isize i = min_field_count-1; i >= 0; i--) {
  7875. Entity *e = t->Struct.fields[i];
  7876. GB_ASSERT(e->kind == Entity_Variable);
  7877. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  7878. min_field_count--;
  7879. } else {
  7880. break;
  7881. }
  7882. }
  7883. if (cl->elems[0]->kind == Ast_FieldValue) {
  7884. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7885. } else {
  7886. bool seen_field_value = false;
  7887. for_array(index, cl->elems) {
  7888. Entity *field = nullptr;
  7889. Ast *elem = cl->elems[index];
  7890. if (elem->kind == Ast_FieldValue) {
  7891. seen_field_value = true;
  7892. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7893. continue;
  7894. } else if (seen_field_value) {
  7895. error(elem, "Value elements cannot be used after a 'field = value'");
  7896. continue;
  7897. }
  7898. if (index >= field_count) {
  7899. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7900. break;
  7901. }
  7902. if (field == nullptr) {
  7903. field = t->Struct.fields[index];
  7904. }
  7905. Operand o = {};
  7906. check_expr_or_type(c, &o, elem, field->type);
  7907. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7908. is_constant = false;
  7909. }
  7910. if (is_constant) {
  7911. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7912. }
  7913. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7914. }
  7915. if (cl->elems.count < field_count) {
  7916. if (min_field_count < field_count) {
  7917. if (cl->elems.count < min_field_count) {
  7918. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  7919. }
  7920. } else {
  7921. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7922. }
  7923. }
  7924. }
  7925. break;
  7926. }
  7927. case Type_Slice:
  7928. case Type_Array:
  7929. case Type_DynamicArray:
  7930. case Type_SimdVector:
  7931. case Type_Matrix:
  7932. {
  7933. Type *elem_type = nullptr;
  7934. String context_name = {};
  7935. i64 max_type_count = -1;
  7936. if (t->kind == Type_Slice) {
  7937. elem_type = t->Slice.elem;
  7938. context_name = str_lit("slice literal");
  7939. } else if (t->kind == Type_Array) {
  7940. elem_type = t->Array.elem;
  7941. context_name = str_lit("array literal");
  7942. if (!is_to_be_determined_array_count) {
  7943. max_type_count = t->Array.count;
  7944. }
  7945. } else if (t->kind == Type_DynamicArray) {
  7946. elem_type = t->DynamicArray.elem;
  7947. context_name = str_lit("dynamic array literal");
  7948. is_constant = false;
  7949. if (!build_context.no_dynamic_literals) {
  7950. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  7951. add_package_dependency(c, "runtime", "__dynamic_array_append");
  7952. }
  7953. } else if (t->kind == Type_SimdVector) {
  7954. elem_type = t->SimdVector.elem;
  7955. context_name = str_lit("simd vector literal");
  7956. max_type_count = t->SimdVector.count;
  7957. } else if (t->kind == Type_Matrix) {
  7958. elem_type = t->Matrix.elem;
  7959. context_name = str_lit("matrix literal");
  7960. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  7961. } else {
  7962. GB_PANIC("unreachable");
  7963. }
  7964. i64 max = 0;
  7965. Type *bet = base_type(elem_type);
  7966. if (!elem_type_can_be_constant(bet)) {
  7967. is_constant = false;
  7968. }
  7969. if (bet == t_invalid) {
  7970. break;
  7971. }
  7972. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7973. RangeCache rc = range_cache_make(heap_allocator());
  7974. defer (range_cache_destroy(&rc));
  7975. for (Ast *elem : cl->elems) {
  7976. if (elem->kind != Ast_FieldValue) {
  7977. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7978. continue;
  7979. }
  7980. ast_node(fv, FieldValue, elem);
  7981. if (is_ast_range(fv->field)) {
  7982. Token op = fv->field->BinaryExpr.op;
  7983. Operand x = {};
  7984. Operand y = {};
  7985. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  7986. if (!ok) {
  7987. continue;
  7988. }
  7989. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  7990. error(x.expr, "Expected a constant integer as an array field");
  7991. continue;
  7992. }
  7993. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  7994. error(y.expr, "Expected a constant integer as an array field");
  7995. continue;
  7996. }
  7997. i64 lo = exact_value_to_i64(x.value);
  7998. i64 hi = exact_value_to_i64(y.value);
  7999. i64 max_index = hi;
  8000. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  8001. hi -= 1;
  8002. } else { // .. (inclusive)
  8003. max_index += 1;
  8004. }
  8005. bool new_range = range_cache_add_range(&rc, lo, hi);
  8006. if (!new_range) {
  8007. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  8008. continue;
  8009. }
  8010. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  8011. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  8012. continue;
  8013. }
  8014. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  8015. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  8016. continue;
  8017. }
  8018. if (max < hi) {
  8019. max = max_index;
  8020. }
  8021. Operand operand = {};
  8022. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8023. check_assignment(c, &operand, elem_type, context_name);
  8024. is_constant = is_constant && operand.mode == Addressing_Constant;
  8025. } else {
  8026. Operand op_index = {};
  8027. check_expr(c, &op_index, fv->field);
  8028. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  8029. error(elem, "Expected a constant integer as an array field");
  8030. continue;
  8031. }
  8032. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  8033. i64 index = exact_value_to_i64(op_index.value);
  8034. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  8035. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  8036. continue;
  8037. }
  8038. bool new_index = range_cache_add_index(&rc, index);
  8039. if (!new_index) {
  8040. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  8041. continue;
  8042. }
  8043. if (max < index+1) {
  8044. max = index+1;
  8045. }
  8046. Operand operand = {};
  8047. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8048. check_assignment(c, &operand, elem_type, context_name);
  8049. is_constant = is_constant && operand.mode == Addressing_Constant;
  8050. }
  8051. }
  8052. cl->max_count = max;
  8053. } else {
  8054. isize index = 0;
  8055. for (; index < cl->elems.count; index++) {
  8056. Ast *e = cl->elems[index];
  8057. if (e == nullptr) {
  8058. error(node, "Invalid literal element");
  8059. continue;
  8060. }
  8061. if (e->kind == Ast_FieldValue) {
  8062. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8063. continue;
  8064. }
  8065. if (0 <= max_type_count && max_type_count <= index) {
  8066. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8067. }
  8068. Operand operand = {};
  8069. check_expr_with_type_hint(c, &operand, e, elem_type);
  8070. check_assignment(c, &operand, elem_type, context_name);
  8071. is_constant = is_constant && operand.mode == Addressing_Constant;
  8072. }
  8073. if (max < index) {
  8074. max = index;
  8075. }
  8076. }
  8077. if (t->kind == Type_Array) {
  8078. if (is_to_be_determined_array_count) {
  8079. t->Array.count = max;
  8080. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8081. if (0 < max && max < t->Array.count) {
  8082. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8083. }
  8084. }
  8085. }
  8086. if (t->kind == Type_SimdVector) {
  8087. if (!is_constant) {
  8088. // error(node, "Expected all constant elements for a simd vector");
  8089. }
  8090. }
  8091. if (t->kind == Type_DynamicArray) {
  8092. if (build_context.no_dynamic_literals && cl->elems.count) {
  8093. error(node, "Compound literals of dynamic types have been disabled");
  8094. }
  8095. }
  8096. if (t->kind == Type_Matrix) {
  8097. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8098. if (0 < max && max < max_type_count) {
  8099. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  8100. }
  8101. }
  8102. }
  8103. break;
  8104. }
  8105. case Type_EnumeratedArray:
  8106. {
  8107. Type *elem_type = t->EnumeratedArray.elem;
  8108. Type *index_type = t->EnumeratedArray.index;
  8109. String context_name = str_lit("enumerated array literal");
  8110. i64 max_type_count = t->EnumeratedArray.count;
  8111. gbString index_type_str = type_to_string(index_type);
  8112. defer (gb_string_free(index_type_str));
  8113. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  8114. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  8115. String total_lo_string = {};
  8116. String total_hi_string = {};
  8117. GB_ASSERT(is_type_enum(index_type));
  8118. {
  8119. Type *bt = base_type(index_type);
  8120. GB_ASSERT(bt->kind == Type_Enum);
  8121. for (Entity *f : bt->Enum.fields) {
  8122. if (f->kind != Entity_Constant) {
  8123. continue;
  8124. }
  8125. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  8126. total_lo_string = f->token.string;
  8127. }
  8128. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  8129. total_hi_string = f->token.string;
  8130. }
  8131. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8132. break;
  8133. }
  8134. }
  8135. }
  8136. i64 max = 0;
  8137. Type *bet = base_type(elem_type);
  8138. if (!elem_type_can_be_constant(bet)) {
  8139. is_constant = false;
  8140. }
  8141. if (bet == t_invalid) {
  8142. break;
  8143. }
  8144. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8145. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8146. defer (map_destroy(&seen));
  8147. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8148. RangeCache rc = range_cache_make(heap_allocator());
  8149. defer (range_cache_destroy(&rc));
  8150. for (Ast *elem : cl->elems) {
  8151. if (elem->kind != Ast_FieldValue) {
  8152. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8153. continue;
  8154. }
  8155. ast_node(fv, FieldValue, elem);
  8156. if (is_ast_range(fv->field)) {
  8157. Token op = fv->field->BinaryExpr.op;
  8158. Operand x = {};
  8159. Operand y = {};
  8160. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8161. if (!ok) {
  8162. continue;
  8163. }
  8164. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8165. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8166. continue;
  8167. }
  8168. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8169. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8170. continue;
  8171. }
  8172. i64 lo = exact_value_to_i64(x.value);
  8173. i64 hi = exact_value_to_i64(y.value);
  8174. i64 max_index = hi;
  8175. if (op.kind == Token_RangeHalf) {
  8176. hi -= 1;
  8177. }
  8178. bool new_range = range_cache_add_range(&rc, lo, hi);
  8179. if (!new_range) {
  8180. gbString lo_str = expr_to_string(x.expr);
  8181. gbString hi_str = expr_to_string(y.expr);
  8182. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8183. gb_string_free(hi_str);
  8184. gb_string_free(lo_str);
  8185. continue;
  8186. }
  8187. // NOTE(bill): These are sanity checks for invalid enum values
  8188. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8189. gbString lo_str = expr_to_string(x.expr);
  8190. 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));
  8191. gb_string_free(lo_str);
  8192. continue;
  8193. }
  8194. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8195. gbString hi_str = expr_to_string(y.expr);
  8196. 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));
  8197. gb_string_free(hi_str);
  8198. continue;
  8199. }
  8200. if (max < hi) {
  8201. max = max_index;
  8202. }
  8203. Operand operand = {};
  8204. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8205. check_assignment(c, &operand, elem_type, context_name);
  8206. is_constant = is_constant && operand.mode == Addressing_Constant;
  8207. TokenKind upper_op = Token_LtEq;
  8208. if (op.kind == Token_RangeHalf) {
  8209. upper_op = Token_Lt;
  8210. }
  8211. add_to_seen_map(c, &seen, upper_op, x, x, y);
  8212. } else {
  8213. Operand op_index = {};
  8214. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8215. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8216. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8217. continue;
  8218. }
  8219. i64 index = exact_value_to_i64(op_index.value);
  8220. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8221. gbString idx_str = expr_to_string(op_index.expr);
  8222. 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));
  8223. gb_string_free(idx_str);
  8224. continue;
  8225. }
  8226. bool new_index = range_cache_add_index(&rc, index);
  8227. if (!new_index) {
  8228. gbString idx_str = expr_to_string(op_index.expr);
  8229. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8230. gb_string_free(idx_str);
  8231. continue;
  8232. }
  8233. if (max < index+1) {
  8234. max = index+1;
  8235. }
  8236. Operand operand = {};
  8237. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8238. check_assignment(c, &operand, elem_type, context_name);
  8239. is_constant = is_constant && operand.mode == Addressing_Constant;
  8240. add_to_seen_map(c, &seen, op_index);
  8241. }
  8242. }
  8243. cl->max_count = max;
  8244. } else {
  8245. isize index = 0;
  8246. for (; index < cl->elems.count; index++) {
  8247. Ast *e = cl->elems[index];
  8248. if (e == nullptr) {
  8249. error(node, "Invalid literal element");
  8250. continue;
  8251. }
  8252. if (e->kind == Ast_FieldValue) {
  8253. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8254. continue;
  8255. }
  8256. if (0 <= max_type_count && max_type_count <= index) {
  8257. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8258. }
  8259. Operand operand = {};
  8260. check_expr_with_type_hint(c, &operand, e, elem_type);
  8261. check_assignment(c, &operand, elem_type, context_name);
  8262. is_constant = is_constant && operand.mode == Addressing_Constant;
  8263. }
  8264. if (max < index) {
  8265. max = index;
  8266. }
  8267. }
  8268. bool was_error = false;
  8269. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8270. if (0 < max && max < t->EnumeratedArray.count) {
  8271. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  8272. was_error = true;
  8273. } else {
  8274. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  8275. was_error = true;
  8276. }
  8277. }
  8278. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  8279. if (cl->elems.count > 0 && !was_error && !is_partial) {
  8280. TEMPORARY_ALLOCATOR_GUARD();
  8281. Type *et = base_type(index_type);
  8282. GB_ASSERT(et->kind == Type_Enum);
  8283. auto fields = et->Enum.fields;
  8284. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  8285. for (Entity *f : fields) {
  8286. if (f->kind != Entity_Constant) {
  8287. continue;
  8288. }
  8289. ExactValue v = f->Constant.value;
  8290. uintptr hash = hash_exact_value(v);
  8291. auto found = map_get(&seen, hash);
  8292. if (!found) {
  8293. array_add(&unhandled, f);
  8294. }
  8295. }
  8296. if (unhandled.count > 0) {
  8297. ERROR_BLOCK();
  8298. if (unhandled.count == 1) {
  8299. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  8300. } else {
  8301. error(node, "Unhandled enumerated array cases:");
  8302. for_array(i, unhandled) {
  8303. Entity *f = unhandled[i];
  8304. error_line("\t%.*s\n", LIT(f->token.string));
  8305. }
  8306. }
  8307. if (!build_context.terse_errors) {
  8308. error_line("\n");
  8309. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  8310. }
  8311. }
  8312. }
  8313. break;
  8314. }
  8315. case Type_Basic: {
  8316. if (!is_type_any(t)) {
  8317. if (cl->elems.count != 0) {
  8318. gbString s = type_to_string(t);
  8319. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  8320. gb_string_free(s);
  8321. is_constant = false;
  8322. }
  8323. break;
  8324. }
  8325. if (cl->elems.count == 0) {
  8326. break; // NOTE(bill): No need to init
  8327. }
  8328. { // Checker values
  8329. Type *field_types[2] = {t_rawptr, t_typeid};
  8330. isize field_count = 2;
  8331. if (cl->elems[0]->kind == Ast_FieldValue) {
  8332. bool fields_visited[2] = {};
  8333. for_array(i, cl->elems) {
  8334. Ast *elem = cl->elems[i];
  8335. if (elem->kind != Ast_FieldValue) {
  8336. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8337. continue;
  8338. }
  8339. ast_node(fv, FieldValue, elem);
  8340. if (fv->field->kind != Ast_Ident) {
  8341. gbString expr_str = expr_to_string(fv->field);
  8342. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  8343. gb_string_free(expr_str);
  8344. continue;
  8345. }
  8346. String name = fv->field->Ident.token.string;
  8347. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8348. if (sel.entity == nullptr) {
  8349. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  8350. continue;
  8351. }
  8352. isize index = sel.index[0];
  8353. if (fields_visited[index]) {
  8354. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  8355. continue;
  8356. }
  8357. fields_visited[index] = true;
  8358. check_expr(c, o, fv->value);
  8359. // NOTE(bill): 'any' literals can never be constant
  8360. is_constant = false;
  8361. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8362. }
  8363. } else {
  8364. for_array(index, cl->elems) {
  8365. Ast *elem = cl->elems[index];
  8366. if (elem->kind == Ast_FieldValue) {
  8367. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8368. continue;
  8369. }
  8370. check_expr(c, o, elem);
  8371. if (index >= field_count) {
  8372. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  8373. break;
  8374. }
  8375. // NOTE(bill): 'any' literals can never be constant
  8376. is_constant = false;
  8377. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8378. }
  8379. if (cl->elems.count < field_count) {
  8380. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  8381. }
  8382. }
  8383. }
  8384. break;
  8385. }
  8386. case Type_Map: {
  8387. if (cl->elems.count == 0) {
  8388. break;
  8389. }
  8390. is_constant = false;
  8391. { // Checker values
  8392. bool key_is_typeid = is_type_typeid(t->Map.key);
  8393. bool value_is_typeid = is_type_typeid(t->Map.value);
  8394. for (Ast *elem : cl->elems) {
  8395. if (elem->kind != Ast_FieldValue) {
  8396. error(elem, "Only 'field = value' elements are allowed in a map literal");
  8397. continue;
  8398. }
  8399. ast_node(fv, FieldValue, elem);
  8400. if (key_is_typeid) {
  8401. check_expr_or_type(c, o, fv->field, t->Map.key);
  8402. } else {
  8403. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  8404. }
  8405. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  8406. if (o->mode == Addressing_Invalid) {
  8407. continue;
  8408. }
  8409. if (value_is_typeid) {
  8410. check_expr_or_type(c, o, fv->value, t->Map.value);
  8411. } else {
  8412. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  8413. }
  8414. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  8415. }
  8416. }
  8417. if (build_context.no_dynamic_literals && cl->elems.count) {
  8418. error(node, "Compound literals of dynamic types have been disabled");
  8419. } else {
  8420. add_map_reserve_dependencies(c);
  8421. add_map_set_dependencies(c);
  8422. }
  8423. break;
  8424. }
  8425. case Type_BitSet: {
  8426. if (cl->elems.count == 0) {
  8427. break; // NOTE(bill): No need to init
  8428. }
  8429. Type *et = base_type(t->BitSet.elem);
  8430. isize field_count = 0;
  8431. if (et->kind == Type_Enum) {
  8432. field_count = et->Enum.fields.count;
  8433. }
  8434. if (cl->elems[0]->kind == Ast_FieldValue) {
  8435. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  8436. is_constant = false;
  8437. } else {
  8438. for (Ast *elem : cl->elems) {
  8439. if (elem->kind == Ast_FieldValue) {
  8440. error(elem, "'field = value' in a bit_set a literal is not allowed");
  8441. continue;
  8442. }
  8443. check_expr_with_type_hint(c, o, elem, et);
  8444. if (is_constant) {
  8445. is_constant = o->mode == Addressing_Constant;
  8446. }
  8447. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  8448. if (o->mode == Addressing_Constant) {
  8449. i64 lower = t->BitSet.lower;
  8450. i64 upper = t->BitSet.upper;
  8451. i64 v = exact_value_to_i64(o->value);
  8452. if (lower <= v && v <= upper) {
  8453. // okay
  8454. } else {
  8455. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  8456. continue;
  8457. }
  8458. }
  8459. }
  8460. }
  8461. break;
  8462. }
  8463. case Type_BitField: {
  8464. if (cl->elems.count == 0) {
  8465. break; // NOTE(bill): No need to init
  8466. }
  8467. is_constant = false;
  8468. if (cl->elems[0]->kind != Ast_FieldValue) {
  8469. gbString type_str = type_to_string(type);
  8470. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  8471. gb_string_free(type_str);
  8472. } else {
  8473. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8474. }
  8475. break;
  8476. }
  8477. default: {
  8478. if (cl->elems.count == 0) {
  8479. break; // NOTE(bill): No need to init
  8480. }
  8481. gbString str = type_to_string(type);
  8482. error(node, "Invalid compound literal type '%s'", str);
  8483. gb_string_free(str);
  8484. return kind;
  8485. }
  8486. }
  8487. if (is_constant) {
  8488. o->mode = Addressing_Constant;
  8489. if (is_type_bit_set(type)) {
  8490. // NOTE(bill): Encode as an integer
  8491. Type *bt = base_type(type);
  8492. BigInt bits = {};
  8493. BigInt one = {};
  8494. big_int_from_u64(&one, 1);
  8495. for (Ast *e : cl->elems) {
  8496. GB_ASSERT(e->kind != Ast_FieldValue);
  8497. TypeAndValue tav = e->tav;
  8498. if (tav.mode != Addressing_Constant) {
  8499. continue;
  8500. }
  8501. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  8502. i64 v = big_int_to_i64(&tav.value.value_integer);
  8503. i64 lower = bt->BitSet.lower;
  8504. u64 index = cast(u64)(v-lower);
  8505. BigInt bit = {};
  8506. big_int_from_u64(&bit, index);
  8507. big_int_shl(&bit, &one, &bit);
  8508. big_int_or(&bits, &bits, &bit);
  8509. }
  8510. o->value.kind = ExactValue_Integer;
  8511. o->value.value_integer = bits;
  8512. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  8513. ExactValue value = exact_value_compound(node);
  8514. Type *bt = core_type(type);
  8515. if (bt->kind == Type_Basic) {
  8516. if (bt->Basic.flags & BasicFlag_Boolean) {
  8517. value = exact_value_bool(false);
  8518. } else if (bt->Basic.flags & BasicFlag_Integer) {
  8519. value = exact_value_i64(0);
  8520. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  8521. value = exact_value_i64(0);
  8522. } else if (bt->Basic.flags & BasicFlag_Float) {
  8523. value = exact_value_float(0);
  8524. } else if (bt->Basic.flags & BasicFlag_Complex) {
  8525. value = exact_value_complex(0, 0);
  8526. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  8527. value = exact_value_quaternion(0, 0, 0, 0);
  8528. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  8529. value = exact_value_pointer(0);
  8530. } else if (bt->Basic.flags & BasicFlag_String) {
  8531. String empty_string = {};
  8532. value = exact_value_string(empty_string);
  8533. } else if (bt->Basic.flags & BasicFlag_Rune) {
  8534. value = exact_value_i64(0);
  8535. }
  8536. }
  8537. o->value = value;
  8538. } else {
  8539. o->value = exact_value_compound(node);
  8540. }
  8541. } else {
  8542. o->mode = Addressing_Value;
  8543. }
  8544. o->type = type;
  8545. return kind;
  8546. }
  8547. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8548. ExprKind kind = Expr_Expr;
  8549. ast_node(ta, TypeAssertion, node);
  8550. check_expr(c, o, ta->expr);
  8551. node->viral_state_flags |= ta->expr->viral_state_flags;
  8552. if (o->mode == Addressing_Invalid) {
  8553. o->expr = node;
  8554. return kind;
  8555. }
  8556. if (o->mode == Addressing_Constant) {
  8557. gbString expr_str = expr_to_string(o->expr);
  8558. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  8559. gb_string_free(expr_str);
  8560. o->mode = Addressing_Invalid;
  8561. o->expr = node;
  8562. return kind;
  8563. }
  8564. if (is_type_untyped(o->type)) {
  8565. gbString expr_str = expr_to_string(o->expr);
  8566. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  8567. gb_string_free(expr_str);
  8568. o->mode = Addressing_Invalid;
  8569. o->expr = node;
  8570. return kind;
  8571. }
  8572. Type *src = type_deref(o->type);
  8573. Type *bsrc = base_type(src);
  8574. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  8575. if (!is_type_union(src)) {
  8576. gbString str = type_to_string(o->type);
  8577. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  8578. gb_string_free(str);
  8579. o->mode = Addressing_Invalid;
  8580. o->expr = node;
  8581. return kind;
  8582. }
  8583. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  8584. bool allowed = false;
  8585. for (Type *vt : bsrc->Union.variants) {
  8586. if (are_types_identical(vt, type_hint)) {
  8587. allowed = true;
  8588. add_type_info_type(c, vt);
  8589. break;
  8590. }
  8591. }
  8592. if (allowed) {
  8593. add_type_info_type(c, o->type);
  8594. o->type = type_hint;
  8595. o->mode = Addressing_OptionalOk;
  8596. return kind;
  8597. }
  8598. }
  8599. if (bsrc->Union.variants.count != 1) {
  8600. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  8601. o->mode = Addressing_Invalid;
  8602. o->expr = node;
  8603. return kind;
  8604. }
  8605. add_type_info_type(c, o->type);
  8606. add_type_info_type(c, bsrc->Union.variants[0]);
  8607. o->type = bsrc->Union.variants[0];
  8608. o->mode = Addressing_OptionalOk;
  8609. } else {
  8610. Type *t = check_type(c, ta->type);
  8611. Type *dst = t;
  8612. if (is_type_union(src)) {
  8613. bool ok = false;
  8614. for (Type *vt : bsrc->Union.variants) {
  8615. if (are_types_identical(vt, dst)) {
  8616. ok = true;
  8617. break;
  8618. }
  8619. }
  8620. if (!ok) {
  8621. gbString expr_str = expr_to_string(o->expr);
  8622. gbString dst_type_str = type_to_string(t);
  8623. defer (gb_string_free(expr_str));
  8624. defer (gb_string_free(dst_type_str));
  8625. if (bsrc->Union.variants.count == 0) {
  8626. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  8627. } else {
  8628. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  8629. }
  8630. o->mode = Addressing_Invalid;
  8631. o->expr = node;
  8632. return kind;
  8633. }
  8634. add_type_info_type(c, o->type);
  8635. add_type_info_type(c, t);
  8636. o->type = t;
  8637. o->mode = Addressing_OptionalOk;
  8638. } else if (is_type_any(src)) {
  8639. o->type = t;
  8640. o->mode = Addressing_OptionalOk;
  8641. add_type_info_type(c, o->type);
  8642. add_type_info_type(c, t);
  8643. } else {
  8644. gbString str = type_to_string(o->type);
  8645. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  8646. gb_string_free(str);
  8647. o->mode = Addressing_Invalid;
  8648. o->expr = node;
  8649. return kind;
  8650. }
  8651. }
  8652. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  8653. add_package_dependency(c, "runtime", "type_assertion_check");
  8654. add_package_dependency(c, "runtime", "type_assertion_check2");
  8655. }
  8656. return kind;
  8657. }
  8658. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8659. ast_node(se, SelectorCallExpr, node);
  8660. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  8661. // COM APIs is a great example of where this kind of thing is extremely useful
  8662. // General idea:
  8663. //
  8664. // x->y(123) == x.y(x, 123)
  8665. //
  8666. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  8667. // Just regenerating a new AST aids things
  8668. //
  8669. // TODO(bill): Is this a good hack or not?
  8670. //
  8671. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  8672. if (se->modified_call) {
  8673. // Prevent double evaluation
  8674. o->expr = node;
  8675. o->type = node->tav.type;
  8676. o->value = node->tav.value;
  8677. o->mode = node->tav.mode;
  8678. return Expr_Expr;
  8679. }
  8680. bool allow_arrow_right_selector_expr;
  8681. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8682. c->allow_arrow_right_selector_expr = true;
  8683. Operand x = {};
  8684. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  8685. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8686. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  8687. o->mode = Addressing_Invalid;
  8688. o->type = t_invalid;
  8689. o->expr = node;
  8690. return kind;
  8691. }
  8692. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  8693. gbString type_str = type_to_string(x.type);
  8694. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  8695. gb_string_free(type_str);
  8696. o->mode = Addressing_Invalid;
  8697. o->type = t_invalid;
  8698. o->expr = node;
  8699. return Expr_Stmt;
  8700. }
  8701. ast_node(ce, CallExpr, se->call);
  8702. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  8703. Ast *first_arg = x.expr->SelectorExpr.expr;
  8704. GB_ASSERT(first_arg != nullptr);
  8705. Entity *e = entity_of_node(se->expr);
  8706. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  8707. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  8708. }
  8709. if (e->kind != Entity_ProcGroup) {
  8710. Type *pt = base_type(x.type);
  8711. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  8712. Type *first_type = nullptr;
  8713. String first_arg_name = {};
  8714. if (pt->Proc.param_count > 0) {
  8715. Entity *f = pt->Proc.params->Tuple.variables[0];
  8716. first_type = f->type;
  8717. first_arg_name = f->token.string;
  8718. }
  8719. if (first_arg_name.len == 0) {
  8720. first_arg_name = str_lit("_");
  8721. }
  8722. if (first_type == nullptr) {
  8723. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  8724. o->mode = Addressing_Invalid;
  8725. o->type = t_invalid;
  8726. o->expr = node;
  8727. return Expr_Stmt;
  8728. }
  8729. Operand y = {};
  8730. y.mode = first_arg->tav.mode;
  8731. y.type = first_arg->tav.type;
  8732. y.value = first_arg->tav.value;
  8733. if (check_is_assignable_to(c, &y, first_type)) {
  8734. // Do nothing, it's valid
  8735. } else {
  8736. Operand z = y;
  8737. z.type = type_deref(y.type);
  8738. if (check_is_assignable_to(c, &z, first_type)) {
  8739. // NOTE(bill): AST GENERATION HACK!
  8740. Token op = {Token_Pointer};
  8741. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  8742. } else if (y.mode == Addressing_Variable) {
  8743. Operand w = y;
  8744. w.type = alloc_type_pointer(y.type);
  8745. if (check_is_assignable_to(c, &w, first_type)) {
  8746. // NOTE(bill): AST GENERATION HACK!
  8747. Token op = {Token_And};
  8748. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  8749. }
  8750. }
  8751. }
  8752. if (ce->args.count > 0) {
  8753. bool fail = false;
  8754. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  8755. for (Ast *arg : ce->args) {
  8756. bool mix = false;
  8757. if (first_is_field_value) {
  8758. mix = arg->kind != Ast_FieldValue;
  8759. } else {
  8760. mix = arg->kind == Ast_FieldValue;
  8761. }
  8762. if (mix) {
  8763. fail = true;
  8764. break;
  8765. }
  8766. }
  8767. if (!fail && first_is_field_value) {
  8768. Token op = {Token_Eq};
  8769. AstFile *f = first_arg->file();
  8770. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  8771. }
  8772. }
  8773. }
  8774. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  8775. modified_args[0] = first_arg;
  8776. slice_copy(&modified_args, ce->args, 1);
  8777. ce->args = modified_args;
  8778. se->modified_call = true;
  8779. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8780. c->allow_arrow_right_selector_expr = true;
  8781. check_expr_base(c, o, se->call, type_hint);
  8782. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8783. o->expr = node;
  8784. return Expr_Expr;
  8785. }
  8786. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8787. ExprKind kind = Expr_Expr;
  8788. ast_node(ie, IndexExpr, node);
  8789. check_expr(c, o, ie->expr);
  8790. node->viral_state_flags |= ie->expr->viral_state_flags;
  8791. if (o->mode == Addressing_Invalid) {
  8792. o->expr = node;
  8793. return kind;
  8794. }
  8795. Type *t = base_type(type_deref(o->type));
  8796. bool is_ptr = is_type_pointer(o->type);
  8797. bool is_const = o->mode == Addressing_Constant;
  8798. if (is_type_map(t)) {
  8799. Operand key = {};
  8800. if (is_type_typeid(t->Map.key)) {
  8801. check_expr_or_type(c, &key, ie->index, t->Map.key);
  8802. } else {
  8803. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  8804. }
  8805. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  8806. if (key.mode == Addressing_Invalid) {
  8807. o->mode = Addressing_Invalid;
  8808. o->expr = node;
  8809. return kind;
  8810. }
  8811. o->mode = Addressing_MapIndex;
  8812. o->type = t->Map.value;
  8813. o->expr = node;
  8814. add_map_get_dependencies(c);
  8815. add_map_set_dependencies(c);
  8816. return Expr_Expr;
  8817. }
  8818. i64 max_count = -1;
  8819. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  8820. if (is_const) {
  8821. if (is_type_array(t)) {
  8822. // Okay
  8823. } else if (is_type_slice(t)) {
  8824. // Okay
  8825. } else if (is_type_enumerated_array(t)) {
  8826. // Okay
  8827. } else if (is_type_string(t)) {
  8828. // Okay
  8829. } else if (is_type_relative_multi_pointer(t)) {
  8830. // Okay
  8831. } else if (is_type_matrix(t)) {
  8832. // Okay
  8833. } else {
  8834. valid = false;
  8835. }
  8836. }
  8837. if (!valid) {
  8838. gbString str = expr_to_string(o->expr);
  8839. gbString type_str = type_to_string(o->type);
  8840. defer (gb_string_free(str));
  8841. defer (gb_string_free(type_str));
  8842. if (is_const) {
  8843. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  8844. } else {
  8845. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  8846. }
  8847. o->mode = Addressing_Invalid;
  8848. o->expr = node;
  8849. return kind;
  8850. }
  8851. if (ie->index == nullptr) {
  8852. gbString str = expr_to_string(o->expr);
  8853. error(o->expr, "Missing index for '%s'", str);
  8854. gb_string_free(str);
  8855. o->mode = Addressing_Invalid;
  8856. o->expr = node;
  8857. return kind;
  8858. }
  8859. Type *index_type_hint = nullptr;
  8860. if (is_type_enumerated_array(t)) {
  8861. Type *bt = base_type(t);
  8862. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  8863. index_type_hint = bt->EnumeratedArray.index;
  8864. }
  8865. i64 index = 0;
  8866. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  8867. if (is_const) {
  8868. if (index < 0) {
  8869. ERROR_BLOCK();
  8870. gbString str = expr_to_string(o->expr);
  8871. error(o->expr, "Cannot index a constant '%s'", str);
  8872. if (!build_context.terse_errors) {
  8873. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8874. }
  8875. gb_string_free(str);
  8876. o->mode = Addressing_Invalid;
  8877. o->expr = node;
  8878. return kind;
  8879. } else if (ok) {
  8880. ExactValue value = type_and_value_of_expr(ie->expr).value;
  8881. o->mode = Addressing_Constant;
  8882. bool success = false;
  8883. bool finish = false;
  8884. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  8885. if (!success) {
  8886. ERROR_BLOCK();
  8887. gbString str = expr_to_string(o->expr);
  8888. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  8889. if (!build_context.terse_errors) {
  8890. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8891. }
  8892. gb_string_free(str);
  8893. o->mode = Addressing_Invalid;
  8894. o->expr = node;
  8895. return kind;
  8896. }
  8897. }
  8898. }
  8899. if (type_hint != nullptr && is_type_matrix(t)) {
  8900. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  8901. // if a type hint exists
  8902. }
  8903. return kind;
  8904. }
  8905. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8906. ExprKind kind = Expr_Stmt;
  8907. ast_node(se, SliceExpr, node);
  8908. check_expr(c, o, se->expr);
  8909. node->viral_state_flags |= se->expr->viral_state_flags;
  8910. if (o->mode == Addressing_Invalid) {
  8911. o->mode = Addressing_Invalid;
  8912. o->expr = node;
  8913. return kind;
  8914. }
  8915. bool valid = false;
  8916. i64 max_count = -1;
  8917. Type *t = base_type(type_deref(o->type));
  8918. switch (t->kind) {
  8919. case Type_Basic:
  8920. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  8921. valid = true;
  8922. if (o->mode == Addressing_Constant) {
  8923. max_count = o->value.value_string.len;
  8924. }
  8925. o->type = type_deref(o->type);
  8926. }
  8927. break;
  8928. case Type_Array:
  8929. valid = true;
  8930. max_count = t->Array.count;
  8931. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  8932. gbString str = expr_to_string(node);
  8933. error(node, "Cannot slice array '%s', value is not addressable", str);
  8934. gb_string_free(str);
  8935. o->mode = Addressing_Invalid;
  8936. o->expr = node;
  8937. return kind;
  8938. }
  8939. o->type = alloc_type_slice(t->Array.elem);
  8940. break;
  8941. case Type_MultiPointer:
  8942. valid = true;
  8943. o->type = type_deref(o->type);
  8944. break;
  8945. case Type_Slice:
  8946. valid = true;
  8947. o->type = type_deref(o->type);
  8948. break;
  8949. case Type_DynamicArray:
  8950. valid = true;
  8951. o->type = alloc_type_slice(t->DynamicArray.elem);
  8952. break;
  8953. case Type_Struct:
  8954. if (is_type_soa_struct(t)) {
  8955. valid = true;
  8956. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  8957. }
  8958. break;
  8959. case Type_RelativeMultiPointer:
  8960. valid = true;
  8961. o->type = type_deref(o->type);
  8962. break;
  8963. case Type_EnumeratedArray:
  8964. {
  8965. gbString str = expr_to_string(o->expr);
  8966. gbString type_str = type_to_string(o->type);
  8967. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  8968. gb_string_free(type_str);
  8969. gb_string_free(str);
  8970. o->mode = Addressing_Invalid;
  8971. o->expr = node;
  8972. return kind;
  8973. }
  8974. break;
  8975. }
  8976. if (!valid) {
  8977. gbString str = expr_to_string(o->expr);
  8978. gbString type_str = type_to_string(o->type);
  8979. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  8980. gb_string_free(type_str);
  8981. gb_string_free(str);
  8982. o->mode = Addressing_Invalid;
  8983. o->expr = node;
  8984. return kind;
  8985. }
  8986. if (se->low == nullptr && se->high != nullptr) {
  8987. // It is okay to continue as it will assume the 1st index is zero
  8988. }
  8989. i64 indices[2] = {};
  8990. Ast *nodes[2] = {se->low, se->high};
  8991. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8992. i64 index = max_count;
  8993. if (nodes[i] != nullptr) {
  8994. i64 capacity = -1;
  8995. if (max_count >= 0) {
  8996. capacity = max_count;
  8997. }
  8998. i64 j = 0;
  8999. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  9000. index = j;
  9001. }
  9002. node->viral_state_flags |= nodes[i]->viral_state_flags;
  9003. } else if (i == 0) {
  9004. index = 0;
  9005. }
  9006. indices[i] = index;
  9007. }
  9008. for (isize i = 0; i < gb_count_of(indices); i++) {
  9009. i64 a = indices[i];
  9010. for (isize j = i+1; j < gb_count_of(indices); j++) {
  9011. i64 b = indices[j];
  9012. if (a > b && b >= 0) {
  9013. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  9014. }
  9015. }
  9016. }
  9017. if (max_count < 0) {
  9018. if (o->mode == Addressing_Constant) {
  9019. gbString s = expr_to_string(se->expr);
  9020. error(se->expr, "Cannot slice constant value '%s'", s);
  9021. gb_string_free(s);
  9022. }
  9023. }
  9024. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  9025. /*
  9026. x[:] -> [^]T
  9027. x[i:] -> [^]T
  9028. x[:n] -> []T
  9029. x[i:n] -> []T
  9030. */
  9031. o->type = alloc_type_slice(t->MultiPointer.elem);
  9032. } else if (t->kind == Type_RelativeMultiPointer && se->high != nullptr) {
  9033. /*
  9034. x[:] -> [^]T
  9035. x[i:] -> [^]T
  9036. x[:n] -> []T
  9037. x[i:n] -> []T
  9038. */
  9039. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  9040. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  9041. o->type = alloc_type_slice(pointer_type->MultiPointer.elem);
  9042. }
  9043. o->mode = Addressing_Value;
  9044. if (is_type_string(t) && max_count >= 0) {
  9045. bool all_constant = true;
  9046. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9047. if (nodes[i] != nullptr) {
  9048. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  9049. if (tav.mode != Addressing_Constant) {
  9050. all_constant = false;
  9051. break;
  9052. }
  9053. }
  9054. }
  9055. if (!all_constant) {
  9056. ERROR_BLOCK();
  9057. gbString str = expr_to_string(o->expr);
  9058. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  9059. if (!build_context.terse_errors) {
  9060. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9061. }
  9062. gb_string_free(str);
  9063. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  9064. o->expr = node;
  9065. return kind;
  9066. }
  9067. String s = {};
  9068. if (o->value.kind == ExactValue_String) {
  9069. s = o->value.value_string;
  9070. }
  9071. o->mode = Addressing_Constant;
  9072. o->type = t;
  9073. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9074. }
  9075. return kind;
  9076. }
  9077. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9078. u32 prev_state_flags = c->state_flags;
  9079. defer (c->state_flags = prev_state_flags);
  9080. if (node->state_flags != 0) {
  9081. u32 in = node->state_flags;
  9082. u32 out = c->state_flags;
  9083. if (in & StateFlag_no_bounds_check) {
  9084. out |= StateFlag_no_bounds_check;
  9085. out &= ~StateFlag_bounds_check;
  9086. } else if (in & StateFlag_bounds_check) {
  9087. out |= StateFlag_bounds_check;
  9088. out &= ~StateFlag_no_bounds_check;
  9089. }
  9090. if (in & StateFlag_no_type_assert) {
  9091. out |= StateFlag_no_type_assert;
  9092. out &= ~StateFlag_type_assert;
  9093. } else if (in & StateFlag_type_assert) {
  9094. out |= StateFlag_type_assert;
  9095. out &= ~StateFlag_no_type_assert;
  9096. }
  9097. c->state_flags = out;
  9098. }
  9099. ExprKind kind = Expr_Stmt;
  9100. o->mode = Addressing_Invalid;
  9101. o->type = t_invalid;
  9102. o->value = {ExactValue_Invalid};
  9103. switch (node->kind) {
  9104. default:
  9105. return kind;
  9106. case_ast_node(be, BadExpr, node)
  9107. return kind;
  9108. case_end;
  9109. case_ast_node(i, Implicit, node)
  9110. switch (i->kind) {
  9111. case Token_context:
  9112. {
  9113. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  9114. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  9115. return kind;
  9116. }
  9117. if (unparen_expr(c->assignment_lhs_hint) == node) {
  9118. c->scope->flags |= ScopeFlag_ContextDefined;
  9119. }
  9120. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  9121. error(node, "'context' has not been defined within this scope");
  9122. // Continue with value
  9123. }
  9124. init_core_context(c->checker);
  9125. o->mode = Addressing_Context;
  9126. o->type = t_context;
  9127. }
  9128. break;
  9129. default:
  9130. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  9131. return kind;
  9132. }
  9133. case_end;
  9134. case_ast_node(i, Ident, node);
  9135. check_ident(c, o, node, nullptr, type_hint, false);
  9136. case_end;
  9137. case_ast_node(u, Uninit, node);
  9138. o->mode = Addressing_Value;
  9139. o->type = t_untyped_uninit;
  9140. error(node, "Use of --- outside of variable declaration");
  9141. case_end;
  9142. case_ast_node(bl, BasicLit, node);
  9143. Type *t = t_invalid;
  9144. switch (node->tav.value.kind) {
  9145. case ExactValue_String: t = t_untyped_string; break;
  9146. case ExactValue_Float: t = t_untyped_float; break;
  9147. case ExactValue_Complex: t = t_untyped_complex; break;
  9148. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  9149. case ExactValue_Integer:
  9150. t = t_untyped_integer;
  9151. if (bl->token.kind == Token_Rune) {
  9152. t = t_untyped_rune;
  9153. }
  9154. break;
  9155. default:
  9156. GB_PANIC("Unhandled value type for basic literal");
  9157. break;
  9158. }
  9159. o->mode = Addressing_Constant;
  9160. o->type = t;
  9161. o->value = node->tav.value;
  9162. case_end;
  9163. case_ast_node(bd, BasicDirective, node);
  9164. kind = check_basic_directive_expr(c, o, node, type_hint);
  9165. case_end;
  9166. case_ast_node(pg, ProcGroup, node);
  9167. error(node, "Illegal use of a procedure group");
  9168. o->mode = Addressing_Invalid;
  9169. case_end;
  9170. case_ast_node(pl, ProcLit, node);
  9171. CheckerContext ctx = *c;
  9172. DeclInfo *decl = nullptr;
  9173. Type *type = alloc_type(Type_Proc);
  9174. check_open_scope(&ctx, pl->type);
  9175. {
  9176. decl = make_decl_info(ctx.scope, ctx.decl);
  9177. decl->proc_lit = node;
  9178. ctx.decl = decl;
  9179. defer (ctx.decl = ctx.decl->parent);
  9180. if (pl->tags != 0) {
  9181. error(node, "A procedure literal cannot have tags");
  9182. pl->tags = 0; // TODO(bill): Should I zero this?!
  9183. }
  9184. check_procedure_type(&ctx, type, pl->type);
  9185. if (!is_type_proc(type)) {
  9186. gbString str = expr_to_string(node);
  9187. error(node, "Invalid procedure literal '%s'", str);
  9188. gb_string_free(str);
  9189. check_close_scope(&ctx);
  9190. return kind;
  9191. }
  9192. if (pl->body == nullptr) {
  9193. error(node, "A procedure literal must have a body");
  9194. return kind;
  9195. }
  9196. pl->decl = decl;
  9197. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  9198. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  9199. array_add(&ctx.checker->nested_proc_lits, decl);
  9200. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  9201. }
  9202. check_close_scope(&ctx);
  9203. o->mode = Addressing_Value;
  9204. o->type = type;
  9205. case_end;
  9206. case_ast_node(te, TernaryIfExpr, node);
  9207. kind = check_ternary_if_expr(c, o, node, type_hint);
  9208. case_end;
  9209. case_ast_node(te, TernaryWhenExpr, node);
  9210. kind = check_ternary_when_expr(c, o, node, type_hint);
  9211. case_end;
  9212. case_ast_node(oe, OrElseExpr, node);
  9213. return check_or_else_expr(c, o, node, type_hint);
  9214. case_end;
  9215. case_ast_node(re, OrReturnExpr, node);
  9216. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  9217. return check_or_return_expr(c, o, node, type_hint);
  9218. case_end;
  9219. case_ast_node(re, OrBranchExpr, node);
  9220. return check_or_branch_expr(c, o, node, type_hint);
  9221. case_end;
  9222. case_ast_node(cl, CompoundLit, node);
  9223. kind = check_compound_literal(c, o, node, type_hint);
  9224. case_end;
  9225. case_ast_node(pe, ParenExpr, node);
  9226. kind = check_expr_base(c, o, pe->expr, type_hint);
  9227. node->viral_state_flags |= pe->expr->viral_state_flags;
  9228. o->expr = node;
  9229. case_end;
  9230. case_ast_node(te, TagExpr, node);
  9231. String name = te->name.string;
  9232. error(node, "Unknown tag expression, #%.*s", LIT(name));
  9233. if (te->expr) {
  9234. kind = check_expr_base(c, o, te->expr, type_hint);
  9235. node->viral_state_flags |= te->expr->viral_state_flags;
  9236. }
  9237. o->expr = node;
  9238. case_end;
  9239. case_ast_node(ta, TypeAssertion, node);
  9240. kind = check_type_assertion(c, o, node, type_hint);
  9241. case_end;
  9242. case_ast_node(tc, TypeCast, node);
  9243. check_expr_or_type(c, o, tc->type);
  9244. if (o->mode != Addressing_Type) {
  9245. gbString str = expr_to_string(tc->type);
  9246. error(tc->type, "Expected a type, got %s", str);
  9247. gb_string_free(str);
  9248. o->mode = Addressing_Invalid;
  9249. }
  9250. if (o->mode == Addressing_Invalid) {
  9251. o->expr = node;
  9252. return kind;
  9253. }
  9254. Type *type = o->type;
  9255. check_expr_base(c, o, tc->expr, type);
  9256. node->viral_state_flags |= tc->expr->viral_state_flags;
  9257. if (o->mode != Addressing_Invalid) {
  9258. switch (tc->token.kind) {
  9259. case Token_transmute:
  9260. check_transmute(c, node, o, type);
  9261. break;
  9262. case Token_cast:
  9263. check_cast(c, o, type);
  9264. break;
  9265. default:
  9266. error(node, "Invalid AST: Invalid casting expression");
  9267. o->mode = Addressing_Invalid;
  9268. break;
  9269. }
  9270. }
  9271. return Expr_Expr;
  9272. case_end;
  9273. case_ast_node(ac, AutoCast, node);
  9274. check_expr_base(c, o, ac->expr, type_hint);
  9275. node->viral_state_flags |= ac->expr->viral_state_flags;
  9276. if (o->mode == Addressing_Invalid) {
  9277. o->expr = node;
  9278. return kind;
  9279. }
  9280. if (type_hint) {
  9281. check_cast(c, o, type_hint);
  9282. }
  9283. o->expr = node;
  9284. return Expr_Expr;
  9285. case_end;
  9286. case_ast_node(ue, UnaryExpr, node);
  9287. Type *th = type_hint;
  9288. if (ue->op.kind == Token_And) {
  9289. th = type_deref(th);
  9290. }
  9291. check_expr_base(c, o, ue->expr, th);
  9292. node->viral_state_flags |= ue->expr->viral_state_flags;
  9293. if (o->mode != Addressing_Invalid) {
  9294. check_unary_expr(c, o, ue->op, node);
  9295. }
  9296. o->expr = node;
  9297. return Expr_Expr;
  9298. case_end;
  9299. case_ast_node(be, BinaryExpr, node);
  9300. check_binary_expr(c, o, node, type_hint, true);
  9301. if (o->mode == Addressing_Invalid) {
  9302. o->expr = node;
  9303. return kind;
  9304. }
  9305. case_end;
  9306. case_ast_node(se, SelectorExpr, node);
  9307. check_selector(c, o, node, type_hint);
  9308. node->viral_state_flags |= se->expr->viral_state_flags;
  9309. case_end;
  9310. case_ast_node(se, SelectorCallExpr, node);
  9311. return check_selector_call_expr(c, o, node, type_hint);
  9312. case_end;
  9313. case_ast_node(ise, ImplicitSelectorExpr, node);
  9314. return check_implicit_selector_expr(c, o, node, type_hint);
  9315. case_end;
  9316. case_ast_node(ie, IndexExpr, node);
  9317. kind = check_index_expr(c, o, node, type_hint);
  9318. case_end;
  9319. case_ast_node(se, SliceExpr, node);
  9320. kind = check_slice_expr(c, o, node, type_hint);
  9321. case_end;
  9322. case_ast_node(mie, MatrixIndexExpr, node);
  9323. check_matrix_index_expr(c, o, node, type_hint);
  9324. o->expr = node;
  9325. return Expr_Expr;
  9326. case_end;
  9327. case_ast_node(ce, CallExpr, node);
  9328. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  9329. case_end;
  9330. case_ast_node(de, DerefExpr, node);
  9331. check_expr_or_type(c, o, de->expr);
  9332. node->viral_state_flags |= de->expr->viral_state_flags;
  9333. if (o->mode == Addressing_Invalid) {
  9334. o->mode = Addressing_Invalid;
  9335. o->expr = node;
  9336. return kind;
  9337. } else {
  9338. Type *t = base_type(o->type);
  9339. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  9340. o->mode = Addressing_Variable;
  9341. o->type = t->Pointer.elem;
  9342. } else if (t->kind == Type_SoaPointer) {
  9343. o->mode = Addressing_SoaVariable;
  9344. o->type = type_deref(t);
  9345. } else if (t->kind == Type_RelativePointer) {
  9346. if (o->mode != Addressing_Variable) {
  9347. gbString str = expr_to_string(o->expr);
  9348. gbString typ = type_to_string(o->type);
  9349. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  9350. gb_string_free(typ);
  9351. gb_string_free(str);
  9352. }
  9353. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  9354. add_type_info_type(c, o->type);
  9355. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  9356. GB_ASSERT(ptr_type->kind == Type_Pointer);
  9357. o->mode = Addressing_Variable;
  9358. o->type = ptr_type->Pointer.elem;
  9359. } else {
  9360. gbString str = expr_to_string(o->expr);
  9361. gbString typ = type_to_string(o->type);
  9362. ERROR_BLOCK();
  9363. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  9364. if (o->type && is_type_multi_pointer(o->type)) {
  9365. if (!build_context.terse_errors) {
  9366. error_line("\tDid you mean '%s[0]'?\n", str);
  9367. }
  9368. }
  9369. gb_string_free(typ);
  9370. gb_string_free(str);
  9371. o->mode = Addressing_Invalid;
  9372. o->expr = node;
  9373. return kind;
  9374. }
  9375. }
  9376. case_end;
  9377. case_ast_node(ia, InlineAsmExpr, node);
  9378. if (c->curr_proc_decl == nullptr) {
  9379. error(node, "Inline asm expressions are only allowed within a procedure body");
  9380. }
  9381. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  9382. Type *return_type = nullptr;
  9383. for_array(i, ia->param_types) {
  9384. param_types[i] = check_type(c, ia->param_types[i]);
  9385. }
  9386. if (ia->return_type != nullptr) {
  9387. return_type = check_type(c, ia->return_type);
  9388. }
  9389. Operand x = {};
  9390. check_expr(c, &x, ia->asm_string);
  9391. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9392. error(x.expr, "Expected a constant string for the inline asm main parameter");
  9393. }
  9394. check_expr(c, &x, ia->constraints_string);
  9395. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9396. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  9397. }
  9398. Scope *scope = create_scope(c->info, c->scope);
  9399. scope->flags |= ScopeFlag_Proc;
  9400. Type *params = alloc_type_tuple();
  9401. Type *results = alloc_type_tuple();
  9402. if (param_types.count != 0) {
  9403. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  9404. for_array(i, param_types) {
  9405. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  9406. }
  9407. }
  9408. if (return_type != nullptr) {
  9409. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  9410. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  9411. }
  9412. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  9413. o->type = pt;
  9414. o->mode = Addressing_Value;
  9415. o->expr = node;
  9416. return Expr_Expr;
  9417. case_end;
  9418. case Ast_TypeidType:
  9419. case Ast_PolyType:
  9420. case Ast_ProcType:
  9421. case Ast_PointerType:
  9422. case Ast_MultiPointerType:
  9423. case Ast_ArrayType:
  9424. case Ast_DynamicArrayType:
  9425. case Ast_StructType:
  9426. case Ast_UnionType:
  9427. case Ast_EnumType:
  9428. case Ast_MapType:
  9429. case Ast_BitSetType:
  9430. case Ast_MatrixType:
  9431. case Ast_RelativeType:
  9432. o->mode = Addressing_Type;
  9433. o->type = check_type(c, node);
  9434. break;
  9435. }
  9436. kind = Expr_Expr;
  9437. o->expr = node;
  9438. return kind;
  9439. }
  9440. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9441. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  9442. if (o->type != nullptr && core_type(o->type) == nullptr) {
  9443. o->type = t_invalid;
  9444. gbString xs = expr_to_string(o->expr);
  9445. if (o->mode == Addressing_Type) {
  9446. error(o->expr, "Invalid type usage '%s'", xs);
  9447. } else {
  9448. error(o->expr, "Invalid expression '%s'", xs);
  9449. }
  9450. gb_string_free(xs);
  9451. }
  9452. if (o->type != nullptr && is_type_untyped(o->type)) {
  9453. add_untyped(c, node, o->mode, o->type, o->value);
  9454. }
  9455. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  9456. add_type_and_value(c, node, o->mode, o->type, o->value);
  9457. return kind;
  9458. }
  9459. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  9460. check_expr_base(c, o, e, nullptr);
  9461. switch (o->mode) {
  9462. default:
  9463. return; // NOTE(bill): Valid
  9464. case Addressing_NoValue:
  9465. error_operand_no_value(o);
  9466. break;
  9467. }
  9468. o->mode = Addressing_Invalid;
  9469. }
  9470. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  9471. check_expr_base(c, o, e, nullptr);
  9472. switch (o->mode) {
  9473. default:
  9474. return; // NOTE(bill): Valid
  9475. case Addressing_NoValue:
  9476. error_operand_no_value(o);
  9477. break;
  9478. case Addressing_Type:
  9479. error_operand_not_expression(o);
  9480. break;
  9481. }
  9482. o->mode = Addressing_Invalid;
  9483. }
  9484. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9485. check_expr_base(c, o, e, type_hint);
  9486. switch (o->mode) {
  9487. default:
  9488. return; // NOTE(bill): Valid
  9489. case Addressing_NoValue:
  9490. error_operand_no_value(o);
  9491. break;
  9492. case Addressing_Type:
  9493. error_operand_not_expression(o);
  9494. break;
  9495. }
  9496. o->mode = Addressing_Invalid;
  9497. }
  9498. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  9499. if (o->mode == Addressing_Value) {
  9500. // NOTE(bill): Tuples are not first class thus never named
  9501. if (o->type->kind == Type_Tuple) {
  9502. isize count = o->type->Tuple.variables.count;
  9503. error(o->expr,
  9504. "%td-valued expression found where single value expected", count);
  9505. o->mode = Addressing_Invalid;
  9506. GB_ASSERT(count != 1);
  9507. }
  9508. }
  9509. }
  9510. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  9511. check_multi_expr(c, o, e);
  9512. check_not_tuple(c, o);
  9513. }
  9514. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9515. check_expr_base(c, o, e, type_hint);
  9516. check_not_tuple(c, o);
  9517. error_operand_no_value(o);
  9518. }
  9519. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  9520. switch (v.kind) {
  9521. case ExactValue_Invalid:
  9522. return true;
  9523. case ExactValue_Bool:
  9524. return !v.value_bool;
  9525. case ExactValue_String:
  9526. return v.value_string.len == 0;
  9527. case ExactValue_Integer:
  9528. return big_int_is_zero(&v.value_integer);
  9529. case ExactValue_Float:
  9530. return v.value_float == 0.0;
  9531. case ExactValue_Complex:
  9532. if (v.value_complex) {
  9533. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  9534. }
  9535. return true;
  9536. case ExactValue_Quaternion:
  9537. if (v.value_quaternion) {
  9538. return v.value_quaternion->real == 0.0 &&
  9539. v.value_quaternion->imag == 0.0 &&
  9540. v.value_quaternion->jmag == 0.0 &&
  9541. v.value_quaternion->kmag == 0.0;
  9542. }
  9543. return true;
  9544. case ExactValue_Pointer:
  9545. return v.value_pointer == 0;
  9546. case ExactValue_Compound:
  9547. if (v.value_compound == nullptr) {
  9548. return true;
  9549. } else {
  9550. ast_node(cl, CompoundLit, v.value_compound);
  9551. if (cl->elems.count == 0) {
  9552. return true;
  9553. } else {
  9554. for (Ast *elem : cl->elems) {
  9555. if (elem->tav.mode != Addressing_Constant) {
  9556. return false;
  9557. }
  9558. if (!is_exact_value_zero(elem->tav.value)) {
  9559. return false;
  9560. }
  9561. }
  9562. return true;
  9563. }
  9564. }
  9565. case ExactValue_Procedure:
  9566. return v.value_procedure == nullptr;
  9567. case ExactValue_Typeid:
  9568. return v.value_typeid == nullptr;
  9569. }
  9570. return true;
  9571. }
  9572. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  9573. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  9574. for_array(i, params) {
  9575. if (i > 0) {
  9576. str = gb_string_appendc(str, ", ");
  9577. }
  9578. str = write_expr_to_string(str, params[i], false);
  9579. }
  9580. return str;
  9581. }
  9582. gb_internal gbString string_append_string(gbString str, String string) {
  9583. if (string.len > 0) {
  9584. return gb_string_append_length(str, &string[0], string.len);
  9585. }
  9586. return str;
  9587. }
  9588. gb_internal gbString string_append_token(gbString str, Token token) {
  9589. str = string_append_string(str, token.string);
  9590. return str;
  9591. }
  9592. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  9593. if (node == nullptr)
  9594. return str;
  9595. if (is_ast_stmt(node)) {
  9596. GB_ASSERT("stmt passed to write_expr_to_string");
  9597. }
  9598. switch (node->kind) {
  9599. default:
  9600. str = gb_string_appendc(str, "(BadExpr)");
  9601. break;
  9602. case_ast_node(i, Ident, node);
  9603. str = string_append_token(str, i->token);
  9604. case_end;
  9605. case_ast_node(i, Implicit, node);
  9606. str = string_append_token(str, *i);
  9607. case_end;
  9608. case_ast_node(bl, BasicLit, node);
  9609. str = string_append_token(str, bl->token);
  9610. case_end;
  9611. case_ast_node(bd, BasicDirective, node);
  9612. str = gb_string_append_rune(str, '#');
  9613. str = string_append_string(str, bd->name.string);
  9614. case_end;
  9615. case_ast_node(ud, Uninit, node);
  9616. str = gb_string_appendc(str, "---");
  9617. case_end;
  9618. case_ast_node(pg, ProcGroup, node);
  9619. str = gb_string_appendc(str, "proc{");
  9620. for_array(i, pg->args) {
  9621. if (i > 0) str = gb_string_appendc(str, ", ");
  9622. str = write_expr_to_string(str, pg->args[i], shorthand);
  9623. }
  9624. str = gb_string_append_rune(str, '}');
  9625. case_end;
  9626. case_ast_node(pl, ProcLit, node);
  9627. str = write_expr_to_string(str, pl->type, shorthand);
  9628. if (pl->body) {
  9629. str = gb_string_appendc(str, " {...}");
  9630. } else {
  9631. str = gb_string_appendc(str, " ---");
  9632. }
  9633. case_end;
  9634. case_ast_node(cl, CompoundLit, node);
  9635. str = write_expr_to_string(str, cl->type, shorthand);
  9636. str = gb_string_append_rune(str, '{');
  9637. if (shorthand) {
  9638. str = gb_string_appendc(str, "...");
  9639. } else {
  9640. for_array(i, cl->elems) {
  9641. if (i > 0) str = gb_string_appendc(str, ", ");
  9642. str = write_expr_to_string(str, cl->elems[i], shorthand);
  9643. }
  9644. }
  9645. str = gb_string_append_rune(str, '}');
  9646. case_end;
  9647. case_ast_node(te, TagExpr, node);
  9648. str = gb_string_append_rune(str, '#');
  9649. str = string_append_token(str, te->name);
  9650. str = write_expr_to_string(str, te->expr, shorthand);
  9651. case_end;
  9652. case_ast_node(ue, UnaryExpr, node);
  9653. str = string_append_token(str, ue->op);
  9654. str = write_expr_to_string(str, ue->expr, shorthand);
  9655. case_end;
  9656. case_ast_node(de, DerefExpr, node);
  9657. str = write_expr_to_string(str, de->expr, shorthand);
  9658. str = gb_string_append_rune(str, '^');
  9659. case_end;
  9660. case_ast_node(be, BinaryExpr, node);
  9661. str = write_expr_to_string(str, be->left, shorthand);
  9662. str = gb_string_append_rune(str, ' ');
  9663. str = string_append_token(str, be->op);
  9664. str = gb_string_append_rune(str, ' ');
  9665. str = write_expr_to_string(str, be->right, shorthand);
  9666. case_end;
  9667. case_ast_node(te, TernaryIfExpr, node);
  9668. TokenPos x = ast_token(te->x).pos;
  9669. TokenPos cond = ast_token(te->cond).pos;
  9670. if (x < cond) {
  9671. str = write_expr_to_string(str, te->x, shorthand);
  9672. str = gb_string_appendc(str, " if ");
  9673. str = write_expr_to_string(str, te->cond, shorthand);
  9674. str = gb_string_appendc(str, " else ");
  9675. str = write_expr_to_string(str, te->y, shorthand);
  9676. } else {
  9677. str = write_expr_to_string(str, te->cond, shorthand);
  9678. str = gb_string_appendc(str, " ? ");
  9679. str = write_expr_to_string(str, te->x, shorthand);
  9680. str = gb_string_appendc(str, " : ");
  9681. str = write_expr_to_string(str, te->y, shorthand);
  9682. }
  9683. case_end;
  9684. case_ast_node(te, TernaryWhenExpr, node);
  9685. str = write_expr_to_string(str, te->x, shorthand);
  9686. str = gb_string_appendc(str, " when ");
  9687. str = write_expr_to_string(str, te->cond, shorthand);
  9688. str = gb_string_appendc(str, " else ");
  9689. str = write_expr_to_string(str, te->y, shorthand);
  9690. case_end;
  9691. case_ast_node(oe, OrElseExpr, node);
  9692. str = write_expr_to_string(str, oe->x, shorthand);
  9693. str = gb_string_appendc(str, " or_else ");
  9694. str = write_expr_to_string(str, oe->y, shorthand);
  9695. case_end;
  9696. case_ast_node(oe, OrReturnExpr, node);
  9697. str = write_expr_to_string(str, oe->expr, shorthand);
  9698. str = gb_string_appendc(str, " or_return");
  9699. case_end;
  9700. case_ast_node(oe, OrBranchExpr, node);
  9701. str = write_expr_to_string(str, oe->expr, shorthand);
  9702. str = gb_string_append_rune(str, ' ');
  9703. str = string_append_token(str, oe->token);
  9704. if (oe->label) {
  9705. str = gb_string_append_rune(str, ' ');
  9706. str = write_expr_to_string(str, oe->label, shorthand);
  9707. }
  9708. case_end;
  9709. case_ast_node(pe, ParenExpr, node);
  9710. str = gb_string_append_rune(str, '(');
  9711. str = write_expr_to_string(str, pe->expr, shorthand);
  9712. str = gb_string_append_rune(str, ')');
  9713. case_end;
  9714. case_ast_node(se, SelectorExpr, node);
  9715. str = write_expr_to_string(str, se->expr, shorthand);
  9716. str = string_append_token(str, se->token);
  9717. str = write_expr_to_string(str, se->selector, shorthand);
  9718. case_end;
  9719. case_ast_node(se, ImplicitSelectorExpr, node);
  9720. str = gb_string_append_rune(str, '.');
  9721. str = write_expr_to_string(str, se->selector, shorthand);
  9722. case_end;
  9723. case_ast_node(se, SelectorCallExpr, node);
  9724. str = write_expr_to_string(str, se->expr, shorthand);
  9725. str = gb_string_appendc(str, "(");
  9726. ast_node(ce, CallExpr, se->call);
  9727. isize start = se->modified_call ? 1 : 0;
  9728. for (isize i = start; i < ce->args.count; i++) {
  9729. Ast *arg = ce->args[i];
  9730. if (i > start) {
  9731. str = gb_string_appendc(str, ", ");
  9732. }
  9733. str = write_expr_to_string(str, arg, shorthand);
  9734. }
  9735. str = gb_string_appendc(str, ")");
  9736. case_end;
  9737. case_ast_node(ta, TypeAssertion, node);
  9738. str = write_expr_to_string(str, ta->expr, shorthand);
  9739. if (ta->type != nullptr &&
  9740. ta->type->kind == Ast_UnaryExpr &&
  9741. ta->type->UnaryExpr.op.kind == Token_Question) {
  9742. str = gb_string_appendc(str, ".?");
  9743. } else {
  9744. str = gb_string_appendc(str, ".(");
  9745. str = write_expr_to_string(str, ta->type, shorthand);
  9746. str = gb_string_append_rune(str, ')');
  9747. }
  9748. case_end;
  9749. case_ast_node(tc, TypeCast, node);
  9750. str = string_append_token(str, tc->token);
  9751. str = gb_string_append_rune(str, '(');
  9752. str = write_expr_to_string(str, tc->type, shorthand);
  9753. str = gb_string_append_rune(str, ')');
  9754. str = write_expr_to_string(str, tc->expr, shorthand);
  9755. case_end;
  9756. case_ast_node(ac, AutoCast, node);
  9757. str = string_append_token(str, ac->token);
  9758. str = gb_string_append_rune(str, ' ');
  9759. str = write_expr_to_string(str, ac->expr, shorthand);
  9760. case_end;
  9761. case_ast_node(ie, IndexExpr, node);
  9762. str = write_expr_to_string(str, ie->expr, shorthand);
  9763. str = gb_string_append_rune(str, '[');
  9764. str = write_expr_to_string(str, ie->index, shorthand);
  9765. str = gb_string_append_rune(str, ']');
  9766. case_end;
  9767. case_ast_node(se, SliceExpr, node);
  9768. str = write_expr_to_string(str, se->expr, shorthand);
  9769. str = gb_string_append_rune(str, '[');
  9770. str = write_expr_to_string(str, se->low, shorthand);
  9771. str = string_append_token(str, se->interval);
  9772. str = write_expr_to_string(str, se->high, shorthand);
  9773. str = gb_string_append_rune(str, ']');
  9774. case_end;
  9775. case_ast_node(mie, MatrixIndexExpr, node);
  9776. str = write_expr_to_string(str, mie->expr, shorthand);
  9777. str = gb_string_append_rune(str, '[');
  9778. str = write_expr_to_string(str, mie->row_index, shorthand);
  9779. str = gb_string_appendc(str, ", ");
  9780. str = write_expr_to_string(str, mie->column_index, shorthand);
  9781. str = gb_string_append_rune(str, ']');
  9782. case_end;
  9783. case_ast_node(e, Ellipsis, node);
  9784. str = gb_string_appendc(str, "..");
  9785. str = write_expr_to_string(str, e->expr, shorthand);
  9786. case_end;
  9787. case_ast_node(fv, FieldValue, node);
  9788. str = write_expr_to_string(str, fv->field, shorthand);
  9789. str = gb_string_appendc(str, " = ");
  9790. str = write_expr_to_string(str, fv->value, shorthand);
  9791. case_end;
  9792. case_ast_node(fv, EnumFieldValue, node);
  9793. str = write_expr_to_string(str, fv->name, shorthand);
  9794. if (fv->value) {
  9795. str = gb_string_appendc(str, " = ");
  9796. str = write_expr_to_string(str, fv->value, shorthand);
  9797. }
  9798. case_end;
  9799. case_ast_node(ht, HelperType, node);
  9800. str = gb_string_appendc(str, "#type ");
  9801. str = write_expr_to_string(str, ht->type, shorthand);
  9802. case_end;
  9803. case_ast_node(ht, DistinctType, node);
  9804. str = gb_string_appendc(str, "distinct ");
  9805. str = write_expr_to_string(str, ht->type, shorthand);
  9806. case_end;
  9807. case_ast_node(pt, PolyType, node);
  9808. str = gb_string_append_rune(str, '$');
  9809. str = write_expr_to_string(str, pt->type, shorthand);
  9810. if (pt->specialization != nullptr) {
  9811. str = gb_string_append_rune(str, '/');
  9812. str = write_expr_to_string(str, pt->specialization, shorthand);
  9813. }
  9814. case_end;
  9815. case_ast_node(pt, PointerType, node);
  9816. str = gb_string_append_rune(str, '^');
  9817. str = write_expr_to_string(str, pt->type, shorthand);
  9818. case_end;
  9819. case_ast_node(pt, MultiPointerType, node);
  9820. str = gb_string_appendc(str, "[^]");
  9821. str = write_expr_to_string(str, pt->type, shorthand);
  9822. case_end;
  9823. case_ast_node(at, ArrayType, node);
  9824. str = gb_string_append_rune(str, '[');
  9825. if (at->count != nullptr &&
  9826. at->count->kind == Ast_UnaryExpr &&
  9827. at->count->UnaryExpr.op.kind == Token_Question) {
  9828. str = gb_string_appendc(str, "?");
  9829. } else {
  9830. str = write_expr_to_string(str, at->count, shorthand);
  9831. }
  9832. str = gb_string_append_rune(str, ']');
  9833. str = write_expr_to_string(str, at->elem, shorthand);
  9834. case_end;
  9835. case_ast_node(at, DynamicArrayType, node);
  9836. str = gb_string_appendc(str, "[dynamic]");
  9837. str = write_expr_to_string(str, at->elem, shorthand);
  9838. case_end;
  9839. case_ast_node(bs, BitSetType, node);
  9840. str = gb_string_appendc(str, "bit_set[");
  9841. str = write_expr_to_string(str, bs->elem, shorthand);
  9842. str = gb_string_appendc(str, "]");
  9843. case_end;
  9844. case_ast_node(mt, MapType, node);
  9845. str = gb_string_appendc(str, "map[");
  9846. str = write_expr_to_string(str, mt->key, shorthand);
  9847. str = gb_string_append_rune(str, ']');
  9848. str = write_expr_to_string(str, mt->value, shorthand);
  9849. case_end;
  9850. case_ast_node(mt, MatrixType, node);
  9851. str = gb_string_appendc(str, "matrix[");
  9852. str = write_expr_to_string(str, mt->row_count, shorthand);
  9853. str = gb_string_appendc(str, ", ");
  9854. str = write_expr_to_string(str, mt->column_count, shorthand);
  9855. str = gb_string_append_rune(str, ']');
  9856. str = write_expr_to_string(str, mt->elem, shorthand);
  9857. case_end;
  9858. case_ast_node(f, Field, node);
  9859. if (f->flags&FieldFlag_using) {
  9860. str = gb_string_appendc(str, "using ");
  9861. }
  9862. if (f->flags&FieldFlag_no_alias) {
  9863. str = gb_string_appendc(str, "#no_alias ");
  9864. }
  9865. if (f->flags&FieldFlag_c_vararg) {
  9866. str = gb_string_appendc(str, "#c_vararg ");
  9867. }
  9868. if (f->flags&FieldFlag_any_int) {
  9869. str = gb_string_appendc(str, "#any_int ");
  9870. }
  9871. if (f->flags&FieldFlag_no_broadcast) {
  9872. str = gb_string_appendc(str, "#no_broadcast ");
  9873. }
  9874. if (f->flags&FieldFlag_const) {
  9875. str = gb_string_appendc(str, "#const ");
  9876. }
  9877. if (f->flags&FieldFlag_subtype) {
  9878. str = gb_string_appendc(str, "#subtype ");
  9879. }
  9880. for_array(i, f->names) {
  9881. Ast *name = f->names[i];
  9882. if (i > 0) str = gb_string_appendc(str, ", ");
  9883. str = write_expr_to_string(str, name, shorthand);
  9884. }
  9885. if (f->names.count > 0) {
  9886. if (f->type == nullptr && f->default_value != nullptr) {
  9887. str = gb_string_append_rune(str, ' ');
  9888. }
  9889. str = gb_string_appendc(str, ":");
  9890. }
  9891. if (f->type != nullptr) {
  9892. str = gb_string_append_rune(str, ' ');
  9893. str = write_expr_to_string(str, f->type, shorthand);
  9894. }
  9895. if (f->default_value != nullptr) {
  9896. if (f->type != nullptr) {
  9897. str = gb_string_append_rune(str, ' ');
  9898. }
  9899. str = gb_string_appendc(str, "= ");
  9900. str = write_expr_to_string(str, f->default_value, shorthand);
  9901. }
  9902. case_end;
  9903. case_ast_node(f, FieldList, node);
  9904. bool has_name = false;
  9905. for_array(i, f->list) {
  9906. ast_node(field, Field, f->list[i]);
  9907. if (field->names.count > 1) {
  9908. has_name = true;
  9909. break;
  9910. }
  9911. if (field->names.count == 0) {
  9912. continue;
  9913. }
  9914. if (!is_blank_ident(field->names[0])) {
  9915. has_name = true;
  9916. break;
  9917. }
  9918. }
  9919. for_array(i, f->list) {
  9920. if (i > 0) str = gb_string_appendc(str, ", ");
  9921. if (has_name) {
  9922. str = write_expr_to_string(str, f->list[i], shorthand);
  9923. } else {
  9924. ast_node(field, Field, f->list[i]);
  9925. if (field->flags&FieldFlag_using) {
  9926. str = gb_string_appendc(str, "using ");
  9927. }
  9928. if (field->flags&FieldFlag_no_alias) {
  9929. str = gb_string_appendc(str, "#no_alias ");
  9930. }
  9931. if (field->flags&FieldFlag_c_vararg) {
  9932. str = gb_string_appendc(str, "#c_vararg ");
  9933. }
  9934. if (field->flags&FieldFlag_any_int) {
  9935. str = gb_string_appendc(str, "#any_int ");
  9936. }
  9937. if (field->flags&FieldFlag_no_broadcast) {
  9938. str = gb_string_appendc(str, "#no_broadcast ");
  9939. }
  9940. if (field->flags&FieldFlag_const) {
  9941. str = gb_string_appendc(str, "#const ");
  9942. }
  9943. if (field->flags&FieldFlag_subtype) {
  9944. str = gb_string_appendc(str, "#subtype ");
  9945. }
  9946. str = write_expr_to_string(str, field->type, shorthand);
  9947. }
  9948. }
  9949. case_end;
  9950. case_ast_node(ce, CallExpr, node);
  9951. switch (ce->inlining) {
  9952. case ProcInlining_inline:
  9953. str = gb_string_appendc(str, "#force_inline ");
  9954. break;
  9955. case ProcInlining_no_inline:
  9956. str = gb_string_appendc(str, "#force_no_inline ");
  9957. break;
  9958. }
  9959. str = write_expr_to_string(str, ce->proc, shorthand);
  9960. str = gb_string_appendc(str, "(");
  9961. isize idx0 = cast(isize)ce->was_selector;
  9962. for (isize i = idx0; i < ce->args.count; i++) {
  9963. Ast *arg = ce->args[i];
  9964. if (i > idx0) {
  9965. str = gb_string_appendc(str, ", ");
  9966. }
  9967. str = write_expr_to_string(str, arg, shorthand);
  9968. }
  9969. str = gb_string_appendc(str, ")");
  9970. case_end;
  9971. case_ast_node(tt, TypeidType, node);
  9972. str = gb_string_appendc(str, "typeid");
  9973. if (tt->specialization) {
  9974. str = gb_string_appendc(str, "/");
  9975. str = write_expr_to_string(str, tt->specialization, shorthand);
  9976. }
  9977. case_end;
  9978. case_ast_node(pt, ProcType, node);
  9979. str = gb_string_appendc(str, "proc(");
  9980. str = write_expr_to_string(str, pt->params, shorthand);
  9981. str = gb_string_appendc(str, ")");
  9982. if (pt->results != nullptr) {
  9983. str = gb_string_appendc(str, " -> ");
  9984. bool parens_needed = false;
  9985. if (pt->results && pt->results->kind == Ast_FieldList) {
  9986. for (Ast *field : pt->results->FieldList.list) {
  9987. ast_node(f, Field, field);
  9988. if (f->names.count != 0) {
  9989. parens_needed = true;
  9990. break;
  9991. }
  9992. }
  9993. }
  9994. if (parens_needed) {
  9995. str = gb_string_append_rune(str, '(');
  9996. }
  9997. str = write_expr_to_string(str, pt->results, shorthand);
  9998. if (parens_needed) {
  9999. str = gb_string_append_rune(str, ')');
  10000. }
  10001. }
  10002. case_end;
  10003. case_ast_node(st, StructType, node);
  10004. str = gb_string_appendc(str, "struct ");
  10005. if (st->polymorphic_params) {
  10006. str = gb_string_append_rune(str, '(');
  10007. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10008. str = gb_string_appendc(str, ") ");
  10009. }
  10010. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  10011. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  10012. if (st->align) {
  10013. str = gb_string_appendc(str, "#align ");
  10014. str = write_expr_to_string(str, st->align, shorthand);
  10015. str = gb_string_append_rune(str, ' ');
  10016. }
  10017. str = gb_string_append_rune(str, '{');
  10018. if (shorthand) {
  10019. str = gb_string_appendc(str, "...");
  10020. } else {
  10021. str = write_struct_fields_to_string(str, st->fields);
  10022. }
  10023. str = gb_string_append_rune(str, '}');
  10024. case_end;
  10025. case_ast_node(st, UnionType, node);
  10026. str = gb_string_appendc(str, "union ");
  10027. if (st->polymorphic_params) {
  10028. str = gb_string_append_rune(str, '(');
  10029. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10030. str = gb_string_appendc(str, ") ");
  10031. }
  10032. switch (st->kind) {
  10033. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  10034. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  10035. }
  10036. if (st->align) {
  10037. str = gb_string_appendc(str, "#align ");
  10038. str = write_expr_to_string(str, st->align, shorthand);
  10039. str = gb_string_append_rune(str, ' ');
  10040. }
  10041. str = gb_string_append_rune(str, '{');
  10042. if (shorthand) {
  10043. str = gb_string_appendc(str, "...");
  10044. } else {
  10045. str = write_struct_fields_to_string(str, st->variants);
  10046. }
  10047. str = gb_string_append_rune(str, '}');
  10048. case_end;
  10049. case_ast_node(et, EnumType, node);
  10050. str = gb_string_appendc(str, "enum ");
  10051. if (et->base_type != nullptr) {
  10052. str = write_expr_to_string(str, et->base_type, shorthand);
  10053. str = gb_string_append_rune(str, ' ');
  10054. }
  10055. str = gb_string_append_rune(str, '{');
  10056. if (shorthand) {
  10057. str = gb_string_appendc(str, "...");
  10058. } else {
  10059. for_array(i, et->fields) {
  10060. if (i > 0) {
  10061. str = gb_string_appendc(str, ", ");
  10062. }
  10063. str = write_expr_to_string(str, et->fields[i], shorthand);
  10064. }
  10065. }
  10066. str = gb_string_append_rune(str, '}');
  10067. case_end;
  10068. case_ast_node(rt, RelativeType, node);
  10069. str = write_expr_to_string(str, rt->tag, shorthand);
  10070. str = gb_string_appendc(str, "" );
  10071. str = write_expr_to_string(str, rt->type, shorthand);
  10072. case_end;
  10073. case_ast_node(f, BitFieldField, node);
  10074. str = write_expr_to_string(str, f->name, shorthand);
  10075. str = gb_string_appendc(str, ": ");
  10076. str = write_expr_to_string(str, f->type, shorthand);
  10077. str = gb_string_appendc(str, " | ");
  10078. str = write_expr_to_string(str, f->bit_size, shorthand);
  10079. case_end;
  10080. case_ast_node(bf, BitFieldType, node);
  10081. str = gb_string_appendc(str, "bit_field ");
  10082. if (!shorthand) {
  10083. str = write_expr_to_string(str, bf->backing_type, shorthand);
  10084. }
  10085. str = gb_string_appendc(str, " {");
  10086. if (shorthand) {
  10087. str = gb_string_appendc(str, "...");
  10088. } else {
  10089. for_array(i, bf->fields) {
  10090. if (i > 0) {
  10091. str = gb_string_appendc(str, ", ");
  10092. }
  10093. str = write_expr_to_string(str, bf->fields[i], false);
  10094. }
  10095. }
  10096. str = gb_string_appendc(str, "}");
  10097. case_end;
  10098. case_ast_node(ia, InlineAsmExpr, node);
  10099. str = gb_string_appendc(str, "asm(");
  10100. for_array(i, ia->param_types) {
  10101. if (i > 0) {
  10102. str = gb_string_appendc(str, ", ");
  10103. }
  10104. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  10105. }
  10106. str = gb_string_appendc(str, ")");
  10107. if (ia->return_type != nullptr) {
  10108. str = gb_string_appendc(str, " -> ");
  10109. str = write_expr_to_string(str, ia->return_type, shorthand);
  10110. }
  10111. if (ia->has_side_effects) {
  10112. str = gb_string_appendc(str, " #side_effects");
  10113. }
  10114. if (ia->is_align_stack) {
  10115. str = gb_string_appendc(str, " #stack_align");
  10116. }
  10117. if (ia->dialect) {
  10118. str = gb_string_appendc(str, " #");
  10119. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  10120. }
  10121. str = gb_string_appendc(str, " {");
  10122. if (shorthand) {
  10123. str = gb_string_appendc(str, "...");
  10124. } else {
  10125. str = write_expr_to_string(str, ia->asm_string, shorthand);
  10126. str = gb_string_appendc(str, ", ");
  10127. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  10128. }
  10129. str = gb_string_appendc(str, "}");
  10130. case_end;
  10131. }
  10132. return str;
  10133. }
  10134. gb_internal gbString expr_to_string(Ast *expression) {
  10135. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  10136. }
  10137. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  10138. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  10139. }
  10140. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  10141. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  10142. }