check_expr.cpp 272 KB

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