check_expr.cpp 310 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859
  1. enum CallArgumentError {
  2. CallArgumentError_None,
  3. CallArgumentError_NoneProcedureType,
  4. CallArgumentError_WrongTypes,
  5. CallArgumentError_NonVariadicExpand,
  6. CallArgumentError_VariadicTuple,
  7. CallArgumentError_MultipleVariadicExpand,
  8. CallArgumentError_AmbiguousPolymorphicVariadic,
  9. CallArgumentError_ArgumentCount,
  10. CallArgumentError_TooFewArguments,
  11. CallArgumentError_TooManyArguments,
  12. CallArgumentError_InvalidFieldValue,
  13. CallArgumentError_ParameterNotFound,
  14. CallArgumentError_ParameterMissing,
  15. CallArgumentError_DuplicateParameter,
  16. CallArgumentError_NoneConstantParameter,
  17. CallArgumentError_OutOfOrderParameters,
  18. CallArgumentError_MAX,
  19. };
  20. gb_global char const *CallArgumentError_strings[CallArgumentError_MAX] = {
  21. "None",
  22. "NoneProcedureType",
  23. "WrongTypes",
  24. "NonVariadicExpand",
  25. "VariadicTuple",
  26. "MultipleVariadicExpand",
  27. "AmbiguousPolymorphicVariadic",
  28. "ArgumentCount",
  29. "TooFewArguments",
  30. "TooManyArguments",
  31. "InvalidFieldValue",
  32. "ParameterNotFound",
  33. "ParameterMissing",
  34. "DuplicateParameter",
  35. "NoneConstantParameter",
  36. "OutOfOrderParameters",
  37. };
  38. enum struct CallArgumentErrorMode {
  39. NoErrors,
  40. ShowErrors,
  41. };
  42. struct CallArgumentData {
  43. Entity *gen_entity;
  44. i64 score;
  45. Type * result_type;
  46. };
  47. struct PolyProcData {
  48. Entity * gen_entity;
  49. ProcInfo *proc_info;
  50. };
  51. struct ValidIndexAndScore {
  52. isize index;
  53. i64 score;
  54. };
  55. gb_internal int valid_index_and_score_cmp(void const *a, void const *b) {
  56. i64 si = (cast(ValidIndexAndScore const *)a)->score;
  57. i64 sj = (cast(ValidIndexAndScore const *)b)->score;
  58. return sj < si ? -1 : sj > si;
  59. }
  60. gb_internal void check_expr (CheckerContext *c, Operand *operand, Ast *expression);
  61. gb_internal void check_multi_expr (CheckerContext *c, Operand *operand, Ast *expression);
  62. gb_internal void check_multi_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression);
  63. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint);
  64. gb_internal void check_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  65. gb_internal ExprKind check_expr_base (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  66. gb_internal void check_expr_with_type_hint (CheckerContext *c, Operand *o, Ast *e, Type *t);
  67. gb_internal Type * check_type (CheckerContext *c, Ast *expression);
  68. gb_internal Type * check_type_expr (CheckerContext *c, Ast *expression, Type *named_type);
  69. gb_internal Type * make_optional_ok_type (Type *value, bool typed=true);
  70. gb_internal Entity * check_selector (CheckerContext *c, Operand *operand, Ast *node, Type *type_hint);
  71. gb_internal Entity * check_ident (CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name);
  72. gb_internal Entity * find_polymorphic_record_entity (CheckerContext *c, Type *original_type, isize param_count, Array<Operand> const &ordered_operands, bool *failure);
  73. gb_internal void check_not_tuple (CheckerContext *c, Operand *operand);
  74. gb_internal void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
  75. gb_internal gbString expr_to_string (Ast *expression);
  76. gb_internal gbString expr_to_string (Ast *expression, gbAllocator allocator);
  77. gb_internal void update_untyped_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
  78. gb_internal bool check_is_terminating (Ast *node, String const &label);
  79. gb_internal bool check_has_break (Ast *stmt, String const &label, bool implicit);
  80. gb_internal void check_stmt (CheckerContext *c, Ast *node, u32 flags);
  81. gb_internal void check_stmt_list (CheckerContext *c, Slice<Ast *> const &stmts, u32 flags);
  82. gb_internal void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
  83. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
  84. gb_internal bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> const *operands = nullptr);
  85. gb_internal void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
  86. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  87. gb_internal void check_union_type (CheckerContext *c, Type *union_type, Ast *node, Array<Operand> *poly_operands,
  88. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  89. gb_internal Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  90. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type);
  91. gb_internal void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
  92. gb_internal Type *make_soa_struct_slice(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  93. gb_internal Type *make_soa_struct_dynamic_array(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  94. gb_internal bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint);
  95. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_);
  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. enum LoadDirectiveResult {
  103. LoadDirective_Success = 0,
  104. LoadDirective_Error = 1,
  105. LoadDirective_NotFound = 2,
  106. };
  107. gb_internal bool is_load_directive_call(Ast *call) {
  108. call = unparen_expr(call);
  109. if (call->kind != Ast_CallExpr) {
  110. return false;
  111. }
  112. ast_node(ce, CallExpr, call);
  113. if (ce->proc->kind != Ast_BasicDirective) {
  114. return false;
  115. }
  116. ast_node(bd, BasicDirective, ce->proc);
  117. String name = bd->name.string;
  118. return name == "load";
  119. }
  120. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  121. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  122. auto results = did_you_mean_results(d);
  123. if (results.count != 0) {
  124. error_line("\tSuggestion: Did you mean?\n");
  125. for (auto const &result : results) {
  126. String const &target = result.target;
  127. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  128. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  129. }
  130. }
  131. }
  132. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  133. if (e->kind != Entity_TypeName) {
  134. return;
  135. }
  136. if (e->TypeName.objc_metadata == nullptr) {
  137. return;
  138. }
  139. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  140. Type *t = base_type(e->type);
  141. GB_ASSERT(t->kind == Type_Struct);
  142. if (is_type) {
  143. for (auto const &entry : objc_metadata->type_entries) {
  144. string_set_add(set, entry.name);
  145. }
  146. } else {
  147. for (auto const &entry : objc_metadata->value_entries) {
  148. string_set_add(set, entry.name);
  149. }
  150. }
  151. for (Entity *f : t->Struct.fields) {
  152. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  153. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  154. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  155. }
  156. }
  157. }
  158. }
  159. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  160. ERROR_BLOCK();
  161. GB_ASSERT(e->kind == Entity_TypeName);
  162. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  163. auto *objc_metadata = e->TypeName.objc_metadata;
  164. MUTEX_GUARD(objc_metadata->mutex);
  165. StringSet set = {};
  166. defer (string_set_destroy(&set));
  167. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  168. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  169. defer (did_you_mean_destroy(&d));
  170. for (String const &target : set) {
  171. did_you_mean_append(&d, target);
  172. }
  173. check_did_you_mean_print(&d, prefix);
  174. }
  175. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  176. ERROR_BLOCK();
  177. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  178. defer (did_you_mean_destroy(&d));
  179. for (Entity *e : fields) {
  180. did_you_mean_append(&d, e->token.string);
  181. }
  182. check_did_you_mean_print(&d, prefix);
  183. }
  184. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  185. ERROR_BLOCK();
  186. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  187. defer (did_you_mean_destroy(&d));
  188. for (Entity *e : fields) {
  189. did_you_mean_append(&d, e->token.string);
  190. }
  191. check_did_you_mean_print(&d, prefix);
  192. }
  193. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  194. ERROR_BLOCK();
  195. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  196. defer (did_you_mean_destroy(&d));
  197. rw_mutex_shared_lock(&scope->mutex);
  198. for (auto const &entry : scope->elements) {
  199. Entity *e = entry.value;
  200. did_you_mean_append(&d, e->token.string);
  201. }
  202. rw_mutex_shared_unlock(&scope->mutex);
  203. check_did_you_mean_print(&d, prefix);
  204. }
  205. gb_internal Entity *entity_from_expr(Ast *expr) {
  206. expr = unparen_expr(expr);
  207. switch (expr->kind) {
  208. case Ast_Ident:
  209. return expr->Ident.entity;
  210. case Ast_SelectorExpr:
  211. return entity_from_expr(expr->SelectorExpr.selector);
  212. }
  213. return nullptr;
  214. }
  215. gb_internal void error_operand_not_expression(Operand *o) {
  216. if (o->mode == Addressing_Type) {
  217. gbString err = expr_to_string(o->expr);
  218. error(o->expr, "'%s' is not an expression but a type", err);
  219. gb_string_free(err);
  220. o->mode = Addressing_Invalid;
  221. }
  222. }
  223. gb_internal void error_operand_no_value(Operand *o) {
  224. if (o->mode == Addressing_NoValue) {
  225. gbString err = expr_to_string(o->expr);
  226. Ast *x = unparen_expr(o->expr);
  227. if (x->kind == Ast_CallExpr) {
  228. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  229. } else {
  230. error(o->expr, "'%s' used as a value", err);
  231. }
  232. gb_string_free(err);
  233. o->mode = Addressing_Invalid;
  234. }
  235. }
  236. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  237. if (build_context.dynamic_map_calls) {
  238. add_package_dependency(c, "runtime", "__dynamic_map_get");
  239. } else {
  240. add_package_dependency(c, "runtime", "map_desired_position");
  241. add_package_dependency(c, "runtime", "map_probe_distance");
  242. }
  243. }
  244. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  245. init_core_source_code_location(c->checker);
  246. if (t_map_set_proc == nullptr) {
  247. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  248. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  249. }
  250. if (build_context.dynamic_map_calls) {
  251. add_package_dependency(c, "runtime", "__dynamic_map_set");
  252. } else {
  253. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  254. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  255. }
  256. }
  257. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  258. init_core_source_code_location(c->checker);
  259. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  260. }
  261. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  262. Scope *s = c->scope;
  263. check_collect_entities(c, nodes);
  264. for (auto const &entry : s->elements) {
  265. Entity *e = entry.value;
  266. switch (e->kind) {
  267. case Entity_Constant:
  268. case Entity_TypeName:
  269. case Entity_Procedure:
  270. break;
  271. default:
  272. continue;
  273. }
  274. DeclInfo *d = decl_info_of_entity(e);
  275. if (d != nullptr) {
  276. check_entity_decl(c, e, d, nullptr);
  277. }
  278. }
  279. }
  280. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  281. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  282. ///////////////////////////////////////////////////////////////////////////////
  283. // //
  284. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  285. // //
  286. ///////////////////////////////////////////////////////////////////////////////
  287. CheckerInfo *info = old_c->info;
  288. if (base_entity == nullptr) {
  289. return false;
  290. }
  291. if (!is_type_proc(base_entity->type)) {
  292. return false;
  293. }
  294. String name = base_entity->token.string;
  295. Type *src = base_type(base_entity->type);
  296. Type *dst = nullptr;
  297. if (type != nullptr) {
  298. dst = base_type(type);
  299. }
  300. if (param_operands == nullptr) {
  301. GB_ASSERT(dst != nullptr);
  302. }
  303. if (param_operands != nullptr) {
  304. GB_ASSERT(dst == nullptr);
  305. }
  306. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  307. return false;
  308. }
  309. if (dst != nullptr) {
  310. if (dst->Proc.is_polymorphic) {
  311. return false;
  312. }
  313. if (dst->Proc.param_count != src->Proc.param_count ||
  314. dst->Proc.result_count != src->Proc.result_count) {
  315. return false;
  316. }
  317. }
  318. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  319. if (old_decl == nullptr) {
  320. return false;
  321. }
  322. gbAllocator a = heap_allocator();
  323. Array<Operand> operands = {};
  324. if (param_operands) {
  325. operands = *param_operands;
  326. } else {
  327. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  328. for (isize i = 0; i < dst->Proc.param_count; i++) {
  329. Entity *param = dst->Proc.params->Tuple.variables[i];
  330. Operand o = {Addressing_Value};
  331. o.type = param->type;
  332. array_add(&operands, o);
  333. }
  334. }
  335. defer (if (param_operands == nullptr) {
  336. array_free(&operands);
  337. });
  338. CheckerContext nctx = *old_c;
  339. Scope *scope = create_scope(info, base_entity->scope);
  340. scope->flags |= ScopeFlag_Proc;
  341. nctx.scope = scope;
  342. nctx.allow_polymorphic_types = true;
  343. if (nctx.polymorphic_scope == nullptr) {
  344. nctx.polymorphic_scope = scope;
  345. }
  346. auto *pt = &src->Proc;
  347. // NOTE(bill): This is slightly memory leaking if the type already exists
  348. // Maybe it's better to check with the previous types first?
  349. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  350. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  351. if (!success) {
  352. return false;
  353. }
  354. GenProcsData *gen_procs = nullptr;
  355. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  356. GB_ASSERT(base_entity->kind == Entity_Procedure);
  357. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  358. gen_procs = base_entity->Procedure.gen_procs;
  359. if (gen_procs) {
  360. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  361. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  362. for (Entity *other : gen_procs->procs) {
  363. Type *pt = base_type(other->type);
  364. if (are_types_identical(pt, final_proc_type)) {
  365. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  366. if (poly_proc_data) {
  367. poly_proc_data->gen_entity = other;
  368. }
  369. return true;
  370. }
  371. }
  372. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  373. } else {
  374. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  375. gen_procs->procs.allocator = heap_allocator();
  376. base_entity->Procedure.gen_procs = gen_procs;
  377. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  378. }
  379. {
  380. // LEAK TODO(bill): This is technically a memory leak as it has to generate the type twice
  381. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  382. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  383. nctx.no_polymorphic_errors = false;
  384. // NOTE(bill): Reset scope from the failed procedure type
  385. scope_reset(scope);
  386. // LEAK TODO(bill): Cloning this AST may be leaky
  387. Ast *cloned_proc_type_node = clone_ast(pt->node);
  388. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  389. if (!success) {
  390. return false;
  391. }
  392. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  393. for (Entity *other : gen_procs->procs) {
  394. Type *pt = base_type(other->type);
  395. if (are_types_identical(pt, final_proc_type)) {
  396. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  397. if (poly_proc_data) {
  398. poly_proc_data->gen_entity = other;
  399. }
  400. DeclInfo *decl = other->decl_info;
  401. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  402. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  403. proc_info->file = other->file;
  404. proc_info->token = other->token;
  405. proc_info->decl = decl;
  406. proc_info->type = other->type;
  407. proc_info->body = decl->proc_lit->ProcLit.body;
  408. proc_info->tags = other->Procedure.tags;;
  409. proc_info->generated_from_polymorphic = true;
  410. proc_info->poly_def_node = poly_def_node;
  411. check_procedure_later(nctx.checker, proc_info);
  412. }
  413. return true;
  414. }
  415. }
  416. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  417. }
  418. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  419. ast_node(pl, ProcLit, proc_lit);
  420. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  421. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  422. final_proc_type->Proc.is_poly_specialized = true;
  423. final_proc_type->Proc.is_polymorphic = true;
  424. final_proc_type->Proc.variadic = src->Proc.variadic;
  425. final_proc_type->Proc.require_results = src->Proc.require_results;
  426. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  427. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  428. final_proc_type->Proc.diverging = src->Proc.diverging;
  429. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  430. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  431. for (isize i = 0; i < operands.count; i++) {
  432. Operand o = operands[i];
  433. if (final_proc_type == o.type ||
  434. base_entity->type == o.type) {
  435. // NOTE(bill): Cycle
  436. final_proc_type->Proc.is_poly_specialized = false;
  437. break;
  438. }
  439. }
  440. u64 tags = base_entity->Procedure.tags;
  441. Ast *ident = clone_ast(base_entity->identifier);
  442. Token token = ident->Ident.token;
  443. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  444. d->gen_proc_type = final_proc_type;
  445. d->type_expr = pl->type;
  446. d->proc_lit = proc_lit;
  447. d->proc_checked_state = ProcCheckedState_Unchecked;
  448. d->defer_use_checked = false;
  449. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  450. entity->identifier = ident;
  451. add_entity_and_decl_info(&nctx, ident, entity, d);
  452. // NOTE(bill): Set the scope afterwards as this is not real overloading
  453. entity->scope = scope->parent;
  454. entity->file = base_entity->file;
  455. entity->pkg = base_entity->pkg;
  456. entity->flags = 0;
  457. d->entity = entity;
  458. AstFile *file = nullptr;
  459. {
  460. Scope *s = entity->scope;
  461. while (s != nullptr && s->file == nullptr) {
  462. file = s->file;
  463. s = s->parent;
  464. }
  465. }
  466. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  467. array_add(&gen_procs->procs, entity);
  468. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  469. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  470. proc_info->file = file;
  471. proc_info->token = token;
  472. proc_info->decl = d;
  473. proc_info->type = final_proc_type;
  474. proc_info->body = pl->body;
  475. proc_info->tags = tags;
  476. proc_info->generated_from_polymorphic = true;
  477. proc_info->poly_def_node = poly_def_node;
  478. if (poly_proc_data) {
  479. poly_proc_data->gen_entity = entity;
  480. poly_proc_data->proc_info = proc_info;
  481. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  482. }
  483. // NOTE(bill): Check the newly generated procedure body
  484. check_procedure_later(nctx.checker, proc_info);
  485. return true;
  486. }
  487. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  488. if (operand->expr == nullptr) return false;
  489. Entity *base_entity = entity_of_node(operand->expr);
  490. if (base_entity == nullptr) return false;
  491. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  492. }
  493. 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) {
  494. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  495. }
  496. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  497. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  498. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  499. #define MAXIMUM_TYPE_DISTANCE 10
  500. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type) {
  501. if (c == nullptr) {
  502. GB_ASSERT(operand->mode == Addressing_Value);
  503. GB_ASSERT(is_type_typed(operand->type));
  504. }
  505. if (operand->mode == Addressing_Invalid ||
  506. type == t_invalid) {
  507. return -1;
  508. }
  509. if (operand->mode == Addressing_Builtin) {
  510. return -1;
  511. }
  512. if (operand->mode == Addressing_Type) {
  513. if (is_type_typeid(type)) {
  514. add_type_info_type(c, operand->type);
  515. return 4;
  516. }
  517. return -1;
  518. }
  519. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  520. return -1;
  521. }
  522. Type *s = operand->type;
  523. if (are_types_identical(s, type)) {
  524. return 0;
  525. }
  526. Type *src = base_type(s);
  527. Type *dst = base_type(type);
  528. if (is_type_untyped_uninit(src)) {
  529. return 1;
  530. }
  531. if (is_type_untyped_nil(src)) {
  532. if (type_has_nil(dst)) {
  533. return 1;
  534. }
  535. return -1;
  536. }
  537. if (is_type_untyped(src)) {
  538. if (is_type_any(dst)) {
  539. // NOTE(bill): Anything can cast to 'Any'
  540. add_type_info_type(c, s);
  541. return MAXIMUM_TYPE_DISTANCE;
  542. }
  543. if (dst->kind == Type_Basic) {
  544. if (operand->mode == Addressing_Constant) {
  545. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  546. if (is_type_typed(dst) && src->kind == Type_Basic) {
  547. switch (src->Basic.kind) {
  548. case Basic_UntypedRune:
  549. if (is_type_integer(dst) || is_type_rune(dst)) {
  550. return 1;
  551. }
  552. break;
  553. case Basic_UntypedInteger:
  554. if (is_type_integer(dst) || is_type_rune(dst)) {
  555. return 1;
  556. }
  557. break;
  558. case Basic_UntypedString:
  559. if (is_type_string(dst)) {
  560. return 1;
  561. }
  562. break;
  563. case Basic_UntypedFloat:
  564. if (is_type_float(dst)) {
  565. return 1;
  566. }
  567. break;
  568. case Basic_UntypedComplex:
  569. if (is_type_complex(dst)) {
  570. return 1;
  571. }
  572. if (is_type_quaternion(dst)) {
  573. return 2;
  574. }
  575. break;
  576. case Basic_UntypedQuaternion:
  577. if (is_type_quaternion(dst)) {
  578. return 1;
  579. }
  580. break;
  581. }
  582. }
  583. return 2;
  584. }
  585. return -1;
  586. }
  587. if (src->kind == Type_Basic) {
  588. i64 score = -1;
  589. switch (src->Basic.kind) {
  590. case Basic_UntypedRune:
  591. if (is_type_integer(dst) || is_type_rune(dst)) {
  592. score = 1;
  593. }
  594. break;
  595. case Basic_UntypedInteger:
  596. if (is_type_integer(dst) || is_type_rune(dst)) {
  597. score = 1;
  598. }
  599. break;
  600. case Basic_UntypedString:
  601. if (is_type_string(dst)) {
  602. score = 1;
  603. }
  604. break;
  605. case Basic_UntypedFloat:
  606. if (is_type_float(dst)) {
  607. score = 1;
  608. }
  609. break;
  610. case Basic_UntypedComplex:
  611. if (is_type_complex(dst)) {
  612. score = 1;
  613. }
  614. if (is_type_quaternion(dst)) {
  615. score = 2;
  616. }
  617. break;
  618. case Basic_UntypedQuaternion:
  619. if (is_type_quaternion(dst)) {
  620. score = 1;
  621. }
  622. break;
  623. }
  624. if (score > 0) {
  625. if (is_type_typed(dst)) {
  626. score += 1;
  627. }
  628. }
  629. return score;
  630. }
  631. }
  632. }
  633. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  634. if (c->in_enum_type) {
  635. return 3;
  636. }
  637. }
  638. {
  639. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  640. if (subtype_level > 0) {
  641. return 4 + subtype_level;
  642. }
  643. }
  644. // ^T <- rawptr
  645. #if 0
  646. // TODO(bill): Should C-style (not C++) pointer cast be allowed?
  647. if (is_type_pointer(dst) && is_type_rawptr(src)) {
  648. return true;
  649. }
  650. #endif
  651. #if 1
  652. // rawptr <- ^T
  653. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  654. return 5;
  655. }
  656. // rawptr <- [^]T
  657. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  658. return 5;
  659. }
  660. // ^T <- [^]T
  661. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  662. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  663. return 4;
  664. }
  665. }
  666. // [^]T <- ^T
  667. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  668. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  669. return 4;
  670. }
  671. }
  672. #endif
  673. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  674. bool modify_type = !c->no_polymorphic_errors;
  675. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  676. return 2;
  677. }
  678. }
  679. if (is_type_union(dst)) {
  680. for (Type *vt : dst->Union.variants) {
  681. if (are_types_identical(vt, s)) {
  682. return 1;
  683. }
  684. }
  685. // TODO(bill): Determine which rule is a better on in practice
  686. if (dst->Union.variants.count == 1) {
  687. Type *vt = dst->Union.variants[0];
  688. i64 score = check_distance_between_types(c, operand, vt);
  689. if (score >= 0) {
  690. return score+2;
  691. }
  692. } else if (is_type_untyped(src)) {
  693. i64 prev_lowest_score = -1;
  694. i64 lowest_score = -1;
  695. for (Type *vt : dst->Union.variants) {
  696. i64 score = check_distance_between_types(c, operand, vt);
  697. if (score >= 0) {
  698. if (lowest_score < 0) {
  699. lowest_score = score;
  700. } else {
  701. if (prev_lowest_score < 0) {
  702. prev_lowest_score = lowest_score;
  703. } else {
  704. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  705. }
  706. lowest_score = gb_min(lowest_score, score);
  707. }
  708. }
  709. }
  710. if (lowest_score >= 0) {
  711. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  712. return lowest_score+2;
  713. }
  714. }
  715. }
  716. }
  717. if (is_type_relative_pointer(dst)) {
  718. i64 score = check_distance_between_types(c, operand, dst->RelativePointer.pointer_type);
  719. if (score >= 0) {
  720. return score+2;
  721. }
  722. }
  723. if (is_type_relative_slice(dst)) {
  724. i64 score = check_distance_between_types(c, operand, dst->RelativeSlice.slice_type);
  725. if (score >= 0) {
  726. return score+2;
  727. }
  728. }
  729. if (is_type_proc(dst)) {
  730. if (are_types_identical(src, dst)) {
  731. return 3;
  732. }
  733. PolyProcData poly_proc_data = {};
  734. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  735. Entity *e = poly_proc_data.gen_entity;
  736. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  737. add_entity_use(c, operand->expr, e);
  738. return 4;
  739. }
  740. }
  741. if (is_type_complex_or_quaternion(dst)) {
  742. Type *elem = base_complex_elem_type(dst);
  743. if (are_types_identical(elem, base_type(src))) {
  744. return 5;
  745. }
  746. }
  747. if (is_type_array(dst)) {
  748. Type *elem = base_array_type(dst);
  749. i64 distance = check_distance_between_types(c, operand, elem);
  750. if (distance >= 0) {
  751. return distance + 6;
  752. }
  753. }
  754. if (is_type_simd_vector(dst)) {
  755. Type *dst_elem = base_array_type(dst);
  756. i64 distance = check_distance_between_types(c, operand, dst_elem);
  757. if (distance >= 0) {
  758. return distance + 6;
  759. }
  760. }
  761. if (is_type_matrix(dst)) {
  762. if (are_types_identical(src, dst)) {
  763. return 5;
  764. }
  765. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  766. Type *dst_elem = base_array_type(dst);
  767. i64 distance = check_distance_between_types(c, operand, dst_elem);
  768. if (distance >= 0) {
  769. return distance + 7;
  770. }
  771. }
  772. }
  773. if (is_type_any(dst)) {
  774. if (!is_type_polymorphic(src)) {
  775. if (operand->mode == Addressing_Context && operand->type == t_context) {
  776. return -1;
  777. } else {
  778. // NOTE(bill): Anything can cast to 'Any'
  779. add_type_info_type(c, s);
  780. return MAXIMUM_TYPE_DISTANCE;
  781. }
  782. }
  783. }
  784. Ast *expr = unparen_expr(operand->expr);
  785. if (expr != nullptr) {
  786. if (expr->kind == Ast_AutoCast) {
  787. Operand x = *operand;
  788. x.expr = expr->AutoCast.expr;
  789. if (check_cast_internal(c, &x, type)) {
  790. return MAXIMUM_TYPE_DISTANCE;
  791. }
  792. }
  793. }
  794. return -1;
  795. }
  796. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  797. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  798. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  799. // TODO(bill): A decent score function
  800. i64 d = distance*distance; // x^2
  801. if (is_variadic && d >= 0) {
  802. d += distance + 1; // x^2 + x + 1
  803. }
  804. return gb_max(c - d, 0);
  805. }
  806. gb_internal bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_, bool is_variadic=false) {
  807. i64 score = 0;
  808. i64 distance = check_distance_between_types(c, operand, type);
  809. bool ok = distance >= 0;
  810. if (ok) {
  811. score = assign_score_function(distance, is_variadic);
  812. }
  813. if (score_) *score_ = score;
  814. return ok;
  815. }
  816. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type) {
  817. i64 score = 0;
  818. return check_is_assignable_to_with_score(c, operand, type, &score);
  819. }
  820. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  821. Operand x = {};
  822. x.type = src;
  823. x.mode = Addressing_Value;
  824. return check_is_assignable_to(nullptr, &x, dst);
  825. }
  826. gb_internal AstPackage *get_package_of_type(Type *type) {
  827. for (;;) {
  828. if (type == nullptr) {
  829. return nullptr;
  830. }
  831. switch (type->kind) {
  832. case Type_Basic:
  833. return builtin_pkg;
  834. case Type_Named:
  835. if (type->Named.type_name != nullptr) {
  836. return type->Named.type_name->pkg;
  837. }
  838. return nullptr;
  839. case Type_Pointer:
  840. type = type->Pointer.elem;
  841. continue;
  842. case Type_Array:
  843. type = type->Array.elem;
  844. continue;
  845. case Type_Slice:
  846. type = type->Slice.elem;
  847. continue;
  848. case Type_DynamicArray:
  849. type = type->DynamicArray.elem;
  850. continue;
  851. case Type_RelativePointer:
  852. type = type->RelativePointer.pointer_type;
  853. continue;
  854. case Type_RelativeSlice:
  855. type = type->RelativeSlice.slice_type;
  856. continue;
  857. }
  858. return nullptr;
  859. }
  860. }
  861. // NOTE(bill): 'content_name' is for debugging and error messages
  862. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  863. check_not_tuple(c, operand);
  864. if (operand->mode == Addressing_Invalid) {
  865. return;
  866. }
  867. if (is_type_untyped(operand->type)) {
  868. Type *target_type = type;
  869. if (type == nullptr || is_type_any(type)) {
  870. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  871. error(operand->expr, "Use of --- in %.*s", LIT(context_name));
  872. operand->mode = Addressing_Invalid;
  873. return;
  874. }
  875. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  876. error(operand->expr, "Use of untyped nil in %.*s", LIT(context_name));
  877. operand->mode = Addressing_Invalid;
  878. return;
  879. }
  880. target_type = default_type(operand->type);
  881. if (type != nullptr && !is_type_any(type)) {
  882. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  883. }
  884. add_type_info_type(c, type);
  885. add_type_info_type(c, target_type);
  886. }
  887. convert_to_typed(c, operand, target_type);
  888. if (operand->mode == Addressing_Invalid) {
  889. return;
  890. }
  891. }
  892. if (type == nullptr) {
  893. return;
  894. }
  895. if (operand->mode == Addressing_ProcGroup) {
  896. bool good = false;
  897. if (type != nullptr && is_type_proc(type)) {
  898. Array<Entity *> procs = proc_group_entities(c, *operand);
  899. // NOTE(bill): These should be done
  900. for (Entity *e : procs) {
  901. Type *t = base_type(e->type);
  902. if (t == t_invalid) {
  903. continue;
  904. }
  905. Operand x = {};
  906. x.mode = Addressing_Value;
  907. x.type = t;
  908. if (check_is_assignable_to(c, &x, type)) {
  909. add_entity_use(c, operand->expr, e);
  910. good = true;
  911. break;
  912. }
  913. }
  914. }
  915. if (!good) {
  916. gbString expr_str = expr_to_string(operand->expr);
  917. gbString op_type_str = type_to_string(operand->type);
  918. gbString type_str = type_to_string(type);
  919. defer (gb_string_free(type_str));
  920. defer (gb_string_free(op_type_str));
  921. defer (gb_string_free(expr_str));
  922. // TODO(bill): is this a good enough error message?
  923. error(operand->expr,
  924. "Cannot assign overloaded procedure '%s' to '%s' in %.*s",
  925. expr_str,
  926. op_type_str,
  927. LIT(context_name));
  928. operand->mode = Addressing_Invalid;
  929. }
  930. convert_to_typed(c, operand, type);
  931. return;
  932. }
  933. if (check_is_assignable_to(c, operand, type)) {
  934. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  935. add_type_info_type(c, operand->type);
  936. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  937. }
  938. } else {
  939. gbString expr_str = expr_to_string(operand->expr);
  940. gbString op_type_str = type_to_string(operand->type);
  941. gbString type_str = type_to_string(type);
  942. defer (gb_string_free(type_str));
  943. defer (gb_string_free(op_type_str));
  944. defer (gb_string_free(expr_str));
  945. switch (operand->mode) {
  946. case Addressing_Builtin:
  947. // TODO(bill): Actually allow built in procedures to be passed around and thus be created on use
  948. error(operand->expr,
  949. "Cannot assign built-in procedure '%s' in %.*s",
  950. expr_str,
  951. LIT(context_name));
  952. break;
  953. case Addressing_Type:
  954. error(operand->expr,
  955. "Cannot assign '%s' which is a type in %.*s",
  956. op_type_str,
  957. LIT(context_name));
  958. break;
  959. default:
  960. // TODO(bill): is this a good enough error message?
  961. {
  962. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  963. gbString type_extra = gb_string_make(heap_allocator(), "");
  964. defer (gb_string_free(op_type_extra));
  965. defer (gb_string_free(type_extra));
  966. isize on = gb_string_length(op_type_str);
  967. isize tn = gb_string_length(type_str);
  968. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  969. AstPackage *op_pkg = get_package_of_type(operand->type);
  970. AstPackage *type_pkg = get_package_of_type(type);
  971. if (op_pkg != nullptr) {
  972. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  973. }
  974. if (type_pkg != nullptr) {
  975. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  976. }
  977. }
  978. ERROR_BLOCK();
  979. error(operand->expr,
  980. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s",
  981. expr_str,
  982. op_type_str, op_type_extra,
  983. type_str, type_extra,
  984. LIT(context_name));
  985. check_assignment_error_suggestion(c, operand, type);
  986. }
  987. break;
  988. }
  989. operand->mode = Addressing_Invalid;
  990. return;
  991. }
  992. }
  993. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  994. Type *gt = *gt_;
  995. GB_ASSERT(gt->kind == Type_Generic);
  996. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  997. GB_ASSERT(e != nullptr);
  998. if (e->kind == Entity_TypeName) {
  999. *gt_ = nullptr;
  1000. *dst_count = source_count;
  1001. e->kind = Entity_Constant;
  1002. e->Constant.value = exact_value_i64(source_count);
  1003. e->type = t_untyped_integer;
  1004. return true;
  1005. } else if (e->kind == Entity_Constant) {
  1006. *gt_ = nullptr;
  1007. if (e->Constant.value.kind != ExactValue_Integer) {
  1008. return false;
  1009. }
  1010. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1011. if (count != source_count) {
  1012. return false;
  1013. }
  1014. *dst_count = source_count;
  1015. return true;
  1016. }
  1017. return false;
  1018. }
  1019. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1020. Operand o = {Addressing_Value};
  1021. o.type = source;
  1022. switch (poly->kind) {
  1023. case Type_Basic:
  1024. if (compound) return are_types_identical(poly, source);
  1025. return check_is_assignable_to(c, &o, poly);
  1026. case Type_Named: {
  1027. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1028. return true;
  1029. }
  1030. if (compound || !is_type_generic(poly)) {
  1031. return are_types_identical(poly, source);
  1032. }
  1033. return check_is_assignable_to(c, &o, poly);
  1034. }
  1035. case Type_Generic: {
  1036. if (poly->Generic.specialized != nullptr) {
  1037. Type *s = poly->Generic.specialized;
  1038. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1039. return false;
  1040. }
  1041. }
  1042. if (modify_type) {
  1043. Type *ds = default_type(source);
  1044. gb_memmove(poly, ds, gb_size_of(Type));
  1045. }
  1046. return true;
  1047. }
  1048. case Type_Pointer:
  1049. if (source->kind == Type_Pointer) {
  1050. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem);
  1051. if (level > 0) {
  1052. return true;
  1053. }
  1054. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1055. } else if (source->kind == Type_MultiPointer) {
  1056. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1057. if (level > 0) {
  1058. return true;
  1059. }
  1060. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1061. }
  1062. return false;
  1063. case Type_MultiPointer:
  1064. if (source->kind == Type_MultiPointer) {
  1065. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1066. if (level > 0) {
  1067. return true;
  1068. }
  1069. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1070. } else if (source->kind == Type_Pointer) {
  1071. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1072. if (level > 0) {
  1073. return true;
  1074. }
  1075. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1076. }
  1077. return false;
  1078. case Type_Array:
  1079. if (source->kind == Type_Array) {
  1080. if (poly->Array.generic_count != nullptr) {
  1081. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1082. return false;
  1083. }
  1084. }
  1085. if (poly->Array.count == source->Array.count) {
  1086. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1087. }
  1088. } else if (source->kind == Type_EnumeratedArray) {
  1089. if (poly->Array.generic_count != nullptr) {
  1090. Type *gt = poly->Array.generic_count;
  1091. GB_ASSERT(gt->kind == Type_Generic);
  1092. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1093. GB_ASSERT(e != nullptr);
  1094. if (e->kind == Entity_TypeName) {
  1095. Type *index = source->EnumeratedArray.index;
  1096. Type *it = base_type(index);
  1097. if (it->kind != Type_Enum) {
  1098. return false;
  1099. }
  1100. poly->kind = Type_EnumeratedArray;
  1101. poly->cached_size = -1;
  1102. poly->cached_align = -1;
  1103. poly->flags.exchange(source->flags);
  1104. poly->failure = false;
  1105. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1106. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1107. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1108. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1109. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1110. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1111. e->kind = Entity_TypeName;
  1112. e->TypeName.is_type_alias = true;
  1113. e->type = index;
  1114. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1115. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1116. }
  1117. }
  1118. }
  1119. }
  1120. return false;
  1121. case Type_EnumeratedArray:
  1122. if (source->kind == Type_EnumeratedArray) {
  1123. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1124. return false;
  1125. }
  1126. if (poly->EnumeratedArray.op) {
  1127. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1128. return false;
  1129. }
  1130. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1131. return false;
  1132. }
  1133. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1134. return false;
  1135. }
  1136. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1137. }
  1138. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1139. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1140. return index || elem;
  1141. }
  1142. return false;
  1143. case Type_DynamicArray:
  1144. if (source->kind == Type_DynamicArray) {
  1145. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1146. }
  1147. return false;
  1148. case Type_Slice:
  1149. if (source->kind == Type_Slice) {
  1150. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1151. }
  1152. return false;
  1153. case Type_Enum:
  1154. return false;
  1155. case Type_BitSet:
  1156. if (source->kind == Type_BitSet) {
  1157. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1158. return false;
  1159. }
  1160. if (poly->BitSet.underlying == nullptr) {
  1161. if (modify_type) {
  1162. poly->BitSet.underlying = source->BitSet.underlying;
  1163. }
  1164. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1165. return false;
  1166. }
  1167. return true;
  1168. }
  1169. return false;
  1170. case Type_Union:
  1171. if (source->kind == Type_Union) {
  1172. TypeUnion *x = &poly->Union;
  1173. TypeUnion *y = &source->Union;
  1174. if (x->variants.count != y->variants.count) {
  1175. return false;
  1176. }
  1177. for_array(i, x->variants) {
  1178. Type *a = x->variants[i];
  1179. Type *b = y->variants[i];
  1180. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1181. if (!ok) return false;
  1182. }
  1183. return true;
  1184. }
  1185. return false;
  1186. case Type_Struct:
  1187. if (source->kind == Type_Struct) {
  1188. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1189. poly->Struct.soa_kind != StructSoa_None) {
  1190. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1191. if (ok) switch (source->Struct.soa_kind) {
  1192. case StructSoa_Fixed:
  1193. default:
  1194. GB_PANIC("Unhandled SOA Kind");
  1195. break;
  1196. case StructSoa_Slice:
  1197. if (modify_type) {
  1198. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1199. gb_memmove(poly, type, gb_size_of(*type));
  1200. }
  1201. break;
  1202. case StructSoa_Dynamic:
  1203. if (modify_type) {
  1204. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1205. gb_memmove(poly, type, gb_size_of(*type));
  1206. }
  1207. break;
  1208. }
  1209. return ok;
  1210. }
  1211. // return check_is_assignable_to(c, &o, poly);
  1212. }
  1213. return false;
  1214. case Type_Tuple:
  1215. GB_PANIC("This should never happen");
  1216. return false;
  1217. case Type_Proc:
  1218. if (source->kind == Type_Proc) {
  1219. // return check_is_assignable_to(c, &o, poly);
  1220. // TODO(bill): Polymorphic type assignment
  1221. #if 1
  1222. TypeProc *x = &poly->Proc;
  1223. TypeProc *y = &source->Proc;
  1224. if (x->calling_convention != y->calling_convention) {
  1225. return false;
  1226. }
  1227. if (x->c_vararg != y->c_vararg) {
  1228. return false;
  1229. }
  1230. if (x->variadic != y->variadic) {
  1231. return false;
  1232. }
  1233. if (x->param_count != y->param_count) {
  1234. return false;
  1235. }
  1236. if (x->result_count != y->result_count) {
  1237. return false;
  1238. }
  1239. for (isize i = 0; i < x->param_count; i++) {
  1240. Entity *a = x->params->Tuple.variables[i];
  1241. Entity *b = y->params->Tuple.variables[i];
  1242. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1243. if (!ok) return false;
  1244. }
  1245. for (isize i = 0; i < x->result_count; i++) {
  1246. Entity *a = x->results->Tuple.variables[i];
  1247. Entity *b = y->results->Tuple.variables[i];
  1248. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1249. if (!ok) return false;
  1250. }
  1251. return true;
  1252. #endif
  1253. }
  1254. return false;
  1255. case Type_Map:
  1256. if (source->kind == Type_Map) {
  1257. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1258. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1259. if (key || value) {
  1260. poly->Map.lookup_result_type = nullptr;
  1261. init_map_internal_types(poly);
  1262. return true;
  1263. }
  1264. }
  1265. return false;
  1266. case Type_Matrix:
  1267. if (source->kind == Type_Matrix) {
  1268. if (poly->Matrix.generic_row_count != nullptr) {
  1269. poly->Matrix.stride_in_bytes = 0;
  1270. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1271. return false;
  1272. }
  1273. }
  1274. if (poly->Matrix.generic_column_count != nullptr) {
  1275. poly->Matrix.stride_in_bytes = 0;
  1276. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1277. return false;
  1278. }
  1279. }
  1280. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1281. poly->Matrix.column_count == source->Matrix.column_count) {
  1282. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1283. }
  1284. }
  1285. return false;
  1286. case Type_SimdVector:
  1287. if (source->kind == Type_SimdVector) {
  1288. if (poly->SimdVector.generic_count != nullptr) {
  1289. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1290. return false;
  1291. }
  1292. }
  1293. if (poly->SimdVector.count == source->SimdVector.count) {
  1294. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1295. }
  1296. }
  1297. return false;
  1298. }
  1299. return false;
  1300. }
  1301. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1302. if (curr->state != EntityState_InProgress) {
  1303. return false;
  1304. }
  1305. for_array(i, *c->type_path) {
  1306. Entity *prev = c->type_path->data[i];
  1307. if (prev == curr) {
  1308. if (report) {
  1309. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1310. for (isize j = i; j < c->type_path->count; j++) {
  1311. Entity *curr = (*c->type_path)[j];
  1312. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1313. }
  1314. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1315. curr->type = t_invalid;
  1316. }
  1317. return true;
  1318. }
  1319. }
  1320. return false;
  1321. }
  1322. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1323. GB_ASSERT(n->kind == Ast_Ident);
  1324. o->mode = Addressing_Invalid;
  1325. o->expr = n;
  1326. String name = n->Ident.token.string;
  1327. Entity *e = scope_lookup(c->scope, name);
  1328. if (e == nullptr) {
  1329. if (is_blank_ident(name)) {
  1330. error(n, "'_' cannot be used as a value");
  1331. } else {
  1332. error(n, "Undeclared name: %.*s", LIT(name));
  1333. }
  1334. o->type = t_invalid;
  1335. o->mode = Addressing_Invalid;
  1336. if (named_type != nullptr) {
  1337. set_base_type(named_type, t_invalid);
  1338. }
  1339. return nullptr;
  1340. }
  1341. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1342. if (e->parent_proc_decl != nullptr &&
  1343. e->parent_proc_decl != c->curr_proc_decl) {
  1344. if (e->kind == Entity_Variable) {
  1345. if ((e->flags & EntityFlag_Static) == 0) {
  1346. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1347. return nullptr;
  1348. }
  1349. } else if (e->kind == Entity_Label) {
  1350. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1351. return nullptr;
  1352. }
  1353. }
  1354. if (e->kind == Entity_ProcGroup) {
  1355. auto *pge = &e->ProcGroup;
  1356. DeclInfo *d = decl_info_of_entity(e);
  1357. check_entity_decl(c, e, d, nullptr);
  1358. Array<Entity *> procs = pge->entities;
  1359. bool skip = false;
  1360. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1361. // NOTE(bill): These should be done
  1362. for (Entity *proc : procs) {
  1363. Type *t = base_type(proc->type);
  1364. if (t == t_invalid) {
  1365. continue;
  1366. }
  1367. Operand x = {};
  1368. x.mode = Addressing_Value;
  1369. x.type = t;
  1370. if (check_is_assignable_to(c, &x, type_hint)) {
  1371. e = proc;
  1372. add_entity_use(c, n, e);
  1373. skip = true;
  1374. break;
  1375. }
  1376. }
  1377. }
  1378. if (!skip) {
  1379. o->mode = Addressing_ProcGroup;
  1380. o->type = t_invalid;
  1381. o->proc_group = e;
  1382. return nullptr;
  1383. }
  1384. }
  1385. add_entity_use(c, n, e);
  1386. if (e->state == EntityState_Unresolved) {
  1387. check_entity_decl(c, e, nullptr, named_type);
  1388. }
  1389. if (e->type == nullptr) {
  1390. // TODO(bill): Which is correct? return or compiler_error?
  1391. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1392. return nullptr;
  1393. }
  1394. e->flags |= EntityFlag_Used;
  1395. Type *type = e->type;
  1396. o->type = type;
  1397. switch (e->kind) {
  1398. case Entity_Constant:
  1399. if (type == t_invalid) {
  1400. o->type = t_invalid;
  1401. return e;
  1402. }
  1403. o->value = e->Constant.value;
  1404. if (o->value.kind == ExactValue_Invalid) {
  1405. return e;
  1406. }
  1407. if (o->value.kind == ExactValue_Procedure) {
  1408. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1409. if (proc != nullptr) {
  1410. o->mode = Addressing_Value;
  1411. o->type = proc->type;
  1412. return proc;
  1413. }
  1414. }
  1415. o->mode = Addressing_Constant;
  1416. break;
  1417. case Entity_Variable:
  1418. e->flags |= EntityFlag_Used;
  1419. if (type == t_invalid) {
  1420. o->type = t_invalid;
  1421. return e;
  1422. }
  1423. o->mode = Addressing_Variable;
  1424. if (e->flags & EntityFlag_Value) {
  1425. o->mode = Addressing_Value;
  1426. }
  1427. break;
  1428. case Entity_Procedure:
  1429. o->mode = Addressing_Value;
  1430. o->value = exact_value_procedure(n);
  1431. break;
  1432. case Entity_Builtin:
  1433. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1434. o->mode = Addressing_Builtin;
  1435. break;
  1436. case Entity_TypeName:
  1437. o->mode = Addressing_Type;
  1438. if (check_cycle(c, e, true)) {
  1439. o->type = t_invalid;
  1440. }
  1441. if (o->type != nullptr && type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1442. o->type = base_type(o->type);
  1443. }
  1444. break;
  1445. case Entity_ImportName:
  1446. if (!allow_import_name) {
  1447. error(n, "Use of import '%.*s' not in selector", LIT(name));
  1448. }
  1449. return e;
  1450. case Entity_LibraryName:
  1451. if (!allow_import_name) {
  1452. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1453. }
  1454. return e;
  1455. case Entity_Label:
  1456. o->mode = Addressing_NoValue;
  1457. break;
  1458. case Entity_Nil:
  1459. o->mode = Addressing_Value;
  1460. break;
  1461. default:
  1462. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1463. break;
  1464. }
  1465. return e;
  1466. }
  1467. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1468. if (o->type == nullptr) {
  1469. gbString str = expr_to_string(o->expr);
  1470. error(o->expr, "Expression has no value '%s'", str);
  1471. gb_string_free(str);
  1472. return false;
  1473. }
  1474. // TODO(bill): Handle errors correctly
  1475. Type *type = base_type(core_array_type(o->type));
  1476. gbString str = nullptr;
  1477. switch (op.kind) {
  1478. case Token_Add:
  1479. case Token_Sub:
  1480. if (!is_type_numeric(type)) {
  1481. str = expr_to_string(o->expr);
  1482. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1483. gb_string_free(str);
  1484. }
  1485. break;
  1486. case Token_Xor:
  1487. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1488. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1489. }
  1490. break;
  1491. case Token_Not:
  1492. if (!is_type_boolean(type)) {
  1493. ERROR_BLOCK();
  1494. str = expr_to_string(o->expr);
  1495. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1496. gb_string_free(str);
  1497. if (is_type_integer(type)) {
  1498. error_line("\tSuggestion: Did you mean to use the bitwise not operator '~'?\n");
  1499. }
  1500. } else {
  1501. o->type = t_untyped_bool;
  1502. }
  1503. break;
  1504. default:
  1505. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1506. return false;
  1507. }
  1508. return true;
  1509. }
  1510. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1511. Type *main_type = o->type;
  1512. // TODO(bill): Handle errors correctly
  1513. Type *type = base_type(core_array_type(main_type));
  1514. Type *ct = core_type(type);
  1515. switch (op.kind) {
  1516. case Token_Sub:
  1517. case Token_SubEq:
  1518. if (is_type_bit_set(type)) {
  1519. return true;
  1520. } else if (!is_type_numeric(type)) {
  1521. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1522. return false;
  1523. }
  1524. break;
  1525. case Token_Quo:
  1526. case Token_QuoEq:
  1527. if (is_type_matrix(main_type)) {
  1528. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1529. return false;
  1530. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1531. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1532. return false;
  1533. }
  1534. /*fallthrough*/
  1535. case Token_Mul:
  1536. case Token_MulEq:
  1537. case Token_AddEq:
  1538. if (is_type_bit_set(type)) {
  1539. return true;
  1540. } else if (!is_type_numeric(type)) {
  1541. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1542. return false;
  1543. }
  1544. break;
  1545. case Token_Add:
  1546. if (is_type_string(type)) {
  1547. if (o->mode == Addressing_Constant) {
  1548. return true;
  1549. }
  1550. error(op, "String concatenation is only allowed with constant strings");
  1551. return false;
  1552. } else if (is_type_bit_set(type)) {
  1553. return true;
  1554. } else if (!is_type_numeric(type)) {
  1555. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1556. return false;
  1557. }
  1558. break;
  1559. case Token_And:
  1560. case Token_Or:
  1561. case Token_AndEq:
  1562. case Token_OrEq:
  1563. case Token_Xor:
  1564. case Token_XorEq:
  1565. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1566. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1567. return false;
  1568. }
  1569. break;
  1570. case Token_Mod:
  1571. case Token_ModMod:
  1572. case Token_ModEq:
  1573. case Token_ModModEq:
  1574. if (is_type_matrix(main_type)) {
  1575. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1576. return false;
  1577. }
  1578. if (!is_type_integer(type)) {
  1579. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1580. return false;
  1581. } else if (is_type_simd_vector(main_type)) {
  1582. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1583. return false;
  1584. }
  1585. break;
  1586. case Token_AndNot:
  1587. case Token_AndNotEq:
  1588. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1589. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1590. return false;
  1591. }
  1592. break;
  1593. case Token_CmpAnd:
  1594. case Token_CmpOr:
  1595. case Token_CmpAndEq:
  1596. case Token_CmpOrEq:
  1597. if (!is_type_boolean(type)) {
  1598. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1599. return false;
  1600. }
  1601. break;
  1602. default:
  1603. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1604. return false;
  1605. }
  1606. return true;
  1607. }
  1608. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1609. if (in_value.kind == ExactValue_Invalid) {
  1610. // NOTE(bill): There's already been an error
  1611. return true;
  1612. }
  1613. type = core_type(type);
  1614. if (type == t_invalid) {
  1615. return false;
  1616. } else if (is_type_boolean(type)) {
  1617. return in_value.kind == ExactValue_Bool;
  1618. } else if (is_type_string(type)) {
  1619. return in_value.kind == ExactValue_String;
  1620. } else if (is_type_integer(type) || is_type_rune(type)) {
  1621. if (in_value.kind == ExactValue_Bool) {
  1622. return false;
  1623. }
  1624. ExactValue v = exact_value_to_integer(in_value);
  1625. if (v.kind != ExactValue_Integer) {
  1626. return false;
  1627. }
  1628. if (out_value) *out_value = v;
  1629. if (is_type_untyped(type)) {
  1630. return true;
  1631. }
  1632. BigInt i = v.value_integer;
  1633. i64 bit_size = type_size_of(type);
  1634. BigInt umax = {};
  1635. BigInt imin = {};
  1636. BigInt imax = {};
  1637. if (bit_size < 16) {
  1638. big_int_from_u64(&umax, unsigned_integer_maxs[bit_size]);
  1639. big_int_from_i64(&imin, signed_integer_mins[bit_size]);
  1640. big_int_from_i64(&imax, signed_integer_maxs[bit_size]);
  1641. } else {
  1642. big_int_from_u64(&umax, 1);
  1643. big_int_from_i64(&imin, 1);
  1644. big_int_from_i64(&imax, 1);
  1645. BigInt bi128 = {};
  1646. BigInt bi127 = {};
  1647. big_int_from_i64(&bi128, 128);
  1648. big_int_from_i64(&bi127, 127);
  1649. big_int_shl_eq(&umax, &bi128);
  1650. mp_decr(&umax);
  1651. big_int_shl_eq(&imin, &bi127);
  1652. big_int_neg(&imin, &imin);
  1653. big_int_shl_eq(&imax, &bi127);
  1654. mp_decr(&imax);
  1655. }
  1656. switch (type->Basic.kind) {
  1657. case Basic_rune:
  1658. case Basic_i8:
  1659. case Basic_i16:
  1660. case Basic_i32:
  1661. case Basic_i64:
  1662. case Basic_i128:
  1663. case Basic_int:
  1664. case Basic_i16le:
  1665. case Basic_i32le:
  1666. case Basic_i64le:
  1667. case Basic_i128le:
  1668. case Basic_i16be:
  1669. case Basic_i32be:
  1670. case Basic_i64be:
  1671. case Basic_i128be:
  1672. {
  1673. // return imin <= i && i <= imax;
  1674. int a = big_int_cmp(&imin, &i);
  1675. int b = big_int_cmp(&i, &imax);
  1676. return (a <= 0) && (b <= 0);
  1677. }
  1678. case Basic_u8:
  1679. case Basic_u16:
  1680. case Basic_u32:
  1681. case Basic_u64:
  1682. case Basic_u128:
  1683. case Basic_uint:
  1684. case Basic_uintptr:
  1685. case Basic_u16le:
  1686. case Basic_u32le:
  1687. case Basic_u64le:
  1688. case Basic_u128le:
  1689. case Basic_u16be:
  1690. case Basic_u32be:
  1691. case Basic_u64be:
  1692. case Basic_u128be:
  1693. {
  1694. // return 0ull <= i && i <= umax;
  1695. int b = big_int_cmp(&i, &umax);
  1696. return !i.sign && (b <= 0);
  1697. }
  1698. case Basic_UntypedInteger:
  1699. return true;
  1700. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1701. }
  1702. } else if (is_type_float(type)) {
  1703. ExactValue v = exact_value_to_float(in_value);
  1704. if (v.kind != ExactValue_Float) {
  1705. return false;
  1706. }
  1707. if (out_value) *out_value = v;
  1708. switch (type->Basic.kind) {
  1709. case Basic_f16:
  1710. case Basic_f32:
  1711. case Basic_f64:
  1712. return true;
  1713. case Basic_f16le:
  1714. case Basic_f16be:
  1715. case Basic_f32le:
  1716. case Basic_f32be:
  1717. case Basic_f64le:
  1718. case Basic_f64be:
  1719. return true;
  1720. case Basic_UntypedFloat:
  1721. return true;
  1722. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1723. }
  1724. } else if (is_type_complex(type)) {
  1725. ExactValue v = exact_value_to_complex(in_value);
  1726. if (v.kind != ExactValue_Complex) {
  1727. return false;
  1728. }
  1729. switch (type->Basic.kind) {
  1730. case Basic_complex32:
  1731. case Basic_complex64:
  1732. case Basic_complex128: {
  1733. ExactValue real = exact_value_real(v);
  1734. ExactValue imag = exact_value_imag(v);
  1735. if (real.kind != ExactValue_Invalid &&
  1736. imag.kind != ExactValue_Invalid) {
  1737. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1738. return true;
  1739. }
  1740. break;
  1741. }
  1742. case Basic_UntypedComplex:
  1743. return true;
  1744. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1745. }
  1746. return false;
  1747. } else if (is_type_quaternion(type)) {
  1748. ExactValue v = exact_value_to_quaternion(in_value);
  1749. if (v.kind != ExactValue_Quaternion) {
  1750. return false;
  1751. }
  1752. switch (type->Basic.kind) {
  1753. case Basic_quaternion64:
  1754. case Basic_quaternion128:
  1755. case Basic_quaternion256: {
  1756. ExactValue real = exact_value_real(v);
  1757. ExactValue imag = exact_value_imag(v);
  1758. ExactValue jmag = exact_value_jmag(v);
  1759. ExactValue kmag = exact_value_kmag(v);
  1760. if (real.kind != ExactValue_Invalid &&
  1761. imag.kind != ExactValue_Invalid) {
  1762. 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));
  1763. return true;
  1764. }
  1765. break;
  1766. }
  1767. case Basic_UntypedComplex:
  1768. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  1769. return true;
  1770. case Basic_UntypedQuaternion:
  1771. return true;
  1772. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1773. }
  1774. return false;
  1775. } else if (is_type_pointer(type)) {
  1776. if (in_value.kind == ExactValue_Pointer) {
  1777. return true;
  1778. }
  1779. if (in_value.kind == ExactValue_Integer) {
  1780. return false;
  1781. // return true;
  1782. }
  1783. if (in_value.kind == ExactValue_String) {
  1784. return false;
  1785. }
  1786. if (out_value) *out_value = in_value;
  1787. } else if (is_type_bit_set(type)) {
  1788. if (in_value.kind == ExactValue_Integer) {
  1789. return true;
  1790. }
  1791. }
  1792. return false;
  1793. }
  1794. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1795. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  1796. gbString b = type_to_string(type);
  1797. i64 sz = type_size_of(type);
  1798. BigInt *bi = &o->value.value_integer;
  1799. if (is_type_unsigned(type)) {
  1800. if (big_int_is_neg(bi)) {
  1801. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  1802. } else {
  1803. BigInt one = big_int_make_u64(1);
  1804. BigInt max_size = big_int_make_u64(1);
  1805. BigInt bits = big_int_make_i64(8*sz);
  1806. big_int_shl_eq(&max_size, &bits);
  1807. big_int_sub_eq(&max_size, &one);
  1808. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1809. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1810. }
  1811. } else {
  1812. BigInt zero = big_int_make_u64(0);
  1813. BigInt one = big_int_make_u64(1);
  1814. BigInt max_size = big_int_make_u64(1);
  1815. BigInt bits = big_int_make_i64(8*sz - 1);
  1816. big_int_shl_eq(&max_size, &bits);
  1817. if (big_int_is_neg(bi)) {
  1818. big_int_neg(&max_size, &max_size);
  1819. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1820. error_line("\tThe minimum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1821. } else {
  1822. big_int_sub_eq(&max_size, &one);
  1823. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  1824. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  1825. }
  1826. }
  1827. gb_string_free(b);
  1828. return true;
  1829. }
  1830. return false;
  1831. }
  1832. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1833. gbString a = expr_to_string(o->expr);
  1834. gbString b = type_to_string(type);
  1835. defer(
  1836. gb_string_free(b);
  1837. gb_string_free(a);
  1838. );
  1839. Type *src = base_type(o->type);
  1840. Type *dst = base_type(type);
  1841. if (is_type_array(src) && is_type_slice(dst)) {
  1842. Type *s = src->Array.elem;
  1843. Type *d = dst->Slice.elem;
  1844. if (are_types_identical(s, d)) {
  1845. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1846. }
  1847. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  1848. Type *s = src->DynamicArray.elem;
  1849. Type *d = dst->Slice.elem;
  1850. if (are_types_identical(s, d)) {
  1851. error_line("\tSuggestion: the dynamic array expression may be sliced with %s[:]\n", a);
  1852. }
  1853. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  1854. error_line("\tSuggestion: the expression may be directly casted to type %s\n", b);
  1855. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1856. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1857. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable, \n");
  1858. error_line("\t whereas slices in general are assumed to be mutable.\n");
  1859. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  1860. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  1861. } else if (check_integer_exceed_suggestion(c, o, type)) {
  1862. return;
  1863. }
  1864. }
  1865. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  1866. gbString a = expr_to_string(o->expr);
  1867. gbString b = type_to_string(type);
  1868. defer(
  1869. gb_string_free(b);
  1870. gb_string_free(a);
  1871. );
  1872. Type *src = base_type(o->type);
  1873. Type *dst = base_type(type);
  1874. if (is_type_array(src) && is_type_slice(dst)) {
  1875. Type *s = src->Array.elem;
  1876. Type *d = dst->Slice.elem;
  1877. if (are_types_identical(s, d)) {
  1878. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  1879. }
  1880. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  1881. if (is_type_uintptr(type)) {
  1882. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  1883. } else {
  1884. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  1885. i64 x = type_size_of(o->type);
  1886. i64 y = type_size_of(type);
  1887. if (x != y) {
  1888. 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);
  1889. }
  1890. }
  1891. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  1892. if (is_type_uintptr(o->type)) {
  1893. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  1894. } else {
  1895. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  1896. }
  1897. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  1898. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  1899. } else if (check_integer_exceed_suggestion(c, o, type)) {
  1900. return;
  1901. }
  1902. }
  1903. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  1904. GB_ASSERT(o->mode == Addressing_Constant);
  1905. ExactValue out_value = o->value;
  1906. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  1907. o->value = out_value;
  1908. return true;
  1909. } else {
  1910. o->value = out_value;
  1911. gbString a = expr_to_string(o->expr);
  1912. gbString b = type_to_string(type);
  1913. gbString c = type_to_string(o->type);
  1914. gbString s = exact_value_to_string(o->value);
  1915. defer(
  1916. gb_string_free(s);
  1917. gb_string_free(c);
  1918. gb_string_free(b);
  1919. gb_string_free(a);
  1920. o->mode = Addressing_Invalid;
  1921. );
  1922. ERROR_BLOCK();
  1923. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  1924. if (!is_type_integer(o->type) && is_type_integer(type)) {
  1925. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  1926. } else {
  1927. if (are_types_identical(o->type, type)) {
  1928. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  1929. } else {
  1930. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  1931. }
  1932. check_assignment_error_suggestion(ctx, o, type);
  1933. }
  1934. } else {
  1935. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  1936. check_assignment_error_suggestion(ctx, o, type);
  1937. }
  1938. return false;
  1939. }
  1940. }
  1941. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  1942. if (o->mode == Addressing_OptionalOk) {
  1943. Ast *expr = unselector_expr(o->expr);
  1944. if (expr->kind != Ast_TypeAssertion) {
  1945. return true;
  1946. }
  1947. ast_node(ta, TypeAssertion, expr);
  1948. TypeAndValue tv = ta->expr->tav;
  1949. if (is_type_pointer(tv.type)) {
  1950. return false;
  1951. }
  1952. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  1953. return false;
  1954. }
  1955. if (is_type_any(tv.type)) {
  1956. return false;
  1957. }
  1958. return true;
  1959. }
  1960. if (o->mode == Addressing_MapIndex) {
  1961. return false;
  1962. }
  1963. Ast *expr = unparen_expr(o->expr);
  1964. if (expr->kind == Ast_CompoundLit) {
  1965. return false;
  1966. }
  1967. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  1968. }
  1969. gb_internal void check_old_for_or_switch_value_usage(Ast *expr) {
  1970. Entity *e = entity_of_node(expr);
  1971. if (e != nullptr && (e->flags & EntityFlag_OldForOrSwitchValue) != 0) {
  1972. GB_ASSERT(e->kind == Entity_Variable);
  1973. begin_error_block();
  1974. defer (end_error_block());
  1975. if ((e->flags & EntityFlag_ForValue) != 0) {
  1976. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  1977. error(expr, "Assuming a for-in defined value is addressable as the iterable is passed by value has been disallowed with '-strict-style'.");
  1978. if (is_type_map(parent_type)) {
  1979. error_line("\tSuggestion: Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  1980. } else {
  1981. error_line("\tSuggestion: Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  1982. }
  1983. } else {
  1984. GB_ASSERT((e->flags & EntityFlag_SwitchValue) != 0);
  1985. error(expr, "Assuming a switch-in defined value is addressable as the iterable is passed by value has been disallowed with '-strict-style'.");
  1986. error_line("\tSuggestion: Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  1987. }
  1988. }
  1989. }
  1990. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  1991. switch (op.kind) {
  1992. case Token_And: { // Pointer address
  1993. if (check_is_not_addressable(c, o)) {
  1994. if (ast_node_expect(node, Ast_UnaryExpr)) {
  1995. ast_node(ue, UnaryExpr, node);
  1996. gbString str = expr_to_string(ue->expr);
  1997. defer (gb_string_free(str));
  1998. Entity *e = entity_of_node(ue->expr);
  1999. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2000. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2001. } else {
  2002. switch (o->mode) {
  2003. case Addressing_Constant:
  2004. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2005. break;
  2006. case Addressing_SwizzleValue:
  2007. case Addressing_SwizzleVariable:
  2008. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2009. break;
  2010. default:
  2011. {
  2012. begin_error_block();
  2013. defer (end_error_block());
  2014. error(op, "Cannot take the pointer address of '%s'", str);
  2015. if (e != nullptr && (e->flags & EntityFlag_ForValue) != 0) {
  2016. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2017. if (parent_type != nullptr && is_type_string(parent_type)) {
  2018. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2019. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2020. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2021. } else {
  2022. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2023. }
  2024. }
  2025. if (e != nullptr && (e->flags & EntityFlag_SwitchValue) != 0) {
  2026. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2027. }
  2028. }
  2029. break;
  2030. }
  2031. }
  2032. }
  2033. o->mode = Addressing_Invalid;
  2034. return;
  2035. }
  2036. if (o->mode == Addressing_SoaVariable) {
  2037. ast_node(ue, UnaryExpr, node);
  2038. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2039. ast_node(ie, IndexExpr, ue->expr);
  2040. Type *soa_type = type_of_expr(ie->expr);
  2041. GB_ASSERT(is_type_soa_struct(soa_type));
  2042. o->type = alloc_type_soa_pointer(soa_type);
  2043. } else {
  2044. o->type = alloc_type_pointer(o->type);
  2045. }
  2046. } else {
  2047. if (build_context.strict_style && ast_node_expect(node, Ast_UnaryExpr)) {
  2048. ast_node(ue, UnaryExpr, node);
  2049. check_old_for_or_switch_value_usage(ue->expr);
  2050. }
  2051. o->type = alloc_type_pointer(o->type);
  2052. }
  2053. switch (o->mode) {
  2054. case Addressing_OptionalOk:
  2055. case Addressing_MapIndex:
  2056. o->mode = Addressing_OptionalOkPtr;
  2057. break;
  2058. default:
  2059. o->mode = Addressing_Value;
  2060. break;
  2061. }
  2062. return;
  2063. }
  2064. }
  2065. if (!check_unary_op(c, o, op)) {
  2066. o->mode = Addressing_Invalid;
  2067. return;
  2068. }
  2069. if (o->mode == Addressing_Constant) {
  2070. Type *type = base_type(o->type);
  2071. if (!is_type_constant_type(o->type)) {
  2072. gbString xt = type_to_string(o->type);
  2073. gbString err_str = expr_to_string(node);
  2074. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2075. gb_string_free(err_str);
  2076. gb_string_free(xt);
  2077. o->mode = Addressing_Invalid;
  2078. return;
  2079. }
  2080. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2081. gbString err_str = expr_to_string(node);
  2082. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2083. gb_string_free(err_str);
  2084. o->mode = Addressing_Invalid;
  2085. return;
  2086. }
  2087. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2088. gbString err_str = expr_to_string(node);
  2089. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2090. gb_string_free(err_str);
  2091. o->mode = Addressing_Invalid;
  2092. return;
  2093. }
  2094. i32 precision = 0;
  2095. if (is_type_typed(type)) {
  2096. precision = cast(i32)(8 * type_size_of(type));
  2097. }
  2098. bool is_unsigned = is_type_unsigned(type);
  2099. if (is_type_rune(type)) {
  2100. GB_ASSERT(!is_unsigned);
  2101. }
  2102. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2103. if (is_type_typed(type)) {
  2104. if (node != nullptr) {
  2105. o->expr = node;
  2106. }
  2107. check_is_expressible(c, o, type);
  2108. }
  2109. return;
  2110. }
  2111. o->mode = Addressing_Value;
  2112. }
  2113. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2114. if (t == nullptr) {
  2115. return;
  2116. }
  2117. t = base_type(t);
  2118. if (!is_type_comparable(t)) {
  2119. return;
  2120. }
  2121. switch (t->kind) {
  2122. case Type_Basic:
  2123. switch (t->Basic.kind) {
  2124. case Basic_complex32:
  2125. add_package_dependency(c, "runtime", "complex32_eq");
  2126. add_package_dependency(c, "runtime", "complex32_ne");
  2127. break;
  2128. case Basic_complex64:
  2129. add_package_dependency(c, "runtime", "complex64_eq");
  2130. add_package_dependency(c, "runtime", "complex64_ne");
  2131. break;
  2132. case Basic_complex128:
  2133. add_package_dependency(c, "runtime", "complex128_eq");
  2134. add_package_dependency(c, "runtime", "complex128_ne");
  2135. break;
  2136. case Basic_quaternion64:
  2137. add_package_dependency(c, "runtime", "quaternion64_eq");
  2138. add_package_dependency(c, "runtime", "quaternion64_ne");
  2139. break;
  2140. case Basic_quaternion128:
  2141. add_package_dependency(c, "runtime", "quaternion128_eq");
  2142. add_package_dependency(c, "runtime", "quaternion128_ne");
  2143. break;
  2144. case Basic_quaternion256:
  2145. add_package_dependency(c, "runtime", "quaternion256_eq");
  2146. add_package_dependency(c, "runtime", "quaternion256_ne");
  2147. break;
  2148. case Basic_cstring:
  2149. add_package_dependency(c, "runtime", "cstring_to_string");
  2150. /*fallthrough*/
  2151. case Basic_string:
  2152. add_package_dependency(c, "runtime", "string_eq");
  2153. add_package_dependency(c, "runtime", "string_ne");
  2154. break;
  2155. }
  2156. break;
  2157. case Type_Struct:
  2158. for (Entity *field : t->Struct.fields) {
  2159. add_comparison_procedures_for_fields(c, field->type);
  2160. }
  2161. break;
  2162. }
  2163. }
  2164. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2165. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2166. bool comp = are_types_identical(x->type, y->type);
  2167. switch (op) {
  2168. case Token_CmpEq: /* comp = comp; */ break;
  2169. case Token_NotEq: comp = !comp; break;
  2170. }
  2171. x->mode = Addressing_Constant;
  2172. x->type = t_untyped_bool;
  2173. x->value = exact_value_bool(comp);
  2174. return;
  2175. }
  2176. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2177. add_type_info_type(c, x->type);
  2178. add_type_info_type(c, y->type);
  2179. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2180. x->mode = Addressing_Value;
  2181. x->type = t_untyped_bool;
  2182. return;
  2183. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2184. add_type_info_type(c, x->type);
  2185. add_type_info_type(c, y->type);
  2186. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2187. x->mode = Addressing_Value;
  2188. x->type = t_untyped_bool;
  2189. return;
  2190. }
  2191. TEMPORARY_ALLOCATOR_GUARD();
  2192. gbString err_str = nullptr;
  2193. if (check_is_assignable_to(c, x, y->type) ||
  2194. check_is_assignable_to(c, y, x->type)) {
  2195. Type *err_type = x->type;
  2196. bool defined = false;
  2197. switch (op) {
  2198. case Token_CmpEq:
  2199. case Token_NotEq:
  2200. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2201. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2202. (is_operand_nil(*y) && type_has_nil(x->type));
  2203. break;
  2204. case Token_Lt:
  2205. case Token_Gt:
  2206. case Token_LtEq:
  2207. case Token_GtEq:
  2208. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2209. defined = true;
  2210. } else {
  2211. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2212. }
  2213. break;
  2214. }
  2215. if (!defined) {
  2216. gbString xs = type_to_string(x->type, temporary_allocator());
  2217. gbString ys = type_to_string(y->type, temporary_allocator());
  2218. err_str = gb_string_make(temporary_allocator(),
  2219. gb_bprintf("operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2220. );
  2221. } else {
  2222. Type *comparison_type = x->type;
  2223. if (x->type == err_type && is_operand_nil(*x)) {
  2224. comparison_type = y->type;
  2225. }
  2226. add_comparison_procedures_for_fields(c, comparison_type);
  2227. }
  2228. } else {
  2229. gbString xt, yt;
  2230. if (x->mode == Addressing_ProcGroup) {
  2231. xt = gb_string_make(temporary_allocator(), "procedure group");
  2232. } else {
  2233. xt = type_to_string(x->type);
  2234. }
  2235. if (y->mode == Addressing_ProcGroup) {
  2236. yt = gb_string_make(temporary_allocator(), "procedure group");
  2237. } else {
  2238. yt = type_to_string(y->type);
  2239. }
  2240. err_str = gb_string_make(temporary_allocator(), gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  2241. }
  2242. if (err_str != nullptr) {
  2243. error(node, "Cannot compare expression, %s", err_str);
  2244. x->type = t_untyped_bool;
  2245. } else {
  2246. if (x->mode == Addressing_Constant &&
  2247. y->mode == Addressing_Constant) {
  2248. if (is_type_constant_type(x->type)) {
  2249. if (is_type_bit_set(x->type)) {
  2250. switch (op) {
  2251. case Token_CmpEq:
  2252. case Token_NotEq:
  2253. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2254. break;
  2255. case Token_Lt:
  2256. case Token_LtEq:
  2257. {
  2258. ExactValue lhs = x->value;
  2259. ExactValue rhs = y->value;
  2260. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2261. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2262. if (op == Token_Lt) {
  2263. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2264. }
  2265. x->value = res;
  2266. break;
  2267. }
  2268. case Token_Gt:
  2269. case Token_GtEq:
  2270. {
  2271. ExactValue lhs = x->value;
  2272. ExactValue rhs = y->value;
  2273. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2274. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2275. if (op == Token_Gt) {
  2276. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2277. }
  2278. x->value = res;
  2279. break;
  2280. }
  2281. }
  2282. } else {
  2283. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2284. }
  2285. } else {
  2286. x->mode = Addressing_Value;
  2287. }
  2288. } else {
  2289. x->mode = Addressing_Value;
  2290. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2291. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2292. i64 size = 0;
  2293. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2294. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2295. if (is_type_string(x->type) || is_type_string(y->type)) {
  2296. switch (op) {
  2297. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2298. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2299. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2300. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2301. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2302. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2303. }
  2304. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2305. switch (op) {
  2306. case Token_CmpEq:
  2307. switch (8*size) {
  2308. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2309. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2310. }
  2311. break;
  2312. case Token_NotEq:
  2313. switch (8*size) {
  2314. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2315. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2316. }
  2317. break;
  2318. }
  2319. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2320. switch (op) {
  2321. case Token_CmpEq:
  2322. switch (8*size) {
  2323. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2324. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2325. }
  2326. break;
  2327. case Token_NotEq:
  2328. switch (8*size) {
  2329. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2330. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2331. }
  2332. break;
  2333. }
  2334. }
  2335. }
  2336. x->type = t_untyped_bool;
  2337. }
  2338. }
  2339. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2340. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2341. ast_node(be, BinaryExpr, node);
  2342. ExactValue x_val = {};
  2343. if (x->mode == Addressing_Constant) {
  2344. x_val = exact_value_to_integer(x->value);
  2345. }
  2346. bool x_is_untyped = is_type_untyped(x->type);
  2347. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  2348. gbString err_str = expr_to_string(x->expr);
  2349. error(node, "Shifted operand '%s' must be an integer", err_str);
  2350. gb_string_free(err_str);
  2351. x->mode = Addressing_Invalid;
  2352. return;
  2353. }
  2354. if (is_type_unsigned(y->type)) {
  2355. } else if (is_type_untyped(y->type)) {
  2356. convert_to_typed(c, y, t_untyped_integer);
  2357. if (y->mode == Addressing_Invalid) {
  2358. x->mode = Addressing_Invalid;
  2359. return;
  2360. }
  2361. } else {
  2362. gbString err_str = expr_to_string(y->expr);
  2363. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2364. gb_string_free(err_str);
  2365. x->mode = Addressing_Invalid;
  2366. return;
  2367. }
  2368. if (x->mode == Addressing_Constant) {
  2369. if (y->mode == Addressing_Constant) {
  2370. ExactValue y_val = exact_value_to_integer(y->value);
  2371. if (y_val.kind != ExactValue_Integer) {
  2372. gbString err_str = expr_to_string(y->expr);
  2373. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2374. gb_string_free(err_str);
  2375. x->mode = Addressing_Invalid;
  2376. return;
  2377. }
  2378. BigInt max_shift = {};
  2379. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2380. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  2381. gbString err_str = expr_to_string(y->expr);
  2382. error(node, "Shift amount too large: '%s'", err_str);
  2383. gb_string_free(err_str);
  2384. x->mode = Addressing_Invalid;
  2385. return;
  2386. }
  2387. if (!is_type_integer(x->type)) {
  2388. // NOTE(bill): It could be an untyped float but still representable
  2389. // as an integer
  2390. x->type = t_untyped_integer;
  2391. }
  2392. x->expr = node;
  2393. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  2394. if (is_type_typed(x->type)) {
  2395. check_is_expressible(c, x, x->type);
  2396. }
  2397. return;
  2398. }
  2399. TokenPos pos = ast_token(x->expr).pos;
  2400. if (x_is_untyped) {
  2401. if (x->expr != nullptr) {
  2402. x->expr->tav.is_lhs = true;
  2403. }
  2404. x->mode = Addressing_Value;
  2405. if (type_hint) {
  2406. if (is_type_integer(type_hint)) {
  2407. x->type = type_hint;
  2408. } else {
  2409. gbString x_str = expr_to_string(x->expr);
  2410. gbString to_type = type_to_string(type_hint);
  2411. error(node, "Conversion of shifted operand '%s' to '%s' is not allowed", x_str, to_type);
  2412. gb_string_free(x_str);
  2413. gb_string_free(to_type);
  2414. x->mode = Addressing_Invalid;
  2415. }
  2416. }
  2417. // x->value = x_val;
  2418. return;
  2419. }
  2420. }
  2421. if (y->mode == Addressing_Constant && big_int_is_neg(&y->value.value_integer)) {
  2422. gbString err_str = expr_to_string(y->expr);
  2423. error(node, "Shift amount cannot be negative: '%s'", err_str);
  2424. gb_string_free(err_str);
  2425. }
  2426. // TODO(bill): Should we support shifts for fixed arrays and #simd vectors?
  2427. if (!is_type_integer(x->type)) {
  2428. gbString err_str = expr_to_string(x->expr);
  2429. error(node, "Shift operand '%s' must be an integer", err_str);
  2430. gb_string_free(err_str);
  2431. x->mode = Addressing_Invalid;
  2432. return;
  2433. }
  2434. if (is_type_untyped(y->type)) {
  2435. convert_to_typed(c, y, t_uint);
  2436. }
  2437. x->mode = Addressing_Value;
  2438. }
  2439. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2440. if (check_is_assignable_to(c, operand, y)) {
  2441. return true;
  2442. }
  2443. bool is_constant = operand->mode == Addressing_Constant;
  2444. Type *x = operand->type;
  2445. Type *src = core_type(x);
  2446. Type *dst = core_type(y);
  2447. if (are_types_identical(src, dst)) {
  2448. return true;
  2449. }
  2450. // if (is_type_tuple(src)) {
  2451. // Ast *expr = unparen_expr(operand->expr);
  2452. // if (expr && expr->kind == Ast_CallExpr) {
  2453. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2454. // ast_node(ce, CallExpr, expr);
  2455. // Type *pt = base_type(type_of_expr(ce->proc));
  2456. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2457. // if (pt->Proc.result_count > 0) {
  2458. // Operand op = *operand;
  2459. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2460. // bool ok = check_is_castable_to(c, &op, y);
  2461. // if (ok) {
  2462. // ce->optional_ok_one = true;
  2463. // }
  2464. // return ok;
  2465. // }
  2466. // }
  2467. // }
  2468. // }
  2469. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2470. if (is_type_u8_array(dst)) {
  2471. String s = operand->value.value_string;
  2472. return s.len == dst->Array.count;
  2473. }
  2474. if (is_type_rune_array(dst)) {
  2475. String s = operand->value.value_string;
  2476. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2477. }
  2478. }
  2479. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2480. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2481. return dst->Array.count == src->Array.count;
  2482. }
  2483. }
  2484. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2485. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2486. }
  2487. // Cast between booleans and integers
  2488. if (is_type_boolean(src) || is_type_integer(src)) {
  2489. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2490. return true;
  2491. }
  2492. }
  2493. // Cast between numbers
  2494. if (is_type_integer(src) || is_type_float(src)) {
  2495. if (is_type_integer(dst) || is_type_float(dst)) {
  2496. return true;
  2497. }
  2498. }
  2499. if (is_type_integer(src) && is_type_rune(dst)) {
  2500. return true;
  2501. }
  2502. if (is_type_rune(src) && is_type_integer(dst)) {
  2503. return true;
  2504. }
  2505. if (is_type_complex(src) && is_type_complex(dst)) {
  2506. return true;
  2507. }
  2508. if (is_type_float(src) && is_type_complex(dst)) {
  2509. return true;
  2510. }
  2511. if (is_type_float(src) && is_type_quaternion(dst)) {
  2512. return true;
  2513. }
  2514. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2515. return true;
  2516. }
  2517. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2518. return true;
  2519. }
  2520. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2521. GB_ASSERT(src->kind == Type_Matrix);
  2522. GB_ASSERT(dst->kind == Type_Matrix);
  2523. Operand op = *operand;
  2524. op.type = src->Matrix.elem;
  2525. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2526. return false;
  2527. }
  2528. if (src->Matrix.row_count != src->Matrix.column_count) {
  2529. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2530. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2531. return src_count == dst_count;
  2532. }
  2533. return is_matrix_square(dst) && is_matrix_square(src);
  2534. }
  2535. // Cast between pointers
  2536. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2537. return true;
  2538. }
  2539. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2540. return true;
  2541. }
  2542. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2543. return true;
  2544. }
  2545. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2546. return true;
  2547. }
  2548. // uintptr <-> pointer
  2549. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2550. return true;
  2551. }
  2552. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2553. return true;
  2554. }
  2555. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2556. return true;
  2557. }
  2558. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2559. return true;
  2560. }
  2561. // []byte/[]u8 <-> string (not cstring)
  2562. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2563. return true;
  2564. }
  2565. // cstring -> string
  2566. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2567. if (operand->mode != Addressing_Constant) {
  2568. add_package_dependency(c, "runtime", "cstring_to_string");
  2569. }
  2570. return true;
  2571. }
  2572. // cstring -> ^u8
  2573. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2574. return !is_constant;
  2575. }
  2576. // cstring -> [^]u8
  2577. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2578. return !is_constant;
  2579. }
  2580. // cstring -> rawptr
  2581. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2582. return !is_constant;
  2583. }
  2584. // ^u8 -> cstring
  2585. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2586. return !is_constant;
  2587. }
  2588. // [^]u8 -> cstring
  2589. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2590. return !is_constant;
  2591. }
  2592. // rawptr -> cstring
  2593. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2594. return !is_constant;
  2595. }
  2596. // proc <-> proc
  2597. if (is_type_proc(src) && is_type_proc(dst)) {
  2598. return true;
  2599. }
  2600. // proc -> rawptr
  2601. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2602. return true;
  2603. }
  2604. // rawptr -> proc
  2605. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2606. return true;
  2607. }
  2608. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2609. if (src->SimdVector.count != dst->SimdVector.count) {
  2610. return false;
  2611. }
  2612. Type *elem_src = base_array_type(src);
  2613. Type *elem_dst = base_array_type(dst);
  2614. Operand x = {};
  2615. x.type = elem_src;
  2616. x.mode = Addressing_Value;
  2617. return check_is_castable_to(c, &x, elem_dst);
  2618. }
  2619. if (is_type_simd_vector(dst)) {
  2620. Type *elem = base_array_type(dst);
  2621. if (check_is_castable_to(c, operand, elem)) {
  2622. return true;
  2623. }
  2624. }
  2625. return false;
  2626. }
  2627. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2628. bool is_const_expr = x->mode == Addressing_Constant;
  2629. Type *bt = base_type(type);
  2630. if (is_const_expr && is_type_constant_type(bt)) {
  2631. if (core_type(bt)->kind == Type_Basic) {
  2632. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2633. return true;
  2634. } else if (check_is_castable_to(c, x, type)) {
  2635. if (is_type_pointer(type)) {
  2636. return true;
  2637. }
  2638. }
  2639. } else if (check_is_castable_to(c, x, type)) {
  2640. x->value = {};
  2641. x->mode = Addressing_Value;
  2642. return true;
  2643. }
  2644. } else if (check_is_castable_to(c, x, type)) {
  2645. if (x->mode != Addressing_Constant) {
  2646. x->mode = Addressing_Value;
  2647. } else if (is_type_slice(type) && is_type_string(x->type)) {
  2648. x->mode = Addressing_Value;
  2649. } else if (is_type_union(type)) {
  2650. x->mode = Addressing_Value;
  2651. }
  2652. if (x->mode == Addressing_Value) {
  2653. x->value = {};
  2654. }
  2655. return true;
  2656. }
  2657. return false;
  2658. }
  2659. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type) {
  2660. if (!is_operand_value(*x)) {
  2661. error(x->expr, "Only values can be casted");
  2662. x->mode = Addressing_Invalid;
  2663. return;
  2664. }
  2665. bool is_const_expr = x->mode == Addressing_Constant;
  2666. bool can_convert = check_cast_internal(c, x, type);
  2667. if (!can_convert) {
  2668. TEMPORARY_ALLOCATOR_GUARD();
  2669. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  2670. gbString to_type = type_to_string(type, temporary_allocator());
  2671. gbString from_type = type_to_string(x->type, temporary_allocator());
  2672. x->mode = Addressing_Invalid;
  2673. begin_error_block();
  2674. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  2675. if (is_const_expr) {
  2676. gbString val_str = exact_value_to_string(x->value);
  2677. if (is_type_float(x->type) && is_type_integer(type)) {
  2678. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  2679. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2680. x->mode = Addressing_Constant;
  2681. x->type = type;
  2682. } else {
  2683. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  2684. if (is_type_numeric(type)) {
  2685. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  2686. x->mode = Addressing_Constant;
  2687. x->type = type;
  2688. }
  2689. }
  2690. gb_string_free(val_str);
  2691. }
  2692. check_cast_error_suggestion(c, x, type);
  2693. end_error_block();
  2694. return;
  2695. }
  2696. if (is_type_untyped(x->type)) {
  2697. Type *final_type = type;
  2698. if (is_const_expr && !is_type_constant_type(type)) {
  2699. final_type = default_type(x->type);
  2700. }
  2701. update_untyped_expr_type(c, x->expr, final_type, true);
  2702. }
  2703. if (build_context.vet_extra) {
  2704. if (are_types_identical(x->type, type)) {
  2705. gbString str = type_to_string(type);
  2706. warning(x->expr, "Unneeded cast to the same type '%s'", str);
  2707. gb_string_free(str);
  2708. }
  2709. }
  2710. x->type = type;
  2711. }
  2712. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  2713. if (!is_operand_value(*o)) {
  2714. error(o->expr, "'transmute' can only be applied to values");
  2715. o->mode = Addressing_Invalid;
  2716. return false;
  2717. }
  2718. // if (o->mode == Addressing_Constant) {
  2719. // gbString expr_str = expr_to_string(o->expr);
  2720. // error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  2721. // gb_string_free(expr_str);
  2722. // o->mode = Addressing_Invalid;
  2723. // o->expr = node;
  2724. // return false;
  2725. // }
  2726. Type *src_t = o->type;
  2727. Type *dst_t = t;
  2728. Type *src_bt = base_type(src_t);
  2729. Type *dst_bt = base_type(dst_t);
  2730. if (is_type_untyped(src_t)) {
  2731. gbString expr_str = expr_to_string(o->expr);
  2732. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  2733. gb_string_free(expr_str);
  2734. o->mode = Addressing_Invalid;
  2735. o->expr = node;
  2736. return false;
  2737. }
  2738. if (dst_bt == nullptr || dst_bt == t_invalid) {
  2739. GB_ASSERT(global_error_collector.count != 0);
  2740. o->mode = Addressing_Invalid;
  2741. o->expr = node;
  2742. return false;
  2743. }
  2744. if (src_bt == nullptr || src_bt == t_invalid) {
  2745. // NOTE(bill): this should be an error
  2746. GB_ASSERT(global_error_collector.count != 0);
  2747. o->mode = Addressing_Value;
  2748. o->expr = node;
  2749. o->type = dst_t;
  2750. return true;
  2751. }
  2752. i64 srcz = type_size_of(src_t);
  2753. i64 dstz = type_size_of(dst_t);
  2754. if (srcz != dstz) {
  2755. gbString expr_str = expr_to_string(o->expr);
  2756. gbString type_str = type_to_string(dst_t);
  2757. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  2758. gb_string_free(type_str);
  2759. gb_string_free(expr_str);
  2760. o->mode = Addressing_Invalid;
  2761. o->expr = node;
  2762. return false;
  2763. }
  2764. if (build_context.vet_extra) {
  2765. if (are_types_identical(o->type, dst_t)) {
  2766. gbString str = type_to_string(dst_t);
  2767. warning(o->expr, "Unneeded transmute to the same type '%s'", str);
  2768. gb_string_free(str);
  2769. }
  2770. }
  2771. o->expr = node;
  2772. o->type = dst_t;
  2773. if (o->mode == Addressing_Constant) {
  2774. if (are_types_identical(src_bt, dst_bt)) {
  2775. return true;
  2776. }
  2777. if (is_type_integer(src_t) && is_type_integer(dst_t)) {
  2778. if (types_have_same_internal_endian(src_t, dst_t)) {
  2779. ExactValue src_v = exact_value_to_integer(o->value);
  2780. GB_ASSERT(src_v.kind == ExactValue_Integer);
  2781. BigInt v = src_v.value_integer;
  2782. BigInt smax = {};
  2783. BigInt umax = {};
  2784. big_int_from_u64(&smax, 0);
  2785. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  2786. big_int_from_u64(&umax, 1);
  2787. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  2788. big_int_shl_eq(&umax, &sz_in_bits);
  2789. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  2790. if (big_int_cmp(&v, &smax) >= 0) {
  2791. big_int_sub_eq(&v, &umax);
  2792. }
  2793. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  2794. if (big_int_is_neg(&v)) {
  2795. big_int_add_eq(&v, &umax);
  2796. }
  2797. }
  2798. o->value.kind = ExactValue_Integer;
  2799. o->value.value_integer = v;
  2800. return true;
  2801. }
  2802. }
  2803. }
  2804. o->mode = Addressing_Value;
  2805. o->value = {};
  2806. return true;
  2807. }
  2808. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  2809. if (is_type_array(x->type) && !is_type_array(y->type)) {
  2810. if (check_is_assignable_to(c, y, x->type)) {
  2811. if (check_binary_op(c, x, op)) {
  2812. return true;
  2813. }
  2814. }
  2815. }
  2816. return false;
  2817. }
  2818. gb_internal bool is_ise_expr(Ast *node) {
  2819. node = unparen_expr(node);
  2820. return node->kind == Ast_ImplicitSelectorExpr;
  2821. }
  2822. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  2823. if (use_lhs_as_type_hint) { // RHS in this case
  2824. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  2825. }
  2826. return false;
  2827. }
  2828. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  2829. Type *xt = base_type(matrix);
  2830. if (type_hint != nullptr) {
  2831. Type *th = base_type(type_hint);
  2832. if (are_types_identical(th, xt)) {
  2833. return type_hint;
  2834. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  2835. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  2836. // ignore
  2837. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  2838. return type_hint;
  2839. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  2840. return type_hint;
  2841. }
  2842. }
  2843. }
  2844. return matrix;
  2845. }
  2846. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  2847. if (!check_binary_op(c, x, op)) {
  2848. x->mode = Addressing_Invalid;
  2849. return;
  2850. }
  2851. Type *xt = base_type(x->type);
  2852. Type *yt = base_type(y->type);
  2853. if (is_type_matrix(x->type)) {
  2854. GB_ASSERT(xt->kind == Type_Matrix);
  2855. if (op.kind == Token_Mul) {
  2856. if (yt->kind == Type_Matrix) {
  2857. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  2858. goto matrix_error;
  2859. }
  2860. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  2861. goto matrix_error;
  2862. }
  2863. x->mode = Addressing_Value;
  2864. if (are_types_identical(xt, yt)) {
  2865. if (!is_type_named(x->type) && is_type_named(y->type)) {
  2866. // prefer the named type
  2867. x->type = y->type;
  2868. }
  2869. } else {
  2870. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count);
  2871. }
  2872. goto matrix_success;
  2873. } else if (yt->kind == Type_Array) {
  2874. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  2875. goto matrix_error;
  2876. }
  2877. if (xt->Matrix.column_count != yt->Array.count) {
  2878. goto matrix_error;
  2879. }
  2880. // Treat arrays as column vectors
  2881. x->mode = Addressing_Value;
  2882. if (type_hint == nullptr && xt->Matrix.row_count == yt->Array.count) {
  2883. x->type = y->type;
  2884. } else {
  2885. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1);
  2886. }
  2887. goto matrix_success;
  2888. }
  2889. }
  2890. if (!are_types_identical(xt, yt)) {
  2891. goto matrix_error;
  2892. }
  2893. x->mode = Addressing_Value;
  2894. x->type = xt;
  2895. goto matrix_success;
  2896. } else {
  2897. GB_ASSERT(!is_type_matrix(xt));
  2898. GB_ASSERT(is_type_matrix(yt));
  2899. if (op.kind == Token_Mul) {
  2900. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  2901. if (xt->kind == Type_Array) {
  2902. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  2903. goto matrix_error;
  2904. }
  2905. if (xt->Array.count != yt->Matrix.row_count) {
  2906. goto matrix_error;
  2907. }
  2908. // Treat arrays as row vectors
  2909. x->mode = Addressing_Value;
  2910. if (type_hint == nullptr && yt->Matrix.column_count == xt->Array.count) {
  2911. x->type = x->type;
  2912. } else {
  2913. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count);
  2914. }
  2915. goto matrix_success;
  2916. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  2917. x->type = check_matrix_type_hint(y->type, type_hint);
  2918. return;
  2919. }
  2920. }
  2921. if (!are_types_identical(xt, yt)) {
  2922. goto matrix_error;
  2923. }
  2924. x->mode = Addressing_Value;
  2925. x->type = xt;
  2926. goto matrix_success;
  2927. }
  2928. matrix_success:
  2929. x->type = check_matrix_type_hint(x->type, type_hint);
  2930. return;
  2931. matrix_error:
  2932. gbString xts = type_to_string(x->type);
  2933. gbString yts = type_to_string(y->type);
  2934. gbString expr_str = expr_to_string(x->expr);
  2935. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  2936. gb_string_free(expr_str);
  2937. gb_string_free(yts);
  2938. gb_string_free(xts);
  2939. x->type = t_invalid;
  2940. x->mode = Addressing_Invalid;
  2941. return;
  2942. }
  2943. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  2944. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2945. Operand y_ = {}, *y = &y_;
  2946. ast_node(be, BinaryExpr, node);
  2947. defer({
  2948. node->viral_state_flags |= be->left->viral_state_flags;
  2949. node->viral_state_flags |= be->right->viral_state_flags;
  2950. });
  2951. Token op = be->op;
  2952. switch (op.kind) {
  2953. case Token_CmpEq:
  2954. case Token_NotEq: {
  2955. // NOTE(bill): Allow comparisons between types
  2956. if (is_ise_expr(be->left)) {
  2957. // Evalute the right before the left for an '.X' expression
  2958. check_expr_or_type(c, y, be->right, type_hint);
  2959. check_expr_or_type(c, x, be->left, y->type);
  2960. } else {
  2961. check_expr_or_type(c, x, be->left, type_hint);
  2962. check_expr_or_type(c, y, be->right, x->type);
  2963. }
  2964. bool xt = x->mode == Addressing_Type;
  2965. bool yt = y->mode == Addressing_Type;
  2966. // If only one is a type, this is an error
  2967. if (xt ^ yt) {
  2968. GB_ASSERT(xt != yt);
  2969. if (xt) {
  2970. if (!is_type_typeid(y->type)) {
  2971. error_operand_not_expression(x);
  2972. }
  2973. }
  2974. if (yt) {
  2975. if (!is_type_typeid(x->type)) {
  2976. error_operand_not_expression(y);
  2977. }
  2978. }
  2979. }
  2980. break;
  2981. }
  2982. case Token_in:
  2983. case Token_not_in:
  2984. {
  2985. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  2986. check_expr(c, y, be->right);
  2987. Type *rhs_type = type_deref(y->type);
  2988. if (is_type_bit_set(rhs_type)) {
  2989. Type *elem = base_type(rhs_type)->BitSet.elem;
  2990. check_expr_with_type_hint(c, x, be->left, elem);
  2991. } else if (is_type_map(rhs_type)) {
  2992. Type *key = base_type(rhs_type)->Map.key;
  2993. check_expr_with_type_hint(c, x, be->left, key);
  2994. } else {
  2995. check_expr(c, x, be->left);
  2996. }
  2997. if (x->mode == Addressing_Invalid) {
  2998. return;
  2999. }
  3000. if (y->mode == Addressing_Invalid) {
  3001. x->mode = Addressing_Invalid;
  3002. x->expr = y->expr;
  3003. return;
  3004. }
  3005. if (is_type_map(rhs_type)) {
  3006. Type *yt = base_type(rhs_type);
  3007. if (op.kind == Token_in) {
  3008. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3009. } else {
  3010. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3011. }
  3012. add_map_get_dependencies(c);
  3013. } else if (is_type_bit_set(rhs_type)) {
  3014. Type *yt = base_type(rhs_type);
  3015. if (op.kind == Token_in) {
  3016. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3017. } else {
  3018. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3019. }
  3020. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3021. ExactValue k = exact_value_to_integer(x->value);
  3022. ExactValue v = exact_value_to_integer(y->value);
  3023. GB_ASSERT(k.kind == ExactValue_Integer);
  3024. GB_ASSERT(v.kind == ExactValue_Integer);
  3025. i64 key = big_int_to_i64(&k.value_integer);
  3026. i64 lower = yt->BitSet.lower;
  3027. i64 upper = yt->BitSet.upper;
  3028. if (lower <= key && key <= upper) {
  3029. i64 bit = 1ll<<key;
  3030. i64 bits = big_int_to_i64(&v.value_integer);
  3031. x->mode = Addressing_Constant;
  3032. x->type = t_untyped_bool;
  3033. if (op.kind == Token_in) {
  3034. x->value = exact_value_bool((bit & bits) != 0);
  3035. } else {
  3036. x->value = exact_value_bool((bit & bits) == 0);
  3037. }
  3038. x->expr = node;
  3039. return;
  3040. } else {
  3041. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3042. x->mode = Addressing_Invalid;
  3043. }
  3044. }
  3045. } else {
  3046. gbString t = type_to_string(y->type);
  3047. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3048. gb_string_free(t);
  3049. x->expr = node;
  3050. x->mode = Addressing_Invalid;
  3051. return;
  3052. }
  3053. if (x->mode != Addressing_Invalid) {
  3054. x->mode = Addressing_Value;
  3055. x->type = t_untyped_bool;
  3056. }
  3057. x->expr = node;
  3058. return;
  3059. }
  3060. default:
  3061. if (is_ise_expr(be->left)) {
  3062. // Evalute the right before the left for an '.X' expression
  3063. check_expr_or_type(c, y, be->right, type_hint);
  3064. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3065. check_expr_or_type(c, x, be->left, y->type);
  3066. } else {
  3067. check_expr_with_type_hint(c, x, be->left, type_hint);
  3068. }
  3069. } else {
  3070. check_expr_with_type_hint(c, x, be->left, type_hint);
  3071. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3072. check_expr_with_type_hint(c, y, be->right, x->type);
  3073. } else {
  3074. check_expr_with_type_hint(c, y, be->right, type_hint);
  3075. }
  3076. }
  3077. break;
  3078. }
  3079. if (x->mode == Addressing_Invalid) {
  3080. return;
  3081. }
  3082. if (y->mode == Addressing_Invalid) {
  3083. x->mode = Addressing_Invalid;
  3084. x->expr = y->expr;
  3085. return;
  3086. }
  3087. if (x->mode == Addressing_Builtin) {
  3088. x->mode = Addressing_Invalid;
  3089. error(x->expr, "built-in expression in binary expression");
  3090. return;
  3091. }
  3092. if (y->mode == Addressing_Builtin) {
  3093. x->mode = Addressing_Invalid;
  3094. error(y->expr, "built-in expression in binary expression");
  3095. return;
  3096. }
  3097. if (x->mode == Addressing_ProcGroup) {
  3098. x->mode = Addressing_Invalid;
  3099. if (x->proc_group != nullptr) {
  3100. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3101. } else {
  3102. error(x->expr, "procedure group used in binary expression");
  3103. }
  3104. return;
  3105. }
  3106. if (y->mode == Addressing_ProcGroup) {
  3107. x->mode = Addressing_Invalid;
  3108. if (x->proc_group != nullptr) {
  3109. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3110. } else {
  3111. error(y->expr, "procedure group used in binary expression");
  3112. }
  3113. return;
  3114. }
  3115. if (token_is_shift(op.kind)) {
  3116. check_shift(c, x, y, node, type_hint);
  3117. return;
  3118. }
  3119. convert_to_typed(c, x, y->type);
  3120. if (x->mode == Addressing_Invalid) {
  3121. return;
  3122. }
  3123. convert_to_typed(c, y, x->type);
  3124. if (y->mode == Addressing_Invalid) {
  3125. x->mode = Addressing_Invalid;
  3126. return;
  3127. }
  3128. if (token_is_comparison(op.kind)) {
  3129. check_comparison(c, node, x, y, op.kind);
  3130. return;
  3131. }
  3132. if (check_binary_array_expr(c, op, x, y)) {
  3133. x->mode = Addressing_Value;
  3134. x->type = x->type;
  3135. return;
  3136. }
  3137. if (check_binary_array_expr(c, op, y, x)) {
  3138. x->mode = Addressing_Value;
  3139. x->type = y->type;
  3140. return;
  3141. }
  3142. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3143. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3144. x->expr = node;
  3145. return;
  3146. }
  3147. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3148. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3149. // NOTE(bill, 2022-06-26)
  3150. // Allow any boolean types within `&&` and `||`
  3151. // This is an exception to all other binary expressions since the result
  3152. // of a comparison will always be an untyped boolean, and allowing
  3153. // any boolean between these two simplifies a lot of expressions
  3154. } else if (!are_types_identical(x->type, y->type)) {
  3155. if (x->type != t_invalid &&
  3156. y->type != t_invalid) {
  3157. gbString xt = type_to_string(x->type);
  3158. gbString yt = type_to_string(y->type);
  3159. gbString expr_str = expr_to_string(node);
  3160. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3161. gb_string_free(expr_str);
  3162. gb_string_free(yt);
  3163. gb_string_free(xt);
  3164. }
  3165. x->mode = Addressing_Invalid;
  3166. return;
  3167. }
  3168. if (!check_binary_op(c, x, op)) {
  3169. x->mode = Addressing_Invalid;
  3170. return;
  3171. }
  3172. switch (op.kind) {
  3173. case Token_Quo:
  3174. case Token_Mod:
  3175. case Token_ModMod:
  3176. case Token_QuoEq:
  3177. case Token_ModEq:
  3178. case Token_ModModEq:
  3179. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3180. y->mode == Addressing_Constant) {
  3181. bool fail = false;
  3182. switch (y->value.kind) {
  3183. case ExactValue_Integer:
  3184. if (big_int_is_zero(&y->value.value_integer)) {
  3185. fail = true;
  3186. }
  3187. break;
  3188. case ExactValue_Float:
  3189. if (y->value.value_float == 0.0) {
  3190. fail = true;
  3191. }
  3192. break;
  3193. }
  3194. if (fail) {
  3195. error(y->expr, "Division by zero not allowed");
  3196. x->mode = Addressing_Invalid;
  3197. return;
  3198. }
  3199. }
  3200. break;
  3201. case Token_CmpAnd:
  3202. case Token_CmpOr:
  3203. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3204. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3205. }
  3206. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3207. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3208. }
  3209. break;
  3210. }
  3211. if (x->mode == Addressing_Constant &&
  3212. y->mode == Addressing_Constant) {
  3213. ExactValue a = x->value;
  3214. ExactValue b = y->value;
  3215. if (!is_type_constant_type(x->type)) {
  3216. #if 0
  3217. gbString xt = type_to_string(x->type);
  3218. gbString err_str = expr_to_string(node);
  3219. error(op, "Invalid type, '%s', for constant binary expression '%s'", xt, err_str);
  3220. gb_string_free(err_str);
  3221. gb_string_free(xt);
  3222. x->mode = Addressing_Invalid;
  3223. #else
  3224. // NOTE(bill, 2021-04-21): The above is literally a useless error message.
  3225. // Why did I add it in the first place?!
  3226. x->mode = Addressing_Value;
  3227. #endif
  3228. return;
  3229. }
  3230. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3231. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3232. }
  3233. if (is_type_bit_set(x->type)) {
  3234. switch (op.kind) {
  3235. case Token_Add: op.kind = Token_Or; break;
  3236. case Token_Sub: op.kind = Token_AndNot; break;
  3237. }
  3238. }
  3239. x->value = exact_binary_operator_value(op.kind, a, b);
  3240. if (is_type_typed(x->type)) {
  3241. if (node != nullptr) {
  3242. x->expr = node;
  3243. }
  3244. check_is_expressible(c, x, x->type);
  3245. }
  3246. return;
  3247. } else if (is_type_string(x->type)) {
  3248. error(node, "String concatenation is only allowed with constant strings");
  3249. x->mode = Addressing_Invalid;
  3250. return;
  3251. }
  3252. if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3253. Type *bt = base_type(x->type);
  3254. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3255. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3256. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3257. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3258. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3259. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3260. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3261. }
  3262. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3263. Type *bt = base_type(x->type);
  3264. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3265. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3266. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3267. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3268. }
  3269. }
  3270. x->mode = Addressing_Value;
  3271. }
  3272. gb_internal Operand make_operand_from_node(Ast *node) {
  3273. GB_ASSERT(node != nullptr);
  3274. Operand x = {};
  3275. x.expr = node;
  3276. x.mode = node->tav.mode;
  3277. x.type = node->tav.type;
  3278. x.value = node->tav.value;
  3279. return x;
  3280. }
  3281. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3282. GB_ASSERT(e != nullptr);
  3283. ExprInfo *old = check_get_expr_info(c, e);
  3284. if (old == nullptr) {
  3285. if (type != nullptr && type != t_invalid) {
  3286. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3287. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3288. if (e->kind == Ast_TernaryIfExpr) {
  3289. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3290. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3291. }
  3292. }
  3293. }
  3294. return;
  3295. }
  3296. switch (e->kind) {
  3297. case_ast_node(ue, UnaryExpr, e);
  3298. if (old->value.kind != ExactValue_Invalid) {
  3299. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3300. // They don't need to be updated as they will be updated later and
  3301. // checked at the end of general checking stage.
  3302. break;
  3303. }
  3304. update_untyped_expr_type(c, ue->expr, type, final);
  3305. case_end;
  3306. case_ast_node(be, BinaryExpr, e);
  3307. if (old->value.kind != ExactValue_Invalid) {
  3308. // See above note in UnaryExpr case
  3309. break;
  3310. }
  3311. if (token_is_comparison(be->op.kind)) {
  3312. // NOTE(bill): Do nothing as the types are fine
  3313. } else if (token_is_shift(be->op.kind)) {
  3314. update_untyped_expr_type(c, be->left, type, final);
  3315. } else {
  3316. update_untyped_expr_type(c, be->left, type, final);
  3317. update_untyped_expr_type(c, be->right, type, final);
  3318. }
  3319. case_end;
  3320. case_ast_node(te, TernaryIfExpr, e);
  3321. if (old->value.kind != ExactValue_Invalid) {
  3322. // See above note in UnaryExpr case
  3323. break;
  3324. }
  3325. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3326. // having an untyped value
  3327. Operand x = make_operand_from_node(te->x);
  3328. Operand y = make_operand_from_node(te->y);
  3329. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3330. update_untyped_expr_type(c, te->x, type, final);
  3331. }
  3332. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3333. update_untyped_expr_type(c, te->y, type, final);
  3334. }
  3335. case_end;
  3336. case_ast_node(te, TernaryWhenExpr, e);
  3337. if (old->value.kind != ExactValue_Invalid) {
  3338. // See above note in UnaryExpr case
  3339. break;
  3340. }
  3341. update_untyped_expr_type(c, te->x, type, final);
  3342. update_untyped_expr_type(c, te->y, type, final);
  3343. case_end;
  3344. case_ast_node(ore, OrReturnExpr, e);
  3345. if (old->value.kind != ExactValue_Invalid) {
  3346. // See above note in UnaryExpr case
  3347. break;
  3348. }
  3349. update_untyped_expr_type(c, ore->expr, type, final);
  3350. case_end;
  3351. case_ast_node(oee, OrElseExpr, e);
  3352. if (old->value.kind != ExactValue_Invalid) {
  3353. // See above note in UnaryExpr case
  3354. break;
  3355. }
  3356. update_untyped_expr_type(c, oee->x, type, final);
  3357. update_untyped_expr_type(c, oee->y, type, final);
  3358. case_end;
  3359. case_ast_node(pe, ParenExpr, e);
  3360. update_untyped_expr_type(c, pe->expr, type, final);
  3361. case_end;
  3362. }
  3363. if (!final && is_type_untyped(type)) {
  3364. old->type = base_type(type);
  3365. return;
  3366. }
  3367. // We need to remove it and then give it a new one
  3368. check_remove_expr_info(c, e);
  3369. if (old->is_lhs && !is_type_integer(type)) {
  3370. gbString expr_str = expr_to_string(e);
  3371. gbString type_str = type_to_string(type);
  3372. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3373. gb_string_free(type_str);
  3374. gb_string_free(expr_str);
  3375. return;
  3376. }
  3377. add_type_and_value(c, e, old->mode, type, old->value);
  3378. }
  3379. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3380. GB_ASSERT(e != nullptr);
  3381. ExprInfo *found = check_get_expr_info(c, e);
  3382. if (found) {
  3383. found->value = value;
  3384. }
  3385. }
  3386. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type) {
  3387. gbString expr_str = expr_to_string(operand->expr);
  3388. gbString type_str = type_to_string(target_type);
  3389. gbString from_type_str = type_to_string(operand->type);
  3390. char const *extra_text = "";
  3391. if (operand->mode == Addressing_Constant) {
  3392. if (big_int_is_zero(&operand->value.value_integer)) {
  3393. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3394. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3395. extra_text = " - Did you want 'nil'?";
  3396. }
  3397. }
  3398. }
  3399. ERROR_BLOCK();
  3400. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3401. if (operand->value.kind == ExactValue_String) {
  3402. String key = operand->value.value_string;
  3403. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3404. Type *et = base_type(target_type);
  3405. check_did_you_mean_type(key, et->Enum.fields, ".");
  3406. }
  3407. }
  3408. gb_string_free(from_type_str);
  3409. gb_string_free(type_str);
  3410. gb_string_free(expr_str);
  3411. operand->mode = Addressing_Invalid;
  3412. }
  3413. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3414. Type *t = core_type(type);
  3415. if (is_type_boolean(t)) {
  3416. // v = exact_value_to_boolean(v);
  3417. } else if (is_type_float(t)) {
  3418. v = exact_value_to_float(v);
  3419. } else if (is_type_integer(t)) {
  3420. v = exact_value_to_integer(v);
  3421. } else if (is_type_pointer(t)) {
  3422. v = exact_value_to_integer(v);
  3423. } else if (is_type_complex(t)) {
  3424. v = exact_value_to_complex(v);
  3425. } else if (is_type_quaternion(t)) {
  3426. v = exact_value_to_quaternion(v);
  3427. }
  3428. return v;
  3429. }
  3430. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3431. GB_ASSERT_NOT_NULL(target_type);
  3432. if (operand->mode == Addressing_Invalid ||
  3433. operand->mode == Addressing_Type ||
  3434. is_type_typed(operand->type) ||
  3435. target_type == t_invalid) {
  3436. return;
  3437. }
  3438. if (is_type_untyped(target_type)) {
  3439. GB_ASSERT(operand->type->kind == Type_Basic);
  3440. GB_ASSERT(target_type->kind == Type_Basic);
  3441. BasicKind x_kind = operand->type->Basic.kind;
  3442. BasicKind y_kind = target_type->Basic.kind;
  3443. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3444. if (x_kind < y_kind) {
  3445. operand->type = target_type;
  3446. update_untyped_expr_type(c, operand->expr, target_type, false);
  3447. }
  3448. } else if (x_kind != y_kind) {
  3449. operand->mode = Addressing_Invalid;
  3450. convert_untyped_error(c, operand, target_type);
  3451. return;
  3452. }
  3453. return;
  3454. }
  3455. Type *t = base_type(target_type);
  3456. if (c->in_enum_type) {
  3457. t = core_type(target_type);
  3458. }
  3459. switch (t->kind) {
  3460. case Type_Basic:
  3461. if (operand->mode == Addressing_Constant) {
  3462. check_is_expressible(c, operand, t);
  3463. if (operand->mode == Addressing_Invalid) {
  3464. return;
  3465. }
  3466. update_untyped_expr_value(c, operand->expr, operand->value);
  3467. } else {
  3468. switch (operand->type->Basic.kind) {
  3469. case Basic_UntypedBool:
  3470. if (!is_type_boolean(target_type)) {
  3471. operand->mode = Addressing_Invalid;
  3472. convert_untyped_error(c, operand, target_type);
  3473. return;
  3474. }
  3475. break;
  3476. case Basic_UntypedInteger:
  3477. case Basic_UntypedFloat:
  3478. case Basic_UntypedComplex:
  3479. case Basic_UntypedQuaternion:
  3480. case Basic_UntypedRune:
  3481. if (!is_type_numeric(target_type)) {
  3482. operand->mode = Addressing_Invalid;
  3483. convert_untyped_error(c, operand, target_type);
  3484. return;
  3485. }
  3486. break;
  3487. case Basic_UntypedNil:
  3488. if (is_type_any(target_type)) {
  3489. // target_type = t_untyped_nil;
  3490. } else if (is_type_cstring(target_type)) {
  3491. // target_type = t_untyped_nil;
  3492. } else if (!type_has_nil(target_type)) {
  3493. operand->mode = Addressing_Invalid;
  3494. convert_untyped_error(c, operand, target_type);
  3495. return;
  3496. }
  3497. break;
  3498. }
  3499. }
  3500. break;
  3501. case Type_Array: {
  3502. Type *elem = base_array_type(t);
  3503. if (check_is_assignable_to(c, operand, elem)) {
  3504. operand->mode = Addressing_Value;
  3505. } else {
  3506. if (operand->value.kind == ExactValue_String) {
  3507. String s = operand->value.value_string;
  3508. if (is_type_u8_array(t)) {
  3509. if (s.len == t->Array.count) {
  3510. break;
  3511. }
  3512. } else if (is_type_rune_array(t)) {
  3513. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  3514. if (rune_count == t->Array.count) {
  3515. break;
  3516. }
  3517. }
  3518. }
  3519. operand->mode = Addressing_Invalid;
  3520. convert_untyped_error(c, operand, target_type);
  3521. return;
  3522. }
  3523. break;
  3524. }
  3525. case Type_Matrix: {
  3526. Type *elem = base_array_type(t);
  3527. if (check_is_assignable_to(c, operand, elem)) {
  3528. if (t->Matrix.row_count != t->Matrix.column_count) {
  3529. operand->mode = Addressing_Invalid;
  3530. begin_error_block();
  3531. defer (end_error_block());
  3532. convert_untyped_error(c, operand, target_type);
  3533. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  3534. return;
  3535. } else {
  3536. operand->mode = Addressing_Value;
  3537. }
  3538. } else {
  3539. operand->mode = Addressing_Invalid;
  3540. convert_untyped_error(c, operand, target_type);
  3541. return;
  3542. }
  3543. break;
  3544. }
  3545. case Type_Union:
  3546. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  3547. TEMPORARY_ALLOCATOR_GUARD();
  3548. isize count = t->Union.variants.count;
  3549. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  3550. isize valid_count = 0;
  3551. isize first_success_index = -1;
  3552. for_array(i, t->Union.variants) {
  3553. Type *vt = t->Union.variants[i];
  3554. i64 score = 0;
  3555. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  3556. valids[valid_count].index = i;
  3557. valids[valid_count].score = score;
  3558. valid_count += 1;
  3559. if (first_success_index < 0) {
  3560. first_success_index = i;
  3561. }
  3562. }
  3563. }
  3564. if (valid_count > 1) {
  3565. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  3566. i64 best_score = valids[0].score;
  3567. for (isize i = 1; i < valid_count; i++) {
  3568. auto v = valids[i];
  3569. if (best_score > v.score) {
  3570. valid_count = i;
  3571. break;
  3572. }
  3573. best_score = v.score;
  3574. }
  3575. first_success_index = valids[0].index;
  3576. }
  3577. gbString type_str = type_to_string(target_type);
  3578. defer (gb_string_free(type_str));
  3579. if (valid_count == 1) {
  3580. operand->mode = Addressing_Value;
  3581. operand->type = t->Union.variants[first_success_index];
  3582. target_type = t->Union.variants[first_success_index];
  3583. break;
  3584. } else if (valid_count > 1) {
  3585. begin_error_block();
  3586. defer (end_error_block());
  3587. GB_ASSERT(first_success_index >= 0);
  3588. operand->mode = Addressing_Invalid;
  3589. convert_untyped_error(c, operand, target_type);
  3590. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  3591. i32 j = 0;
  3592. for (i32 i = 0; i < valid_count; i++) {
  3593. ValidIndexAndScore valid = valids[i];
  3594. if (j > 0 && valid_count > 2) error_line(", ");
  3595. if (j == valid_count-1) {
  3596. if (valid_count == 2) error_line(" ");
  3597. error_line("or ");
  3598. }
  3599. gbString str = type_to_string(t->Union.variants[valid.index]);
  3600. error_line("'%s'", str);
  3601. gb_string_free(str);
  3602. j++;
  3603. }
  3604. error_line("\n\n");
  3605. return;
  3606. } else if (is_type_untyped_uninit(operand->type)) {
  3607. target_type = t_untyped_uninit;
  3608. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  3609. begin_error_block();
  3610. defer (end_error_block());
  3611. operand->mode = Addressing_Invalid;
  3612. convert_untyped_error(c, operand, target_type);
  3613. if (count > 0) {
  3614. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  3615. error_line("\t");
  3616. for (i32 i = 0; i < count; i++) {
  3617. Type *v = t->Union.variants[i];
  3618. if (i > 0 && count > 2) error_line(", ");
  3619. if (i == count-1) {
  3620. if (count == 2) error_line(" ");
  3621. if (count > 1) {
  3622. error_line("or ");
  3623. }
  3624. }
  3625. gbString str = type_to_string(v);
  3626. error_line("'%s'", str);
  3627. gb_string_free(str);
  3628. }
  3629. error_line("\n\n");
  3630. }
  3631. return;
  3632. }
  3633. }
  3634. /* fallthrough */
  3635. default:
  3636. if (is_type_untyped_uninit(operand->type)) {
  3637. target_type = t_untyped_uninit;
  3638. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  3639. target_type = t_untyped_nil;
  3640. } else {
  3641. operand->mode = Addressing_Invalid;
  3642. convert_untyped_error(c, operand, target_type);
  3643. return;
  3644. }
  3645. break;
  3646. }
  3647. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  3648. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  3649. } else {
  3650. target_type = default_type(operand->type);
  3651. }
  3652. }
  3653. update_untyped_expr_type(c, operand->expr, target_type, true);
  3654. operand->type = target_type;
  3655. }
  3656. 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) {
  3657. Operand operand = {Addressing_Invalid};
  3658. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  3659. if (operand.mode == Addressing_Invalid) {
  3660. if (value) *value = 0;
  3661. return false;
  3662. }
  3663. Type *index_type = t_int;
  3664. if (type_hint != nullptr) {
  3665. index_type = type_hint;
  3666. }
  3667. convert_to_typed(c, &operand, index_type);
  3668. if (operand.mode == Addressing_Invalid) {
  3669. if (value) *value = 0;
  3670. return false;
  3671. }
  3672. if (type_hint != nullptr) {
  3673. if (!check_is_assignable_to(c, &operand, type_hint)) {
  3674. gbString expr_str = expr_to_string(operand.expr);
  3675. gbString index_type_str = type_to_string(type_hint);
  3676. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  3677. gb_string_free(index_type_str);
  3678. gb_string_free(expr_str);
  3679. if (value) *value = 0;
  3680. return false;
  3681. }
  3682. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  3683. gbString expr_str = expr_to_string(operand.expr);
  3684. gbString type_str = type_to_string(operand.type);
  3685. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  3686. gb_string_free(type_str);
  3687. gb_string_free(expr_str);
  3688. if (value) *value = 0;
  3689. return false;
  3690. }
  3691. if (operand.mode == Addressing_Constant &&
  3692. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  3693. BigInt i = exact_value_to_integer(operand.value).value_integer;
  3694. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  3695. TEMPORARY_ALLOCATOR_GUARD();
  3696. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3697. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3698. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  3699. if (value) *value = 0;
  3700. return false;
  3701. }
  3702. if (max_count >= 0) {
  3703. if (is_type_enum(index_type)) {
  3704. Type *bt = base_type(index_type);
  3705. GB_ASSERT(bt->kind == Type_Enum);
  3706. ExactValue const &lo = *bt->Enum.min_value;
  3707. ExactValue const &hi = *bt->Enum.max_value;
  3708. String lo_str = {};
  3709. String hi_str = {};
  3710. if (bt->Enum.fields.count > 0) {
  3711. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  3712. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  3713. lo_str = bt->Enum.fields[lo_idx]->token.string;
  3714. hi_str = bt->Enum.fields[hi_idx]->token.string;
  3715. }
  3716. bool out_of_bounds = false;
  3717. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  3718. out_of_bounds = true;
  3719. }
  3720. if (out_of_bounds) {
  3721. gbString expr_str = expr_to_string(operand.expr);
  3722. if (lo_str.len > 0) {
  3723. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  3724. } else {
  3725. gbString index_type_str = type_to_string(index_type);
  3726. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  3727. gb_string_free(index_type_str);
  3728. }
  3729. gb_string_free(expr_str);
  3730. return false;
  3731. }
  3732. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  3733. return true;
  3734. } else { // NOTE(bill): Do array bound checking
  3735. i64 v = -1;
  3736. if (i.used <= 1) {
  3737. v = big_int_to_i64(&i);
  3738. }
  3739. if (value) *value = v;
  3740. bool out_of_bounds = false;
  3741. if (v < 0) {
  3742. out_of_bounds = true;
  3743. } else if (open_range) {
  3744. out_of_bounds = v > max_count;
  3745. } else {
  3746. out_of_bounds = v >= max_count;
  3747. }
  3748. if (out_of_bounds) {
  3749. TEMPORARY_ALLOCATOR_GUARD();
  3750. String idx_str = big_int_to_string(temporary_allocator(), &i);
  3751. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  3752. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  3753. return false;
  3754. }
  3755. return true;
  3756. }
  3757. } else {
  3758. if (value) *value = exact_value_to_i64(operand.value);
  3759. return true;
  3760. }
  3761. }
  3762. // NOTE(bill): It's alright :D
  3763. if (value) *value = -1;
  3764. return true;
  3765. }
  3766. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  3767. if (value.kind == ExactValue_String) {
  3768. GB_ASSERT(0 <= index && index < value.value_string.len);
  3769. u8 val = value.value_string[index];
  3770. if (success_) *success_ = true;
  3771. if (finish_) *finish_ = true;
  3772. return exact_value_u64(val);
  3773. }
  3774. if (value.kind != ExactValue_Compound) {
  3775. if (success_) *success_ = true;
  3776. if (finish_) *finish_ = true;
  3777. return value;
  3778. }
  3779. Ast *node = value.value_compound;
  3780. switch (node->kind) {
  3781. case_ast_node(cl, CompoundLit, node);
  3782. if (cl->elems.count == 0) {
  3783. if (success_) *success_ = true;
  3784. if (finish_) *finish_ = true;
  3785. return empty_exact_value;
  3786. }
  3787. if (cl->elems[0]->kind == Ast_FieldValue) {
  3788. if (is_type_struct(node->tav.type)) {
  3789. bool found = false;
  3790. for (Ast *elem : cl->elems) {
  3791. if (elem->kind != Ast_FieldValue) {
  3792. continue;
  3793. }
  3794. ast_node(fv, FieldValue, elem);
  3795. String name = fv->field->Ident.token.string;
  3796. Selection sub_sel = lookup_field(node->tav.type, name, false);
  3797. defer (array_free(&sub_sel.index));
  3798. if (sub_sel.index[0] == index) {
  3799. value = fv->value->tav.value;
  3800. found = true;
  3801. break;
  3802. }
  3803. }
  3804. if (!found) {
  3805. // Use the zero value if it is not found
  3806. value = {};
  3807. }
  3808. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  3809. for (Ast *elem : cl->elems) {
  3810. if (elem->kind != Ast_FieldValue) {
  3811. continue;
  3812. }
  3813. ast_node(fv, FieldValue, elem);
  3814. if (is_ast_range(fv->field)) {
  3815. ast_node(ie, BinaryExpr, fv->field);
  3816. TypeAndValue lo_tav = ie->left->tav;
  3817. TypeAndValue hi_tav = ie->right->tav;
  3818. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3819. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3820. TokenKind op = ie->op.kind;
  3821. i64 lo = exact_value_to_i64(lo_tav.value);
  3822. i64 hi = exact_value_to_i64(hi_tav.value);
  3823. i64 corrected_index = index;
  3824. if (is_type_enumerated_array(node->tav.type)) {
  3825. Type *bt = base_type(node->tav.type);
  3826. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3827. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  3828. }
  3829. if (op != Token_RangeHalf) {
  3830. if (lo <= corrected_index && corrected_index <= hi) {
  3831. TypeAndValue tav = fv->value->tav;
  3832. if (success_) *success_ = true;
  3833. if (finish_) *finish_ = false;
  3834. return tav.value;
  3835. }
  3836. } else {
  3837. if (lo <= corrected_index && corrected_index < hi) {
  3838. TypeAndValue tav = fv->value->tav;
  3839. if (success_) *success_ = true;
  3840. if (finish_) *finish_ = false;
  3841. return tav.value;
  3842. }
  3843. }
  3844. } else {
  3845. TypeAndValue index_tav = fv->field->tav;
  3846. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3847. ExactValue index_value = index_tav.value;
  3848. if (is_type_enumerated_array(node->tav.type)) {
  3849. Type *bt = base_type(node->tav.type);
  3850. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3851. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  3852. }
  3853. i64 field_index = exact_value_to_i64(index_value);
  3854. if (index == field_index) {
  3855. TypeAndValue tav = fv->value->tav;
  3856. if (success_) *success_ = true;
  3857. if (finish_) *finish_ = false;
  3858. return tav.value;;
  3859. }
  3860. }
  3861. }
  3862. }
  3863. } else {
  3864. i32 count = (i32)cl->elems.count;
  3865. if (count < index) {
  3866. if (success_) *success_ = false;
  3867. if (finish_) *finish_ = true;
  3868. return empty_exact_value;
  3869. }
  3870. if (cl->elems.count <= index) {
  3871. if (success_) *success_ = false;
  3872. if (finish_) *finish_ = false;
  3873. return value;
  3874. }
  3875. TypeAndValue tav = cl->elems[index]->tav;
  3876. if (tav.mode == Addressing_Constant) {
  3877. if (success_) *success_ = true;
  3878. if (finish_) *finish_ = false;
  3879. return tav.value;
  3880. } else {
  3881. GB_ASSERT(is_type_untyped_nil(tav.type));
  3882. if (success_) *success_ = true;
  3883. if (finish_) *finish_ = false;
  3884. return tav.value;
  3885. }
  3886. }
  3887. case_end;
  3888. default:
  3889. // TODO(bill): Should this be a general fallback?
  3890. if (success_) *success_ = true;
  3891. if (finish_) *finish_ = true;
  3892. return empty_exact_value;
  3893. }
  3894. if (finish_) *finish_ = false;
  3895. return value;
  3896. }
  3897. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  3898. if (operand->mode != Addressing_Constant) {
  3899. if (success_) *success_ = false;
  3900. return empty_exact_value;
  3901. }
  3902. if (sel.indirect) {
  3903. if (success_) *success_ = false;
  3904. return empty_exact_value;
  3905. }
  3906. if (sel.index.count == 0) {
  3907. if (success_) *success_ = false;
  3908. return empty_exact_value;
  3909. }
  3910. ExactValue value = operand->value;
  3911. if (value.kind == ExactValue_Compound) {
  3912. while (sel.index.count > 0) {
  3913. i32 index = sel.index[0];
  3914. sel = sub_selection(sel, 1);
  3915. bool finish = false;
  3916. value = get_constant_field_single(c, value, index, success_, &finish);
  3917. if (finish) {
  3918. return value;
  3919. }
  3920. }
  3921. if (success_) *success_ = true;
  3922. return value;
  3923. } else if (value.kind == ExactValue_Quaternion) {
  3924. // @QuaternionLayout
  3925. Quaternion256 q = *value.value_quaternion;
  3926. GB_ASSERT(sel.index.count == 1);
  3927. switch (sel.index[0]) {
  3928. case 3: // w
  3929. if (success_) *success_ = true;
  3930. return exact_value_float(q.real);
  3931. case 0: // x
  3932. if (success_) *success_ = true;
  3933. return exact_value_float(q.imag);
  3934. case 1: // y
  3935. if (success_) *success_ = true;
  3936. return exact_value_float(q.jmag);
  3937. case 2: // z
  3938. if (success_) *success_ = true;
  3939. return exact_value_float(q.kmag);
  3940. }
  3941. if (success_) *success_ = false;
  3942. return empty_exact_value;
  3943. } else if (value.kind == ExactValue_Complex) {
  3944. // @QuaternionLayout
  3945. Complex128 c = *value.value_complex;
  3946. GB_ASSERT(sel.index.count == 1);
  3947. switch (sel.index[0]) {
  3948. case 0: // real
  3949. if (success_) *success_ = true;
  3950. return exact_value_float(c.real);
  3951. case 1: // imag
  3952. if (success_) *success_ = true;
  3953. return exact_value_float(c.imag);
  3954. }
  3955. if (success_) *success_ = false;
  3956. return empty_exact_value;
  3957. }
  3958. if (success_) *success_ = true;
  3959. return empty_exact_value;
  3960. }
  3961. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  3962. Type *array_type = base_type(type_deref(original_type));
  3963. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  3964. if (array_type->kind == Type_SimdVector) {
  3965. Type *elem_type = array_type->SimdVector.elem;
  3966. return alloc_type_simd_vector(new_count, elem_type);
  3967. }
  3968. Type *elem_type = array_type->Array.elem;
  3969. Type *swizzle_array_type = nullptr;
  3970. Type *bth = base_type(type_deref(type_hint));
  3971. if (bth != nullptr && bth->kind == Type_Array &&
  3972. bth->Array.count == new_count &&
  3973. are_types_identical(bth->Array.elem, elem_type)) {
  3974. swizzle_array_type = type_hint;
  3975. } else {
  3976. i64 max_count = array_type->Array.count;
  3977. if (new_count == max_count) {
  3978. swizzle_array_type = original_type;
  3979. } else {
  3980. swizzle_array_type = alloc_type_array(elem_type, new_count);
  3981. }
  3982. }
  3983. return swizzle_array_type;
  3984. }
  3985. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  3986. bool is_declared = entity != nullptr;
  3987. if (is_declared) {
  3988. if (entity->kind == Entity_Builtin) {
  3989. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  3990. // This means that we should just ignore the found result through it
  3991. *allow_builtin = entity->scope == import_scope || entity->scope != builtin_pkg->scope;
  3992. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  3993. is_declared = false;
  3994. }
  3995. }
  3996. return is_declared;
  3997. }
  3998. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  3999. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4000. if (node->kind == Ast_Ident) {
  4001. String name = node->Ident.token.string;
  4002. return scope_lookup(c->scope, name);
  4003. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4004. ast_node(se, SelectorExpr, node);
  4005. if (se->token.kind == Token_ArrowRight) {
  4006. return nullptr;
  4007. }
  4008. Ast *op_expr = se->expr;
  4009. Ast *selector = unparen_expr(se->selector);
  4010. if (selector == nullptr) {
  4011. return nullptr;
  4012. }
  4013. if (selector->kind != Ast_Ident) {
  4014. return nullptr;
  4015. }
  4016. Entity *entity = nullptr;
  4017. Entity *expr_entity = nullptr;
  4018. bool check_op_expr = true;
  4019. if (op_expr->kind == Ast_Ident) {
  4020. String op_name = op_expr->Ident.token.string;
  4021. Entity *e = scope_lookup(c->scope, op_name);
  4022. if (e == nullptr) {
  4023. return nullptr;
  4024. }
  4025. add_entity_use(c, op_expr, e);
  4026. expr_entity = e;
  4027. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4028. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4029. // It pretty much needs to be in this order and this way
  4030. // If you can clean this up, please do but be really careful
  4031. String import_name = op_name;
  4032. Scope *import_scope = e->ImportName.scope;
  4033. String entity_name = selector->Ident.token.string;
  4034. check_op_expr = false;
  4035. entity = scope_lookup_current(import_scope, entity_name);
  4036. bool allow_builtin = false;
  4037. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4038. return nullptr;
  4039. }
  4040. check_entity_decl(c, entity, nullptr, nullptr);
  4041. if (entity->kind == Entity_ProcGroup) {
  4042. return entity;
  4043. }
  4044. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4045. }
  4046. }
  4047. Operand operand = {};
  4048. if (check_op_expr) {
  4049. check_expr_base(c, &operand, op_expr, nullptr);
  4050. if (operand.mode == Addressing_Invalid) {
  4051. return nullptr;
  4052. }
  4053. }
  4054. if (entity == nullptr && selector->kind == Ast_Ident) {
  4055. String field_name = selector->Ident.token.string;
  4056. if (is_type_dynamic_array(type_deref(operand.type))) {
  4057. init_mem_allocator(c->checker);
  4058. }
  4059. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4060. entity = sel.entity;
  4061. }
  4062. if (entity != nullptr) {
  4063. return entity;
  4064. }
  4065. }
  4066. return nullptr;
  4067. }
  4068. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4069. ast_node(se, SelectorExpr, node);
  4070. bool check_op_expr = true;
  4071. Entity *expr_entity = nullptr;
  4072. Entity *entity = nullptr;
  4073. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4074. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4075. error(node, "Illegal use of -> selector shorthand outside of a call");
  4076. operand->mode = Addressing_Invalid;
  4077. operand->expr = node;
  4078. return nullptr;
  4079. }
  4080. operand->expr = node;
  4081. Ast *op_expr = se->expr;
  4082. Ast *selector = unparen_expr(se->selector);
  4083. if (selector == nullptr) {
  4084. operand->mode = Addressing_Invalid;
  4085. operand->expr = node;
  4086. return nullptr;
  4087. }
  4088. if (selector->kind != Ast_Ident) {
  4089. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4090. operand->mode = Addressing_Invalid;
  4091. operand->expr = node;
  4092. return nullptr;
  4093. }
  4094. if (op_expr->kind == Ast_Ident) {
  4095. String op_name = op_expr->Ident.token.string;
  4096. Entity *e = scope_lookup(c->scope, op_name);
  4097. add_entity_use(c, op_expr, e);
  4098. expr_entity = e;
  4099. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4100. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4101. // It pretty much needs to be in this order and this way
  4102. // If you can clean this up, please do but be really careful
  4103. String import_name = op_name;
  4104. Scope *import_scope = e->ImportName.scope;
  4105. String entity_name = selector->Ident.token.string;
  4106. check_op_expr = false;
  4107. entity = scope_lookup_current(import_scope, entity_name);
  4108. bool allow_builtin = false;
  4109. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4110. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4111. operand->mode = Addressing_Invalid;
  4112. operand->expr = node;
  4113. check_did_you_mean_scope(entity_name, import_scope);
  4114. return nullptr;
  4115. }
  4116. check_entity_decl(c, entity, nullptr, nullptr);
  4117. if (entity->kind == Entity_ProcGroup) {
  4118. operand->mode = Addressing_ProcGroup;
  4119. operand->proc_group = entity;
  4120. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4121. return entity;
  4122. }
  4123. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4124. if (!is_entity_exported(entity, allow_builtin)) {
  4125. gbString sel_str = expr_to_string(selector);
  4126. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4127. gb_string_free(sel_str);
  4128. // NOTE(bill): make the state valid still, even if it's "invalid"
  4129. // operand->mode = Addressing_Invalid;
  4130. // operand->expr = node;
  4131. // return nullptr;
  4132. }
  4133. if (entity->kind == Entity_ProcGroup) {
  4134. Array<Entity *> procs = entity->ProcGroup.entities;
  4135. bool skip = false;
  4136. for (Entity *p : procs) {
  4137. Type *t = base_type(p->type);
  4138. if (t == t_invalid) {
  4139. continue;
  4140. }
  4141. Operand x = {};
  4142. x.mode = Addressing_Value;
  4143. x.type = t;
  4144. if (type_hint != nullptr) {
  4145. if (check_is_assignable_to(c, &x, type_hint)) {
  4146. entity = p;
  4147. skip = true;
  4148. break;
  4149. }
  4150. }
  4151. }
  4152. if (!skip) {
  4153. GB_ASSERT(entity != nullptr);
  4154. operand->mode = Addressing_ProcGroup;
  4155. operand->type = t_invalid;
  4156. operand->expr = node;
  4157. operand->proc_group = entity;
  4158. return entity;
  4159. }
  4160. }
  4161. }
  4162. }
  4163. if (check_op_expr) {
  4164. check_expr_base(c, operand, op_expr, nullptr);
  4165. if (operand->mode == Addressing_Invalid) {
  4166. operand->mode = Addressing_Invalid;
  4167. operand->expr = node;
  4168. return nullptr;
  4169. }
  4170. }
  4171. if (entity == nullptr && selector->kind == Ast_Ident) {
  4172. String field_name = selector->Ident.token.string;
  4173. if (is_type_dynamic_array(type_deref(operand->type))) {
  4174. init_mem_allocator(c->checker);
  4175. }
  4176. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4177. entity = sel.entity;
  4178. // NOTE(bill): Add type info needed for fields like 'names'
  4179. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4180. add_type_info_type(c, operand->type);
  4181. }
  4182. if (is_type_enum(operand->type)) {
  4183. add_type_info_type(c, operand->type);
  4184. }
  4185. }
  4186. if (entity == nullptr && selector->kind == Ast_Ident && is_type_array(type_deref(operand->type))) {
  4187. // TODO(bill): Simd_Vector swizzling
  4188. String field_name = selector->Ident.token.string;
  4189. if (1 < field_name.len && field_name.len <= 4) {
  4190. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4191. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4192. bool found_xyzw = false;
  4193. bool found_rgba = false;
  4194. for (isize i = 0; i < field_name.len; i++) {
  4195. bool valid = false;
  4196. for (isize j = 0; j < 4; j++) {
  4197. if (field_name.text[i] == swizzles_xyzw[j]) {
  4198. found_xyzw = true;
  4199. valid = true;
  4200. break;
  4201. }
  4202. if (field_name.text[i] == swizzles_rgba[j]) {
  4203. found_rgba = true;
  4204. valid = true;
  4205. break;
  4206. }
  4207. }
  4208. if (!valid) {
  4209. goto end_of_array_selector_swizzle;
  4210. }
  4211. }
  4212. u8 *swizzles = nullptr;
  4213. u8 index_count = cast(u8)field_name.len;
  4214. if (found_xyzw && found_rgba) {
  4215. gbString op_str = expr_to_string(op_expr);
  4216. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4217. gb_string_free(op_str);
  4218. operand->mode = Addressing_Invalid;
  4219. operand->expr = node;
  4220. return nullptr;
  4221. }
  4222. u8 indices = 0;
  4223. if (found_xyzw) {
  4224. swizzles = swizzles_xyzw;
  4225. } else if (found_rgba) {
  4226. swizzles = swizzles_rgba;
  4227. }
  4228. for (isize i = 0; i < field_name.len; i++) {
  4229. for (isize j = 0; j < 4; j++) {
  4230. if (field_name.text[i] == swizzles[j]) {
  4231. indices |= cast(u8)(j)<<(i*2);
  4232. break;
  4233. }
  4234. }
  4235. }
  4236. Type *original_type = operand->type;
  4237. Type *array_type = base_type(type_deref(original_type));
  4238. GB_ASSERT(array_type->kind == Type_Array);
  4239. i64 array_count = array_type->Array.count;
  4240. for (u8 i = 0; i < index_count; i++) {
  4241. u8 idx = indices>>(i*2) & 3;
  4242. if (idx >= array_count) {
  4243. char c = 0;
  4244. if (found_xyzw) {
  4245. c = swizzles_xyzw[idx];
  4246. } else if (found_rgba) {
  4247. c = swizzles_rgba[idx];
  4248. } else {
  4249. GB_PANIC("unknown swizzle kind");
  4250. }
  4251. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4252. break;
  4253. }
  4254. }
  4255. se->swizzle_count = index_count;
  4256. se->swizzle_indices = indices;
  4257. AddressingMode prev_mode = operand->mode;
  4258. operand->mode = Addressing_SwizzleValue;
  4259. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4260. operand->expr = node;
  4261. switch (prev_mode) {
  4262. case Addressing_Variable:
  4263. case Addressing_SoaVariable:
  4264. case Addressing_SwizzleVariable:
  4265. operand->mode = Addressing_SwizzleVariable;
  4266. break;
  4267. }
  4268. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4269. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4270. return swizzle_entity;
  4271. }
  4272. end_of_array_selector_swizzle:;
  4273. }
  4274. if (entity == nullptr) {
  4275. gbString op_str = expr_to_string(op_expr);
  4276. gbString type_str = type_to_string_shorthand(operand->type);
  4277. gbString sel_str = expr_to_string(selector);
  4278. if (operand->mode == Addressing_Type) {
  4279. if (is_type_polymorphic(operand->type, true)) {
  4280. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4281. } else {
  4282. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4283. }
  4284. } else {
  4285. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4286. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4287. String const &name = selector->Ident.token.string;
  4288. Type *bt = base_type(operand->type);
  4289. if (operand->type->kind == Type_Named &&
  4290. operand->type->Named.type_name &&
  4291. operand->type->Named.type_name->kind == Entity_TypeName &&
  4292. operand->type->Named.type_name->TypeName.objc_metadata) {
  4293. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4294. } else if (bt->kind == Type_Struct) {
  4295. check_did_you_mean_type(name, bt->Struct.fields);
  4296. } else if (bt->kind == Type_Enum) {
  4297. check_did_you_mean_type(name, bt->Enum.fields);
  4298. }
  4299. }
  4300. }
  4301. gb_string_free(sel_str);
  4302. gb_string_free(type_str);
  4303. gb_string_free(op_str);
  4304. operand->mode = Addressing_Invalid;
  4305. operand->expr = node;
  4306. return nullptr;
  4307. }
  4308. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4309. bool success = false;
  4310. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4311. if (success) {
  4312. operand->mode = Addressing_Constant;
  4313. operand->expr = node;
  4314. operand->value = field_value;
  4315. operand->type = entity->type;
  4316. add_entity_use(c, selector, entity);
  4317. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4318. return entity;
  4319. }
  4320. gbString op_str = expr_to_string(op_expr);
  4321. gbString type_str = type_to_string_shorthand(operand->type);
  4322. gbString sel_str = expr_to_string(selector);
  4323. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4324. gb_string_free(sel_str);
  4325. gb_string_free(type_str);
  4326. gb_string_free(op_str);
  4327. operand->mode = Addressing_Invalid;
  4328. operand->expr = node;
  4329. return nullptr;
  4330. }
  4331. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4332. bool success = false;
  4333. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4334. if (success) {
  4335. operand->mode = Addressing_Constant;
  4336. operand->expr = node;
  4337. operand->value = field_value;
  4338. operand->type = entity->type;
  4339. add_entity_use(c, selector, entity);
  4340. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4341. return entity;
  4342. }
  4343. gbString op_str = expr_to_string(op_expr);
  4344. gbString type_str = type_to_string_shorthand(operand->type);
  4345. gbString sel_str = expr_to_string(selector);
  4346. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4347. gb_string_free(sel_str);
  4348. gb_string_free(type_str);
  4349. gb_string_free(op_str);
  4350. operand->mode = Addressing_Invalid;
  4351. operand->expr = node;
  4352. return nullptr;
  4353. }
  4354. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4355. gbString op_str = expr_to_string(op_expr);
  4356. gbString type_str = type_to_string_shorthand(operand->type);
  4357. gbString sel_str = expr_to_string(selector);
  4358. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4359. gb_string_free(sel_str);
  4360. gb_string_free(type_str);
  4361. gb_string_free(op_str);
  4362. operand->mode = Addressing_Invalid;
  4363. operand->expr = node;
  4364. return nullptr;
  4365. }
  4366. add_entity_use(c, selector, entity);
  4367. operand->type = entity->type;
  4368. operand->expr = node;
  4369. switch (entity->kind) {
  4370. case Entity_Constant:
  4371. operand->value = entity->Constant.value;
  4372. operand->mode = Addressing_Constant;
  4373. if (operand->value.kind == ExactValue_Procedure) {
  4374. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4375. if (proc != nullptr) {
  4376. operand->mode = Addressing_Value;
  4377. operand->type = proc->type;
  4378. }
  4379. }
  4380. break;
  4381. case Entity_Variable:
  4382. if (sel.indirect) {
  4383. operand->mode = Addressing_Variable;
  4384. } else if (operand->mode == Addressing_Context) {
  4385. // Do nothing
  4386. } else if (operand->mode == Addressing_MapIndex) {
  4387. operand->mode = Addressing_Value;
  4388. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4389. operand->mode = Addressing_SoaVariable;
  4390. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4391. operand->mode = Addressing_Value;
  4392. } else if (operand->mode == Addressing_SoaVariable) {
  4393. operand->mode = Addressing_Variable;
  4394. } else if (operand->mode != Addressing_Value) {
  4395. operand->mode = Addressing_Variable;
  4396. } else {
  4397. operand->mode = Addressing_Value;
  4398. }
  4399. break;
  4400. case Entity_TypeName:
  4401. operand->mode = Addressing_Type;
  4402. break;
  4403. case Entity_Procedure:
  4404. operand->mode = Addressing_Value;
  4405. operand->value = exact_value_procedure(node);
  4406. break;
  4407. case Entity_Builtin:
  4408. operand->mode = Addressing_Builtin;
  4409. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  4410. break;
  4411. case Entity_ProcGroup:
  4412. operand->mode = Addressing_ProcGroup;
  4413. operand->proc_group = entity;
  4414. break;
  4415. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  4416. case Entity_Nil:
  4417. operand->mode = Addressing_Value;
  4418. break;
  4419. }
  4420. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4421. return entity;
  4422. }
  4423. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  4424. ptr = base_type(ptr);
  4425. if (is_type_pointer(ptr)) {
  4426. if (is_type_rawptr(ptr)) {
  4427. return false;
  4428. }
  4429. if (elem) *elem = ptr->Pointer.elem;
  4430. return true;
  4431. }
  4432. return false;
  4433. }
  4434. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  4435. elem = core_type(elem);
  4436. if (is_type_internally_pointer_like(elem)) {
  4437. return true;
  4438. }
  4439. if (elem->kind == Type_BitSet) {
  4440. elem = bit_set_to_int(elem);
  4441. }
  4442. if (elem->kind != Type_Basic) {
  4443. return false;
  4444. }
  4445. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  4446. }
  4447. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  4448. switch (node->kind) {
  4449. case_ast_node(i, Ident, node);
  4450. String name = i->token.string;
  4451. if (nested) {
  4452. Entity *e = scope_lookup_current(s, name);
  4453. if (e != nullptr) {
  4454. if (out_scope) *out_scope = e->scope;
  4455. return true;
  4456. }
  4457. } else {
  4458. Entity *e = scope_lookup(s, name);
  4459. if (e != nullptr) {
  4460. if (out_scope) *out_scope = e->scope;
  4461. return true;
  4462. }
  4463. }
  4464. case_end;
  4465. case_ast_node(se, SelectorExpr, node);
  4466. Ast *lhs = se->expr;
  4467. Ast *rhs = se->selector;
  4468. Scope *lhs_scope = nullptr;
  4469. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  4470. return check_identifier_exists(lhs_scope, rhs, true);
  4471. }
  4472. case_end;
  4473. }
  4474. return false;
  4475. }
  4476. gb_internal isize add_dependencies_from_unpacking(CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) {
  4477. if (lhs != nullptr && c->decl != nullptr) {
  4478. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  4479. Entity *e = lhs[tuple_index + j];
  4480. if (e != nullptr) {
  4481. DeclInfo *decl = decl_info_of_entity(e);
  4482. if (decl != nullptr) {
  4483. rw_mutex_shared_lock(&decl->deps_mutex);
  4484. rw_mutex_lock(&c->decl->deps_mutex);
  4485. for (Entity *dep : decl->deps) {
  4486. ptr_set_add(&c->decl->deps, dep);
  4487. }
  4488. rw_mutex_unlock(&c->decl->deps_mutex);
  4489. rw_mutex_shared_unlock(&decl->deps_mutex);
  4490. }
  4491. }
  4492. }
  4493. }
  4494. return tuple_count;
  4495. }
  4496. gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) {
  4497. if (o.type && is_type_no_copy(o.type)) {
  4498. Ast *expr = unparen_expr(o.expr);
  4499. if (expr && o.mode != Addressing_Constant) {
  4500. if (expr->kind == Ast_CallExpr) {
  4501. // Okay
  4502. } else {
  4503. error(o.expr, "Invalid use of #no_copy value in %.*s", LIT(context));
  4504. return true;
  4505. }
  4506. }
  4507. }
  4508. return false;
  4509. }
  4510. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  4511. bool optional_ok = false;
  4512. isize tuple_index = 0;
  4513. for (Ast *rhs_expr : rhs) {
  4514. CheckerContext c_ = *ctx;
  4515. CheckerContext *c = &c_;
  4516. Operand o = {};
  4517. Type *type_hint = nullptr;
  4518. if (tuple_index < lhs.count) {
  4519. type_hint = lhs[tuple_index].type;
  4520. }
  4521. check_expr_base(c, &o, rhs_expr, type_hint);
  4522. if (o.mode == Addressing_NoValue) {
  4523. error_operand_no_value(&o);
  4524. o.mode = Addressing_Invalid;
  4525. }
  4526. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4527. if (lhs.count == 2 && rhs.count == 1 &&
  4528. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4529. Ast *expr = unparen_expr(o.expr);
  4530. Operand val0 = o;
  4531. Operand val1 = o;
  4532. val0.mode = Addressing_Value;
  4533. val1.mode = Addressing_Value;
  4534. val1.type = t_untyped_bool;
  4535. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4536. if (expr->kind == Ast_TypeAssertion &&
  4537. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4538. // NOTE(bill): Used only for optimizations in the backend
  4539. if (is_blank_ident(lhs[0].expr)) {
  4540. expr->TypeAssertion.ignores[0] = true;
  4541. }
  4542. if (is_blank_ident(lhs[1].expr)) {
  4543. expr->TypeAssertion.ignores[1] = true;
  4544. }
  4545. }
  4546. array_add(operands, val0);
  4547. array_add(operands, val1);
  4548. optional_ok = true;
  4549. tuple_index += 2;
  4550. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  4551. Type *tuple = o.type;
  4552. GB_ASSERT(tuple->Tuple.variables.count == 2);
  4553. Ast *expr = unparen_expr(o.expr);
  4554. if (expr->kind == Ast_CallExpr) {
  4555. expr->CallExpr.optional_ok_one = true;
  4556. }
  4557. Operand val = o;
  4558. val.type = tuple->Tuple.variables[0]->type;
  4559. val.mode = Addressing_Value;
  4560. array_add(operands, val);
  4561. tuple_index += tuple->Tuple.variables.count;
  4562. } else {
  4563. array_add(operands, o);
  4564. tuple_index += 1;
  4565. }
  4566. } else {
  4567. TypeTuple *tuple = &o.type->Tuple;
  4568. for (Entity *e : tuple->variables) {
  4569. o.type = e->type;
  4570. array_add(operands, o);
  4571. check_no_copy_assignment(o, str_lit("assignment"));
  4572. }
  4573. tuple_index += tuple->variables.count;
  4574. }
  4575. }
  4576. return optional_ok;
  4577. }
  4578. typedef u32 UnpackFlags;
  4579. enum UnpackFlag : u32 {
  4580. UnpackFlag_None = 0,
  4581. UnpackFlag_AllowOk = 1<<0,
  4582. UnpackFlag_IsVariadic = 1<<1,
  4583. UnpackFlag_AllowUndef = 1<<2,
  4584. };
  4585. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags) {
  4586. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  4587. bool is_variadic = (flags & UnpackFlag_IsVariadic) != 0;
  4588. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  4589. bool optional_ok = false;
  4590. isize tuple_index = 0;
  4591. for (Ast *rhs : rhs_arguments) {
  4592. if (rhs->kind == Ast_FieldValue) {
  4593. error(rhs, "Invalid use of 'field = value'");
  4594. rhs = rhs->FieldValue.value;
  4595. }
  4596. CheckerContext c_ = *ctx;
  4597. CheckerContext *c = &c_;
  4598. Operand o = {};
  4599. Type *type_hint = nullptr;
  4600. if (lhs != nullptr && tuple_index < lhs_count) {
  4601. // NOTE(bill): override DeclInfo for dependency
  4602. Entity *e = lhs[tuple_index];
  4603. if (e != nullptr) {
  4604. type_hint = e->type;
  4605. if (e->flags & EntityFlag_Ellipsis) {
  4606. GB_ASSERT(is_type_slice(e->type));
  4607. GB_ASSERT(e->type->kind == Type_Slice);
  4608. type_hint = e->type->Slice.elem;
  4609. }
  4610. }
  4611. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  4612. // NOTE(bill): override DeclInfo for dependency
  4613. Entity *e = lhs[lhs_count-1];
  4614. if (e != nullptr) {
  4615. type_hint = e->type;
  4616. if (e->flags & EntityFlag_Ellipsis) {
  4617. GB_ASSERT(is_type_slice(e->type));
  4618. GB_ASSERT(e->type->kind == Type_Slice);
  4619. type_hint = e->type->Slice.elem;
  4620. }
  4621. }
  4622. }
  4623. Ast *rhs_expr = unparen_expr(rhs);
  4624. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  4625. // NOTE(bill): Just handle this very specific logic here
  4626. o.type = t_untyped_uninit;
  4627. o.mode = Addressing_Value;
  4628. o.expr = rhs;
  4629. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  4630. } else {
  4631. check_expr_base(c, &o, rhs, type_hint);
  4632. }
  4633. if (o.mode == Addressing_NoValue) {
  4634. error_operand_no_value(&o);
  4635. o.mode = Addressing_Invalid;
  4636. }
  4637. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4638. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  4639. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4640. Ast *expr = unparen_expr(o.expr);
  4641. Operand val0 = o;
  4642. Operand val1 = o;
  4643. val0.mode = Addressing_Value;
  4644. val1.mode = Addressing_Value;
  4645. val1.type = t_untyped_bool;
  4646. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4647. if (expr->kind == Ast_TypeAssertion &&
  4648. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4649. // NOTE(bill): Used only for optimizations in the backend
  4650. if (is_blank_ident(lhs[0]->token)) {
  4651. expr->TypeAssertion.ignores[0] = true;
  4652. }
  4653. if (is_blank_ident(lhs[1]->token)) {
  4654. expr->TypeAssertion.ignores[1] = true;
  4655. }
  4656. }
  4657. array_add(operands, val0);
  4658. array_add(operands, val1);
  4659. optional_ok = true;
  4660. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  4661. } else {
  4662. array_add(operands, o);
  4663. tuple_index += 1;
  4664. }
  4665. } else {
  4666. TypeTuple *tuple = &o.type->Tuple;
  4667. for (Entity *e : tuple->variables) {
  4668. o.type = e->type;
  4669. array_add(operands, o);
  4670. }
  4671. isize count = tuple->variables.count;
  4672. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  4673. }
  4674. }
  4675. return optional_ok;
  4676. }
  4677. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  4678. GB_ASSERT(pt != nullptr);
  4679. GB_ASSERT(pt->kind == Type_Proc);
  4680. isize param_count = 0;
  4681. isize param_count_excluding_defaults = 0;
  4682. bool variadic = pt->Proc.variadic;
  4683. TypeTuple *param_tuple = nullptr;
  4684. if (pt->Proc.params != nullptr) {
  4685. param_tuple = &pt->Proc.params->Tuple;
  4686. param_count = param_tuple->variables.count;
  4687. if (variadic) {
  4688. for (isize i = param_count-1; i >= 0; i--) {
  4689. Entity *e = param_tuple->variables[i];
  4690. if (e->kind == Entity_TypeName) {
  4691. break;
  4692. }
  4693. if (e->kind == Entity_Variable) {
  4694. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4695. param_count--;
  4696. continue;
  4697. }
  4698. }
  4699. break;
  4700. }
  4701. param_count--;
  4702. }
  4703. }
  4704. param_count_excluding_defaults = param_count;
  4705. if (param_tuple != nullptr) {
  4706. for (isize i = param_count-1; i >= 0; i--) {
  4707. Entity *e = param_tuple->variables[i];
  4708. if (e->kind == Entity_TypeName) {
  4709. break;
  4710. }
  4711. if (e->kind == Entity_Variable) {
  4712. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4713. param_count_excluding_defaults--;
  4714. continue;
  4715. }
  4716. }
  4717. break;
  4718. }
  4719. }
  4720. if (param_count_) *param_count_ = param_count;
  4721. return param_count_excluding_defaults;
  4722. }
  4723. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  4724. isize param_count = pt->param_count;
  4725. for (isize i = 0; i < param_count; i++) {
  4726. Entity *e = pt->params->Tuple.variables[i];
  4727. String name = e->token.string;
  4728. if (is_blank_ident(name)) {
  4729. continue;
  4730. }
  4731. if (name == parameter_name) {
  4732. return i;
  4733. }
  4734. }
  4735. return -1;
  4736. }
  4737. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  4738. type = base_type(type);
  4739. GB_ASSERT(type->kind == Type_Proc);
  4740. return lookup_procedure_parameter(&type->Proc, parameter_name);
  4741. }
  4742. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  4743. Entity *entity, Type *proc_type,
  4744. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  4745. CallArgumentErrorMode show_error_mode,
  4746. CallArgumentData *data) {
  4747. TEMPORARY_ALLOCATOR_GUARD();
  4748. CallArgumentError err = CallArgumentError_None;
  4749. ast_node(ce, CallExpr, call);
  4750. GB_ASSERT(is_type_proc(proc_type));
  4751. proc_type = base_type(proc_type);
  4752. TypeProc *pt = &proc_type->Proc;
  4753. isize param_count = 0;
  4754. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  4755. bool variadic = pt->variadic;
  4756. bool vari_expand = (ce->ellipsis.pos.line != 0);
  4757. i64 score = 0;
  4758. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  4759. Type *final_proc_type = proc_type;
  4760. Entity *gen_entity = nullptr;
  4761. if (vari_expand && !variadic) {
  4762. if (show_error) {
  4763. error(ce->ellipsis,
  4764. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  4765. LIT(ce->proc->Ident.token.string));
  4766. }
  4767. err = CallArgumentError_NonVariadicExpand;
  4768. } else if (vari_expand && pt->c_vararg) {
  4769. if (show_error) {
  4770. error(ce->ellipsis,
  4771. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  4772. LIT(ce->proc->Ident.token.string));
  4773. }
  4774. err = CallArgumentError_NonVariadicExpand;
  4775. }
  4776. GB_ASSERT(ce->split_args);
  4777. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  4778. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  4779. defer ({
  4780. for (Operand const &o : ordered_operands) {
  4781. if (o.expr != nullptr) {
  4782. call->viral_state_flags |= o.expr->viral_state_flags;
  4783. }
  4784. }
  4785. });
  4786. isize positional_operand_count = positional_operands.count;
  4787. if (variadic) {
  4788. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  4789. } else if (positional_operand_count > pt->param_count) {
  4790. err = CallArgumentError_TooManyArguments;
  4791. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  4792. if (show_error) {
  4793. gbString proc_str = expr_to_string(ce->proc);
  4794. defer (gb_string_free(proc_str));
  4795. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  4796. }
  4797. return err;
  4798. }
  4799. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  4800. for (isize i = 0; i < positional_operand_count; i++) {
  4801. ordered_operands[i] = positional_operands[i];
  4802. visited[i] = true;
  4803. }
  4804. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  4805. if (named_operands.count != 0) {
  4806. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  4807. for_array(i, ce->split_args->named) {
  4808. Ast *arg = ce->split_args->named[i];
  4809. Operand operand = named_operands[i];
  4810. ast_node(fv, FieldValue, arg);
  4811. if (fv->field->kind != Ast_Ident) {
  4812. if (show_error) {
  4813. gbString expr_str = expr_to_string(fv->field);
  4814. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  4815. gb_string_free(expr_str);
  4816. }
  4817. err = CallArgumentError_InvalidFieldValue;
  4818. continue;
  4819. }
  4820. String name = fv->field->Ident.token.string;
  4821. isize param_index = lookup_procedure_parameter(pt, name);
  4822. if (param_index < 0) {
  4823. if (show_error) {
  4824. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  4825. }
  4826. err = CallArgumentError_ParameterNotFound;
  4827. continue;
  4828. }
  4829. if (visited[param_index]) {
  4830. if (show_error) {
  4831. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  4832. }
  4833. err = CallArgumentError_DuplicateParameter;
  4834. continue;
  4835. }
  4836. visited[param_index] = true;
  4837. ordered_operands[param_index] = operand;
  4838. }
  4839. }
  4840. isize dummy_argument_count = 0;
  4841. bool actually_variadic = false;
  4842. if (variadic) {
  4843. if (visited[pt->variadic_index] &&
  4844. positional_operand_count < positional_operands.count) {
  4845. if (show_error) {
  4846. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  4847. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  4848. }
  4849. err = CallArgumentError_DuplicateParameter;
  4850. } else if (!visited[pt->variadic_index]) {
  4851. visited[pt->variadic_index] = true;
  4852. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  4853. if (vari_expand) {
  4854. GB_ASSERT(variadic_operands.count != 0);
  4855. *variadic_operand = variadic_operands[0];
  4856. variadic_operand->type = default_type(variadic_operand->type);
  4857. actually_variadic = true;
  4858. } else {
  4859. AstFile *f = call->file();
  4860. // HACK(bill): this is an awful hack
  4861. Operand o = {};
  4862. o.mode = Addressing_Value;
  4863. o.expr = ast_ident(f, make_token_ident("nil"));
  4864. o.expr->Ident.token.pos = ast_token(call).pos;
  4865. if (variadic_operands.count != 0) {
  4866. actually_variadic = true;
  4867. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  4868. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  4869. if (is_type_polymorphic(vt->type)) {
  4870. o.type = alloc_type_slice(default_type(variadic_operands[0].type));
  4871. } else {
  4872. o.type = vt->type;
  4873. }
  4874. } else {
  4875. dummy_argument_count += 1;
  4876. o.type = t_untyped_nil;
  4877. }
  4878. *variadic_operand = o;
  4879. }
  4880. }
  4881. }
  4882. for (Operand const &o : ordered_operands) {
  4883. if (o.mode != Addressing_Invalid) {
  4884. check_no_copy_assignment(o, str_lit("procedure call expression"));
  4885. }
  4886. }
  4887. for (isize i = 0; i < pt->param_count; i++) {
  4888. if (!visited[i]) {
  4889. Entity *e = pt->params->Tuple.variables[i];
  4890. if (is_blank_ident(e->token)) {
  4891. continue;
  4892. }
  4893. if (e->kind == Entity_Variable) {
  4894. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4895. ordered_operands[i].mode = Addressing_Value;
  4896. ordered_operands[i].type = e->type;
  4897. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  4898. dummy_argument_count += 1;
  4899. score += assign_score_function(1);
  4900. continue;
  4901. }
  4902. }
  4903. if (show_error) {
  4904. if (e->kind == Entity_TypeName) {
  4905. error(call, "Type parameter '%.*s' is missing in procedure call",
  4906. LIT(e->token.string));
  4907. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  4908. // Ignore
  4909. } else {
  4910. gbString str = type_to_string(e->type);
  4911. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  4912. LIT(e->token.string), str);
  4913. gb_string_free(str);
  4914. }
  4915. }
  4916. err = CallArgumentError_ParameterMissing;
  4917. }
  4918. }
  4919. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  4920. i64 s = 0;
  4921. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic)) {
  4922. bool ok = false;
  4923. if (e && e->flags & EntityFlag_AnyInt) {
  4924. if (is_type_integer(param_type)) {
  4925. ok = check_is_castable_to(c, o, param_type);
  4926. }
  4927. }
  4928. if (ok) {
  4929. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  4930. } else {
  4931. if (show_error) {
  4932. check_assignment(c, o, param_type, str_lit("procedure argument"));
  4933. }
  4934. err = CallArgumentError_WrongTypes;
  4935. }
  4936. } else if (show_error) {
  4937. check_assignment(c, o, param_type, str_lit("procedure argument"));
  4938. }
  4939. if (e && e->flags & EntityFlag_ConstInput) {
  4940. if (o->mode != Addressing_Constant) {
  4941. if (show_error) {
  4942. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  4943. }
  4944. err = CallArgumentError_NoneConstantParameter;
  4945. }
  4946. }
  4947. if (!err && is_type_any(param_type)) {
  4948. add_type_info_type(c, o->type);
  4949. }
  4950. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  4951. add_type_info_type(c, o->type);
  4952. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  4953. } else if (show_error && is_type_untyped(o->type)) {
  4954. update_untyped_expr_type(c, o->expr, param_type, true);
  4955. }
  4956. return s;
  4957. };
  4958. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  4959. err = CallArgumentError_None;
  4960. if (variadic) {
  4961. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  4962. Type *t = pt->params->Tuple.variables[0]->type;
  4963. if (is_type_polymorphic(t)) {
  4964. if (show_error) {
  4965. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  4966. }
  4967. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  4968. }
  4969. }
  4970. } else {
  4971. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  4972. PolyProcData poly_proc_data = {};
  4973. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  4974. gen_entity = poly_proc_data.gen_entity;
  4975. Type *gept = base_type(gen_entity->type);
  4976. GB_ASSERT(is_type_proc(gept));
  4977. final_proc_type = gen_entity->type;
  4978. pt = &gept->Proc;
  4979. } else {
  4980. err = CallArgumentError_WrongTypes;
  4981. }
  4982. }
  4983. for (isize i = 0; i < pt->param_count; i++) {
  4984. Operand *o = &ordered_operands[i];
  4985. if (o->mode == Addressing_Invalid) {
  4986. continue;
  4987. }
  4988. Entity *e = pt->params->Tuple.variables[i];
  4989. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  4990. if (e->kind == Entity_TypeName) {
  4991. GB_ASSERT(pt->is_polymorphic);
  4992. if (o->mode != Addressing_Type) {
  4993. if (show_error) {
  4994. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  4995. }
  4996. err = CallArgumentError_WrongTypes;
  4997. }
  4998. if (are_types_identical(e->type, o->type)) {
  4999. score += assign_score_function(1);
  5000. } else {
  5001. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5002. }
  5003. continue;
  5004. }
  5005. if (param_is_variadic) {
  5006. continue;
  5007. }
  5008. score += eval_param_and_score(c, o, e->type, err, param_is_variadic, e, show_error);
  5009. }
  5010. }
  5011. if (variadic) {
  5012. Type *slice = pt->params->Tuple.variables[pt->variadic_index]->type;
  5013. GB_ASSERT(is_type_slice(slice));
  5014. Type *elem = base_type(slice)->Slice.elem;
  5015. Type *t = elem;
  5016. if (is_type_polymorphic(t)) {
  5017. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5018. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5019. }
  5020. for_array(operand_index, variadic_operands) {
  5021. Operand *o = &variadic_operands[operand_index];
  5022. if (vari_expand) {
  5023. t = slice;
  5024. if (operand_index > 0) {
  5025. if (show_error) {
  5026. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5027. }
  5028. if (data) {
  5029. data->score = score;
  5030. data->result_type = final_proc_type->Proc.results;
  5031. data->gen_entity = gen_entity;
  5032. }
  5033. return CallArgumentError_MultipleVariadicExpand;
  5034. }
  5035. }
  5036. score += eval_param_and_score(c, o, t, err, true, nullptr, show_error);
  5037. }
  5038. }
  5039. if (data) {
  5040. data->score = score;
  5041. data->result_type = final_proc_type->Proc.results;
  5042. data->gen_entity = gen_entity;
  5043. Ast *proc_lit = nullptr;
  5044. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5045. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5046. if (vp && vp->kind == Ast_ProcLit) {
  5047. proc_lit = vp;
  5048. }
  5049. }
  5050. if (proc_lit == nullptr) {
  5051. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5052. }
  5053. }
  5054. return err;
  5055. }
  5056. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5057. GB_ASSERT(ce != nullptr);
  5058. if (ce->args.count == 0) {
  5059. return false;
  5060. }
  5061. return ce->args[0]->kind == Ast_FieldValue;
  5062. }
  5063. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  5064. Entity **lhs = nullptr;
  5065. isize lhs_count = -1;
  5066. if (proc_type == nullptr) {
  5067. return nullptr;
  5068. }
  5069. GB_ASSERT(is_type_proc(proc_type));
  5070. TypeProc *pt = &base_type(proc_type)->Proc;
  5071. *is_variadic = pt->variadic;
  5072. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5073. if (pt->params != nullptr) {
  5074. lhs = pt->params->Tuple.variables.data;
  5075. lhs_count = pt->params->Tuple.variables.count;
  5076. }
  5077. } else {
  5078. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5079. if (pt->params == nullptr) {
  5080. lhs_count = 0;
  5081. } else {
  5082. lhs_count = pt->params->Tuple.variables.count;
  5083. }
  5084. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5085. for (isize i = 0; i < lhs_count; i++) {
  5086. Entity *e = pt->params->Tuple.variables[i];
  5087. if (!is_type_polymorphic(e->type)) {
  5088. lhs[i] = e;
  5089. }
  5090. }
  5091. }
  5092. if (lhs_count_) *lhs_count_ = lhs_count;
  5093. return lhs;
  5094. }
  5095. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5096. if (clauses != nullptr) {
  5097. for (Ast *clause : *clauses) {
  5098. Operand o = {};
  5099. check_expr(ctx, &o, clause);
  5100. if (o.mode != Addressing_Constant) {
  5101. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5102. if (print_err && call_expr) error(call_expr, "at caller location");
  5103. return false;
  5104. } else if (o.value.kind != ExactValue_Bool) {
  5105. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5106. if (print_err && call_expr) error(call_expr, "at caller location");
  5107. return false;
  5108. } else if (!o.value.value_bool) {
  5109. if (print_err) {
  5110. ERROR_BLOCK();
  5111. gbString str = expr_to_string(clause);
  5112. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5113. gb_string_free(str);
  5114. if (scope != nullptr) {
  5115. isize print_count = 0;
  5116. for (auto const &entry : scope->elements) {
  5117. Entity *e = entry.value;
  5118. switch (e->kind) {
  5119. case Entity_TypeName: {
  5120. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5121. gbString str = type_to_string(e->type);
  5122. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5123. gb_string_free(str);
  5124. print_count += 1;
  5125. break;
  5126. }
  5127. case Entity_Constant: {
  5128. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5129. gbString str = exact_value_to_string(e->Constant.value);
  5130. if (is_type_untyped(e->type)) {
  5131. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5132. } else {
  5133. gbString t = type_to_string(e->type);
  5134. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5135. gb_string_free(t);
  5136. }
  5137. gb_string_free(str);
  5138. print_count += 1;
  5139. break;
  5140. }
  5141. }
  5142. }
  5143. }
  5144. if (call_expr) error(call_expr, "at caller location");
  5145. }
  5146. return false;
  5147. }
  5148. }
  5149. }
  5150. return true;
  5151. }
  5152. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5153. bool success = true;
  5154. type = base_type(type);
  5155. if (named_args.count > 0) {
  5156. TypeProc *pt = nullptr;
  5157. if (is_type_proc(type)) {
  5158. pt = &type->Proc;
  5159. }
  5160. for_array(i, named_args) {
  5161. Ast *arg = named_args[i];
  5162. if (arg->kind != Ast_FieldValue) {
  5163. if (show_error) {
  5164. error(arg, "Expected a 'field = value'");
  5165. }
  5166. return false;
  5167. }
  5168. ast_node(fv, FieldValue, arg);
  5169. if (fv->field->kind != Ast_Ident) {
  5170. if (show_error) {
  5171. gbString expr_str = expr_to_string(fv->field);
  5172. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5173. gb_string_free(expr_str);
  5174. }
  5175. success = false;
  5176. continue;
  5177. }
  5178. String key = fv->field->Ident.token.string;
  5179. Ast *value = fv->value;
  5180. Type *type_hint = nullptr;
  5181. if (pt) {
  5182. isize param_index = lookup_procedure_parameter(pt, key);
  5183. if (param_index < 0) {
  5184. if (show_error) {
  5185. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5186. }
  5187. success = false;
  5188. continue;
  5189. }
  5190. Entity *e = pt->params->Tuple.variables[param_index];
  5191. if (!is_type_polymorphic(e->type)) {
  5192. type_hint = e->type;
  5193. }
  5194. }
  5195. Operand o = {};
  5196. check_expr_with_type_hint(c, &o, value, type_hint);
  5197. if (o.mode == Addressing_Invalid) {
  5198. success = false;
  5199. }
  5200. array_add(named_operands, o);
  5201. }
  5202. }
  5203. return success;
  5204. }
  5205. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5206. Entity *e, Type *proc_type,
  5207. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5208. CallArgumentErrorMode show_error_mode,
  5209. CallArgumentData *data) {
  5210. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5211. Ast *ident = operand->expr;
  5212. while (ident->kind == Ast_SelectorExpr) {
  5213. Ast *s = ident->SelectorExpr.selector;
  5214. ident = s;
  5215. }
  5216. if (e == nullptr) {
  5217. e = entity_of_node(ident);
  5218. if (e != nullptr) {
  5219. proc_type = e->type;
  5220. }
  5221. }
  5222. GB_ASSERT(proc_type != nullptr);
  5223. proc_type = base_type(proc_type);
  5224. GB_ASSERT(proc_type->kind == Type_Proc);
  5225. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5226. if (return_on_failure && err != CallArgumentError_None) {
  5227. return false;
  5228. }
  5229. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5230. if (!return_on_failure && entity_to_use != nullptr) {
  5231. add_entity_use(c, ident, entity_to_use);
  5232. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5233. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5234. }
  5235. if (data->gen_entity != nullptr) {
  5236. Entity *e = data->gen_entity;
  5237. DeclInfo *decl = data->gen_entity->decl_info;
  5238. CheckerContext ctx = *c;
  5239. ctx.scope = decl->scope;
  5240. ctx.decl = decl;
  5241. ctx.proc_name = e->token.string;
  5242. ctx.curr_proc_decl = decl;
  5243. ctx.curr_proc_sig = e->type;
  5244. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5245. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5246. if (return_on_failure) {
  5247. if (!ok) {
  5248. return false;
  5249. }
  5250. } else {
  5251. decl->where_clauses_evaluated = true;
  5252. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5253. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5254. }
  5255. if (is_type_proc(data->gen_entity->type)) {
  5256. Type *t = base_type(entity_to_use->type);
  5257. data->result_type = t->Proc.results;
  5258. }
  5259. }
  5260. }
  5261. return true;
  5262. }
  5263. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5264. ast_node(ce, CallExpr, call);
  5265. GB_ASSERT(ce->split_args != nullptr);
  5266. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5267. Slice<Ast *> const &named_args = ce->split_args->named;
  5268. CallArgumentData data = {};
  5269. data.result_type = t_invalid;
  5270. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5271. auto procs = proc_group_entities_cloned(c, *operand);
  5272. if (procs.count > 1) {
  5273. isize max_arg_count = positional_args.count + named_args.count;
  5274. for (Ast *arg : positional_args) {
  5275. // NOTE(bill): The only thing that may have multiple values
  5276. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5277. arg = strip_or_return_expr(arg);
  5278. if (arg && arg->kind == Ast_CallExpr) {
  5279. max_arg_count = ISIZE_MAX;
  5280. break;
  5281. }
  5282. }
  5283. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5284. // NOTE(bill): The only thing that may have multiple values
  5285. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5286. if (arg->kind == Ast_FieldValue) {
  5287. arg = strip_or_return_expr(arg->FieldValue.value);
  5288. if (arg && arg->kind == Ast_CallExpr) {
  5289. max_arg_count = ISIZE_MAX;
  5290. break;
  5291. }
  5292. }
  5293. }
  5294. // ignore named arguments first
  5295. for (Ast *arg : named_args) {
  5296. if (arg->kind != Ast_FieldValue) {
  5297. continue;
  5298. }
  5299. ast_node(fv, FieldValue, arg);
  5300. if (fv->field->kind != Ast_Ident) {
  5301. continue;
  5302. }
  5303. String key = fv->field->Ident.token.string;
  5304. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5305. Type *t = procs[proc_index]->type;
  5306. if (is_type_proc(t)) {
  5307. isize param_index = lookup_procedure_parameter(t, key);
  5308. if (param_index < 0) {
  5309. array_unordered_remove(&procs, proc_index);
  5310. }
  5311. }
  5312. }
  5313. }
  5314. if (procs.count == 0) {
  5315. // if any of the named arguments are wrong, the `procs` will be empty
  5316. // just start from scratch
  5317. array_free(&procs);
  5318. procs = proc_group_entities_cloned(c, *operand);
  5319. }
  5320. // filter by positional argument length
  5321. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5322. Entity *proc = procs[proc_index];
  5323. Type *pt = base_type(proc->type);
  5324. if (!(pt != nullptr && is_type_proc(pt))) {
  5325. proc_index++;
  5326. continue;
  5327. }
  5328. isize param_count = 0;
  5329. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5330. if (param_count_excluding_defaults > max_arg_count) {
  5331. array_unordered_remove(&procs, proc_index);
  5332. continue;
  5333. }
  5334. proc_index++;
  5335. }
  5336. }
  5337. Entity **lhs = nullptr;
  5338. isize lhs_count = -1;
  5339. bool is_variadic = false;
  5340. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5341. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5342. defer (array_free(&positional_operands));
  5343. defer (array_free(&named_operands));
  5344. if (procs.count == 1) {
  5345. Entity *e = procs[0];
  5346. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  5347. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5348. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5349. check_call_arguments_single(c, call, operand,
  5350. e, e->type,
  5351. positional_operands, named_operands,
  5352. CallArgumentErrorMode::ShowErrors,
  5353. &data);
  5354. }
  5355. return data;
  5356. }
  5357. {
  5358. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  5359. // where the same positional parameter has the same type value (and ellipsis)
  5360. bool proc_arg_count_all_equal = true;
  5361. isize proc_arg_count = -1;
  5362. for (Entity *p : procs) {
  5363. Type *pt = base_type(p->type);
  5364. if (pt != nullptr && is_type_proc(pt)) {
  5365. if (proc_arg_count < 0) {
  5366. proc_arg_count = pt->Proc.param_count;
  5367. } else {
  5368. if (proc_arg_count != pt->Proc.param_count) {
  5369. proc_arg_count_all_equal = false;
  5370. break;
  5371. }
  5372. }
  5373. }
  5374. }
  5375. if (proc_arg_count >= 0 && proc_arg_count_all_equal) {
  5376. lhs_count = proc_arg_count;
  5377. if (lhs_count > 0) {
  5378. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  5379. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  5380. Entity *e = nullptr;
  5381. for (Entity *p : procs) {
  5382. Type *pt = base_type(p->type);
  5383. if (!(pt != nullptr && is_type_proc(pt))) {
  5384. continue;
  5385. }
  5386. if (e == nullptr) {
  5387. e = pt->Proc.params->Tuple.variables[param_index];
  5388. } else {
  5389. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  5390. if (e == f) {
  5391. continue;
  5392. }
  5393. if (are_types_identical(e->type, f->type)) {
  5394. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  5395. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  5396. if (ee == fe) {
  5397. continue;
  5398. }
  5399. }
  5400. // NOTE(bill): Entities are not close enough to be used
  5401. e = nullptr;
  5402. break;
  5403. }
  5404. }
  5405. lhs[param_index] = e;
  5406. }
  5407. }
  5408. }
  5409. }
  5410. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5411. for_array(i, named_args) {
  5412. Ast *arg = named_args[i];
  5413. if (arg->kind != Ast_FieldValue) {
  5414. error(arg, "Expected a 'field = value'");
  5415. return data;
  5416. }
  5417. ast_node(fv, FieldValue, arg);
  5418. if (fv->field->kind != Ast_Ident) {
  5419. gbString expr_str = expr_to_string(fv->field);
  5420. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5421. gb_string_free(expr_str);
  5422. return data;
  5423. }
  5424. String key = fv->field->Ident.token.string;
  5425. Ast *value = fv->value;
  5426. Type *type_hint = nullptr;
  5427. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  5428. Entity *e = lhs[lhs_idx];
  5429. if (e != nullptr && e->token.string == key &&
  5430. !is_type_polymorphic(e->type)) {
  5431. type_hint = e->type;
  5432. break;
  5433. }
  5434. }
  5435. Operand o = {};
  5436. check_expr_with_type_hint(c, &o, value, type_hint);
  5437. array_add(&named_operands, o);
  5438. }
  5439. gb_free(heap_allocator(), lhs);
  5440. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  5441. defer (array_free(&valids));
  5442. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  5443. defer (array_free(&proc_entities));
  5444. for (Entity *proc : procs) {
  5445. array_add(&proc_entities, proc);
  5446. }
  5447. gbString expr_name = expr_to_string(operand->expr);
  5448. defer (gb_string_free(expr_name));
  5449. for_array(i, procs) {
  5450. Entity *p = procs[i];
  5451. Type *pt = base_type(p->type);
  5452. if (pt != nullptr && is_type_proc(pt)) {
  5453. CallArgumentData data = {};
  5454. CheckerContext ctx = *c;
  5455. ctx.no_polymorphic_errors = true;
  5456. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  5457. ctx.hide_polymorphic_errors = true;
  5458. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  5459. p, pt,
  5460. positional_operands, named_operands,
  5461. CallArgumentErrorMode::NoErrors,
  5462. &data);
  5463. if (!is_a_candidate) {
  5464. continue;
  5465. }
  5466. isize index = i;
  5467. if (data.gen_entity != nullptr) {
  5468. array_add(&proc_entities, data.gen_entity);
  5469. index = proc_entities.count-1;
  5470. }
  5471. ValidIndexAndScore item = {};
  5472. item.index = index;
  5473. item.score = data.score;
  5474. array_add(&valids, item);
  5475. }
  5476. }
  5477. if (valids.count > 1) {
  5478. gb_sort_array(valids.data, valids.count, valid_index_and_score_cmp);
  5479. i64 best_score = valids[0].score;
  5480. Entity *best_entity = proc_entities[valids[0].index];
  5481. GB_ASSERT(best_entity != nullptr);
  5482. for (isize i = 1; i < valids.count; i++) {
  5483. if (best_score > valids[i].score) {
  5484. valids.count = i;
  5485. break;
  5486. }
  5487. if (best_entity == proc_entities[valids[i].index]) {
  5488. valids.count = i;
  5489. break;
  5490. }
  5491. }
  5492. }
  5493. auto print_argument_types = [&]() {
  5494. error_line("\tGiven argument types: (");
  5495. isize i = 0;
  5496. for (Operand const &o : positional_operands) {
  5497. if (i++ > 0) error_line(", ");
  5498. gbString type = type_to_string(o.type);
  5499. defer (gb_string_free(type));
  5500. error_line("%s", type);
  5501. }
  5502. for (Operand const &o : named_operands) {
  5503. if (i++ > 0) error_line(", ");
  5504. gbString type = type_to_string(o.type);
  5505. defer (gb_string_free(type));
  5506. if (i < ce->split_args->named.count) {
  5507. Ast *named_field = ce->split_args->named[i];
  5508. ast_node(fv, FieldValue, named_field);
  5509. gbString field = expr_to_string(fv->field);
  5510. defer (gb_string_free(field));
  5511. error_line("%s = %s", field, type);
  5512. } else {
  5513. error_line("%s", type);
  5514. }
  5515. }
  5516. error_line(")\n");
  5517. };
  5518. if (valids.count == 0) {
  5519. begin_error_block();
  5520. defer (end_error_block());
  5521. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  5522. if (positional_operands.count == 0 && named_operands.count == 0) {
  5523. error_line("\tNo given arguments\n");
  5524. } else {
  5525. print_argument_types();
  5526. }
  5527. if (procs.count > 0) {
  5528. error_line("Did you mean to use one of the following:\n");
  5529. }
  5530. for (Entity *proc : procs) {
  5531. TokenPos pos = proc->token.pos;
  5532. Type *t = base_type(proc->type);
  5533. if (t == t_invalid) continue;
  5534. GB_ASSERT(t->kind == Type_Proc);
  5535. gbString pt;
  5536. defer (gb_string_free(pt));
  5537. if (t->Proc.node != nullptr) {
  5538. pt = expr_to_string(t->Proc.node);
  5539. } else {
  5540. pt = type_to_string(t);
  5541. }
  5542. String prefix = {};
  5543. String prefix_sep = {};
  5544. if (proc->pkg) {
  5545. prefix = proc->pkg->name;
  5546. prefix_sep = str_lit(".");
  5547. }
  5548. String name = proc->token.string;
  5549. char const *sep = "::";
  5550. if (proc->kind == Entity_Variable) {
  5551. sep = ":=";
  5552. }
  5553. error_line("\t%.*s%.*s%.*s %s %s at %s\n", LIT(prefix), LIT(prefix_sep), LIT(name), sep, pt, token_pos_to_string(pos));
  5554. }
  5555. if (procs.count > 0) {
  5556. error_line("\n");
  5557. }
  5558. data.result_type = t_invalid;
  5559. } else if (valids.count > 1) {
  5560. begin_error_block();
  5561. defer (end_error_block());
  5562. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  5563. print_argument_types();
  5564. for (isize i = 0; i < valids.count; i++) {
  5565. Entity *proc = proc_entities[valids[i].index];
  5566. GB_ASSERT(proc != nullptr);
  5567. TokenPos pos = proc->token.pos;
  5568. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  5569. gbString pt = nullptr;
  5570. defer (gb_string_free(pt));
  5571. if (t->Proc.node != nullptr) {
  5572. pt = expr_to_string(t->Proc.node);
  5573. } else {
  5574. pt = type_to_string(t);
  5575. }
  5576. String name = proc->token.string;
  5577. char const *sep = "::";
  5578. if (proc->kind == Entity_Variable) {
  5579. sep = ":=";
  5580. }
  5581. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  5582. if (proc->decl_info->proc_lit != nullptr) {
  5583. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  5584. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  5585. if (pl->where_token.kind != Token_Invalid) {
  5586. error_line("\n\t\twhere ");
  5587. for_array(j, pl->where_clauses) {
  5588. Ast *clause = pl->where_clauses[j];
  5589. if (j != 0) {
  5590. error_line("\t\t ");
  5591. }
  5592. gbString str = expr_to_string(clause);
  5593. error_line("%s", str);
  5594. gb_string_free(str);
  5595. if (j != pl->where_clauses.count-1) {
  5596. error_line(",");
  5597. }
  5598. }
  5599. error_line("\n\t");
  5600. }
  5601. }
  5602. error_line("at %s\n", token_pos_to_string(pos));
  5603. }
  5604. data.result_type = t_invalid;
  5605. } else {
  5606. GB_ASSERT(valids.count == 1);
  5607. Ast *ident = operand->expr;
  5608. while (ident->kind == Ast_SelectorExpr) {
  5609. Ast *s = ident->SelectorExpr.selector;
  5610. ident = s;
  5611. }
  5612. Entity *e = proc_entities[valids[0].index];
  5613. GB_ASSERT(e != nullptr);
  5614. Array<Operand> named_operands = {};
  5615. check_call_arguments_single(c, call, operand,
  5616. e, e->type,
  5617. positional_operands, named_operands,
  5618. CallArgumentErrorMode::ShowErrors,
  5619. &data);
  5620. return data;
  5621. }
  5622. return data;
  5623. }
  5624. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  5625. Type *proc_type = nullptr;
  5626. CallArgumentData data = {};
  5627. data.result_type = t_invalid;
  5628. proc_type = base_type(operand->type);
  5629. TypeProc *pt = nullptr;
  5630. if (proc_type) {
  5631. pt = &proc_type->Proc;
  5632. }
  5633. TEMPORARY_ALLOCATOR_GUARD();
  5634. ast_node(ce, CallExpr, call);
  5635. bool any_failure = false;
  5636. // Split positional and named args into separate arrays/slices
  5637. Slice<Ast *> positional_args = {};
  5638. Slice<Ast *> named_args = {};
  5639. if (ce->split_args == nullptr) {
  5640. positional_args = ce->args;
  5641. for (isize i = 0; i < ce->args.count; i++) {
  5642. Ast *arg = ce->args.data[i];
  5643. if (arg->kind == Ast_FieldValue) {
  5644. positional_args.count = i;
  5645. break;
  5646. }
  5647. }
  5648. named_args = slice(ce->args, positional_args.count, ce->args.count);
  5649. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  5650. split_args->positional = positional_args;
  5651. split_args->named = named_args;
  5652. ce->split_args = split_args;
  5653. } else {
  5654. positional_args = ce->split_args->positional;
  5655. named_args = ce->split_args->named;
  5656. }
  5657. if (operand->mode == Addressing_ProcGroup) {
  5658. return check_call_arguments_proc_group(c, operand, call);
  5659. }
  5660. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  5661. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5662. defer (array_free(&positional_operands));
  5663. defer (array_free(&named_operands));
  5664. if (positional_args.count > 0) {
  5665. isize lhs_count = -1;
  5666. bool is_variadic = false;
  5667. Entity **lhs = nullptr;
  5668. if (pt != nullptr) {
  5669. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  5670. }
  5671. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5672. }
  5673. if (named_args.count > 0) {
  5674. for_array(i, named_args) {
  5675. Ast *arg = named_args[i];
  5676. if (arg->kind != Ast_FieldValue) {
  5677. error(arg, "Expected a 'field = value'");
  5678. return data;
  5679. }
  5680. ast_node(fv, FieldValue, arg);
  5681. if (fv->field->kind != Ast_Ident) {
  5682. gbString expr_str = expr_to_string(fv->field);
  5683. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5684. any_failure = true;
  5685. gb_string_free(expr_str);
  5686. continue;
  5687. }
  5688. String key = fv->field->Ident.token.string;
  5689. Ast *value = fv->value;
  5690. isize param_index = lookup_procedure_parameter(pt, key);
  5691. Type *type_hint = nullptr;
  5692. if (param_index >= 0) {
  5693. Entity *e = pt->params->Tuple.variables[param_index];
  5694. type_hint = e->type;
  5695. }
  5696. Operand o = {};
  5697. check_expr_with_type_hint(c, &o, value, type_hint);
  5698. if (o.mode == Addressing_Invalid) {
  5699. any_failure = true;
  5700. }
  5701. array_add(&named_operands, o);
  5702. }
  5703. }
  5704. if (!any_failure) {
  5705. check_call_arguments_single(c, call, operand,
  5706. nullptr, proc_type,
  5707. positional_operands, named_operands,
  5708. CallArgumentErrorMode::ShowErrors,
  5709. &data);
  5710. } else if (pt) {
  5711. data.result_type = pt->results;
  5712. }
  5713. return data;
  5714. }
  5715. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  5716. if (!is_type_polymorphic_record(t)) {
  5717. return -1;
  5718. }
  5719. TypeTuple *params = get_record_polymorphic_params(t);
  5720. if (params == nullptr) {
  5721. return -1;
  5722. }
  5723. for_array(i, params->variables) {
  5724. Entity *e = params->variables[i];
  5725. String name = e->token.string;
  5726. if (is_blank_ident(name)) {
  5727. continue;
  5728. }
  5729. if (name == parameter_name) {
  5730. return i;
  5731. }
  5732. }
  5733. return -1;
  5734. }
  5735. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  5736. ast_node(ce, CallExpr, call);
  5737. Type *original_type = operand->type;
  5738. GB_ASSERT(is_type_polymorphic_record(original_type));
  5739. bool show_error = true;
  5740. Array<Operand> operands = {};
  5741. defer (array_free(&operands));
  5742. bool named_fields = false;
  5743. {
  5744. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  5745. auto prev_type_path = c->type_path;
  5746. c->type_path = new_checker_type_path();
  5747. defer ({
  5748. destroy_checker_type_path(c->type_path);
  5749. c->type_path = prev_type_path;
  5750. });
  5751. if (is_call_expr_field_value(ce)) {
  5752. named_fields = true;
  5753. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  5754. for_array(i, ce->args) {
  5755. Ast *arg = ce->args[i];
  5756. ast_node(fv, FieldValue, arg);
  5757. if (fv->field->kind == Ast_Ident) {
  5758. String name = fv->field->Ident.token.string;
  5759. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5760. if (index >= 0) {
  5761. TypeTuple *params = get_record_polymorphic_params(original_type);
  5762. Entity *e = params->variables[i];
  5763. if (e->kind == Entity_Constant) {
  5764. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  5765. continue;
  5766. }
  5767. }
  5768. }
  5769. check_expr_or_type(c, &operands[i], fv->value);
  5770. }
  5771. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5772. if (vari_expand) {
  5773. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  5774. }
  5775. } else {
  5776. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  5777. Entity **lhs = nullptr;
  5778. isize lhs_count = -1;
  5779. TypeTuple *params = get_record_polymorphic_params(original_type);
  5780. if (params != nullptr) {
  5781. lhs = params->variables.data;
  5782. lhs_count = params->variables.count;
  5783. }
  5784. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  5785. }
  5786. }
  5787. CallArgumentError err = CallArgumentError_None;
  5788. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  5789. isize param_count = tuple->variables.count;
  5790. isize minimum_param_count = param_count;
  5791. for (; minimum_param_count > 0; minimum_param_count--) {
  5792. Entity *e = tuple->variables[minimum_param_count-1];
  5793. if (e->kind != Entity_Constant) {
  5794. break;
  5795. }
  5796. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  5797. break;
  5798. }
  5799. }
  5800. Array<Operand> ordered_operands = operands;
  5801. if (!named_fields) {
  5802. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5803. array_copy(&ordered_operands, operands, 0);
  5804. } else {
  5805. TEMPORARY_ALLOCATOR_GUARD();
  5806. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  5807. // LEAK(bill)
  5808. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5809. for_array(i, ce->args) {
  5810. Ast *arg = ce->args[i];
  5811. ast_node(fv, FieldValue, arg);
  5812. if (fv->field->kind != Ast_Ident) {
  5813. if (show_error) {
  5814. gbString expr_str = expr_to_string(fv->field);
  5815. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  5816. gb_string_free(expr_str);
  5817. }
  5818. err = CallArgumentError_InvalidFieldValue;
  5819. continue;
  5820. }
  5821. String name = fv->field->Ident.token.string;
  5822. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5823. if (index < 0) {
  5824. if (show_error) {
  5825. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  5826. }
  5827. err = CallArgumentError_ParameterNotFound;
  5828. continue;
  5829. }
  5830. if (visited[index]) {
  5831. if (show_error) {
  5832. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  5833. }
  5834. err = CallArgumentError_DuplicateParameter;
  5835. continue;
  5836. }
  5837. visited[index] = true;
  5838. ordered_operands[index] = operands[i];
  5839. }
  5840. for (isize i = 0; i < param_count; i++) {
  5841. if (!visited[i]) {
  5842. Entity *e = tuple->variables[i];
  5843. if (is_blank_ident(e->token)) {
  5844. continue;
  5845. }
  5846. if (show_error) {
  5847. if (e->kind == Entity_TypeName) {
  5848. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  5849. LIT(e->token.string));
  5850. } else {
  5851. gbString str = type_to_string(e->type);
  5852. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  5853. LIT(e->token.string), str);
  5854. gb_string_free(str);
  5855. }
  5856. }
  5857. err = CallArgumentError_ParameterMissing;
  5858. }
  5859. }
  5860. }
  5861. if (err != 0) {
  5862. operand->mode = Addressing_Invalid;
  5863. return err;
  5864. }
  5865. while (ordered_operands.count > 0) {
  5866. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  5867. break;
  5868. }
  5869. array_pop(&ordered_operands);
  5870. }
  5871. if (minimum_param_count != param_count) {
  5872. if (param_count < ordered_operands.count) {
  5873. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  5874. err = CallArgumentError_TooManyArguments;
  5875. } else if (minimum_param_count > ordered_operands.count) {
  5876. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  5877. err = CallArgumentError_TooFewArguments;
  5878. }
  5879. } else {
  5880. if (param_count < ordered_operands.count) {
  5881. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  5882. err = CallArgumentError_TooManyArguments;
  5883. } else if (param_count > ordered_operands.count) {
  5884. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  5885. err = CallArgumentError_TooFewArguments;
  5886. }
  5887. }
  5888. if (err != 0) {
  5889. return err;
  5890. }
  5891. if (minimum_param_count != param_count) {
  5892. array_resize(&ordered_operands, param_count);
  5893. isize missing_count = 0;
  5894. // NOTE(bill): Replace missing operands with the default values (if possible)
  5895. for_array(i, ordered_operands) {
  5896. Operand *o = &ordered_operands[i];
  5897. if (o->expr == nullptr) {
  5898. Entity *e = tuple->variables[i];
  5899. if (e->kind == Entity_Constant) {
  5900. missing_count += 1;
  5901. o->mode = Addressing_Constant;
  5902. o->type = default_type(e->type);
  5903. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  5904. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  5905. o->value = e->Constant.param_value.value;
  5906. }
  5907. } else if (e->kind == Entity_TypeName) {
  5908. missing_count += 1;
  5909. o->mode = Addressing_Type;
  5910. o->type = e->type;
  5911. o->expr = e->identifier;
  5912. }
  5913. }
  5914. }
  5915. }
  5916. isize oo_count = gb_min(param_count, ordered_operands.count);
  5917. i64 score = 0;
  5918. for (isize i = 0; i < oo_count; i++) {
  5919. Entity *e = tuple->variables[i];
  5920. Operand *o = &ordered_operands[i];
  5921. if (o->mode == Addressing_Invalid) {
  5922. continue;
  5923. }
  5924. if (e->kind == Entity_TypeName) {
  5925. if (o->mode != Addressing_Type) {
  5926. if (show_error) {
  5927. gbString expr = expr_to_string(o->expr);
  5928. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  5929. gb_string_free(expr);
  5930. }
  5931. err = CallArgumentError_WrongTypes;
  5932. }
  5933. if (are_types_identical(e->type, o->type)) {
  5934. score += assign_score_function(1);
  5935. } else {
  5936. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5937. }
  5938. } else {
  5939. i64 s = 0;
  5940. if (o->type->kind == Type_Generic) {
  5941. // Polymorphic name!
  5942. score += assign_score_function(1);
  5943. continue;
  5944. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  5945. if (show_error) {
  5946. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  5947. }
  5948. err = CallArgumentError_WrongTypes;
  5949. }
  5950. o->type = e->type;
  5951. if (o->mode != Addressing_Constant) {
  5952. bool valid = false;
  5953. if (is_type_proc(o->type)) {
  5954. Entity *proc_entity = entity_from_expr(o->expr);
  5955. valid = proc_entity != nullptr;
  5956. }
  5957. if (!valid) {
  5958. if (show_error) {
  5959. error(o->expr, "Expected a constant value for this polymorphic type argument");
  5960. }
  5961. err = CallArgumentError_NoneConstantParameter;
  5962. }
  5963. }
  5964. score += s;
  5965. }
  5966. // NOTE(bill): Add type info the parameters
  5967. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  5968. // add_type_info_type(c, o->type);
  5969. }
  5970. if (show_error && err) {
  5971. return err;
  5972. }
  5973. {
  5974. bool failure = false;
  5975. Entity *found_entity = find_polymorphic_record_entity(c, original_type, param_count, ordered_operands, &failure);
  5976. if (found_entity) {
  5977. operand->mode = Addressing_Type;
  5978. operand->type = found_entity->type;
  5979. return err;
  5980. }
  5981. String generated_name = make_string_c(expr_to_string(call));
  5982. CheckerContext ctx = *c;
  5983. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  5984. ctx.scope = polymorphic_record_parent_scope(original_type);
  5985. GB_ASSERT(ctx.scope != nullptr);
  5986. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  5987. Type *bt = base_type(original_type);
  5988. if (bt->kind == Type_Struct) {
  5989. Ast *node = clone_ast(bt->Struct.node);
  5990. Type *struct_type = alloc_type_struct();
  5991. struct_type->Struct.node = node;
  5992. struct_type->Struct.polymorphic_parent = original_type;
  5993. set_base_type(named_type, struct_type);
  5994. check_open_scope(&ctx, node);
  5995. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  5996. check_close_scope(&ctx);
  5997. } else if (bt->kind == Type_Union) {
  5998. Ast *node = clone_ast(bt->Union.node);
  5999. Type *union_type = alloc_type_union();
  6000. union_type->Union.node = node;
  6001. union_type->Union.polymorphic_parent = original_type;
  6002. set_base_type(named_type, union_type);
  6003. check_open_scope(&ctx, node);
  6004. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6005. check_close_scope(&ctx);
  6006. } else {
  6007. GB_PANIC("Unsupported parametric polymorphic record type");
  6008. }
  6009. operand->mode = Addressing_Type;
  6010. operand->type = named_type;
  6011. }
  6012. return err;
  6013. }
  6014. // returns true on success
  6015. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6016. bool success = true;
  6017. if (args.count > 0) {
  6018. if (allow_mixed) {
  6019. bool was_named = false;
  6020. for (Ast *arg : args) {
  6021. if (was_named && arg->kind != Ast_FieldValue) {
  6022. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6023. success = false;
  6024. break;
  6025. }
  6026. was_named = was_named || arg->kind == Ast_FieldValue;
  6027. }
  6028. } else {
  6029. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6030. for (Ast *arg : args) {
  6031. bool mix = false;
  6032. if (first_is_field_value) {
  6033. mix = arg->kind != Ast_FieldValue;
  6034. } else {
  6035. mix = arg->kind == Ast_FieldValue;
  6036. }
  6037. if (mix) {
  6038. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6039. success = false;
  6040. }
  6041. }
  6042. }
  6043. }
  6044. return success;
  6045. }
  6046. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6047. operand->mode = Addressing_Invalid; \
  6048. operand->expr = call; \
  6049. return Expr_Stmt; \
  6050. }
  6051. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6052. if (proc != nullptr &&
  6053. proc->kind == Ast_BasicDirective) {
  6054. ast_node(bd, BasicDirective, proc);
  6055. String name = bd->name.string;
  6056. if (
  6057. name == "location" ||
  6058. name == "assert" ||
  6059. name == "panic" ||
  6060. name == "defined" ||
  6061. name == "config" ||
  6062. name == "load" ||
  6063. name == "load_hash" ||
  6064. name == "load_or"
  6065. ) {
  6066. operand->mode = Addressing_Builtin;
  6067. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6068. operand->expr = proc;
  6069. operand->type = t_invalid;
  6070. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6071. } else {
  6072. error(proc, "Unknown directive: #%.*s", LIT(name));
  6073. operand->expr = proc;
  6074. operand->type = t_invalid;
  6075. operand->mode = Addressing_Invalid;
  6076. return Expr_Expr;
  6077. }
  6078. if (inlining != ProcInlining_none) {
  6079. error(call, "Inlining operators are not allowed on built-in procedures");
  6080. }
  6081. } else {
  6082. if (proc != nullptr) {
  6083. check_expr_or_type(c, operand, proc);
  6084. } else {
  6085. GB_ASSERT(operand->expr != nullptr);
  6086. }
  6087. }
  6088. if (operand->mode == Addressing_Invalid) {
  6089. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6090. for (Ast *arg : args) {
  6091. if (arg->kind == Ast_FieldValue) {
  6092. arg = arg->FieldValue.value;
  6093. }
  6094. check_expr_base(c, operand, arg, nullptr);
  6095. }
  6096. operand->mode = Addressing_Invalid;
  6097. operand->expr = call;
  6098. return Expr_Stmt;
  6099. }
  6100. if (operand->mode == Addressing_Type) {
  6101. Type *t = operand->type;
  6102. if (is_type_polymorphic_record(t)) {
  6103. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6104. if (!is_type_named(t)) {
  6105. gbString s = expr_to_string(operand->expr);
  6106. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6107. gb_string_free(s);
  6108. operand->mode = Addressing_Invalid;
  6109. operand->type = t_invalid;;
  6110. return Expr_Expr;
  6111. }
  6112. auto err = check_polymorphic_record_type(c, operand, call);
  6113. if (err == 0) {
  6114. Ast *ident = operand->expr;
  6115. while (ident->kind == Ast_SelectorExpr) {
  6116. Ast *s = ident->SelectorExpr.selector;
  6117. ident = s;
  6118. }
  6119. Type *ot = operand->type;
  6120. GB_ASSERT(ot->kind == Type_Named);
  6121. Entity *e = ot->Named.type_name;
  6122. add_entity_use(c, ident, e);
  6123. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6124. } else {
  6125. operand->mode = Addressing_Invalid;
  6126. operand->type = t_invalid;
  6127. }
  6128. } else {
  6129. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6130. operand->mode = Addressing_Invalid;
  6131. isize arg_count = args.count;
  6132. switch (arg_count) {
  6133. case 0:
  6134. {
  6135. gbString str = type_to_string(t);
  6136. error(call, "Missing argument in conversion to '%s'", str);
  6137. gb_string_free(str);
  6138. } break;
  6139. default:
  6140. {
  6141. gbString str = type_to_string(t);
  6142. error(call, "Too many arguments in conversion to '%s'", str);
  6143. gb_string_free(str);
  6144. } break;
  6145. case 1: {
  6146. Ast *arg = args[0];
  6147. if (arg->kind == Ast_FieldValue) {
  6148. error(call, "'field = value' cannot be used in a type conversion");
  6149. arg = arg->FieldValue.value;
  6150. // NOTE(bill): Carry on the cast regardless
  6151. }
  6152. check_expr_with_type_hint(c, operand, arg, t);
  6153. if (operand->mode != Addressing_Invalid) {
  6154. if (is_type_polymorphic(t)) {
  6155. error(call, "A polymorphic type cannot be used in a type conversion");
  6156. } else {
  6157. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  6158. // as it assumes it is determining the type
  6159. check_cast(c, operand, t);
  6160. }
  6161. }
  6162. operand->type = t;
  6163. operand->expr = call;
  6164. if (operand->mode != Addressing_Invalid) {
  6165. update_untyped_expr_type(c, arg, t, false);
  6166. }
  6167. break;
  6168. }
  6169. }
  6170. }
  6171. return Expr_Expr;
  6172. }
  6173. if (operand->mode == Addressing_Builtin) {
  6174. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  6175. i32 id = operand->builtin_id;
  6176. Entity *e = entity_of_node(operand->expr);
  6177. if (e != nullptr && e->token.string == "expand_to_tuple") {
  6178. warning(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  6179. }
  6180. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  6181. operand->mode = Addressing_Invalid;
  6182. operand->type = t_invalid;
  6183. }
  6184. operand->expr = call;
  6185. return builtin_procs[id].kind;
  6186. }
  6187. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  6188. Entity *initial_entity = entity_of_node(operand->expr);
  6189. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  6190. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  6191. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  6192. if (c->decl) {
  6193. c->decl->defer_used += 1;
  6194. }
  6195. }
  6196. }
  6197. if (operand->mode != Addressing_ProcGroup) {
  6198. Type *proc_type = base_type(operand->type);
  6199. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  6200. bool valid_mode = is_operand_value(*operand);
  6201. if (!valid_type || !valid_mode) {
  6202. Ast *e = operand->expr;
  6203. gbString str = expr_to_string(e);
  6204. gbString type_str = type_to_string(operand->type);
  6205. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  6206. gb_string_free(type_str);
  6207. gb_string_free(str);
  6208. operand->mode = Addressing_Invalid;
  6209. operand->expr = call;
  6210. return Expr_Stmt;
  6211. }
  6212. }
  6213. CallArgumentData data = check_call_arguments(c, operand, call);
  6214. Type *result_type = data.result_type;
  6215. gb_zero_item(operand);
  6216. operand->expr = call;
  6217. if (result_type == t_invalid) {
  6218. operand->mode = Addressing_Invalid;
  6219. operand->type = t_invalid;
  6220. return Expr_Stmt;
  6221. }
  6222. Type *pt = base_type(operand->type);
  6223. if (pt == nullptr) {
  6224. pt = t_invalid;
  6225. }
  6226. if (pt == t_invalid) {
  6227. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6228. pt = type_of_expr(operand->expr->CallExpr.proc);
  6229. }
  6230. if (pt == t_invalid && data.gen_entity) {
  6231. pt = data.gen_entity->type;
  6232. }
  6233. }
  6234. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  6235. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  6236. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  6237. }
  6238. }
  6239. if (result_type == nullptr) {
  6240. operand->mode = Addressing_NoValue;
  6241. } else {
  6242. GB_ASSERT(is_type_tuple(result_type));
  6243. isize count = result_type->Tuple.variables.count;
  6244. switch (count) {
  6245. case 0:
  6246. operand->mode = Addressing_NoValue;
  6247. break;
  6248. case 1:
  6249. operand->mode = Addressing_Value;
  6250. operand->type = result_type->Tuple.variables[0]->type;
  6251. break;
  6252. default:
  6253. operand->mode = Addressing_Value;
  6254. operand->type = result_type;
  6255. break;
  6256. }
  6257. }
  6258. switch (inlining) {
  6259. case ProcInlining_inline:
  6260. if (proc != nullptr) {
  6261. Entity *e = entity_from_expr(proc);
  6262. if (e != nullptr && e->kind == Entity_Procedure) {
  6263. DeclInfo *decl = e->decl_info;
  6264. if (decl->proc_lit) {
  6265. ast_node(pl, ProcLit, decl->proc_lit);
  6266. if (pl->inlining == ProcInlining_no_inline) {
  6267. error(call, "'#force_inline' cannot be applied to a procedure that has be marked as '#force_no_inline'");
  6268. }
  6269. }
  6270. }
  6271. }
  6272. break;
  6273. case ProcInlining_no_inline:
  6274. break;
  6275. }
  6276. operand->expr = call;
  6277. {
  6278. Type *type = nullptr;
  6279. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6280. type = type_of_expr(operand->expr->CallExpr.proc);
  6281. }
  6282. if (type == nullptr) {
  6283. type = pt;
  6284. }
  6285. type = base_type(type);
  6286. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  6287. operand->mode = Addressing_OptionalOk;
  6288. operand->type = type->Proc.results->Tuple.variables[0]->type;
  6289. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  6290. operand->expr->CallExpr.optional_ok_one = true;
  6291. }
  6292. }
  6293. }
  6294. return Expr_Expr;
  6295. }
  6296. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  6297. check_expr_base(c, o, e, t);
  6298. check_not_tuple(c, o);
  6299. char const *err_str = nullptr;
  6300. switch (o->mode) {
  6301. case Addressing_NoValue:
  6302. err_str = "used as a value";
  6303. break;
  6304. case Addressing_Type:
  6305. if (t == nullptr || !is_type_typeid(t)) {
  6306. err_str = "is not an expression but a type, in this context it is ambiguous";
  6307. }
  6308. break;
  6309. case Addressing_Builtin:
  6310. err_str = "must be called";
  6311. break;
  6312. }
  6313. if (err_str != nullptr) {
  6314. gbString str = expr_to_string(e);
  6315. error(e, "'%s' %s", str, err_str);
  6316. gb_string_free(str);
  6317. o->mode = Addressing_Invalid;
  6318. }
  6319. }
  6320. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  6321. switch (t->kind) {
  6322. case Type_Basic:
  6323. if (t->Basic.kind == Basic_string) {
  6324. if (o->mode == Addressing_Constant) {
  6325. *max_count = o->value.value_string.len;
  6326. }
  6327. if (o->mode != Addressing_Constant) {
  6328. o->mode = Addressing_Value;
  6329. }
  6330. o->type = t_u8;
  6331. return true;
  6332. } else if (t->Basic.kind == Basic_UntypedString) {
  6333. if (o->mode == Addressing_Constant) {
  6334. *max_count = o->value.value_string.len;
  6335. o->type = t_u8;
  6336. return true;
  6337. }
  6338. return false;
  6339. }
  6340. break;
  6341. case Type_MultiPointer:
  6342. o->type = t->MultiPointer.elem;
  6343. if (o->mode != Addressing_Constant) {
  6344. o->mode = Addressing_Variable;
  6345. }
  6346. return true;
  6347. case Type_Array:
  6348. *max_count = t->Array.count;
  6349. if (indirection) {
  6350. o->mode = Addressing_Variable;
  6351. } else if (o->mode != Addressing_Variable &&
  6352. o->mode != Addressing_Constant) {
  6353. o->mode = Addressing_Value;
  6354. }
  6355. o->type = t->Array.elem;
  6356. return true;
  6357. case Type_EnumeratedArray:
  6358. *max_count = t->EnumeratedArray.count;
  6359. if (indirection) {
  6360. o->mode = Addressing_Variable;
  6361. } else if (o->mode != Addressing_Variable &&
  6362. o->mode != Addressing_Constant) {
  6363. o->mode = Addressing_Value;
  6364. }
  6365. o->type = t->EnumeratedArray.elem;
  6366. return true;
  6367. case Type_Matrix:
  6368. *max_count = t->Matrix.column_count;
  6369. if (indirection) {
  6370. o->mode = Addressing_Variable;
  6371. } else if (o->mode != Addressing_Variable) {
  6372. o->mode = Addressing_Value;
  6373. }
  6374. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  6375. return true;
  6376. case Type_Slice:
  6377. o->type = t->Slice.elem;
  6378. if (o->mode != Addressing_Constant) {
  6379. o->mode = Addressing_Variable;
  6380. }
  6381. return true;
  6382. case Type_RelativeSlice:
  6383. {
  6384. Type *slice_type = base_type(t->RelativeSlice.slice_type);
  6385. GB_ASSERT(slice_type->kind == Type_Slice);
  6386. o->type = slice_type->Slice.elem;
  6387. if (o->mode != Addressing_Constant) {
  6388. o->mode = Addressing_Variable;
  6389. }
  6390. }
  6391. return true;
  6392. case Type_DynamicArray:
  6393. o->type = t->DynamicArray.elem;
  6394. if (o->mode != Addressing_Constant) {
  6395. o->mode = Addressing_Variable;
  6396. }
  6397. return true;
  6398. case Type_Struct:
  6399. if (t->Struct.soa_kind != StructSoa_None) {
  6400. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6401. *max_count = t->Struct.soa_count;
  6402. }
  6403. o->type = t->Struct.soa_elem;
  6404. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable) {
  6405. o->mode = Addressing_SoaVariable;
  6406. } else {
  6407. o->mode = Addressing_Value;
  6408. }
  6409. return true;
  6410. }
  6411. return false;
  6412. }
  6413. if (is_type_pointer(original_type) && indirection) {
  6414. Type *ptr = base_type(original_type);
  6415. if (ptr->kind == Type_Pointer && o->mode == Addressing_SoaVariable) {
  6416. o->type = ptr->Pointer.elem;
  6417. o->mode = Addressing_Value;
  6418. return true;
  6419. }
  6420. }
  6421. return false;
  6422. }
  6423. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  6424. if (is_type_untyped_uninit(x)) {
  6425. return true;
  6426. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  6427. return true;
  6428. } else if (is_type_untyped_uninit(y)) {
  6429. return true;
  6430. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  6431. return true;
  6432. }
  6433. return are_types_identical(x, y);
  6434. }
  6435. 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) {
  6436. if (!is_ast_range(node)) {
  6437. return false;
  6438. }
  6439. ast_node(ie, BinaryExpr, node);
  6440. check_expr_with_type_hint(c, x, ie->left, type_hint);
  6441. if (x->mode == Addressing_Invalid) {
  6442. return false;
  6443. }
  6444. check_expr_with_type_hint(c, y, ie->right, type_hint);
  6445. if (y->mode == Addressing_Invalid) {
  6446. return false;
  6447. }
  6448. convert_to_typed(c, x, y->type);
  6449. if (x->mode == Addressing_Invalid) {
  6450. return false;
  6451. }
  6452. convert_to_typed(c, y, x->type);
  6453. if (y->mode == Addressing_Invalid) {
  6454. return false;
  6455. }
  6456. convert_to_typed(c, x, default_type(y->type));
  6457. if (x->mode == Addressing_Invalid) {
  6458. return false;
  6459. }
  6460. convert_to_typed(c, y, default_type(x->type));
  6461. if (y->mode == Addressing_Invalid) {
  6462. return false;
  6463. }
  6464. if (!are_types_identical(x->type, y->type)) {
  6465. if (x->type != t_invalid &&
  6466. y->type != t_invalid) {
  6467. gbString xt = type_to_string(x->type);
  6468. gbString yt = type_to_string(y->type);
  6469. gbString expr_str = expr_to_string(x->expr);
  6470. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  6471. gb_string_free(expr_str);
  6472. gb_string_free(yt);
  6473. gb_string_free(xt);
  6474. }
  6475. return false;
  6476. }
  6477. Type *type = x->type;
  6478. if (is_for_loop) {
  6479. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  6480. error(ie->op, "Only numerical types are allowed within interval expressions");
  6481. return false;
  6482. }
  6483. } else {
  6484. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  6485. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  6486. return false;
  6487. }
  6488. }
  6489. if (x->mode == Addressing_Constant &&
  6490. y->mode == Addressing_Constant) {
  6491. ExactValue a = x->value;
  6492. ExactValue b = y->value;
  6493. GB_ASSERT(are_types_identical(x->type, y->type));
  6494. TokenKind op = Token_Lt;
  6495. switch (ie->op.kind) {
  6496. case Token_Ellipsis: op = Token_LtEq; break; // ..
  6497. case Token_RangeFull: op = Token_LtEq; break; // ..=
  6498. case Token_RangeHalf: op = Token_Lt; break; // ..<
  6499. default: error(ie->op, "Invalid range operator"); break;
  6500. }
  6501. bool ok = compare_exact_values(op, a, b);
  6502. if (!ok) {
  6503. // TODO(bill): Better error message
  6504. error(ie->op, "Invalid interval range");
  6505. return false;
  6506. }
  6507. ExactValue inline_for_depth = exact_value_sub(b, a);
  6508. if (ie->op.kind != Token_RangeHalf) {
  6509. inline_for_depth = exact_value_increment_one(inline_for_depth);
  6510. }
  6511. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  6512. } else if (inline_for_depth_ != nullptr) {
  6513. error(ie->op, "Interval expressions must be constant");
  6514. return false;
  6515. }
  6516. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  6517. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  6518. return true;
  6519. }
  6520. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  6521. if (is_operand_nil(*o)) {
  6522. return true;
  6523. }
  6524. Ast *expr = unparen_expr(o->expr);
  6525. if (expr != nullptr) {
  6526. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  6527. if (e != nullptr && e->kind == Entity_Procedure) {
  6528. return true;
  6529. }
  6530. if (expr->kind == Ast_ProcLit) {
  6531. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  6532. return true;
  6533. }
  6534. }
  6535. return o->mode == Addressing_Constant;
  6536. }
  6537. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  6538. if (is_type_enum(th)) {
  6539. Type *enum_type = base_type(th);
  6540. GB_ASSERT(enum_type->kind == Type_Enum);
  6541. String name = ise->selector->Ident.token.string;
  6542. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  6543. if (e == nullptr) {
  6544. return false;
  6545. }
  6546. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  6547. GB_ASSERT(e->kind == Entity_Constant);
  6548. o->value = e->Constant.value;
  6549. o->mode = Addressing_Constant;
  6550. o->type = e->type;
  6551. return true;
  6552. }
  6553. if (is_type_union(th)) {
  6554. TEMPORARY_ALLOCATOR_GUARD();
  6555. Type *union_type = base_type(th);
  6556. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  6557. for (Type *vt : union_type->Union.variants) {
  6558. Operand x = {};
  6559. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  6560. array_add(&operands, x);
  6561. }
  6562. }
  6563. if (operands.count == 1) {
  6564. *o = operands[0];
  6565. return true;
  6566. }
  6567. }
  6568. return false;
  6569. }
  6570. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6571. ast_node(ise, ImplicitSelectorExpr, node);
  6572. o->type = t_invalid;
  6573. o->expr = node;
  6574. o->mode = Addressing_Invalid;
  6575. Type *th = type_hint;
  6576. if (th == nullptr) {
  6577. gbString str = expr_to_string(node);
  6578. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  6579. gb_string_free(str);
  6580. return Expr_Expr;
  6581. }
  6582. o->type = th;
  6583. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  6584. if (!ok) {
  6585. String name = ise->selector->Ident.token.string;
  6586. if (is_type_enum(th)) {
  6587. Type *bt = base_type(th);
  6588. GB_ASSERT(bt->kind == Type_Enum);
  6589. gbString typ = type_to_string(th);
  6590. defer (gb_string_free(typ));
  6591. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  6592. check_did_you_mean_type(name, bt->Enum.fields);
  6593. } else {
  6594. gbString typ = type_to_string(th);
  6595. gbString str = expr_to_string(node);
  6596. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  6597. gb_string_free(str);
  6598. gb_string_free(typ);
  6599. }
  6600. }
  6601. o->expr = node;
  6602. return Expr_Expr;
  6603. }
  6604. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_) {
  6605. switch (x->mode) {
  6606. case Addressing_MapIndex:
  6607. case Addressing_OptionalOk:
  6608. case Addressing_OptionalOkPtr:
  6609. if (val_type_) *val_type_ = x->type;
  6610. break;
  6611. default:
  6612. if (ok_type_) *ok_type_ = x->type;
  6613. return;
  6614. }
  6615. Ast *expr = unparen_expr(x->expr);
  6616. if (expr->kind == Ast_CallExpr) {
  6617. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  6618. if (is_type_proc(pt)) {
  6619. Type *tuple = pt->Proc.results;
  6620. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6621. if (pt->Proc.result_count >= 2) {
  6622. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6623. }
  6624. expr->CallExpr.optional_ok_one = false;
  6625. x->type = tuple;
  6626. return;
  6627. }
  6628. }
  6629. Type *tuple = make_optional_ok_type(x->type);
  6630. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  6631. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  6632. x->type = tuple;
  6633. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  6634. }
  6635. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6636. ast_node(ie, MatrixIndexExpr, node);
  6637. check_expr(c, o, ie->expr);
  6638. node->viral_state_flags |= ie->expr->viral_state_flags;
  6639. if (o->mode == Addressing_Invalid) {
  6640. o->expr = node;
  6641. return;
  6642. }
  6643. Type *t = base_type(type_deref(o->type));
  6644. bool is_ptr = is_type_pointer(o->type);
  6645. bool is_const = o->mode == Addressing_Constant;
  6646. if (t->kind != Type_Matrix) {
  6647. gbString str = expr_to_string(o->expr);
  6648. gbString type_str = type_to_string(o->type);
  6649. defer (gb_string_free(str));
  6650. defer (gb_string_free(type_str));
  6651. if (is_const) {
  6652. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  6653. } else {
  6654. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  6655. }
  6656. o->mode = Addressing_Invalid;
  6657. o->expr = node;
  6658. return;
  6659. }
  6660. o->type = t->Matrix.elem;
  6661. if (is_ptr) {
  6662. o->mode = Addressing_Variable;
  6663. } else if (o->mode != Addressing_Variable) {
  6664. o->mode = Addressing_Value;
  6665. }
  6666. if (ie->row_index == nullptr) {
  6667. gbString str = expr_to_string(o->expr);
  6668. error(o->expr, "Missing row index for '%s'", str);
  6669. gb_string_free(str);
  6670. o->mode = Addressing_Invalid;
  6671. o->expr = node;
  6672. return;
  6673. }
  6674. if (ie->column_index == nullptr) {
  6675. gbString str = expr_to_string(o->expr);
  6676. error(o->expr, "Missing column index for '%s'", str);
  6677. gb_string_free(str);
  6678. o->mode = Addressing_Invalid;
  6679. o->expr = node;
  6680. return;
  6681. }
  6682. i64 row_count = t->Matrix.row_count;
  6683. i64 column_count = t->Matrix.column_count;
  6684. i64 row_index = 0;
  6685. i64 column_index = 0;
  6686. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  6687. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  6688. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  6689. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  6690. }
  6691. gb_unused(row_ok);
  6692. gb_unused(column_ok);
  6693. }
  6694. struct TypeAndToken {
  6695. Type *type;
  6696. Token token;
  6697. };
  6698. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  6699. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  6700. if (operand.mode != Addressing_Constant) {
  6701. return;
  6702. }
  6703. if (operand.value.kind == ExactValue_Invalid) {
  6704. return;
  6705. }
  6706. uintptr key = hash_exact_value(operand.value);
  6707. TypeAndToken *found = map_get(seen, key);
  6708. if (found != nullptr) {
  6709. TEMPORARY_ALLOCATOR_GUARD();
  6710. isize count = multi_map_count(seen, key);
  6711. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  6712. multi_map_get_all(seen, key, taps);
  6713. for (isize i = 0; i < count; i++) {
  6714. TypeAndToken tap = taps[i];
  6715. if (!are_types_identical(operand.type, tap.type)) {
  6716. continue;
  6717. }
  6718. TokenPos pos = tap.token.pos;
  6719. if (use_expr) {
  6720. gbString expr_str = expr_to_string(operand.expr);
  6721. error(operand.expr,
  6722. "Duplicate case '%s'\n"
  6723. "\tprevious case at %s",
  6724. expr_str,
  6725. token_pos_to_string(pos));
  6726. gb_string_free(expr_str);
  6727. } else {
  6728. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  6729. }
  6730. return;
  6731. }
  6732. }
  6733. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  6734. multi_map_insert(seen, key, tap);
  6735. }
  6736. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  6737. if (is_type_enum(x.type)) {
  6738. // TODO(bill): Fix this logic so it's fast!!!
  6739. i64 v0 = exact_value_to_i64(lhs.value);
  6740. i64 v1 = exact_value_to_i64(rhs.value);
  6741. Operand v = {};
  6742. v.mode = Addressing_Constant;
  6743. v.type = x.type;
  6744. v.expr = x.expr;
  6745. Type *bt = base_type(x.type);
  6746. GB_ASSERT(bt->kind == Type_Enum);
  6747. for (i64 vi = v0; vi <= v1; vi++) {
  6748. if (upper_op != Token_LtEq && vi == v1) {
  6749. break;
  6750. }
  6751. bool found = false;
  6752. for (Entity *f : bt->Enum.fields) {
  6753. GB_ASSERT(f->kind == Entity_Constant);
  6754. i64 fv = exact_value_to_i64(f->Constant.value);
  6755. if (fv == vi) {
  6756. found = true;
  6757. break;
  6758. }
  6759. }
  6760. if (found) {
  6761. v.value = exact_value_i64(vi);
  6762. add_constant_switch_case(ctx, seen, v);
  6763. }
  6764. }
  6765. } else {
  6766. add_constant_switch_case(ctx, seen, lhs);
  6767. if (upper_op == Token_LtEq) {
  6768. add_constant_switch_case(ctx, seen, rhs);
  6769. }
  6770. }
  6771. }
  6772. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  6773. add_constant_switch_case(ctx, seen, x);
  6774. }
  6775. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6776. ast_node(bd, BasicDirective, node);
  6777. ExprKind kind = Expr_Expr;
  6778. o->mode = Addressing_Constant;
  6779. String name = bd->name.string;
  6780. if (name == "file") {
  6781. o->type = t_untyped_string;
  6782. o->value = exact_value_string(get_file_path_string(bd->token.pos.file_id));
  6783. } else if (name == "line") {
  6784. o->type = t_untyped_integer;
  6785. o->value = exact_value_i64(bd->token.pos.line);
  6786. } else if (name == "procedure") {
  6787. if (c->curr_proc_decl == nullptr) {
  6788. error(node, "#procedure may only be used within procedures");
  6789. o->type = t_untyped_string;
  6790. o->value = exact_value_string(str_lit(""));
  6791. } else {
  6792. o->type = t_untyped_string;
  6793. o->value = exact_value_string(c->proc_name);
  6794. }
  6795. } else if (name == "caller_location") {
  6796. init_core_source_code_location(c->checker);
  6797. error(node, "#caller_location may only be used as a default argument parameter");
  6798. o->type = t_source_code_location;
  6799. o->mode = Addressing_Value;
  6800. } else {
  6801. if (name == "location") {
  6802. init_core_source_code_location(c->checker);
  6803. error(node, "'#%.*s' must be used in a call expression", LIT(name));
  6804. o->type = t_source_code_location;
  6805. o->mode = Addressing_Value;
  6806. } else if (
  6807. name == "assert" ||
  6808. name == "defined" ||
  6809. name == "config" ||
  6810. name == "load" ||
  6811. name == "load_hash" ||
  6812. name == "load_or"
  6813. ) {
  6814. error(node, "'#%.*s' must be used as a call", LIT(name));
  6815. o->type = t_invalid;
  6816. o->mode = Addressing_Invalid;
  6817. } else {
  6818. error(node, "Unknown directive: #%.*s", LIT(name));
  6819. o->type = t_invalid;
  6820. o->mode = Addressing_Invalid;
  6821. }
  6822. }
  6823. return kind;
  6824. }
  6825. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6826. ExprKind kind = Expr_Expr;
  6827. Operand cond = {Addressing_Invalid};
  6828. ast_node(te, TernaryIfExpr, node);
  6829. check_expr(c, &cond, te->cond);
  6830. node->viral_state_flags |= te->cond->viral_state_flags;
  6831. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  6832. error(te->cond, "Non-boolean condition in ternary if expression");
  6833. }
  6834. Operand x = {Addressing_Invalid};
  6835. Operand y = {Addressing_Invalid};
  6836. check_expr_or_type(c, &x, te->x, type_hint);
  6837. node->viral_state_flags |= te->x->viral_state_flags;
  6838. if (te->y != nullptr) {
  6839. Type *th = type_hint;
  6840. if (type_hint == nullptr && is_type_typed(x.type)) {
  6841. th = x.type;
  6842. }
  6843. check_expr_or_type(c, &y, te->y, th);
  6844. node->viral_state_flags |= te->y->viral_state_flags;
  6845. } else {
  6846. error(node, "A ternary expression must have an else clause");
  6847. return kind;
  6848. }
  6849. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  6850. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  6851. gbString type_string = expr_to_string(type_expr);
  6852. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  6853. gb_string_free(type_string);
  6854. return kind;
  6855. }
  6856. if (x.type == nullptr || x.type == t_invalid ||
  6857. y.type == nullptr || y.type == t_invalid) {
  6858. return kind;
  6859. }
  6860. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  6861. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  6862. if (x.mode == Addressing_Invalid) {
  6863. return kind;
  6864. }
  6865. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  6866. if (y.mode == Addressing_Invalid) {
  6867. x.mode = Addressing_Invalid;
  6868. return kind;
  6869. }
  6870. // NOTE(bill, 2023-01-30): Allow for expression like this:
  6871. // x: union{f32} = f32(123) if cond else nil
  6872. if (type_hint && !is_type_any(type_hint) && !ternary_compare_types(x.type, y.type)) {
  6873. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  6874. check_cast(c, &x, type_hint);
  6875. check_cast(c, &y, type_hint);
  6876. }
  6877. }
  6878. if (!ternary_compare_types(x.type, y.type)) {
  6879. gbString its = type_to_string(x.type);
  6880. gbString ets = type_to_string(y.type);
  6881. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  6882. gb_string_free(ets);
  6883. gb_string_free(its);
  6884. return kind;
  6885. }
  6886. o->type = x.type;
  6887. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  6888. o->type = y.type;
  6889. }
  6890. o->mode = Addressing_Value;
  6891. o->expr = node;
  6892. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  6893. if (check_cast_internal(c, &x, type_hint) &&
  6894. check_cast_internal(c, &y, type_hint)) {
  6895. convert_to_typed(c, o, type_hint);
  6896. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  6897. o->type = type_hint;
  6898. }
  6899. }
  6900. return kind;
  6901. }
  6902. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6903. ExprKind kind = Expr_Expr;
  6904. Operand cond = {};
  6905. ast_node(te, TernaryWhenExpr, node);
  6906. check_expr(c, &cond, te->cond);
  6907. node->viral_state_flags |= te->cond->viral_state_flags;
  6908. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  6909. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  6910. return kind;
  6911. }
  6912. if (cond.value.value_bool) {
  6913. check_expr_or_type(c, o, te->x, type_hint);
  6914. node->viral_state_flags |= te->x->viral_state_flags;
  6915. } else {
  6916. if (te->y != nullptr) {
  6917. check_expr_or_type(c, o, te->y, type_hint);
  6918. node->viral_state_flags |= te->y->viral_state_flags;
  6919. } else {
  6920. error(node, "A ternary when expression must have an else clause");
  6921. return kind;
  6922. }
  6923. }
  6924. return kind;
  6925. }
  6926. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6927. ast_node(oe, OrElseExpr, node);
  6928. String name = oe->token.string;
  6929. Ast *arg = oe->x;
  6930. Ast *default_value = oe->y;
  6931. Operand x = {};
  6932. Operand y = {};
  6933. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  6934. if (is_load_directive_call(arg)) {
  6935. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  6936. // Allow for chaining of '#load(path) or_else #load(path)'
  6937. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  6938. bool y_is_diverging = false;
  6939. check_expr_base(c, &y, default_value, x.type);
  6940. switch (y.mode) {
  6941. case Addressing_NoValue:
  6942. if (is_diverging_expr(y.expr)) {
  6943. // Allow
  6944. y.mode = Addressing_Value;
  6945. y_is_diverging = true;
  6946. } else {
  6947. error_operand_no_value(&y);
  6948. y.mode = Addressing_Invalid;
  6949. }
  6950. break;
  6951. case Addressing_Type:
  6952. error_operand_not_expression(&y);
  6953. y.mode = Addressing_Invalid;
  6954. break;
  6955. }
  6956. if (y.mode == Addressing_Invalid) {
  6957. o->mode = Addressing_Value;
  6958. o->type = t_invalid;
  6959. o->expr = node;
  6960. return Expr_Expr;
  6961. }
  6962. if (!y_is_diverging) {
  6963. check_assignment(c, &y, x.type, name);
  6964. if (y.mode != Addressing_Constant) {
  6965. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  6966. }
  6967. }
  6968. }
  6969. if (res == LoadDirective_Success) {
  6970. *o = x;
  6971. } else {
  6972. *o = y;
  6973. }
  6974. o->expr = node;
  6975. return Expr_Expr;
  6976. }
  6977. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  6978. if (x.mode == Addressing_Invalid) {
  6979. o->mode = Addressing_Value;
  6980. o->type = t_invalid;
  6981. o->expr = node;
  6982. return Expr_Expr;
  6983. }
  6984. bool y_is_diverging = false;
  6985. check_expr_base(c, &y, default_value, x.type);
  6986. switch (y.mode) {
  6987. case Addressing_NoValue:
  6988. if (is_diverging_expr(y.expr)) {
  6989. // Allow
  6990. y.mode = Addressing_Value;
  6991. y_is_diverging = true;
  6992. } else {
  6993. error_operand_no_value(&y);
  6994. y.mode = Addressing_Invalid;
  6995. }
  6996. break;
  6997. case Addressing_Type:
  6998. error_operand_not_expression(&y);
  6999. y.mode = Addressing_Invalid;
  7000. break;
  7001. }
  7002. if (y.mode == Addressing_Invalid) {
  7003. o->mode = Addressing_Value;
  7004. o->type = t_invalid;
  7005. o->expr = node;
  7006. return Expr_Expr;
  7007. }
  7008. Type *left_type = nullptr;
  7009. Type *right_type = nullptr;
  7010. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7011. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7012. if (left_type != nullptr) {
  7013. if (!y_is_diverging) {
  7014. check_assignment(c, &y, left_type, name);
  7015. }
  7016. } else {
  7017. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7018. }
  7019. if (left_type == nullptr) {
  7020. left_type = t_invalid;
  7021. }
  7022. o->mode = Addressing_Value;
  7023. o->type = left_type;
  7024. o->expr = node;
  7025. return Expr_Expr;
  7026. }
  7027. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7028. ast_node(re, OrReturnExpr, node);
  7029. String name = re->token.string;
  7030. Operand x = {};
  7031. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  7032. if (x.mode == Addressing_Invalid) {
  7033. o->mode = Addressing_Value;
  7034. o->type = t_invalid;
  7035. o->expr = node;
  7036. return Expr_Expr;
  7037. }
  7038. Type *left_type = nullptr;
  7039. Type *right_type = nullptr;
  7040. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7041. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  7042. if (right_type == nullptr) {
  7043. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7044. } else {
  7045. Type *proc_type = base_type(c->curr_proc_sig);
  7046. GB_ASSERT(proc_type->kind == Type_Proc);
  7047. Type *result_type = proc_type->Proc.results;
  7048. if (result_type == nullptr) {
  7049. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  7050. } else {
  7051. GB_ASSERT(result_type->kind == Type_Tuple);
  7052. auto const &vars = result_type->Tuple.variables;
  7053. Type *end_type = vars[vars.count-1]->type;
  7054. if (vars.count > 1) {
  7055. if (!proc_type->Proc.has_named_results) {
  7056. 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));
  7057. }
  7058. }
  7059. Operand rhs = {};
  7060. rhs.type = right_type;
  7061. rhs.mode = Addressing_Value;
  7062. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  7063. // NOTE(bill): allow implicit conversion between boolean types
  7064. // within 'or_return' to improve the experience using third-party code
  7065. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  7066. // TODO(bill): better error message
  7067. gbString a = type_to_string(right_type);
  7068. gbString b = type_to_string(end_type);
  7069. gbString ret_type = type_to_string(result_type);
  7070. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  7071. if (vars.count == 1) {
  7072. error_line("\tProcedure return value type: %s\n", ret_type);
  7073. } else {
  7074. error_line("\tProcedure return value types: (%s)\n", ret_type);
  7075. }
  7076. gb_string_free(ret_type);
  7077. gb_string_free(b);
  7078. gb_string_free(a);
  7079. }
  7080. }
  7081. }
  7082. o->expr = node;
  7083. o->type = left_type;
  7084. if (left_type != nullptr) {
  7085. o->mode = Addressing_Value;
  7086. } else {
  7087. o->mode = Addressing_NoValue;
  7088. }
  7089. if (c->curr_proc_sig == nullptr) {
  7090. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7091. }
  7092. if (c->in_defer) {
  7093. error(node, "'or_return' cannot be used within a defer statement");
  7094. }
  7095. return Expr_Expr;
  7096. }
  7097. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  7098. Type *bt = base_type(type);
  7099. StringSet fields_visited = {};
  7100. defer (string_set_destroy(&fields_visited));
  7101. StringMap<String> fields_visited_through_raw_union = {};
  7102. defer (string_map_destroy(&fields_visited_through_raw_union));
  7103. for (Ast *elem : elems) {
  7104. if (elem->kind != Ast_FieldValue) {
  7105. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7106. continue;
  7107. }
  7108. ast_node(fv, FieldValue, elem);
  7109. if (fv->field->kind != Ast_Ident) {
  7110. gbString expr_str = expr_to_string(fv->field);
  7111. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  7112. gb_string_free(expr_str);
  7113. continue;
  7114. }
  7115. String name = fv->field->Ident.token.string;
  7116. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7117. bool is_unknown = sel.entity == nullptr;
  7118. if (is_unknown) {
  7119. error(fv->field, "Unknown field '%.*s' in structure literal", LIT(name));
  7120. continue;
  7121. }
  7122. Entity *field = bt->Struct.fields[sel.index[0]];
  7123. add_entity_use(c, fv->field, field);
  7124. if (string_set_update(&fields_visited, name)) {
  7125. if (sel.index.count > 1) {
  7126. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7127. error(fv->field, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7128. } else {
  7129. error(fv->field, "Duplicate or reused field '%.*s' in structure literal", LIT(sel.entity->token.string));
  7130. }
  7131. } else {
  7132. error(fv->field, "Duplicate field '%.*s' in structure literal", LIT(field->token.string));
  7133. }
  7134. continue;
  7135. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  7136. error(fv->field, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  7137. continue;
  7138. }
  7139. if (sel.indirect) {
  7140. error(fv->field, "Cannot assign to the %d-nested anonymous indirect field '%.*s' in a structure literal", cast(int)sel.index.count-1, LIT(name));
  7141. continue;
  7142. }
  7143. if (sel.index.count > 1) {
  7144. if (is_constant) {
  7145. Type *ft = type;
  7146. for (i32 index : sel.index) {
  7147. Type *bt = base_type(ft);
  7148. switch (bt->kind) {
  7149. case Type_Struct:
  7150. if (bt->Struct.is_raw_union) {
  7151. is_constant = false;
  7152. break;
  7153. }
  7154. ft = bt->Struct.fields[index]->type;
  7155. break;
  7156. case Type_Array:
  7157. ft = bt->Array.elem;
  7158. break;
  7159. default:
  7160. GB_PANIC("invalid type: %s", type_to_string(ft));
  7161. break;
  7162. }
  7163. }
  7164. if (is_constant &&
  7165. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  7166. is_constant = false;
  7167. }
  7168. }
  7169. Type *nested_ft = bt;
  7170. for (i32 index : sel.index) {
  7171. Type *bt = base_type(nested_ft);
  7172. switch (bt->kind) {
  7173. case Type_Struct:
  7174. if (bt->Struct.is_raw_union) {
  7175. for (Entity *re : bt->Struct.fields) {
  7176. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  7177. }
  7178. }
  7179. nested_ft = bt->Struct.fields[index]->type;
  7180. break;
  7181. case Type_Array:
  7182. nested_ft = bt->Array.elem;
  7183. break;
  7184. default:
  7185. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  7186. break;
  7187. }
  7188. }
  7189. field = sel.entity;
  7190. }
  7191. Operand o = {};
  7192. check_expr_or_type(c, &o, fv->value, field->type);
  7193. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7194. is_constant = false;
  7195. }
  7196. if (is_constant) {
  7197. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7198. }
  7199. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7200. }
  7201. }
  7202. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7203. ExprKind kind = Expr_Expr;
  7204. ast_node(cl, CompoundLit, node);
  7205. Type *type = type_hint;
  7206. if (type != nullptr && is_type_untyped(type)) {
  7207. type = nullptr;
  7208. }
  7209. bool is_to_be_determined_array_count = false;
  7210. bool is_constant = true;
  7211. if (cl->type != nullptr) {
  7212. type = nullptr;
  7213. // [?]Type
  7214. if (cl->type->kind == Ast_ArrayType && cl->type->ArrayType.count != nullptr) {
  7215. Ast *count = cl->type->ArrayType.count;
  7216. if (count->kind == Ast_UnaryExpr &&
  7217. count->UnaryExpr.op.kind == Token_Question) {
  7218. type = alloc_type_array(check_type(c, cl->type->ArrayType.elem), -1);
  7219. is_to_be_determined_array_count = true;
  7220. }
  7221. if (cl->elems.count > 0) {
  7222. if (cl->type->ArrayType.tag != nullptr) {
  7223. Ast *tag = cl->type->ArrayType.tag;
  7224. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7225. String name = tag->BasicDirective.name.string;
  7226. if (name == "soa") {
  7227. error(node, "#soa arrays are not supported for compound literals");
  7228. return kind;
  7229. }
  7230. }
  7231. }
  7232. }
  7233. if (cl->type->kind == Ast_DynamicArrayType && cl->type->DynamicArrayType.tag != nullptr) {
  7234. if (cl->elems.count > 0) {
  7235. Ast *tag = cl->type->DynamicArrayType.tag;
  7236. GB_ASSERT(tag->kind == Ast_BasicDirective);
  7237. String name = tag->BasicDirective.name.string;
  7238. if (name == "soa") {
  7239. error(node, "#soa arrays are not supported for compound literals");
  7240. return kind;
  7241. }
  7242. }
  7243. }
  7244. if (type == nullptr) {
  7245. type = check_type(c, cl->type);
  7246. }
  7247. }
  7248. if (type == nullptr) {
  7249. error(node, "Missing type in compound literal");
  7250. return kind;
  7251. }
  7252. Type *t = base_type(type);
  7253. if (is_type_polymorphic(t)) {
  7254. gbString str = type_to_string(type);
  7255. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  7256. o->expr = node;
  7257. o->type = type;
  7258. gb_string_free(str);
  7259. return kind;
  7260. }
  7261. switch (t->kind) {
  7262. case Type_Struct: {
  7263. if (cl->elems.count == 0) {
  7264. break; // NOTE(bill): No need to init
  7265. }
  7266. if (t->Struct.is_raw_union) {
  7267. if (cl->elems.count > 0) {
  7268. // NOTE: unions cannot be constant
  7269. is_constant = false;
  7270. if (cl->elems[0]->kind != Ast_FieldValue) {
  7271. gbString type_str = type_to_string(type);
  7272. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  7273. gb_string_free(type_str);
  7274. } else {
  7275. if (cl->elems.count != 1) {
  7276. gbString type_str = type_to_string(type);
  7277. 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);
  7278. gb_string_free(type_str);
  7279. } else {
  7280. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7281. }
  7282. }
  7283. }
  7284. break;
  7285. }
  7286. isize field_count = t->Struct.fields.count;
  7287. isize min_field_count = t->Struct.fields.count;
  7288. for (isize i = min_field_count-1; i >= 0; i--) {
  7289. Entity *e = t->Struct.fields[i];
  7290. GB_ASSERT(e->kind == Entity_Variable);
  7291. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  7292. min_field_count--;
  7293. } else {
  7294. break;
  7295. }
  7296. }
  7297. if (cl->elems[0]->kind == Ast_FieldValue) {
  7298. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  7299. } else {
  7300. bool seen_field_value = false;
  7301. for_array(index, cl->elems) {
  7302. Entity *field = nullptr;
  7303. Ast *elem = cl->elems[index];
  7304. if (elem->kind == Ast_FieldValue) {
  7305. seen_field_value = true;
  7306. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7307. continue;
  7308. } else if (seen_field_value) {
  7309. error(elem, "Value elements cannot be used after a 'field = value'");
  7310. continue;
  7311. }
  7312. if (index >= field_count) {
  7313. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7314. break;
  7315. }
  7316. if (field == nullptr) {
  7317. field = t->Struct.fields[index];
  7318. }
  7319. Operand o = {};
  7320. check_expr_or_type(c, &o, elem, field->type);
  7321. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  7322. is_constant = false;
  7323. }
  7324. if (is_constant) {
  7325. is_constant = check_is_operand_compound_lit_constant(c, &o);
  7326. }
  7327. check_assignment(c, &o, field->type, str_lit("structure literal"));
  7328. }
  7329. if (cl->elems.count < field_count) {
  7330. if (min_field_count < field_count) {
  7331. if (cl->elems.count < min_field_count) {
  7332. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  7333. }
  7334. } else {
  7335. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  7336. }
  7337. }
  7338. }
  7339. break;
  7340. }
  7341. case Type_Slice:
  7342. case Type_Array:
  7343. case Type_DynamicArray:
  7344. case Type_SimdVector:
  7345. case Type_Matrix:
  7346. {
  7347. Type *elem_type = nullptr;
  7348. String context_name = {};
  7349. i64 max_type_count = -1;
  7350. if (t->kind == Type_Slice) {
  7351. elem_type = t->Slice.elem;
  7352. context_name = str_lit("slice literal");
  7353. } else if (t->kind == Type_Array) {
  7354. elem_type = t->Array.elem;
  7355. context_name = str_lit("array literal");
  7356. if (!is_to_be_determined_array_count) {
  7357. max_type_count = t->Array.count;
  7358. }
  7359. } else if (t->kind == Type_DynamicArray) {
  7360. elem_type = t->DynamicArray.elem;
  7361. context_name = str_lit("dynamic array literal");
  7362. is_constant = false;
  7363. if (!build_context.no_dynamic_literals) {
  7364. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  7365. add_package_dependency(c, "runtime", "__dynamic_array_append");
  7366. }
  7367. } else if (t->kind == Type_SimdVector) {
  7368. elem_type = t->SimdVector.elem;
  7369. context_name = str_lit("simd vector literal");
  7370. max_type_count = t->SimdVector.count;
  7371. } else if (t->kind == Type_Matrix) {
  7372. elem_type = t->Matrix.elem;
  7373. context_name = str_lit("matrix literal");
  7374. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  7375. } else {
  7376. GB_PANIC("unreachable");
  7377. }
  7378. i64 max = 0;
  7379. Type *bet = base_type(elem_type);
  7380. if (!elem_type_can_be_constant(bet)) {
  7381. is_constant = false;
  7382. }
  7383. if (bet == t_invalid) {
  7384. break;
  7385. }
  7386. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7387. RangeCache rc = range_cache_make(heap_allocator());
  7388. defer (range_cache_destroy(&rc));
  7389. for (Ast *elem : cl->elems) {
  7390. if (elem->kind != Ast_FieldValue) {
  7391. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7392. continue;
  7393. }
  7394. ast_node(fv, FieldValue, elem);
  7395. if (is_ast_range(fv->field)) {
  7396. Token op = fv->field->BinaryExpr.op;
  7397. Operand x = {};
  7398. Operand y = {};
  7399. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  7400. if (!ok) {
  7401. continue;
  7402. }
  7403. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  7404. error(x.expr, "Expected a constant integer as an array field");
  7405. continue;
  7406. }
  7407. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  7408. error(y.expr, "Expected a constant integer as an array field");
  7409. continue;
  7410. }
  7411. i64 lo = exact_value_to_i64(x.value);
  7412. i64 hi = exact_value_to_i64(y.value);
  7413. i64 max_index = hi;
  7414. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  7415. hi -= 1;
  7416. } else { // .. (inclusive)
  7417. max_index += 1;
  7418. }
  7419. bool new_range = range_cache_add_range(&rc, lo, hi);
  7420. if (!new_range) {
  7421. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  7422. continue;
  7423. }
  7424. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  7425. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  7426. continue;
  7427. }
  7428. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  7429. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  7430. continue;
  7431. }
  7432. if (max < hi) {
  7433. max = max_index;
  7434. }
  7435. Operand operand = {};
  7436. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7437. check_assignment(c, &operand, elem_type, context_name);
  7438. is_constant = is_constant && operand.mode == Addressing_Constant;
  7439. } else {
  7440. Operand op_index = {};
  7441. check_expr(c, &op_index, fv->field);
  7442. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  7443. error(elem, "Expected a constant integer as an array field");
  7444. continue;
  7445. }
  7446. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  7447. i64 index = exact_value_to_i64(op_index.value);
  7448. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  7449. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  7450. continue;
  7451. }
  7452. bool new_index = range_cache_add_index(&rc, index);
  7453. if (!new_index) {
  7454. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  7455. continue;
  7456. }
  7457. if (max < index+1) {
  7458. max = index+1;
  7459. }
  7460. Operand operand = {};
  7461. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7462. check_assignment(c, &operand, elem_type, context_name);
  7463. is_constant = is_constant && operand.mode == Addressing_Constant;
  7464. }
  7465. }
  7466. cl->max_count = max;
  7467. } else {
  7468. isize index = 0;
  7469. for (; index < cl->elems.count; index++) {
  7470. Ast *e = cl->elems[index];
  7471. if (e == nullptr) {
  7472. error(node, "Invalid literal element");
  7473. continue;
  7474. }
  7475. if (e->kind == Ast_FieldValue) {
  7476. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7477. continue;
  7478. }
  7479. if (0 <= max_type_count && max_type_count <= index) {
  7480. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  7481. }
  7482. Operand operand = {};
  7483. check_expr_with_type_hint(c, &operand, e, elem_type);
  7484. check_assignment(c, &operand, elem_type, context_name);
  7485. is_constant = is_constant && operand.mode == Addressing_Constant;
  7486. }
  7487. if (max < index) {
  7488. max = index;
  7489. }
  7490. }
  7491. if (t->kind == Type_Array) {
  7492. if (is_to_be_determined_array_count) {
  7493. t->Array.count = max;
  7494. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7495. if (0 < max && max < t->Array.count) {
  7496. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  7497. }
  7498. }
  7499. }
  7500. if (t->kind == Type_SimdVector) {
  7501. if (!is_constant) {
  7502. // error(node, "Expected all constant elements for a simd vector");
  7503. }
  7504. }
  7505. if (t->kind == Type_DynamicArray) {
  7506. if (build_context.no_dynamic_literals && cl->elems.count) {
  7507. error(node, "Compound literals of dynamic types have been disabled");
  7508. }
  7509. }
  7510. if (t->kind == Type_Matrix) {
  7511. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7512. if (0 < max && max < max_type_count) {
  7513. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  7514. }
  7515. }
  7516. }
  7517. break;
  7518. }
  7519. case Type_EnumeratedArray:
  7520. {
  7521. Type *elem_type = t->EnumeratedArray.elem;
  7522. Type *index_type = t->EnumeratedArray.index;
  7523. String context_name = str_lit("enumerated array literal");
  7524. i64 max_type_count = t->EnumeratedArray.count;
  7525. gbString index_type_str = type_to_string(index_type);
  7526. defer (gb_string_free(index_type_str));
  7527. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  7528. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  7529. String total_lo_string = {};
  7530. String total_hi_string = {};
  7531. GB_ASSERT(is_type_enum(index_type));
  7532. {
  7533. Type *bt = base_type(index_type);
  7534. GB_ASSERT(bt->kind == Type_Enum);
  7535. for (Entity *f : bt->Enum.fields) {
  7536. if (f->kind != Entity_Constant) {
  7537. continue;
  7538. }
  7539. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  7540. total_lo_string = f->token.string;
  7541. }
  7542. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  7543. total_hi_string = f->token.string;
  7544. }
  7545. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  7546. break;
  7547. }
  7548. }
  7549. }
  7550. i64 max = 0;
  7551. Type *bet = base_type(elem_type);
  7552. if (!elem_type_can_be_constant(bet)) {
  7553. is_constant = false;
  7554. }
  7555. if (bet == t_invalid) {
  7556. break;
  7557. }
  7558. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  7559. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  7560. defer (map_destroy(&seen));
  7561. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  7562. RangeCache rc = range_cache_make(heap_allocator());
  7563. defer (range_cache_destroy(&rc));
  7564. for (Ast *elem : cl->elems) {
  7565. if (elem->kind != Ast_FieldValue) {
  7566. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7567. continue;
  7568. }
  7569. ast_node(fv, FieldValue, elem);
  7570. if (is_ast_range(fv->field)) {
  7571. Token op = fv->field->BinaryExpr.op;
  7572. Operand x = {};
  7573. Operand y = {};
  7574. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  7575. if (!ok) {
  7576. continue;
  7577. }
  7578. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  7579. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7580. continue;
  7581. }
  7582. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  7583. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7584. continue;
  7585. }
  7586. i64 lo = exact_value_to_i64(x.value);
  7587. i64 hi = exact_value_to_i64(y.value);
  7588. i64 max_index = hi;
  7589. if (op.kind == Token_RangeHalf) {
  7590. hi -= 1;
  7591. }
  7592. bool new_range = range_cache_add_range(&rc, lo, hi);
  7593. if (!new_range) {
  7594. gbString lo_str = expr_to_string(x.expr);
  7595. gbString hi_str = expr_to_string(y.expr);
  7596. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  7597. gb_string_free(hi_str);
  7598. gb_string_free(lo_str);
  7599. continue;
  7600. }
  7601. // NOTE(bill): These are sanity checks for invalid enum values
  7602. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  7603. gbString lo_str = expr_to_string(x.expr);
  7604. 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));
  7605. gb_string_free(lo_str);
  7606. continue;
  7607. }
  7608. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  7609. gbString hi_str = expr_to_string(y.expr);
  7610. 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));
  7611. gb_string_free(hi_str);
  7612. continue;
  7613. }
  7614. if (max < hi) {
  7615. max = max_index;
  7616. }
  7617. Operand operand = {};
  7618. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7619. check_assignment(c, &operand, elem_type, context_name);
  7620. is_constant = is_constant && operand.mode == Addressing_Constant;
  7621. TokenKind upper_op = Token_LtEq;
  7622. if (op.kind == Token_RangeHalf) {
  7623. upper_op = Token_Lt;
  7624. }
  7625. add_to_seen_map(c, &seen, upper_op, x, x, y);
  7626. } else {
  7627. Operand op_index = {};
  7628. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  7629. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  7630. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  7631. continue;
  7632. }
  7633. i64 index = exact_value_to_i64(op_index.value);
  7634. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  7635. gbString idx_str = expr_to_string(op_index.expr);
  7636. 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));
  7637. gb_string_free(idx_str);
  7638. continue;
  7639. }
  7640. bool new_index = range_cache_add_index(&rc, index);
  7641. if (!new_index) {
  7642. gbString idx_str = expr_to_string(op_index.expr);
  7643. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  7644. gb_string_free(idx_str);
  7645. continue;
  7646. }
  7647. if (max < index+1) {
  7648. max = index+1;
  7649. }
  7650. Operand operand = {};
  7651. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  7652. check_assignment(c, &operand, elem_type, context_name);
  7653. is_constant = is_constant && operand.mode == Addressing_Constant;
  7654. add_to_seen_map(c, &seen, op_index);
  7655. }
  7656. }
  7657. cl->max_count = max;
  7658. } else {
  7659. isize index = 0;
  7660. for (; index < cl->elems.count; index++) {
  7661. Ast *e = cl->elems[index];
  7662. if (e == nullptr) {
  7663. error(node, "Invalid literal element");
  7664. continue;
  7665. }
  7666. if (e->kind == Ast_FieldValue) {
  7667. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  7668. continue;
  7669. }
  7670. if (0 <= max_type_count && max_type_count <= index) {
  7671. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  7672. }
  7673. Operand operand = {};
  7674. check_expr_with_type_hint(c, &operand, e, elem_type);
  7675. check_assignment(c, &operand, elem_type, context_name);
  7676. is_constant = is_constant && operand.mode == Addressing_Constant;
  7677. }
  7678. if (max < index) {
  7679. max = index;
  7680. }
  7681. }
  7682. bool was_error = false;
  7683. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  7684. if (0 < max && max < t->EnumeratedArray.count) {
  7685. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  7686. was_error = true;
  7687. } else {
  7688. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  7689. was_error = true;
  7690. }
  7691. }
  7692. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  7693. if (cl->elems.count > 0 && !was_error && !is_partial) {
  7694. TEMPORARY_ALLOCATOR_GUARD();
  7695. Type *et = base_type(index_type);
  7696. GB_ASSERT(et->kind == Type_Enum);
  7697. auto fields = et->Enum.fields;
  7698. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  7699. for (Entity *f : fields) {
  7700. if (f->kind != Entity_Constant) {
  7701. continue;
  7702. }
  7703. ExactValue v = f->Constant.value;
  7704. auto found = map_get(&seen, hash_exact_value(v));
  7705. if (!found) {
  7706. array_add(&unhandled, f);
  7707. }
  7708. }
  7709. if (unhandled.count > 0) {
  7710. begin_error_block();
  7711. defer (end_error_block());
  7712. if (unhandled.count == 1) {
  7713. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  7714. } else {
  7715. error(node, "Unhandled enumerated array cases:");
  7716. for_array(i, unhandled) {
  7717. Entity *f = unhandled[i];
  7718. error_line("\t%.*s\n", LIT(f->token.string));
  7719. }
  7720. }
  7721. error_line("\n");
  7722. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  7723. }
  7724. }
  7725. break;
  7726. }
  7727. case Type_Basic: {
  7728. if (!is_type_any(t)) {
  7729. if (cl->elems.count != 0) {
  7730. gbString s = type_to_string(t);
  7731. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  7732. gb_string_free(s);
  7733. is_constant = false;
  7734. }
  7735. break;
  7736. }
  7737. if (cl->elems.count == 0) {
  7738. break; // NOTE(bill): No need to init
  7739. }
  7740. { // Checker values
  7741. Type *field_types[2] = {t_rawptr, t_typeid};
  7742. isize field_count = 2;
  7743. if (cl->elems[0]->kind == Ast_FieldValue) {
  7744. bool fields_visited[2] = {};
  7745. for_array(i, cl->elems) {
  7746. Ast *elem = cl->elems[i];
  7747. if (elem->kind != Ast_FieldValue) {
  7748. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  7749. continue;
  7750. }
  7751. ast_node(fv, FieldValue, elem);
  7752. if (fv->field->kind != Ast_Ident) {
  7753. gbString expr_str = expr_to_string(fv->field);
  7754. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  7755. gb_string_free(expr_str);
  7756. continue;
  7757. }
  7758. String name = fv->field->Ident.token.string;
  7759. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  7760. if (sel.entity == nullptr) {
  7761. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  7762. continue;
  7763. }
  7764. isize index = sel.index[0];
  7765. if (fields_visited[index]) {
  7766. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  7767. continue;
  7768. }
  7769. fields_visited[index] = true;
  7770. check_expr(c, o, fv->value);
  7771. // NOTE(bill): 'any' literals can never be constant
  7772. is_constant = false;
  7773. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  7774. }
  7775. } else {
  7776. for_array(index, cl->elems) {
  7777. Ast *elem = cl->elems[index];
  7778. if (elem->kind == Ast_FieldValue) {
  7779. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  7780. continue;
  7781. }
  7782. check_expr(c, o, elem);
  7783. if (index >= field_count) {
  7784. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  7785. break;
  7786. }
  7787. // NOTE(bill): 'any' literals can never be constant
  7788. is_constant = false;
  7789. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  7790. }
  7791. if (cl->elems.count < field_count) {
  7792. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  7793. }
  7794. }
  7795. }
  7796. break;
  7797. }
  7798. case Type_Map: {
  7799. if (cl->elems.count == 0) {
  7800. break;
  7801. }
  7802. is_constant = false;
  7803. { // Checker values
  7804. bool key_is_typeid = is_type_typeid(t->Map.key);
  7805. bool value_is_typeid = is_type_typeid(t->Map.value);
  7806. for (Ast *elem : cl->elems) {
  7807. if (elem->kind != Ast_FieldValue) {
  7808. error(elem, "Only 'field = value' elements are allowed in a map literal");
  7809. continue;
  7810. }
  7811. ast_node(fv, FieldValue, elem);
  7812. if (key_is_typeid) {
  7813. check_expr_or_type(c, o, fv->field, t->Map.key);
  7814. } else {
  7815. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  7816. }
  7817. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  7818. if (o->mode == Addressing_Invalid) {
  7819. continue;
  7820. }
  7821. if (value_is_typeid) {
  7822. check_expr_or_type(c, o, fv->value, t->Map.value);
  7823. } else {
  7824. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  7825. }
  7826. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  7827. }
  7828. }
  7829. if (build_context.no_dynamic_literals && cl->elems.count) {
  7830. error(node, "Compound literals of dynamic types have been disabled");
  7831. } else {
  7832. add_map_reserve_dependencies(c);
  7833. add_map_set_dependencies(c);
  7834. }
  7835. break;
  7836. }
  7837. case Type_BitSet: {
  7838. if (cl->elems.count == 0) {
  7839. break; // NOTE(bill): No need to init
  7840. }
  7841. Type *et = base_type(t->BitSet.elem);
  7842. isize field_count = 0;
  7843. if (et->kind == Type_Enum) {
  7844. field_count = et->Enum.fields.count;
  7845. }
  7846. if (cl->elems[0]->kind == Ast_FieldValue) {
  7847. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  7848. is_constant = false;
  7849. } else {
  7850. for (Ast *elem : cl->elems) {
  7851. if (elem->kind == Ast_FieldValue) {
  7852. error(elem, "'field = value' in a bit_set a literal is not allowed");
  7853. continue;
  7854. }
  7855. check_expr_with_type_hint(c, o, elem, et);
  7856. if (is_constant) {
  7857. is_constant = o->mode == Addressing_Constant;
  7858. }
  7859. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  7860. if (o->mode == Addressing_Constant) {
  7861. i64 lower = t->BitSet.lower;
  7862. i64 upper = t->BitSet.upper;
  7863. i64 v = exact_value_to_i64(o->value);
  7864. if (lower <= v && v <= upper) {
  7865. // okay
  7866. } else {
  7867. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  7868. continue;
  7869. }
  7870. }
  7871. }
  7872. }
  7873. break;
  7874. }
  7875. default: {
  7876. if (cl->elems.count == 0) {
  7877. break; // NOTE(bill): No need to init
  7878. }
  7879. gbString str = type_to_string(type);
  7880. error(node, "Invalid compound literal type '%s'", str);
  7881. gb_string_free(str);
  7882. return kind;
  7883. }
  7884. }
  7885. if (is_constant) {
  7886. o->mode = Addressing_Constant;
  7887. if (is_type_bit_set(type)) {
  7888. // NOTE(bill): Encode as an integer
  7889. Type *bt = base_type(type);
  7890. BigInt bits = {};
  7891. BigInt one = {};
  7892. big_int_from_u64(&one, 1);
  7893. for (Ast *e : cl->elems) {
  7894. GB_ASSERT(e->kind != Ast_FieldValue);
  7895. TypeAndValue tav = e->tav;
  7896. if (tav.mode != Addressing_Constant) {
  7897. continue;
  7898. }
  7899. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  7900. i64 v = big_int_to_i64(&tav.value.value_integer);
  7901. i64 lower = bt->BitSet.lower;
  7902. u64 index = cast(u64)(v-lower);
  7903. BigInt bit = {};
  7904. big_int_from_u64(&bit, index);
  7905. big_int_shl(&bit, &one, &bit);
  7906. big_int_or(&bits, &bits, &bit);
  7907. }
  7908. o->value.kind = ExactValue_Integer;
  7909. o->value.value_integer = bits;
  7910. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  7911. ExactValue value = exact_value_compound(node);
  7912. Type *bt = core_type(type);
  7913. if (bt->kind == Type_Basic) {
  7914. if (bt->Basic.flags & BasicFlag_Boolean) {
  7915. value = exact_value_bool(false);
  7916. } else if (bt->Basic.flags & BasicFlag_Integer) {
  7917. value = exact_value_i64(0);
  7918. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  7919. value = exact_value_i64(0);
  7920. } else if (bt->Basic.flags & BasicFlag_Float) {
  7921. value = exact_value_float(0);
  7922. } else if (bt->Basic.flags & BasicFlag_Complex) {
  7923. value = exact_value_complex(0, 0);
  7924. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  7925. value = exact_value_quaternion(0, 0, 0, 0);
  7926. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  7927. value = exact_value_pointer(0);
  7928. } else if (bt->Basic.flags & BasicFlag_String) {
  7929. String empty_string = {};
  7930. value = exact_value_string(empty_string);
  7931. } else if (bt->Basic.flags & BasicFlag_Rune) {
  7932. value = exact_value_i64(0);
  7933. }
  7934. }
  7935. o->value = value;
  7936. } else {
  7937. o->value = exact_value_compound(node);
  7938. }
  7939. } else {
  7940. o->mode = Addressing_Value;
  7941. }
  7942. o->type = type;
  7943. return kind;
  7944. }
  7945. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7946. ExprKind kind = Expr_Expr;
  7947. ast_node(ta, TypeAssertion, node);
  7948. check_expr(c, o, ta->expr);
  7949. node->viral_state_flags |= ta->expr->viral_state_flags;
  7950. if (o->mode == Addressing_Invalid) {
  7951. o->expr = node;
  7952. return kind;
  7953. }
  7954. if (o->mode == Addressing_Constant) {
  7955. gbString expr_str = expr_to_string(o->expr);
  7956. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  7957. gb_string_free(expr_str);
  7958. o->mode = Addressing_Invalid;
  7959. o->expr = node;
  7960. return kind;
  7961. }
  7962. if (is_type_untyped(o->type)) {
  7963. gbString expr_str = expr_to_string(o->expr);
  7964. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  7965. gb_string_free(expr_str);
  7966. o->mode = Addressing_Invalid;
  7967. o->expr = node;
  7968. return kind;
  7969. }
  7970. Type *src = type_deref(o->type);
  7971. Type *bsrc = base_type(src);
  7972. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  7973. if (!is_type_union(src)) {
  7974. gbString str = type_to_string(o->type);
  7975. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  7976. gb_string_free(str);
  7977. o->mode = Addressing_Invalid;
  7978. o->expr = node;
  7979. return kind;
  7980. }
  7981. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  7982. bool allowed = false;
  7983. for (Type *vt : bsrc->Union.variants) {
  7984. if (are_types_identical(vt, type_hint)) {
  7985. allowed = true;
  7986. add_type_info_type(c, vt);
  7987. break;
  7988. }
  7989. }
  7990. if (allowed) {
  7991. add_type_info_type(c, o->type);
  7992. o->type = type_hint;
  7993. o->mode = Addressing_OptionalOk;
  7994. return kind;
  7995. }
  7996. }
  7997. if (bsrc->Union.variants.count != 1) {
  7998. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  7999. o->mode = Addressing_Invalid;
  8000. o->expr = node;
  8001. return kind;
  8002. }
  8003. add_type_info_type(c, o->type);
  8004. add_type_info_type(c, bsrc->Union.variants[0]);
  8005. o->type = bsrc->Union.variants[0];
  8006. o->mode = Addressing_OptionalOk;
  8007. } else {
  8008. Type *t = check_type(c, ta->type);
  8009. Type *dst = t;
  8010. if (is_type_union(src)) {
  8011. bool ok = false;
  8012. for (Type *vt : bsrc->Union.variants) {
  8013. if (are_types_identical(vt, dst)) {
  8014. ok = true;
  8015. break;
  8016. }
  8017. }
  8018. if (!ok) {
  8019. gbString expr_str = expr_to_string(o->expr);
  8020. gbString dst_type_str = type_to_string(t);
  8021. defer (gb_string_free(expr_str));
  8022. defer (gb_string_free(dst_type_str));
  8023. if (bsrc->Union.variants.count == 0) {
  8024. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  8025. } else {
  8026. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  8027. }
  8028. o->mode = Addressing_Invalid;
  8029. o->expr = node;
  8030. return kind;
  8031. }
  8032. add_type_info_type(c, o->type);
  8033. add_type_info_type(c, t);
  8034. o->type = t;
  8035. o->mode = Addressing_OptionalOk;
  8036. } else if (is_type_any(src)) {
  8037. o->type = t;
  8038. o->mode = Addressing_OptionalOk;
  8039. add_type_info_type(c, o->type);
  8040. add_type_info_type(c, t);
  8041. } else {
  8042. gbString str = type_to_string(o->type);
  8043. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  8044. gb_string_free(str);
  8045. o->mode = Addressing_Invalid;
  8046. o->expr = node;
  8047. return kind;
  8048. }
  8049. }
  8050. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  8051. add_package_dependency(c, "runtime", "type_assertion_check");
  8052. add_package_dependency(c, "runtime", "type_assertion_check2");
  8053. }
  8054. return kind;
  8055. }
  8056. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8057. ast_node(se, SelectorCallExpr, node);
  8058. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  8059. // COM APIs is a great example of where this kind of thing is extremely useful
  8060. // General idea:
  8061. //
  8062. // x->y(123) == x.y(x, 123)
  8063. //
  8064. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  8065. // Just regenerating a new AST aids things
  8066. //
  8067. // TODO(bill): Is this a good hack or not?
  8068. //
  8069. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  8070. if (se->modified_call) {
  8071. // Prevent double evaluation
  8072. o->expr = node;
  8073. o->type = node->tav.type;
  8074. o->value = node->tav.value;
  8075. o->mode = node->tav.mode;
  8076. return Expr_Expr;
  8077. }
  8078. bool allow_arrow_right_selector_expr;
  8079. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8080. c->allow_arrow_right_selector_expr = true;
  8081. Operand x = {};
  8082. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  8083. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8084. if (x.mode == Addressing_Invalid || x.type == t_invalid) {
  8085. o->mode = Addressing_Invalid;
  8086. o->type = t_invalid;
  8087. o->expr = node;
  8088. return kind;
  8089. }
  8090. if (!is_type_proc(x.type)) {
  8091. gbString type_str = type_to_string(x.type);
  8092. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  8093. gb_string_free(type_str);
  8094. o->mode = Addressing_Invalid;
  8095. o->type = t_invalid;
  8096. o->expr = node;
  8097. return Expr_Stmt;
  8098. }
  8099. ast_node(ce, CallExpr, se->call);
  8100. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  8101. Ast *first_arg = x.expr->SelectorExpr.expr;
  8102. GB_ASSERT(first_arg != nullptr);
  8103. Entity *e = entity_of_node(se->expr);
  8104. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  8105. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  8106. }
  8107. Type *pt = base_type(x.type);
  8108. GB_ASSERT(pt->kind == Type_Proc);
  8109. Type *first_type = nullptr;
  8110. String first_arg_name = {};
  8111. if (pt->Proc.param_count > 0) {
  8112. Entity *f = pt->Proc.params->Tuple.variables[0];
  8113. first_type = f->type;
  8114. first_arg_name = f->token.string;
  8115. }
  8116. if (first_arg_name.len == 0) {
  8117. first_arg_name = str_lit("_");
  8118. }
  8119. if (first_type == nullptr) {
  8120. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  8121. o->mode = Addressing_Invalid;
  8122. o->type = t_invalid;
  8123. o->expr = node;
  8124. return Expr_Stmt;
  8125. }
  8126. Operand y = {};
  8127. y.mode = first_arg->tav.mode;
  8128. y.type = first_arg->tav.type;
  8129. y.value = first_arg->tav.value;
  8130. if (check_is_assignable_to(c, &y, first_type)) {
  8131. // Do nothing, it's valid
  8132. } else {
  8133. Operand z = y;
  8134. z.type = type_deref(y.type);
  8135. if (check_is_assignable_to(c, &z, first_type)) {
  8136. // NOTE(bill): AST GENERATION HACK!
  8137. Token op = {Token_Pointer};
  8138. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  8139. } else if (y.mode == Addressing_Variable) {
  8140. Operand w = y;
  8141. w.type = alloc_type_pointer(y.type);
  8142. if (check_is_assignable_to(c, &w, first_type)) {
  8143. // NOTE(bill): AST GENERATION HACK!
  8144. Token op = {Token_And};
  8145. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  8146. }
  8147. }
  8148. }
  8149. if (ce->args.count > 0) {
  8150. bool fail = false;
  8151. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  8152. for (Ast *arg : ce->args) {
  8153. bool mix = false;
  8154. if (first_is_field_value) {
  8155. mix = arg->kind != Ast_FieldValue;
  8156. } else {
  8157. mix = arg->kind == Ast_FieldValue;
  8158. }
  8159. if (mix) {
  8160. fail = true;
  8161. break;
  8162. }
  8163. }
  8164. if (!fail && first_is_field_value) {
  8165. Token op = {Token_Eq};
  8166. AstFile *f = first_arg->file();
  8167. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  8168. }
  8169. }
  8170. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  8171. modified_args[0] = first_arg;
  8172. slice_copy(&modified_args, ce->args, 1);
  8173. ce->args = modified_args;
  8174. se->modified_call = true;
  8175. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  8176. c->allow_arrow_right_selector_expr = true;
  8177. check_expr_base(c, o, se->call, type_hint);
  8178. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  8179. o->expr = node;
  8180. return Expr_Expr;
  8181. }
  8182. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8183. ExprKind kind = Expr_Expr;
  8184. ast_node(ie, IndexExpr, node);
  8185. check_expr(c, o, ie->expr);
  8186. node->viral_state_flags |= ie->expr->viral_state_flags;
  8187. if (o->mode == Addressing_Invalid) {
  8188. o->expr = node;
  8189. return kind;
  8190. }
  8191. Type *t = base_type(type_deref(o->type));
  8192. bool is_ptr = is_type_pointer(o->type);
  8193. bool is_const = o->mode == Addressing_Constant;
  8194. if (is_type_map(t)) {
  8195. Operand key = {};
  8196. if (is_type_typeid(t->Map.key)) {
  8197. check_expr_or_type(c, &key, ie->index, t->Map.key);
  8198. } else {
  8199. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  8200. }
  8201. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  8202. if (key.mode == Addressing_Invalid) {
  8203. o->mode = Addressing_Invalid;
  8204. o->expr = node;
  8205. return kind;
  8206. }
  8207. o->mode = Addressing_MapIndex;
  8208. o->type = t->Map.value;
  8209. o->expr = node;
  8210. add_map_get_dependencies(c);
  8211. add_map_set_dependencies(c);
  8212. return Expr_Expr;
  8213. }
  8214. i64 max_count = -1;
  8215. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  8216. if (is_const) {
  8217. if (is_type_array(t)) {
  8218. // OKay
  8219. } else if (is_type_slice(t)) {
  8220. // Okay
  8221. } else if (is_type_enumerated_array(t)) {
  8222. // Okay
  8223. } else if (is_type_string(t)) {
  8224. // Okay
  8225. } else if (is_type_relative_slice(t)) {
  8226. // Okay
  8227. } else if (is_type_matrix(t)) {
  8228. // Okay
  8229. } else {
  8230. valid = false;
  8231. }
  8232. }
  8233. if (!valid) {
  8234. gbString str = expr_to_string(o->expr);
  8235. gbString type_str = type_to_string(o->type);
  8236. defer (gb_string_free(str));
  8237. defer (gb_string_free(type_str));
  8238. if (is_const) {
  8239. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  8240. } else {
  8241. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  8242. }
  8243. o->mode = Addressing_Invalid;
  8244. o->expr = node;
  8245. return kind;
  8246. }
  8247. if (ie->index == nullptr) {
  8248. gbString str = expr_to_string(o->expr);
  8249. error(o->expr, "Missing index for '%s'", str);
  8250. gb_string_free(str);
  8251. o->mode = Addressing_Invalid;
  8252. o->expr = node;
  8253. return kind;
  8254. }
  8255. Type *index_type_hint = nullptr;
  8256. if (is_type_enumerated_array(t)) {
  8257. Type *bt = base_type(t);
  8258. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  8259. index_type_hint = bt->EnumeratedArray.index;
  8260. }
  8261. i64 index = 0;
  8262. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  8263. if (is_const) {
  8264. if (index < 0) {
  8265. gbString str = expr_to_string(o->expr);
  8266. error(o->expr, "Cannot index a constant '%s'", str);
  8267. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8268. gb_string_free(str);
  8269. o->mode = Addressing_Invalid;
  8270. o->expr = node;
  8271. return kind;
  8272. } else if (ok) {
  8273. ExactValue value = type_and_value_of_expr(ie->expr).value;
  8274. o->mode = Addressing_Constant;
  8275. bool success = false;
  8276. bool finish = false;
  8277. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  8278. if (!success) {
  8279. gbString str = expr_to_string(o->expr);
  8280. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  8281. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8282. gb_string_free(str);
  8283. o->mode = Addressing_Invalid;
  8284. o->expr = node;
  8285. return kind;
  8286. }
  8287. }
  8288. }
  8289. if (type_hint != nullptr && is_type_matrix(t)) {
  8290. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  8291. // if a type hint exists
  8292. }
  8293. return kind;
  8294. }
  8295. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8296. ExprKind kind = Expr_Stmt;
  8297. ast_node(se, SliceExpr, node);
  8298. check_expr(c, o, se->expr);
  8299. node->viral_state_flags |= se->expr->viral_state_flags;
  8300. if (o->mode == Addressing_Invalid) {
  8301. o->mode = Addressing_Invalid;
  8302. o->expr = node;
  8303. return kind;
  8304. }
  8305. bool valid = false;
  8306. i64 max_count = -1;
  8307. Type *t = base_type(type_deref(o->type));
  8308. switch (t->kind) {
  8309. case Type_Basic:
  8310. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  8311. valid = true;
  8312. if (o->mode == Addressing_Constant) {
  8313. max_count = o->value.value_string.len;
  8314. }
  8315. o->type = type_deref(o->type);
  8316. }
  8317. break;
  8318. case Type_Array:
  8319. valid = true;
  8320. max_count = t->Array.count;
  8321. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  8322. gbString str = expr_to_string(node);
  8323. error(node, "Cannot slice array '%s', value is not addressable", str);
  8324. gb_string_free(str);
  8325. o->mode = Addressing_Invalid;
  8326. o->expr = node;
  8327. return kind;
  8328. }
  8329. o->type = alloc_type_slice(t->Array.elem);
  8330. break;
  8331. case Type_MultiPointer:
  8332. valid = true;
  8333. o->type = type_deref(o->type);
  8334. break;
  8335. case Type_Slice:
  8336. valid = true;
  8337. o->type = type_deref(o->type);
  8338. break;
  8339. case Type_DynamicArray:
  8340. valid = true;
  8341. o->type = alloc_type_slice(t->DynamicArray.elem);
  8342. break;
  8343. case Type_Struct:
  8344. if (is_type_soa_struct(t)) {
  8345. valid = true;
  8346. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  8347. }
  8348. break;
  8349. case Type_RelativeSlice:
  8350. valid = true;
  8351. o->type = t->RelativeSlice.slice_type;
  8352. if (o->mode != Addressing_Variable) {
  8353. gbString str = expr_to_string(node);
  8354. error(node, "Cannot relative slice '%s', as value is not addressable", str);
  8355. gb_string_free(str);
  8356. o->mode = Addressing_Invalid;
  8357. o->expr = node;
  8358. return kind;
  8359. }
  8360. break;
  8361. case Type_EnumeratedArray:
  8362. {
  8363. gbString str = expr_to_string(o->expr);
  8364. gbString type_str = type_to_string(o->type);
  8365. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  8366. gb_string_free(type_str);
  8367. gb_string_free(str);
  8368. o->mode = Addressing_Invalid;
  8369. o->expr = node;
  8370. return kind;
  8371. }
  8372. break;
  8373. }
  8374. if (!valid) {
  8375. gbString str = expr_to_string(o->expr);
  8376. gbString type_str = type_to_string(o->type);
  8377. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  8378. gb_string_free(type_str);
  8379. gb_string_free(str);
  8380. o->mode = Addressing_Invalid;
  8381. o->expr = node;
  8382. return kind;
  8383. }
  8384. if (se->low == nullptr && se->high != nullptr) {
  8385. // It is okay to continue as it will assume the 1st index is zero
  8386. }
  8387. i64 indices[2] = {};
  8388. Ast *nodes[2] = {se->low, se->high};
  8389. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8390. i64 index = max_count;
  8391. if (nodes[i] != nullptr) {
  8392. i64 capacity = -1;
  8393. if (max_count >= 0) {
  8394. capacity = max_count;
  8395. }
  8396. i64 j = 0;
  8397. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  8398. index = j;
  8399. }
  8400. node->viral_state_flags |= nodes[i]->viral_state_flags;
  8401. } else if (i == 0) {
  8402. index = 0;
  8403. }
  8404. indices[i] = index;
  8405. }
  8406. for (isize i = 0; i < gb_count_of(indices); i++) {
  8407. i64 a = indices[i];
  8408. for (isize j = i+1; j < gb_count_of(indices); j++) {
  8409. i64 b = indices[j];
  8410. if (a > b && b >= 0) {
  8411. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  8412. }
  8413. }
  8414. }
  8415. if (max_count < 0) {
  8416. if (o->mode == Addressing_Constant) {
  8417. gbString s = expr_to_string(se->expr);
  8418. error(se->expr, "Cannot slice constant value '%s'", s);
  8419. gb_string_free(s);
  8420. }
  8421. }
  8422. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  8423. /*
  8424. x[:] -> [^]T
  8425. x[i:] -> [^]T
  8426. x[:n] -> []T
  8427. x[i:n] -> []T
  8428. */
  8429. o->type = alloc_type_slice(t->MultiPointer.elem);
  8430. }
  8431. o->mode = Addressing_Value;
  8432. if (is_type_string(t) && max_count >= 0) {
  8433. bool all_constant = true;
  8434. for (isize i = 0; i < gb_count_of(nodes); i++) {
  8435. if (nodes[i] != nullptr) {
  8436. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  8437. if (tav.mode != Addressing_Constant) {
  8438. all_constant = false;
  8439. break;
  8440. }
  8441. }
  8442. }
  8443. if (!all_constant) {
  8444. gbString str = expr_to_string(o->expr);
  8445. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  8446. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  8447. gb_string_free(str);
  8448. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  8449. o->expr = node;
  8450. return kind;
  8451. }
  8452. String s = {};
  8453. if (o->value.kind == ExactValue_String) {
  8454. s = o->value.value_string;
  8455. }
  8456. o->mode = Addressing_Constant;
  8457. o->type = t;
  8458. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  8459. }
  8460. return kind;
  8461. }
  8462. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8463. u32 prev_state_flags = c->state_flags;
  8464. defer (c->state_flags = prev_state_flags);
  8465. if (node->state_flags != 0) {
  8466. u32 in = node->state_flags;
  8467. u32 out = c->state_flags;
  8468. if (in & StateFlag_no_bounds_check) {
  8469. out |= StateFlag_no_bounds_check;
  8470. out &= ~StateFlag_bounds_check;
  8471. } else if (in & StateFlag_bounds_check) {
  8472. out |= StateFlag_bounds_check;
  8473. out &= ~StateFlag_no_bounds_check;
  8474. }
  8475. if (in & StateFlag_no_type_assert) {
  8476. out |= StateFlag_no_type_assert;
  8477. out &= ~StateFlag_type_assert;
  8478. } else if (in & StateFlag_type_assert) {
  8479. out |= StateFlag_type_assert;
  8480. out &= ~StateFlag_no_type_assert;
  8481. }
  8482. c->state_flags = out;
  8483. }
  8484. ExprKind kind = Expr_Stmt;
  8485. o->mode = Addressing_Invalid;
  8486. o->type = t_invalid;
  8487. o->value = {ExactValue_Invalid};
  8488. switch (node->kind) {
  8489. default:
  8490. return kind;
  8491. case_ast_node(be, BadExpr, node)
  8492. return kind;
  8493. case_end;
  8494. case_ast_node(i, Implicit, node)
  8495. switch (i->kind) {
  8496. case Token_context:
  8497. {
  8498. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  8499. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  8500. return kind;
  8501. }
  8502. if (unparen_expr(c->assignment_lhs_hint) == node) {
  8503. c->scope->flags |= ScopeFlag_ContextDefined;
  8504. }
  8505. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  8506. error(node, "'context' has not been defined within this scope");
  8507. // Continue with value
  8508. }
  8509. init_core_context(c->checker);
  8510. o->mode = Addressing_Context;
  8511. o->type = t_context;
  8512. }
  8513. break;
  8514. default:
  8515. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  8516. return kind;
  8517. }
  8518. case_end;
  8519. case_ast_node(i, Ident, node);
  8520. check_ident(c, o, node, nullptr, type_hint, false);
  8521. case_end;
  8522. case_ast_node(u, Uninit, node);
  8523. o->mode = Addressing_Value;
  8524. o->type = t_untyped_uninit;
  8525. error(node, "Use of --- outside of variable declaration");
  8526. case_end;
  8527. case_ast_node(bl, BasicLit, node);
  8528. Type *t = t_invalid;
  8529. switch (node->tav.value.kind) {
  8530. case ExactValue_String: t = t_untyped_string; break;
  8531. case ExactValue_Float: t = t_untyped_float; break;
  8532. case ExactValue_Complex: t = t_untyped_complex; break;
  8533. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  8534. case ExactValue_Integer:
  8535. t = t_untyped_integer;
  8536. if (bl->token.kind == Token_Rune) {
  8537. t = t_untyped_rune;
  8538. }
  8539. break;
  8540. default:
  8541. GB_PANIC("Unhandled value type for basic literal");
  8542. break;
  8543. }
  8544. o->mode = Addressing_Constant;
  8545. o->type = t;
  8546. o->value = node->tav.value;
  8547. case_end;
  8548. case_ast_node(bd, BasicDirective, node);
  8549. kind = check_basic_directive_expr(c, o, node, type_hint);
  8550. case_end;
  8551. case_ast_node(pg, ProcGroup, node);
  8552. error(node, "Illegal use of a procedure group");
  8553. o->mode = Addressing_Invalid;
  8554. case_end;
  8555. case_ast_node(pl, ProcLit, node);
  8556. CheckerContext ctx = *c;
  8557. DeclInfo *decl = nullptr;
  8558. Type *type = alloc_type(Type_Proc);
  8559. check_open_scope(&ctx, pl->type);
  8560. {
  8561. decl = make_decl_info(ctx.scope, ctx.decl);
  8562. decl->proc_lit = node;
  8563. ctx.decl = decl;
  8564. defer (ctx.decl = ctx.decl->parent);
  8565. if (pl->tags != 0) {
  8566. error(node, "A procedure literal cannot have tags");
  8567. pl->tags = 0; // TODO(bill): Should I zero this?!
  8568. }
  8569. check_procedure_type(&ctx, type, pl->type);
  8570. if (!is_type_proc(type)) {
  8571. gbString str = expr_to_string(node);
  8572. error(node, "Invalid procedure literal '%s'", str);
  8573. gb_string_free(str);
  8574. check_close_scope(&ctx);
  8575. return kind;
  8576. }
  8577. if (pl->body == nullptr) {
  8578. error(node, "A procedure literal must have a body");
  8579. return kind;
  8580. }
  8581. pl->decl = decl;
  8582. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  8583. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  8584. array_add(&ctx.checker->nested_proc_lits, decl);
  8585. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  8586. }
  8587. check_close_scope(&ctx);
  8588. o->mode = Addressing_Value;
  8589. o->type = type;
  8590. case_end;
  8591. case_ast_node(te, TernaryIfExpr, node);
  8592. kind = check_ternary_if_expr(c, o, node, type_hint);
  8593. case_end;
  8594. case_ast_node(te, TernaryWhenExpr, node);
  8595. kind = check_ternary_when_expr(c, o, node, type_hint);
  8596. case_end;
  8597. case_ast_node(oe, OrElseExpr, node);
  8598. return check_or_else_expr(c, o, node, type_hint);
  8599. case_end;
  8600. case_ast_node(re, OrReturnExpr, node);
  8601. return check_or_return_expr(c, o, node, type_hint);
  8602. case_end;
  8603. case_ast_node(cl, CompoundLit, node);
  8604. kind = check_compound_literal(c, o, node, type_hint);
  8605. case_end;
  8606. case_ast_node(pe, ParenExpr, node);
  8607. kind = check_expr_base(c, o, pe->expr, type_hint);
  8608. node->viral_state_flags |= pe->expr->viral_state_flags;
  8609. o->expr = node;
  8610. case_end;
  8611. case_ast_node(te, TagExpr, node);
  8612. String name = te->name.string;
  8613. error(node, "Unknown tag expression, #%.*s", LIT(name));
  8614. if (te->expr) {
  8615. kind = check_expr_base(c, o, te->expr, type_hint);
  8616. node->viral_state_flags |= te->expr->viral_state_flags;
  8617. }
  8618. o->expr = node;
  8619. case_end;
  8620. case_ast_node(ta, TypeAssertion, node);
  8621. kind = check_type_assertion(c, o, node, type_hint);
  8622. case_end;
  8623. case_ast_node(tc, TypeCast, node);
  8624. check_expr_or_type(c, o, tc->type);
  8625. if (o->mode != Addressing_Type) {
  8626. gbString str = expr_to_string(tc->type);
  8627. error(tc->type, "Expected a type, got %s", str);
  8628. gb_string_free(str);
  8629. o->mode = Addressing_Invalid;
  8630. }
  8631. if (o->mode == Addressing_Invalid) {
  8632. o->expr = node;
  8633. return kind;
  8634. }
  8635. Type *type = o->type;
  8636. check_expr_base(c, o, tc->expr, type);
  8637. node->viral_state_flags |= tc->expr->viral_state_flags;
  8638. if (o->mode != Addressing_Invalid) {
  8639. switch (tc->token.kind) {
  8640. case Token_transmute:
  8641. check_transmute(c, node, o, type);
  8642. break;
  8643. case Token_cast:
  8644. check_cast(c, o, type);
  8645. break;
  8646. default:
  8647. error(node, "Invalid AST: Invalid casting expression");
  8648. o->mode = Addressing_Invalid;
  8649. break;
  8650. }
  8651. }
  8652. return Expr_Expr;
  8653. case_end;
  8654. case_ast_node(ac, AutoCast, node);
  8655. check_expr_base(c, o, ac->expr, type_hint);
  8656. node->viral_state_flags |= ac->expr->viral_state_flags;
  8657. if (o->mode == Addressing_Invalid) {
  8658. o->expr = node;
  8659. return kind;
  8660. }
  8661. if (type_hint) {
  8662. Type *type = type_of_expr(ac->expr);
  8663. check_cast(c, o, type_hint);
  8664. if (is_type_typed(type) && are_types_identical(type, type_hint)) {
  8665. if (build_context.vet_extra) {
  8666. error(node, "Redundant 'auto_cast' applied to expression");
  8667. }
  8668. }
  8669. }
  8670. o->expr = node;
  8671. return Expr_Expr;
  8672. case_end;
  8673. case_ast_node(ue, UnaryExpr, node);
  8674. Type *th = type_hint;
  8675. if (ue->op.kind == Token_And) {
  8676. th = type_deref(th);
  8677. }
  8678. check_expr_base(c, o, ue->expr, th);
  8679. node->viral_state_flags |= ue->expr->viral_state_flags;
  8680. if (o->mode != Addressing_Invalid) {
  8681. check_unary_expr(c, o, ue->op, node);
  8682. }
  8683. o->expr = node;
  8684. return Expr_Expr;
  8685. case_end;
  8686. case_ast_node(be, BinaryExpr, node);
  8687. check_binary_expr(c, o, node, type_hint, true);
  8688. if (o->mode == Addressing_Invalid) {
  8689. o->expr = node;
  8690. return kind;
  8691. }
  8692. case_end;
  8693. case_ast_node(se, SelectorExpr, node);
  8694. check_selector(c, o, node, type_hint);
  8695. node->viral_state_flags |= se->expr->viral_state_flags;
  8696. case_end;
  8697. case_ast_node(se, SelectorCallExpr, node);
  8698. return check_selector_call_expr(c, o, node, type_hint);
  8699. case_end;
  8700. case_ast_node(ise, ImplicitSelectorExpr, node);
  8701. return check_implicit_selector_expr(c, o, node, type_hint);
  8702. case_end;
  8703. case_ast_node(ie, IndexExpr, node);
  8704. kind = check_index_expr(c, o, node, type_hint);
  8705. case_end;
  8706. case_ast_node(se, SliceExpr, node);
  8707. kind = check_slice_expr(c, o, node, type_hint);
  8708. case_end;
  8709. case_ast_node(mie, MatrixIndexExpr, node);
  8710. check_matrix_index_expr(c, o, node, type_hint);
  8711. o->expr = node;
  8712. return Expr_Expr;
  8713. case_end;
  8714. case_ast_node(ce, CallExpr, node);
  8715. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  8716. case_end;
  8717. case_ast_node(de, DerefExpr, node);
  8718. check_expr_or_type(c, o, de->expr);
  8719. node->viral_state_flags |= de->expr->viral_state_flags;
  8720. if (o->mode == Addressing_Invalid) {
  8721. o->mode = Addressing_Invalid;
  8722. o->expr = node;
  8723. return kind;
  8724. } else {
  8725. Type *t = base_type(o->type);
  8726. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  8727. o->mode = Addressing_Variable;
  8728. o->type = t->Pointer.elem;
  8729. } else if (t->kind == Type_SoaPointer) {
  8730. o->mode = Addressing_SoaVariable;
  8731. o->type = type_deref(t);
  8732. } else if (t->kind == Type_RelativePointer) {
  8733. if (o->mode != Addressing_Variable) {
  8734. gbString str = expr_to_string(o->expr);
  8735. gbString typ = type_to_string(o->type);
  8736. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  8737. gb_string_free(typ);
  8738. gb_string_free(str);
  8739. }
  8740. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  8741. add_type_info_type(c, o->type);
  8742. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  8743. GB_ASSERT(ptr_type->kind == Type_Pointer);
  8744. o->mode = Addressing_Variable;
  8745. o->type = ptr_type->Pointer.elem;
  8746. } else {
  8747. gbString str = expr_to_string(o->expr);
  8748. gbString typ = type_to_string(o->type);
  8749. begin_error_block();
  8750. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  8751. if (o->type && is_type_multi_pointer(o->type)) {
  8752. error_line("\tDid you mean '%s[0]'?\n", str);
  8753. }
  8754. end_error_block();
  8755. gb_string_free(typ);
  8756. gb_string_free(str);
  8757. o->mode = Addressing_Invalid;
  8758. o->expr = node;
  8759. return kind;
  8760. }
  8761. }
  8762. case_end;
  8763. case_ast_node(ia, InlineAsmExpr, node);
  8764. if (c->curr_proc_decl == nullptr) {
  8765. error(node, "Inline asm expressions are only allowed within a procedure body");
  8766. }
  8767. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  8768. Type *return_type = nullptr;
  8769. for_array(i, ia->param_types) {
  8770. param_types[i] = check_type(c, ia->param_types[i]);
  8771. }
  8772. if (ia->return_type != nullptr) {
  8773. return_type = check_type(c, ia->return_type);
  8774. }
  8775. Operand x = {};
  8776. check_expr(c, &x, ia->asm_string);
  8777. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  8778. error(x.expr, "Expected a constant string for the inline asm main parameter");
  8779. }
  8780. check_expr(c, &x, ia->constraints_string);
  8781. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  8782. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  8783. }
  8784. Scope *scope = create_scope(c->info, c->scope);
  8785. scope->flags |= ScopeFlag_Proc;
  8786. Type *params = alloc_type_tuple();
  8787. Type *results = alloc_type_tuple();
  8788. if (param_types.count != 0) {
  8789. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  8790. for_array(i, param_types) {
  8791. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  8792. }
  8793. }
  8794. if (return_type != nullptr) {
  8795. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  8796. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  8797. }
  8798. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  8799. o->type = pt;
  8800. o->mode = Addressing_Value;
  8801. o->expr = node;
  8802. return Expr_Expr;
  8803. case_end;
  8804. case Ast_TypeidType:
  8805. case Ast_PolyType:
  8806. case Ast_ProcType:
  8807. case Ast_PointerType:
  8808. case Ast_MultiPointerType:
  8809. case Ast_ArrayType:
  8810. case Ast_DynamicArrayType:
  8811. case Ast_StructType:
  8812. case Ast_UnionType:
  8813. case Ast_EnumType:
  8814. case Ast_MapType:
  8815. case Ast_BitSetType:
  8816. case Ast_MatrixType:
  8817. case Ast_RelativeType:
  8818. o->mode = Addressing_Type;
  8819. o->type = check_type(c, node);
  8820. break;
  8821. }
  8822. kind = Expr_Expr;
  8823. o->expr = node;
  8824. return kind;
  8825. }
  8826. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8827. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  8828. if (o->type != nullptr && core_type(o->type) == nullptr) {
  8829. o->type = t_invalid;
  8830. gbString xs = expr_to_string(o->expr);
  8831. if (o->mode == Addressing_Type) {
  8832. error(o->expr, "Invalid type usage '%s'", xs);
  8833. } else {
  8834. error(o->expr, "Invalid expression '%s'", xs);
  8835. }
  8836. gb_string_free(xs);
  8837. }
  8838. if (o->type != nullptr && is_type_untyped(o->type)) {
  8839. add_untyped(c, node, o->mode, o->type, o->value);
  8840. }
  8841. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  8842. add_type_and_value(c, node, o->mode, o->type, o->value);
  8843. return kind;
  8844. }
  8845. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  8846. check_expr_base(c, o, e, nullptr);
  8847. switch (o->mode) {
  8848. default:
  8849. return; // NOTE(bill): Valid
  8850. case Addressing_NoValue:
  8851. error_operand_no_value(o);
  8852. break;
  8853. }
  8854. o->mode = Addressing_Invalid;
  8855. }
  8856. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  8857. check_expr_base(c, o, e, nullptr);
  8858. switch (o->mode) {
  8859. default:
  8860. return; // NOTE(bill): Valid
  8861. case Addressing_NoValue:
  8862. error_operand_no_value(o);
  8863. break;
  8864. case Addressing_Type:
  8865. error_operand_not_expression(o);
  8866. break;
  8867. }
  8868. o->mode = Addressing_Invalid;
  8869. }
  8870. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  8871. check_expr_base(c, o, e, type_hint);
  8872. switch (o->mode) {
  8873. default:
  8874. return; // NOTE(bill): Valid
  8875. case Addressing_NoValue:
  8876. error_operand_no_value(o);
  8877. break;
  8878. case Addressing_Type:
  8879. error_operand_not_expression(o);
  8880. break;
  8881. }
  8882. o->mode = Addressing_Invalid;
  8883. }
  8884. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  8885. if (o->mode == Addressing_Value) {
  8886. // NOTE(bill): Tuples are not first class thus never named
  8887. if (o->type->kind == Type_Tuple) {
  8888. isize count = o->type->Tuple.variables.count;
  8889. error(o->expr,
  8890. "%td-valued expression found where single value expected", count);
  8891. o->mode = Addressing_Invalid;
  8892. GB_ASSERT(count != 1);
  8893. }
  8894. }
  8895. }
  8896. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  8897. check_multi_expr(c, o, e);
  8898. check_not_tuple(c, o);
  8899. }
  8900. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  8901. check_expr_base(c, o, e, type_hint);
  8902. check_not_tuple(c, o);
  8903. error_operand_no_value(o);
  8904. }
  8905. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  8906. switch (v.kind) {
  8907. case ExactValue_Invalid:
  8908. return true;
  8909. case ExactValue_Bool:
  8910. return !v.value_bool;
  8911. case ExactValue_String:
  8912. return v.value_string.len == 0;
  8913. case ExactValue_Integer:
  8914. return big_int_is_zero(&v.value_integer);
  8915. case ExactValue_Float:
  8916. return v.value_float == 0.0;
  8917. case ExactValue_Complex:
  8918. if (v.value_complex) {
  8919. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  8920. }
  8921. return true;
  8922. case ExactValue_Quaternion:
  8923. if (v.value_quaternion) {
  8924. return v.value_quaternion->real == 0.0 &&
  8925. v.value_quaternion->imag == 0.0 &&
  8926. v.value_quaternion->jmag == 0.0 &&
  8927. v.value_quaternion->kmag == 0.0;
  8928. }
  8929. return true;
  8930. case ExactValue_Pointer:
  8931. return v.value_pointer == 0;
  8932. case ExactValue_Compound:
  8933. if (v.value_compound == nullptr) {
  8934. return true;
  8935. } else {
  8936. ast_node(cl, CompoundLit, v.value_compound);
  8937. if (cl->elems.count == 0) {
  8938. return true;
  8939. } else {
  8940. for (Ast *elem : cl->elems) {
  8941. if (elem->tav.mode != Addressing_Constant) {
  8942. return false;
  8943. }
  8944. if (!is_exact_value_zero(elem->tav.value)) {
  8945. return false;
  8946. }
  8947. }
  8948. return true;
  8949. }
  8950. }
  8951. case ExactValue_Procedure:
  8952. return v.value_procedure == nullptr;
  8953. case ExactValue_Typeid:
  8954. return v.value_typeid == nullptr;
  8955. }
  8956. return true;
  8957. }
  8958. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  8959. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  8960. for_array(i, params) {
  8961. if (i > 0) {
  8962. str = gb_string_appendc(str, ", ");
  8963. }
  8964. str = write_expr_to_string(str, params[i], false);
  8965. }
  8966. return str;
  8967. }
  8968. gb_internal gbString string_append_string(gbString str, String string) {
  8969. if (string.len > 0) {
  8970. return gb_string_append_length(str, &string[0], string.len);
  8971. }
  8972. return str;
  8973. }
  8974. gb_internal gbString string_append_token(gbString str, Token token) {
  8975. str = string_append_string(str, token.string);
  8976. return str;
  8977. }
  8978. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  8979. if (node == nullptr)
  8980. return str;
  8981. if (is_ast_stmt(node)) {
  8982. GB_ASSERT("stmt passed to write_expr_to_string");
  8983. }
  8984. switch (node->kind) {
  8985. default:
  8986. str = gb_string_appendc(str, "(BadExpr)");
  8987. break;
  8988. case_ast_node(i, Ident, node);
  8989. str = string_append_token(str, i->token);
  8990. case_end;
  8991. case_ast_node(i, Implicit, node);
  8992. str = string_append_token(str, *i);
  8993. case_end;
  8994. case_ast_node(bl, BasicLit, node);
  8995. str = string_append_token(str, bl->token);
  8996. case_end;
  8997. case_ast_node(bd, BasicDirective, node);
  8998. str = gb_string_append_rune(str, '#');
  8999. str = string_append_string(str, bd->name.string);
  9000. case_end;
  9001. case_ast_node(ud, Uninit, node);
  9002. str = gb_string_appendc(str, "---");
  9003. case_end;
  9004. case_ast_node(pg, ProcGroup, node);
  9005. str = gb_string_appendc(str, "proc{");
  9006. for_array(i, pg->args) {
  9007. if (i > 0) str = gb_string_appendc(str, ", ");
  9008. str = write_expr_to_string(str, pg->args[i], shorthand);
  9009. }
  9010. str = gb_string_append_rune(str, '}');
  9011. case_end;
  9012. case_ast_node(pl, ProcLit, node);
  9013. str = write_expr_to_string(str, pl->type, shorthand);
  9014. if (pl->body) {
  9015. str = gb_string_appendc(str, " {...}");
  9016. } else {
  9017. str = gb_string_appendc(str, " ---");
  9018. }
  9019. case_end;
  9020. case_ast_node(cl, CompoundLit, node);
  9021. str = write_expr_to_string(str, cl->type, shorthand);
  9022. str = gb_string_append_rune(str, '{');
  9023. if (shorthand) {
  9024. str = gb_string_appendc(str, "...");
  9025. } else {
  9026. for_array(i, cl->elems) {
  9027. if (i > 0) str = gb_string_appendc(str, ", ");
  9028. str = write_expr_to_string(str, cl->elems[i], shorthand);
  9029. }
  9030. }
  9031. str = gb_string_append_rune(str, '}');
  9032. case_end;
  9033. case_ast_node(te, TagExpr, node);
  9034. str = gb_string_append_rune(str, '#');
  9035. str = string_append_token(str, te->name);
  9036. str = write_expr_to_string(str, te->expr, shorthand);
  9037. case_end;
  9038. case_ast_node(ue, UnaryExpr, node);
  9039. str = string_append_token(str, ue->op);
  9040. str = write_expr_to_string(str, ue->expr, shorthand);
  9041. case_end;
  9042. case_ast_node(de, DerefExpr, node);
  9043. str = write_expr_to_string(str, de->expr, shorthand);
  9044. str = gb_string_append_rune(str, '^');
  9045. case_end;
  9046. case_ast_node(be, BinaryExpr, node);
  9047. str = write_expr_to_string(str, be->left, shorthand);
  9048. str = gb_string_append_rune(str, ' ');
  9049. str = string_append_token(str, be->op);
  9050. str = gb_string_append_rune(str, ' ');
  9051. str = write_expr_to_string(str, be->right, shorthand);
  9052. case_end;
  9053. case_ast_node(te, TernaryIfExpr, node);
  9054. TokenPos x = ast_token(te->x).pos;
  9055. TokenPos cond = ast_token(te->cond).pos;
  9056. if (x < cond) {
  9057. str = write_expr_to_string(str, te->x, shorthand);
  9058. str = gb_string_appendc(str, " if ");
  9059. str = write_expr_to_string(str, te->cond, shorthand);
  9060. str = gb_string_appendc(str, " else ");
  9061. str = write_expr_to_string(str, te->y, shorthand);
  9062. } else {
  9063. str = write_expr_to_string(str, te->cond, shorthand);
  9064. str = gb_string_appendc(str, " ? ");
  9065. str = write_expr_to_string(str, te->x, shorthand);
  9066. str = gb_string_appendc(str, " : ");
  9067. str = write_expr_to_string(str, te->y, shorthand);
  9068. }
  9069. case_end;
  9070. case_ast_node(te, TernaryWhenExpr, node);
  9071. str = write_expr_to_string(str, te->x, shorthand);
  9072. str = gb_string_appendc(str, " when ");
  9073. str = write_expr_to_string(str, te->cond, shorthand);
  9074. str = gb_string_appendc(str, " else ");
  9075. str = write_expr_to_string(str, te->y, shorthand);
  9076. case_end;
  9077. case_ast_node(oe, OrElseExpr, node);
  9078. str = write_expr_to_string(str, oe->x, shorthand);
  9079. str = gb_string_appendc(str, " or_else ");
  9080. str = write_expr_to_string(str, oe->y, shorthand);
  9081. case_end;
  9082. case_ast_node(oe, OrReturnExpr, node);
  9083. str = write_expr_to_string(str, oe->expr, shorthand);
  9084. str = gb_string_appendc(str, " or_return");
  9085. case_end;
  9086. case_ast_node(pe, ParenExpr, node);
  9087. str = gb_string_append_rune(str, '(');
  9088. str = write_expr_to_string(str, pe->expr, shorthand);
  9089. str = gb_string_append_rune(str, ')');
  9090. case_end;
  9091. case_ast_node(se, SelectorExpr, node);
  9092. str = write_expr_to_string(str, se->expr, shorthand);
  9093. str = string_append_token(str, se->token);
  9094. str = write_expr_to_string(str, se->selector, shorthand);
  9095. case_end;
  9096. case_ast_node(se, ImplicitSelectorExpr, node);
  9097. str = gb_string_append_rune(str, '.');
  9098. str = write_expr_to_string(str, se->selector, shorthand);
  9099. case_end;
  9100. case_ast_node(se, SelectorCallExpr, node);
  9101. str = write_expr_to_string(str, se->expr, shorthand);
  9102. str = gb_string_appendc(str, "(");
  9103. ast_node(ce, CallExpr, se->call);
  9104. isize start = se->modified_call ? 1 : 0;
  9105. for (isize i = start; i < ce->args.count; i++) {
  9106. Ast *arg = ce->args[i];
  9107. if (i > start) {
  9108. str = gb_string_appendc(str, ", ");
  9109. }
  9110. str = write_expr_to_string(str, arg, shorthand);
  9111. }
  9112. str = gb_string_appendc(str, ")");
  9113. case_end;
  9114. case_ast_node(ta, TypeAssertion, node);
  9115. str = write_expr_to_string(str, ta->expr, shorthand);
  9116. if (ta->type != nullptr &&
  9117. ta->type->kind == Ast_UnaryExpr &&
  9118. ta->type->UnaryExpr.op.kind == Token_Question) {
  9119. str = gb_string_appendc(str, ".?");
  9120. } else {
  9121. str = gb_string_appendc(str, ".(");
  9122. str = write_expr_to_string(str, ta->type, shorthand);
  9123. str = gb_string_append_rune(str, ')');
  9124. }
  9125. case_end;
  9126. case_ast_node(tc, TypeCast, node);
  9127. str = string_append_token(str, tc->token);
  9128. str = gb_string_append_rune(str, '(');
  9129. str = write_expr_to_string(str, tc->type, shorthand);
  9130. str = gb_string_append_rune(str, ')');
  9131. str = write_expr_to_string(str, tc->expr, shorthand);
  9132. case_end;
  9133. case_ast_node(ac, AutoCast, node);
  9134. str = string_append_token(str, ac->token);
  9135. str = gb_string_append_rune(str, ' ');
  9136. str = write_expr_to_string(str, ac->expr, shorthand);
  9137. case_end;
  9138. case_ast_node(ie, IndexExpr, node);
  9139. str = write_expr_to_string(str, ie->expr, shorthand);
  9140. str = gb_string_append_rune(str, '[');
  9141. str = write_expr_to_string(str, ie->index, shorthand);
  9142. str = gb_string_append_rune(str, ']');
  9143. case_end;
  9144. case_ast_node(se, SliceExpr, node);
  9145. str = write_expr_to_string(str, se->expr, shorthand);
  9146. str = gb_string_append_rune(str, '[');
  9147. str = write_expr_to_string(str, se->low, shorthand);
  9148. str = string_append_token(str, se->interval);
  9149. str = write_expr_to_string(str, se->high, shorthand);
  9150. str = gb_string_append_rune(str, ']');
  9151. case_end;
  9152. case_ast_node(mie, MatrixIndexExpr, node);
  9153. str = write_expr_to_string(str, mie->expr, shorthand);
  9154. str = gb_string_append_rune(str, '[');
  9155. str = write_expr_to_string(str, mie->row_index, shorthand);
  9156. str = gb_string_appendc(str, ", ");
  9157. str = write_expr_to_string(str, mie->column_index, shorthand);
  9158. str = gb_string_append_rune(str, ']');
  9159. case_end;
  9160. case_ast_node(e, Ellipsis, node);
  9161. str = gb_string_appendc(str, "..");
  9162. str = write_expr_to_string(str, e->expr, shorthand);
  9163. case_end;
  9164. case_ast_node(fv, FieldValue, node);
  9165. str = write_expr_to_string(str, fv->field, shorthand);
  9166. str = gb_string_appendc(str, " = ");
  9167. str = write_expr_to_string(str, fv->value, shorthand);
  9168. case_end;
  9169. case_ast_node(fv, EnumFieldValue, node);
  9170. str = write_expr_to_string(str, fv->name, shorthand);
  9171. if (fv->value) {
  9172. str = gb_string_appendc(str, " = ");
  9173. str = write_expr_to_string(str, fv->value, shorthand);
  9174. }
  9175. case_end;
  9176. case_ast_node(ht, HelperType, node);
  9177. str = gb_string_appendc(str, "#type ");
  9178. str = write_expr_to_string(str, ht->type, shorthand);
  9179. case_end;
  9180. case_ast_node(ht, DistinctType, node);
  9181. str = gb_string_appendc(str, "distinct ");
  9182. str = write_expr_to_string(str, ht->type, shorthand);
  9183. case_end;
  9184. case_ast_node(pt, PolyType, node);
  9185. str = gb_string_append_rune(str, '$');
  9186. str = write_expr_to_string(str, pt->type, shorthand);
  9187. if (pt->specialization != nullptr) {
  9188. str = gb_string_append_rune(str, '/');
  9189. str = write_expr_to_string(str, pt->specialization, shorthand);
  9190. }
  9191. case_end;
  9192. case_ast_node(pt, PointerType, node);
  9193. str = gb_string_append_rune(str, '^');
  9194. str = write_expr_to_string(str, pt->type, shorthand);
  9195. case_end;
  9196. case_ast_node(pt, MultiPointerType, node);
  9197. str = gb_string_appendc(str, "[^]");
  9198. str = write_expr_to_string(str, pt->type, shorthand);
  9199. case_end;
  9200. case_ast_node(at, ArrayType, node);
  9201. str = gb_string_append_rune(str, '[');
  9202. if (at->count != nullptr &&
  9203. at->count->kind == Ast_UnaryExpr &&
  9204. at->count->UnaryExpr.op.kind == Token_Question) {
  9205. str = gb_string_appendc(str, "?");
  9206. } else {
  9207. str = write_expr_to_string(str, at->count, shorthand);
  9208. }
  9209. str = gb_string_append_rune(str, ']');
  9210. str = write_expr_to_string(str, at->elem, shorthand);
  9211. case_end;
  9212. case_ast_node(at, DynamicArrayType, node);
  9213. str = gb_string_appendc(str, "[dynamic]");
  9214. str = write_expr_to_string(str, at->elem, shorthand);
  9215. case_end;
  9216. case_ast_node(bs, BitSetType, node);
  9217. str = gb_string_appendc(str, "bit_set[");
  9218. str = write_expr_to_string(str, bs->elem, shorthand);
  9219. str = gb_string_appendc(str, "]");
  9220. case_end;
  9221. case_ast_node(mt, MapType, node);
  9222. str = gb_string_appendc(str, "map[");
  9223. str = write_expr_to_string(str, mt->key, shorthand);
  9224. str = gb_string_append_rune(str, ']');
  9225. str = write_expr_to_string(str, mt->value, shorthand);
  9226. case_end;
  9227. case_ast_node(mt, MatrixType, node);
  9228. str = gb_string_appendc(str, "matrix[");
  9229. str = write_expr_to_string(str, mt->row_count, shorthand);
  9230. str = gb_string_appendc(str, ", ");
  9231. str = write_expr_to_string(str, mt->column_count, shorthand);
  9232. str = gb_string_append_rune(str, ']');
  9233. str = write_expr_to_string(str, mt->elem, shorthand);
  9234. case_end;
  9235. case_ast_node(f, Field, node);
  9236. if (f->flags&FieldFlag_using) {
  9237. str = gb_string_appendc(str, "using ");
  9238. }
  9239. if (f->flags&FieldFlag_no_alias) {
  9240. str = gb_string_appendc(str, "#no_alias ");
  9241. }
  9242. if (f->flags&FieldFlag_c_vararg) {
  9243. str = gb_string_appendc(str, "#c_vararg ");
  9244. }
  9245. if (f->flags&FieldFlag_any_int) {
  9246. str = gb_string_appendc(str, "#any_int ");
  9247. }
  9248. if (f->flags&FieldFlag_const) {
  9249. str = gb_string_appendc(str, "#const ");
  9250. }
  9251. if (f->flags&FieldFlag_subtype) {
  9252. str = gb_string_appendc(str, "#subtype ");
  9253. }
  9254. for_array(i, f->names) {
  9255. Ast *name = f->names[i];
  9256. if (i > 0) str = gb_string_appendc(str, ", ");
  9257. str = write_expr_to_string(str, name, shorthand);
  9258. }
  9259. if (f->names.count > 0) {
  9260. if (f->type == nullptr && f->default_value != nullptr) {
  9261. str = gb_string_append_rune(str, ' ');
  9262. }
  9263. str = gb_string_appendc(str, ":");
  9264. }
  9265. if (f->type != nullptr) {
  9266. str = gb_string_append_rune(str, ' ');
  9267. str = write_expr_to_string(str, f->type, shorthand);
  9268. }
  9269. if (f->default_value != nullptr) {
  9270. if (f->type != nullptr) {
  9271. str = gb_string_append_rune(str, ' ');
  9272. }
  9273. str = gb_string_appendc(str, "= ");
  9274. str = write_expr_to_string(str, f->default_value, shorthand);
  9275. }
  9276. case_end;
  9277. case_ast_node(f, FieldList, node);
  9278. bool has_name = false;
  9279. for_array(i, f->list) {
  9280. ast_node(field, Field, f->list[i]);
  9281. if (field->names.count > 1) {
  9282. has_name = true;
  9283. break;
  9284. }
  9285. if (field->names.count == 0) {
  9286. continue;
  9287. }
  9288. if (!is_blank_ident(field->names[0])) {
  9289. has_name = true;
  9290. break;
  9291. }
  9292. }
  9293. for_array(i, f->list) {
  9294. if (i > 0) str = gb_string_appendc(str, ", ");
  9295. if (has_name) {
  9296. str = write_expr_to_string(str, f->list[i], shorthand);
  9297. } else {
  9298. ast_node(field, Field, f->list[i]);
  9299. if (field->flags&FieldFlag_using) {
  9300. str = gb_string_appendc(str, "using ");
  9301. }
  9302. if (field->flags&FieldFlag_no_alias) {
  9303. str = gb_string_appendc(str, "#no_alias ");
  9304. }
  9305. if (field->flags&FieldFlag_c_vararg) {
  9306. str = gb_string_appendc(str, "#c_vararg ");
  9307. }
  9308. str = write_expr_to_string(str, field->type, shorthand);
  9309. }
  9310. }
  9311. case_end;
  9312. case_ast_node(ce, CallExpr, node);
  9313. switch (ce->inlining) {
  9314. case ProcInlining_inline:
  9315. str = gb_string_appendc(str, "#force_inline ");
  9316. break;
  9317. case ProcInlining_no_inline:
  9318. str = gb_string_appendc(str, "#force_no_inline ");
  9319. break;
  9320. }
  9321. str = write_expr_to_string(str, ce->proc, shorthand);
  9322. str = gb_string_appendc(str, "(");
  9323. isize idx0 = cast(isize)ce->was_selector;
  9324. for (isize i = idx0; i < ce->args.count; i++) {
  9325. Ast *arg = ce->args[i];
  9326. if (i > idx0) {
  9327. str = gb_string_appendc(str, ", ");
  9328. }
  9329. str = write_expr_to_string(str, arg, shorthand);
  9330. }
  9331. str = gb_string_appendc(str, ")");
  9332. case_end;
  9333. case_ast_node(tt, TypeidType, node);
  9334. str = gb_string_appendc(str, "typeid");
  9335. if (tt->specialization) {
  9336. str = gb_string_appendc(str, "/");
  9337. str = write_expr_to_string(str, tt->specialization, shorthand);
  9338. }
  9339. case_end;
  9340. case_ast_node(pt, ProcType, node);
  9341. str = gb_string_appendc(str, "proc(");
  9342. str = write_expr_to_string(str, pt->params, shorthand);
  9343. str = gb_string_appendc(str, ")");
  9344. if (pt->results != nullptr) {
  9345. str = gb_string_appendc(str, " -> ");
  9346. bool parens_needed = false;
  9347. if (pt->results && pt->results->kind == Ast_FieldList) {
  9348. for (Ast *field : pt->results->FieldList.list) {
  9349. ast_node(f, Field, field);
  9350. if (f->names.count != 0) {
  9351. parens_needed = true;
  9352. break;
  9353. }
  9354. }
  9355. }
  9356. if (parens_needed) {
  9357. str = gb_string_append_rune(str, '(');
  9358. }
  9359. str = write_expr_to_string(str, pt->results, shorthand);
  9360. if (parens_needed) {
  9361. str = gb_string_append_rune(str, ')');
  9362. }
  9363. }
  9364. case_end;
  9365. case_ast_node(st, StructType, node);
  9366. str = gb_string_appendc(str, "struct ");
  9367. if (st->polymorphic_params) {
  9368. str = gb_string_append_rune(str, '(');
  9369. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9370. str = gb_string_appendc(str, ") ");
  9371. }
  9372. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  9373. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  9374. if (st->align) {
  9375. str = gb_string_appendc(str, "#align ");
  9376. str = write_expr_to_string(str, st->align, shorthand);
  9377. str = gb_string_append_rune(str, ' ');
  9378. }
  9379. str = gb_string_append_rune(str, '{');
  9380. if (shorthand) {
  9381. str = gb_string_appendc(str, "...");
  9382. } else {
  9383. str = write_struct_fields_to_string(str, st->fields);
  9384. }
  9385. str = gb_string_append_rune(str, '}');
  9386. case_end;
  9387. case_ast_node(st, UnionType, node);
  9388. str = gb_string_appendc(str, "union ");
  9389. if (st->polymorphic_params) {
  9390. str = gb_string_append_rune(str, '(');
  9391. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  9392. str = gb_string_appendc(str, ") ");
  9393. }
  9394. switch (st->kind) {
  9395. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  9396. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  9397. }
  9398. if (st->align) {
  9399. str = gb_string_appendc(str, "#align ");
  9400. str = write_expr_to_string(str, st->align, shorthand);
  9401. str = gb_string_append_rune(str, ' ');
  9402. }
  9403. str = gb_string_append_rune(str, '{');
  9404. if (shorthand) {
  9405. str = gb_string_appendc(str, "...");
  9406. } else {
  9407. str = write_struct_fields_to_string(str, st->variants);
  9408. }
  9409. str = gb_string_append_rune(str, '}');
  9410. case_end;
  9411. case_ast_node(et, EnumType, node);
  9412. str = gb_string_appendc(str, "enum ");
  9413. if (et->base_type != nullptr) {
  9414. str = write_expr_to_string(str, et->base_type, shorthand);
  9415. str = gb_string_append_rune(str, ' ');
  9416. }
  9417. str = gb_string_append_rune(str, '{');
  9418. if (shorthand) {
  9419. str = gb_string_appendc(str, "...");
  9420. } else {
  9421. for_array(i, et->fields) {
  9422. if (i > 0) {
  9423. str = gb_string_appendc(str, ", ");
  9424. }
  9425. str = write_expr_to_string(str, et->fields[i], shorthand);
  9426. }
  9427. }
  9428. str = gb_string_append_rune(str, '}');
  9429. case_end;
  9430. case_ast_node(rt, RelativeType, node);
  9431. str = write_expr_to_string(str, rt->tag, shorthand);
  9432. str = gb_string_appendc(str, "" );
  9433. str = write_expr_to_string(str, rt->type, shorthand);
  9434. case_end;
  9435. case_ast_node(ia, InlineAsmExpr, node);
  9436. str = gb_string_appendc(str, "asm(");
  9437. for_array(i, ia->param_types) {
  9438. if (i > 0) {
  9439. str = gb_string_appendc(str, ", ");
  9440. }
  9441. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  9442. }
  9443. str = gb_string_appendc(str, ")");
  9444. if (ia->return_type != nullptr) {
  9445. str = gb_string_appendc(str, " -> ");
  9446. str = write_expr_to_string(str, ia->return_type, shorthand);
  9447. }
  9448. if (ia->has_side_effects) {
  9449. str = gb_string_appendc(str, " #side_effects");
  9450. }
  9451. if (ia->is_align_stack) {
  9452. str = gb_string_appendc(str, " #stack_align");
  9453. }
  9454. if (ia->dialect) {
  9455. str = gb_string_appendc(str, " #");
  9456. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  9457. }
  9458. str = gb_string_appendc(str, " {");
  9459. if (shorthand) {
  9460. str = gb_string_appendc(str, "...");
  9461. } else {
  9462. str = write_expr_to_string(str, ia->asm_string, shorthand);
  9463. str = gb_string_appendc(str, ", ");
  9464. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  9465. }
  9466. str = gb_string_appendc(str, "}");
  9467. case_end;
  9468. }
  9469. return str;
  9470. }
  9471. gb_internal gbString expr_to_string(Ast *expression) {
  9472. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  9473. }
  9474. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  9475. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  9476. }
  9477. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  9478. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  9479. }