check_expr.cpp 287 KB

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