check_expr.cpp 272 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637
  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, base_entity->identifier.load());
  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, base_entity->identifier.load(), 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 *dst_elem = base_array_type(dst);
  561. i64 distance = check_distance_between_types(c, operand, dst_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_float(src) && is_type_quaternion(dst)) {
  2159. return true;
  2160. }
  2161. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2162. return true;
  2163. }
  2164. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2165. return true;
  2166. }
  2167. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2168. GB_ASSERT(src->kind == Type_Matrix);
  2169. GB_ASSERT(dst->kind == Type_Matrix);
  2170. Operand op = *operand;
  2171. op.type = src->Matrix.elem;
  2172. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2173. return false;
  2174. }
  2175. if (src->Matrix.row_count != src->Matrix.column_count) {
  2176. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2177. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2178. return src_count == dst_count;
  2179. }
  2180. return is_matrix_square(dst) && is_matrix_square(src);
  2181. }
  2182. // Cast between pointers
  2183. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2184. return true;
  2185. }
  2186. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2187. return true;
  2188. }
  2189. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2190. return true;
  2191. }
  2192. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2193. return true;
  2194. }
  2195. // uintptr <-> pointer
  2196. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2197. return true;
  2198. }
  2199. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2200. return true;
  2201. }
  2202. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2203. return true;
  2204. }
  2205. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2206. return true;
  2207. }
  2208. // []byte/[]u8 <-> string (not cstring)
  2209. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2210. return true;
  2211. }
  2212. // cstring -> string
  2213. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2214. if (operand->mode != Addressing_Constant) {
  2215. add_package_dependency(c, "runtime", "cstring_to_string");
  2216. }
  2217. return true;
  2218. }
  2219. // cstring -> ^u8
  2220. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2221. return !is_constant;
  2222. }
  2223. // cstring -> [^]u8
  2224. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2225. return !is_constant;
  2226. }
  2227. // cstring -> rawptr
  2228. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2229. return !is_constant;
  2230. }
  2231. // ^u8 -> cstring
  2232. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2233. return !is_constant;
  2234. }
  2235. // [^]u8 -> cstring
  2236. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2237. return !is_constant;
  2238. }
  2239. // rawptr -> cstring
  2240. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2241. return !is_constant;
  2242. }
  2243. // proc <-> proc
  2244. if (is_type_proc(src) && is_type_proc(dst)) {
  2245. return true;
  2246. }
  2247. // proc -> rawptr
  2248. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2249. return true;
  2250. }
  2251. // rawptr -> proc
  2252. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2253. return true;
  2254. }
  2255. return false;
  2256. }
  2257. bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2258. bool is_const_expr = x->mode == Addressing_Constant;
  2259. Type *bt = base_type(type);
  2260. if (is_const_expr && is_type_constant_type(bt)) {
  2261. if (core_type(bt)->kind == Type_Basic) {
  2262. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2263. return true;
  2264. } else if (check_is_castable_to(c, x, type)) {
  2265. if (is_type_pointer(type)) {
  2266. return true;
  2267. }
  2268. }
  2269. } else if (check_is_castable_to(c, x, type)) {
  2270. x->value = {};
  2271. x->mode = Addressing_Value;
  2272. return true;
  2273. }
  2274. } else if (check_is_castable_to(c, x, type)) {
  2275. if (x->mode != Addressing_Constant) {
  2276. x->mode = Addressing_Value;
  2277. } else if (is_type_slice(type) && is_type_string(x->type)) {
  2278. x->mode = Addressing_Value;
  2279. } else if (is_type_union(type)) {
  2280. x->mode = Addressing_Value;
  2281. }
  2282. if (x->mode == Addressing_Value) {
  2283. x->value = {};
  2284. }
  2285. return true;
  2286. }
  2287. return false;
  2288. }
  2289. void check_cast(CheckerContext *c, Operand *x, Type *type) {
  2290. if (!is_operand_value(*x)) {
  2291. error(x->expr, "Only values can be casted");
  2292. x->mode = Addressing_Invalid;
  2293. return;
  2294. }
  2295. bool is_const_expr = x->mode == Addressing_Constant;
  2296. bool can_convert = check_cast_internal(c, x, type);
  2297. if (!can_convert) {
  2298. gbString expr_str = expr_to_string(x->expr);
  2299. gbString to_type = type_to_string(type);
  2300. gbString from_type = type_to_string(x->type);
  2301. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  2302. gb_string_free(from_type);
  2303. gb_string_free(to_type);
  2304. gb_string_free(expr_str);
  2305. check_cast_error_suggestion(c, x, type);
  2306. x->mode = Addressing_Invalid;
  2307. return;
  2308. }
  2309. if (is_type_untyped(x->type)) {
  2310. Type *final_type = type;
  2311. if (is_const_expr && !is_type_constant_type(type)) {
  2312. final_type = default_type(x->type);
  2313. }
  2314. update_untyped_expr_type(c, x->expr, final_type, true);
  2315. }
  2316. if (build_context.vet_extra) {
  2317. if (are_types_identical(x->type, type)) {
  2318. gbString str = type_to_string(type);
  2319. warning(x->expr, "Unneeded cast to the same type '%s'", str);
  2320. gb_string_free(str);
  2321. }
  2322. }
  2323. x->type = type;
  2324. }
  2325. bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t) {
  2326. if (!is_operand_value(*o)) {
  2327. error(o->expr, "'transmute' can only be applied to values");
  2328. o->mode = Addressing_Invalid;
  2329. return false;
  2330. }
  2331. if (o->mode == Addressing_Constant) {
  2332. gbString expr_str = expr_to_string(o->expr);
  2333. error(o->expr, "Cannot transmute a constant expression: '%s'", expr_str);
  2334. gb_string_free(expr_str);
  2335. o->mode = Addressing_Invalid;
  2336. o->expr = node;
  2337. return false;
  2338. }
  2339. if (is_type_untyped(o->type)) {
  2340. gbString expr_str = expr_to_string(o->expr);
  2341. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  2342. gb_string_free(expr_str);
  2343. o->mode = Addressing_Invalid;
  2344. o->expr = node;
  2345. return false;
  2346. }
  2347. Type *dst_bt = base_type(t);
  2348. if (dst_bt == nullptr || dst_bt == t_invalid) {
  2349. GB_ASSERT(global_error_collector.count != 0);
  2350. o->mode = Addressing_Invalid;
  2351. o->expr = node;
  2352. return false;
  2353. }
  2354. Type *src_bt = base_type(o->type);
  2355. if (src_bt == nullptr || src_bt == t_invalid) {
  2356. // NOTE(bill): this should be an error
  2357. GB_ASSERT(global_error_collector.count != 0);
  2358. o->mode = Addressing_Value;
  2359. o->expr = node;
  2360. o->type = t;
  2361. return true;
  2362. }
  2363. i64 srcz = type_size_of(o->type);
  2364. i64 dstz = type_size_of(t);
  2365. if (srcz != dstz) {
  2366. gbString expr_str = expr_to_string(o->expr);
  2367. gbString type_str = type_to_string(t);
  2368. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  2369. gb_string_free(type_str);
  2370. gb_string_free(expr_str);
  2371. o->mode = Addressing_Invalid;
  2372. o->expr = node;
  2373. return false;
  2374. }
  2375. if (build_context.vet_extra) {
  2376. if (are_types_identical(o->type, t)) {
  2377. gbString str = type_to_string(t);
  2378. warning(o->expr, "Unneeded transmute to the same type '%s'", str);
  2379. gb_string_free(str);
  2380. }
  2381. }
  2382. o->mode = Addressing_Value;
  2383. o->type = t;
  2384. return true;
  2385. }
  2386. bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  2387. if (is_type_array(x->type) && !is_type_array(y->type)) {
  2388. if (check_is_assignable_to(c, y, x->type)) {
  2389. if (check_binary_op(c, x, op)) {
  2390. return true;
  2391. }
  2392. }
  2393. }
  2394. return false;
  2395. }
  2396. bool is_ise_expr(Ast *node) {
  2397. node = unparen_expr(node);
  2398. return node->kind == Ast_ImplicitSelectorExpr;
  2399. }
  2400. bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  2401. if (use_lhs_as_type_hint) { // RHS in this case
  2402. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  2403. }
  2404. return false;
  2405. }
  2406. Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  2407. Type *xt = base_type(matrix);
  2408. if (type_hint != nullptr) {
  2409. Type *th = base_type(type_hint);
  2410. if (are_types_identical(th, xt)) {
  2411. return type_hint;
  2412. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  2413. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  2414. // ignore
  2415. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  2416. return type_hint;
  2417. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  2418. return type_hint;
  2419. }
  2420. }
  2421. }
  2422. return matrix;
  2423. }
  2424. void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  2425. if (!check_binary_op(c, x, op)) {
  2426. x->mode = Addressing_Invalid;
  2427. return;
  2428. }
  2429. Type *xt = base_type(x->type);
  2430. Type *yt = base_type(y->type);
  2431. if (is_type_matrix(x->type)) {
  2432. GB_ASSERT(xt->kind == Type_Matrix);
  2433. if (op.kind == Token_Mul) {
  2434. if (yt->kind == Type_Matrix) {
  2435. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  2436. goto matrix_error;
  2437. }
  2438. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  2439. goto matrix_error;
  2440. }
  2441. x->mode = Addressing_Value;
  2442. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count);
  2443. goto matrix_success;
  2444. } else if (yt->kind == Type_Array) {
  2445. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  2446. goto matrix_error;
  2447. }
  2448. if (xt->Matrix.column_count != yt->Array.count) {
  2449. goto matrix_error;
  2450. }
  2451. // Treat arrays as column vectors
  2452. x->mode = Addressing_Value;
  2453. if (type_hint == nullptr && xt->Matrix.row_count == yt->Array.count) {
  2454. x->type = y->type;
  2455. } else {
  2456. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1);
  2457. }
  2458. goto matrix_success;
  2459. }
  2460. }
  2461. if (!are_types_identical(xt, yt)) {
  2462. goto matrix_error;
  2463. }
  2464. x->mode = Addressing_Value;
  2465. x->type = xt;
  2466. goto matrix_success;
  2467. } else {
  2468. GB_ASSERT(is_type_matrix(yt));
  2469. GB_ASSERT(!is_type_matrix(xt));
  2470. if (op.kind == Token_Mul) {
  2471. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  2472. if (xt->kind == Type_Array) {
  2473. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  2474. goto matrix_error;
  2475. }
  2476. if (xt->Array.count != yt->Matrix.row_count) {
  2477. goto matrix_error;
  2478. }
  2479. // Treat arrays as row vectors
  2480. x->mode = Addressing_Value;
  2481. if (type_hint == nullptr && yt->Matrix.column_count == xt->Array.count) {
  2482. x->type = x->type;
  2483. } else {
  2484. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count);
  2485. }
  2486. goto matrix_success;
  2487. }
  2488. }
  2489. if (!are_types_identical(xt, yt)) {
  2490. goto matrix_error;
  2491. }
  2492. x->mode = Addressing_Value;
  2493. x->type = xt;
  2494. goto matrix_success;
  2495. }
  2496. matrix_success:
  2497. x->type = check_matrix_type_hint(x->type, type_hint);
  2498. return;
  2499. matrix_error:
  2500. gbString xts = type_to_string(x->type);
  2501. gbString yts = type_to_string(y->type);
  2502. gbString expr_str = expr_to_string(x->expr);
  2503. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  2504. gb_string_free(expr_str);
  2505. gb_string_free(yts);
  2506. gb_string_free(xts);
  2507. x->type = t_invalid;
  2508. x->mode = Addressing_Invalid;
  2509. return;
  2510. }
  2511. void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  2512. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2513. Operand y_ = {}, *y = &y_;
  2514. ast_node(be, BinaryExpr, node);
  2515. defer({
  2516. node->viral_state_flags |= be->left->viral_state_flags;
  2517. node->viral_state_flags |= be->right->viral_state_flags;
  2518. });
  2519. Token op = be->op;
  2520. switch (op.kind) {
  2521. case Token_CmpEq:
  2522. case Token_NotEq: {
  2523. // NOTE(bill): Allow comparisons between types
  2524. if (is_ise_expr(be->left)) {
  2525. // Evalute the right before the left for an '.X' expression
  2526. check_expr_or_type(c, y, be->right, type_hint);
  2527. check_expr_or_type(c, x, be->left, y->type);
  2528. } else {
  2529. check_expr_or_type(c, x, be->left, type_hint);
  2530. check_expr_or_type(c, y, be->right, x->type);
  2531. }
  2532. bool xt = x->mode == Addressing_Type;
  2533. bool yt = y->mode == Addressing_Type;
  2534. // If only one is a type, this is an error
  2535. if (xt ^ yt) {
  2536. GB_ASSERT(xt != yt);
  2537. if (xt) {
  2538. if (!is_type_typeid(y->type)) {
  2539. error_operand_not_expression(x);
  2540. }
  2541. }
  2542. if (yt) {
  2543. if (!is_type_typeid(x->type)) {
  2544. error_operand_not_expression(y);
  2545. }
  2546. }
  2547. }
  2548. break;
  2549. }
  2550. case Token_in:
  2551. case Token_not_in:
  2552. {
  2553. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  2554. check_expr(c, y, be->right);
  2555. Type *rhs_type = type_deref(y->type);
  2556. if (is_type_bit_set(rhs_type)) {
  2557. Type *elem = base_type(rhs_type)->BitSet.elem;
  2558. check_expr_with_type_hint(c, x, be->left, elem);
  2559. } else if (is_type_map(rhs_type)) {
  2560. Type *key = base_type(rhs_type)->Map.key;
  2561. check_expr_with_type_hint(c, x, be->left, key);
  2562. } else {
  2563. check_expr(c, x, be->left);
  2564. }
  2565. if (x->mode == Addressing_Invalid) {
  2566. return;
  2567. }
  2568. if (y->mode == Addressing_Invalid) {
  2569. x->mode = Addressing_Invalid;
  2570. x->expr = y->expr;
  2571. return;
  2572. }
  2573. if (is_type_map(rhs_type)) {
  2574. Type *yt = base_type(rhs_type);
  2575. if (op.kind == Token_in) {
  2576. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  2577. } else {
  2578. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  2579. }
  2580. add_package_dependency(c, "runtime", "__dynamic_map_get");
  2581. } else if (is_type_bit_set(rhs_type)) {
  2582. Type *yt = base_type(rhs_type);
  2583. if (op.kind == Token_in) {
  2584. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  2585. } else {
  2586. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  2587. }
  2588. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  2589. ExactValue k = exact_value_to_integer(x->value);
  2590. ExactValue v = exact_value_to_integer(y->value);
  2591. GB_ASSERT(k.kind == ExactValue_Integer);
  2592. GB_ASSERT(v.kind == ExactValue_Integer);
  2593. i64 key = big_int_to_i64(&k.value_integer);
  2594. i64 lower = yt->BitSet.lower;
  2595. i64 upper = yt->BitSet.upper;
  2596. if (lower <= key && key <= upper) {
  2597. i64 bit = 1ll<<key;
  2598. i64 bits = big_int_to_i64(&v.value_integer);
  2599. x->mode = Addressing_Constant;
  2600. x->type = t_untyped_bool;
  2601. if (op.kind == Token_in) {
  2602. x->value = exact_value_bool((bit & bits) != 0);
  2603. } else {
  2604. x->value = exact_value_bool((bit & bits) == 0);
  2605. }
  2606. x->expr = node;
  2607. return;
  2608. } else {
  2609. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  2610. x->mode = Addressing_Invalid;
  2611. }
  2612. }
  2613. } else {
  2614. gbString t = type_to_string(y->type);
  2615. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  2616. gb_string_free(t);
  2617. x->expr = node;
  2618. x->mode = Addressing_Invalid;
  2619. return;
  2620. }
  2621. if (x->mode != Addressing_Invalid) {
  2622. x->mode = Addressing_Value;
  2623. x->type = t_untyped_bool;
  2624. }
  2625. x->expr = node;
  2626. return;
  2627. }
  2628. default:
  2629. if (is_ise_expr(be->left)) {
  2630. // Evalute the right before the left for an '.X' expression
  2631. check_expr_or_type(c, y, be->right, type_hint);
  2632. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  2633. check_expr_or_type(c, x, be->left, y->type);
  2634. } else {
  2635. check_expr_with_type_hint(c, x, be->left, type_hint);
  2636. }
  2637. } else {
  2638. check_expr_with_type_hint(c, x, be->left, type_hint);
  2639. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  2640. check_expr_with_type_hint(c, y, be->right, x->type);
  2641. } else {
  2642. check_expr_with_type_hint(c, y, be->right, type_hint);
  2643. }
  2644. }
  2645. break;
  2646. }
  2647. if (x->mode == Addressing_Invalid) {
  2648. return;
  2649. }
  2650. if (y->mode == Addressing_Invalid) {
  2651. x->mode = Addressing_Invalid;
  2652. x->expr = y->expr;
  2653. return;
  2654. }
  2655. if (x->mode == Addressing_Builtin) {
  2656. x->mode = Addressing_Invalid;
  2657. error(x->expr, "built-in expression in binary expression");
  2658. return;
  2659. }
  2660. if (y->mode == Addressing_Builtin) {
  2661. x->mode = Addressing_Invalid;
  2662. error(y->expr, "built-in expression in binary expression");
  2663. return;
  2664. }
  2665. if (token_is_shift(op.kind)) {
  2666. check_shift(c, x, y, node, type_hint);
  2667. return;
  2668. }
  2669. convert_to_typed(c, x, y->type);
  2670. if (x->mode == Addressing_Invalid) {
  2671. return;
  2672. }
  2673. convert_to_typed(c, y, x->type);
  2674. if (y->mode == Addressing_Invalid) {
  2675. x->mode = Addressing_Invalid;
  2676. return;
  2677. }
  2678. if (token_is_comparison(op.kind)) {
  2679. check_comparison(c, x, y, op.kind);
  2680. return;
  2681. }
  2682. if (check_binary_array_expr(c, op, x, y)) {
  2683. x->mode = Addressing_Value;
  2684. x->type = x->type;
  2685. return;
  2686. }
  2687. if (check_binary_array_expr(c, op, y, x)) {
  2688. x->mode = Addressing_Value;
  2689. x->type = y->type;
  2690. return;
  2691. }
  2692. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  2693. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  2694. x->expr = node;
  2695. return;
  2696. }
  2697. if (!are_types_identical(x->type, y->type)) {
  2698. if (x->type != t_invalid &&
  2699. y->type != t_invalid) {
  2700. gbString xt = type_to_string(x->type);
  2701. gbString yt = type_to_string(y->type);
  2702. gbString expr_str = expr_to_string(x->expr);
  2703. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  2704. gb_string_free(expr_str);
  2705. gb_string_free(yt);
  2706. gb_string_free(xt);
  2707. }
  2708. x->mode = Addressing_Invalid;
  2709. return;
  2710. }
  2711. if (!check_binary_op(c, x, op)) {
  2712. x->mode = Addressing_Invalid;
  2713. return;
  2714. }
  2715. switch (op.kind) {
  2716. case Token_Quo:
  2717. case Token_Mod:
  2718. case Token_ModMod:
  2719. case Token_QuoEq:
  2720. case Token_ModEq:
  2721. case Token_ModModEq:
  2722. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  2723. y->mode == Addressing_Constant) {
  2724. bool fail = false;
  2725. switch (y->value.kind) {
  2726. case ExactValue_Integer:
  2727. if (big_int_is_zero(&y->value.value_integer)) {
  2728. fail = true;
  2729. }
  2730. break;
  2731. case ExactValue_Float:
  2732. if (y->value.value_float == 0.0) {
  2733. fail = true;
  2734. }
  2735. break;
  2736. }
  2737. if (fail) {
  2738. error(y->expr, "Division by zero not allowed");
  2739. x->mode = Addressing_Invalid;
  2740. return;
  2741. }
  2742. }
  2743. break;
  2744. case Token_CmpAnd:
  2745. case Token_CmpOr:
  2746. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  2747. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  2748. }
  2749. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  2750. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  2751. }
  2752. break;
  2753. }
  2754. if (x->mode == Addressing_Constant &&
  2755. y->mode == Addressing_Constant) {
  2756. ExactValue a = x->value;
  2757. ExactValue b = y->value;
  2758. if (!is_type_constant_type(x->type)) {
  2759. #if 0
  2760. gbString xt = type_to_string(x->type);
  2761. gbString err_str = expr_to_string(node);
  2762. error(op, "Invalid type, '%s', for constant binary expression '%s'", xt, err_str);
  2763. gb_string_free(err_str);
  2764. gb_string_free(xt);
  2765. x->mode = Addressing_Invalid;
  2766. #else
  2767. // NOTE(bill, 2021-04-21): The above is literally a useless error message.
  2768. // Why did I add it in the first place?!
  2769. x->mode = Addressing_Value;
  2770. #endif
  2771. return;
  2772. }
  2773. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  2774. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  2775. }
  2776. if (is_type_bit_set(x->type)) {
  2777. switch (op.kind) {
  2778. case Token_Add: op.kind = Token_Or; break;
  2779. case Token_Sub: op.kind = Token_AndNot; break;
  2780. }
  2781. }
  2782. x->value = exact_binary_operator_value(op.kind, a, b);
  2783. if (is_type_typed(x->type)) {
  2784. if (node != nullptr) {
  2785. x->expr = node;
  2786. }
  2787. check_is_expressible(c, x, x->type);
  2788. }
  2789. return;
  2790. } else if (is_type_string(x->type)) {
  2791. error(node, "String concatenation is only allowed with constant strings");
  2792. x->mode = Addressing_Invalid;
  2793. return;
  2794. }
  2795. if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  2796. Type *bt = base_type(x->type);
  2797. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  2798. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  2799. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  2800. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  2801. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  2802. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  2803. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  2804. }
  2805. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  2806. Type *bt = base_type(x->type);
  2807. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  2808. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  2809. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  2810. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  2811. }
  2812. }
  2813. x->mode = Addressing_Value;
  2814. }
  2815. void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  2816. GB_ASSERT(e != nullptr);
  2817. ExprInfo *old = check_get_expr_info(c, e);
  2818. if (old == nullptr) {
  2819. if (type != nullptr && type != t_invalid) {
  2820. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  2821. add_type_and_value(c->info, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  2822. if (e->kind == Ast_TernaryIfExpr) {
  2823. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  2824. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  2825. }
  2826. }
  2827. }
  2828. return;
  2829. }
  2830. switch (e->kind) {
  2831. case_ast_node(ue, UnaryExpr, e);
  2832. if (old->value.kind != ExactValue_Invalid) {
  2833. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  2834. // They don't need to be updated as they will be updated later and
  2835. // checked at the end of general checking stage.
  2836. break;
  2837. }
  2838. update_untyped_expr_type(c, ue->expr, type, final);
  2839. case_end;
  2840. case_ast_node(be, BinaryExpr, e);
  2841. if (old->value.kind != ExactValue_Invalid) {
  2842. // See above note in UnaryExpr case
  2843. break;
  2844. }
  2845. if (token_is_comparison(be->op.kind)) {
  2846. // NOTE(bill): Do nothing as the types are fine
  2847. } else if (token_is_shift(be->op.kind)) {
  2848. update_untyped_expr_type(c, be->left, type, final);
  2849. } else {
  2850. update_untyped_expr_type(c, be->left, type, final);
  2851. update_untyped_expr_type(c, be->right, type, final);
  2852. }
  2853. case_end;
  2854. case_ast_node(te, TernaryIfExpr, e);
  2855. if (old->value.kind != ExactValue_Invalid) {
  2856. // See above note in UnaryExpr case
  2857. break;
  2858. }
  2859. update_untyped_expr_type(c, te->x, type, final);
  2860. update_untyped_expr_type(c, te->y, type, final);
  2861. case_end;
  2862. case_ast_node(te, TernaryWhenExpr, e);
  2863. if (old->value.kind != ExactValue_Invalid) {
  2864. // See above note in UnaryExpr case
  2865. break;
  2866. }
  2867. update_untyped_expr_type(c, te->x, type, final);
  2868. update_untyped_expr_type(c, te->y, type, final);
  2869. case_end;
  2870. case_ast_node(ore, OrReturnExpr, e);
  2871. if (old->value.kind != ExactValue_Invalid) {
  2872. // See above note in UnaryExpr case
  2873. break;
  2874. }
  2875. update_untyped_expr_type(c, ore->expr, type, final);
  2876. case_end;
  2877. case_ast_node(oee, OrElseExpr, e);
  2878. if (old->value.kind != ExactValue_Invalid) {
  2879. // See above note in UnaryExpr case
  2880. break;
  2881. }
  2882. update_untyped_expr_type(c, oee->x, type, final);
  2883. update_untyped_expr_type(c, oee->y, type, final);
  2884. case_end;
  2885. case_ast_node(pe, ParenExpr, e);
  2886. update_untyped_expr_type(c, pe->expr, type, final);
  2887. case_end;
  2888. }
  2889. if (!final && is_type_untyped(type)) {
  2890. old->type = base_type(type);
  2891. return;
  2892. }
  2893. // We need to remove it and then give it a new one
  2894. check_remove_expr_info(c, e);
  2895. if (old->is_lhs && !is_type_integer(type)) {
  2896. gbString expr_str = expr_to_string(e);
  2897. gbString type_str = type_to_string(type);
  2898. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  2899. gb_string_free(type_str);
  2900. gb_string_free(expr_str);
  2901. return;
  2902. }
  2903. add_type_and_value(c->info, e, old->mode, type, old->value);
  2904. }
  2905. void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  2906. GB_ASSERT(e != nullptr);
  2907. ExprInfo *found = check_get_expr_info(c, e);
  2908. if (found) {
  2909. found->value = value;
  2910. }
  2911. }
  2912. void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type) {
  2913. gbString expr_str = expr_to_string(operand->expr);
  2914. gbString type_str = type_to_string(target_type);
  2915. gbString from_type_str = type_to_string(operand->type);
  2916. char const *extra_text = "";
  2917. if (operand->mode == Addressing_Constant) {
  2918. if (big_int_is_zero(&operand->value.value_integer)) {
  2919. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  2920. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  2921. extra_text = " - Did you want 'nil'?";
  2922. }
  2923. }
  2924. }
  2925. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  2926. gb_string_free(from_type_str);
  2927. gb_string_free(type_str);
  2928. gb_string_free(expr_str);
  2929. operand->mode = Addressing_Invalid;
  2930. }
  2931. ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  2932. Type *t = core_type(type);
  2933. if (is_type_boolean(t)) {
  2934. // v = exact_value_to_boolean(v);
  2935. } else if (is_type_float(t)) {
  2936. v = exact_value_to_float(v);
  2937. } else if (is_type_integer(t)) {
  2938. v = exact_value_to_integer(v);
  2939. } else if (is_type_pointer(t)) {
  2940. v = exact_value_to_integer(v);
  2941. } else if (is_type_complex(t)) {
  2942. v = exact_value_to_complex(v);
  2943. } else if (is_type_quaternion(t)) {
  2944. v = exact_value_to_quaternion(v);
  2945. }
  2946. return v;
  2947. }
  2948. void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  2949. GB_ASSERT_NOT_NULL(target_type);
  2950. if (operand->mode == Addressing_Invalid ||
  2951. operand->mode == Addressing_Type ||
  2952. is_type_typed(operand->type) ||
  2953. target_type == t_invalid) {
  2954. return;
  2955. }
  2956. if (is_type_untyped(target_type)) {
  2957. GB_ASSERT(operand->type->kind == Type_Basic);
  2958. GB_ASSERT(target_type->kind == Type_Basic);
  2959. BasicKind x_kind = operand->type->Basic.kind;
  2960. BasicKind y_kind = target_type->Basic.kind;
  2961. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  2962. if (x_kind < y_kind) {
  2963. operand->type = target_type;
  2964. update_untyped_expr_type(c, operand->expr, target_type, false);
  2965. }
  2966. } else if (x_kind != y_kind) {
  2967. operand->mode = Addressing_Invalid;
  2968. convert_untyped_error(c, operand, target_type);
  2969. return;
  2970. }
  2971. return;
  2972. }
  2973. Type *t = base_type(target_type);
  2974. if (c->in_enum_type) {
  2975. t = core_type(target_type);
  2976. }
  2977. switch (t->kind) {
  2978. case Type_Basic:
  2979. if (operand->mode == Addressing_Constant) {
  2980. check_is_expressible(c, operand, t);
  2981. if (operand->mode == Addressing_Invalid) {
  2982. return;
  2983. }
  2984. update_untyped_expr_value(c, operand->expr, operand->value);
  2985. } else {
  2986. switch (operand->type->Basic.kind) {
  2987. case Basic_UntypedBool:
  2988. if (!is_type_boolean(target_type)) {
  2989. operand->mode = Addressing_Invalid;
  2990. convert_untyped_error(c, operand, target_type);
  2991. return;
  2992. }
  2993. break;
  2994. case Basic_UntypedInteger:
  2995. case Basic_UntypedFloat:
  2996. case Basic_UntypedComplex:
  2997. case Basic_UntypedQuaternion:
  2998. case Basic_UntypedRune:
  2999. if (!is_type_numeric(target_type)) {
  3000. operand->mode = Addressing_Invalid;
  3001. convert_untyped_error(c, operand, target_type);
  3002. return;
  3003. }
  3004. break;
  3005. case Basic_UntypedNil:
  3006. if (is_type_any(target_type)) {
  3007. // target_type = t_untyped_nil;
  3008. } else if (is_type_cstring(target_type)) {
  3009. // target_type = t_untyped_nil;
  3010. } else if (!type_has_nil(target_type)) {
  3011. operand->mode = Addressing_Invalid;
  3012. convert_untyped_error(c, operand, target_type);
  3013. return;
  3014. }
  3015. break;
  3016. }
  3017. }
  3018. break;
  3019. case Type_Array: {
  3020. Type *elem = base_array_type(t);
  3021. if (check_is_assignable_to(c, operand, elem)) {
  3022. operand->mode = Addressing_Value;
  3023. } else {
  3024. if (operand->value.kind == ExactValue_String) {
  3025. String s = operand->value.value_string;
  3026. if (is_type_u8_array(t)) {
  3027. if (s.len == t->Array.count) {
  3028. break;
  3029. }
  3030. } else if (is_type_rune_array(t)) {
  3031. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  3032. if (rune_count == t->Array.count) {
  3033. break;
  3034. }
  3035. }
  3036. }
  3037. operand->mode = Addressing_Invalid;
  3038. convert_untyped_error(c, operand, target_type);
  3039. return;
  3040. }
  3041. break;
  3042. }
  3043. case Type_Matrix: {
  3044. Type *elem = base_array_type(t);
  3045. if (check_is_assignable_to(c, operand, elem)) {
  3046. if (t->Matrix.row_count != t->Matrix.column_count) {
  3047. operand->mode = Addressing_Invalid;
  3048. begin_error_block();
  3049. defer (end_error_block());
  3050. convert_untyped_error(c, operand, target_type);
  3051. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  3052. return;
  3053. } else {
  3054. operand->mode = Addressing_Value;
  3055. }
  3056. } else {
  3057. operand->mode = Addressing_Invalid;
  3058. convert_untyped_error(c, operand, target_type);
  3059. return;
  3060. }
  3061. break;
  3062. }
  3063. case Type_Union:
  3064. if (!is_operand_nil(*operand) && !is_operand_undef(*operand)) {
  3065. isize count = t->Union.variants.count;
  3066. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  3067. isize valid_count = 0;
  3068. isize first_success_index = -1;
  3069. for_array(i, t->Union.variants) {
  3070. Type *vt = t->Union.variants[i];
  3071. i64 score = 0;
  3072. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  3073. valids[valid_count].index = i;
  3074. valids[valid_count].score = score;
  3075. valid_count += 1;
  3076. if (first_success_index < 0) {
  3077. first_success_index = i;
  3078. }
  3079. }
  3080. }
  3081. if (valid_count > 1) {
  3082. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  3083. i64 best_score = valids[0].score;
  3084. for (isize i = 1; i < valid_count; i++) {
  3085. auto v = valids[i];
  3086. if (best_score > v.score) {
  3087. valid_count = i;
  3088. break;
  3089. }
  3090. best_score = v.score;
  3091. }
  3092. first_success_index = valids[0].index;
  3093. }
  3094. gbString type_str = type_to_string(target_type);
  3095. defer (gb_string_free(type_str));
  3096. if (valid_count == 1) {
  3097. operand->mode = Addressing_Value;
  3098. operand->type = t->Union.variants[first_success_index];
  3099. target_type = t->Union.variants[first_success_index];
  3100. break;
  3101. } else if (valid_count > 1) {
  3102. begin_error_block();
  3103. defer (end_error_block());
  3104. GB_ASSERT(first_success_index >= 0);
  3105. operand->mode = Addressing_Invalid;
  3106. convert_untyped_error(c, operand, target_type);
  3107. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  3108. i32 j = 0;
  3109. for (i32 i = 0; i < valid_count; i++) {
  3110. ValidIndexAndScore valid = valids[i];
  3111. if (j > 0 && valid_count > 2) error_line(", ");
  3112. if (j == valid_count-1) {
  3113. if (valid_count == 2) error_line(" ");
  3114. error_line("or ");
  3115. }
  3116. gbString str = type_to_string(t->Union.variants[valid.index]);
  3117. error_line("'%s'", str);
  3118. gb_string_free(str);
  3119. j++;
  3120. }
  3121. error_line("\n\n");
  3122. return;
  3123. } else if (is_type_untyped_undef(operand->type) && type_has_undef(target_type)) {
  3124. target_type = t_untyped_undef;
  3125. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  3126. begin_error_block();
  3127. defer (end_error_block());
  3128. operand->mode = Addressing_Invalid;
  3129. convert_untyped_error(c, operand, target_type);
  3130. if (count > 0) {
  3131. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  3132. error_line("\t");
  3133. for (i32 i = 0; i < count; i++) {
  3134. Type *v = t->Union.variants[i];
  3135. if (i > 0 && count > 2) error_line(", ");
  3136. if (i == count-1) {
  3137. if (count == 2) error_line(" ");
  3138. if (count > 1) {
  3139. error_line("or ");
  3140. }
  3141. }
  3142. gbString str = type_to_string(v);
  3143. error_line("'%s'", str);
  3144. gb_string_free(str);
  3145. }
  3146. error_line("\n\n");
  3147. }
  3148. return;
  3149. }
  3150. }
  3151. /* fallthrough */
  3152. default:
  3153. if (is_type_untyped_undef(operand->type) && type_has_undef(target_type)) {
  3154. target_type = t_untyped_undef;
  3155. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  3156. target_type = t_untyped_nil;
  3157. } else {
  3158. operand->mode = Addressing_Invalid;
  3159. convert_untyped_error(c, operand, target_type);
  3160. return;
  3161. }
  3162. break;
  3163. }
  3164. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  3165. if (is_type_untyped_nil(operand->type) && is_type_untyped_undef(operand->type)) {
  3166. } else {
  3167. target_type = default_type(operand->type);
  3168. }
  3169. }
  3170. update_untyped_expr_type(c, operand->expr, target_type, true);
  3171. operand->type = target_type;
  3172. }
  3173. bool check_index_value(CheckerContext *c, Type *main_type, bool open_range, Ast *index_value, i64 max_count, i64 *value, Type *type_hint=nullptr) {
  3174. Operand operand = {Addressing_Invalid};
  3175. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  3176. if (operand.mode == Addressing_Invalid) {
  3177. if (value) *value = 0;
  3178. return false;
  3179. }
  3180. Type *index_type = t_int;
  3181. if (type_hint != nullptr) {
  3182. index_type = type_hint;
  3183. }
  3184. convert_to_typed(c, &operand, index_type);
  3185. if (operand.mode == Addressing_Invalid) {
  3186. if (value) *value = 0;
  3187. return false;
  3188. }
  3189. if (type_hint != nullptr) {
  3190. if (!check_is_assignable_to(c, &operand, type_hint)) {
  3191. gbString expr_str = expr_to_string(operand.expr);
  3192. gbString index_type_str = type_to_string(type_hint);
  3193. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  3194. gb_string_free(index_type_str);
  3195. gb_string_free(expr_str);
  3196. if (value) *value = 0;
  3197. return false;
  3198. }
  3199. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  3200. gbString expr_str = expr_to_string(operand.expr);
  3201. error(operand.expr, "Index '%s' must be an integer", expr_str);
  3202. gb_string_free(expr_str);
  3203. if (value) *value = 0;
  3204. return false;
  3205. }
  3206. if (operand.mode == Addressing_Constant &&
  3207. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  3208. BigInt i = exact_value_to_integer(operand.value).value_integer;
  3209. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  3210. gbString expr_str = expr_to_string(operand.expr);
  3211. error(operand.expr, "Index '%s' cannot be a negative value", expr_str);
  3212. gb_string_free(expr_str);
  3213. if (value) *value = 0;
  3214. return false;
  3215. }
  3216. if (max_count >= 0) {
  3217. if (is_type_enum(index_type)) {
  3218. Type *bt = base_type(index_type);
  3219. GB_ASSERT(bt->kind == Type_Enum);
  3220. ExactValue const &lo = *bt->Enum.min_value;
  3221. ExactValue const &hi = *bt->Enum.max_value;
  3222. String lo_str = {};
  3223. String hi_str = {};
  3224. if (bt->Enum.fields.count > 0) {
  3225. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  3226. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  3227. lo_str = bt->Enum.fields[lo_idx]->token.string;
  3228. hi_str = bt->Enum.fields[hi_idx]->token.string;
  3229. }
  3230. bool out_of_bounds = false;
  3231. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  3232. out_of_bounds = true;
  3233. }
  3234. if (out_of_bounds) {
  3235. gbString expr_str = expr_to_string(operand.expr);
  3236. if (lo_str.len > 0) {
  3237. error(operand.expr, "Index '%s' is out of bounds range %.*s .. %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  3238. } else {
  3239. gbString index_type_str = type_to_string(index_type);
  3240. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  3241. gb_string_free(index_type_str);
  3242. }
  3243. gb_string_free(expr_str);
  3244. return false;
  3245. }
  3246. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  3247. return true;
  3248. } else { // NOTE(bill): Do array bound checking
  3249. i64 v = -1;
  3250. if (i.used <= 1) {
  3251. v = big_int_to_i64(&i);
  3252. }
  3253. if (value) *value = v;
  3254. bool out_of_bounds = false;
  3255. if (v < 0) {
  3256. out_of_bounds = true;
  3257. } else if (open_range) {
  3258. out_of_bounds = v > max_count;
  3259. } else {
  3260. out_of_bounds = v >= max_count;
  3261. }
  3262. if (out_of_bounds) {
  3263. gbString expr_str = expr_to_string(operand.expr);
  3264. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld", expr_str, max_count);
  3265. gb_string_free(expr_str);
  3266. return false;
  3267. }
  3268. return true;
  3269. }
  3270. } else {
  3271. if (value) *value = exact_value_to_i64(operand.value);
  3272. return true;
  3273. }
  3274. }
  3275. // NOTE(bill): It's alright :D
  3276. if (value) *value = -1;
  3277. return true;
  3278. }
  3279. ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  3280. if (value.kind == ExactValue_String) {
  3281. GB_ASSERT(0 <= index && index < value.value_string.len);
  3282. u8 val = value.value_string[index];
  3283. if (success_) *success_ = true;
  3284. if (finish_) *finish_ = true;
  3285. return exact_value_u64(val);
  3286. }
  3287. if (value.kind != ExactValue_Compound) {
  3288. if (success_) *success_ = true;
  3289. if (finish_) *finish_ = true;
  3290. return value;
  3291. }
  3292. Ast *node = value.value_compound;
  3293. switch (node->kind) {
  3294. case_ast_node(cl, CompoundLit, node);
  3295. if (cl->elems.count == 0) {
  3296. if (success_) *success_ = true;
  3297. if (finish_) *finish_ = true;
  3298. return empty_exact_value;
  3299. }
  3300. if (cl->elems[0]->kind == Ast_FieldValue) {
  3301. if (is_type_struct(node->tav.type)) {
  3302. for_array(i, cl->elems) {
  3303. Ast *elem = cl->elems[i];
  3304. if (elem->kind != Ast_FieldValue) {
  3305. continue;
  3306. }
  3307. ast_node(fv, FieldValue, elem);
  3308. String name = fv->field->Ident.token.string;
  3309. Selection sub_sel = lookup_field(node->tav.type, name, false);
  3310. defer (array_free(&sub_sel.index));
  3311. if (sub_sel.index[0] == index) {
  3312. value = fv->value->tav.value;
  3313. break;
  3314. }
  3315. }
  3316. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  3317. for_array(i, cl->elems) {
  3318. Ast *elem = cl->elems[i];
  3319. if (elem->kind != Ast_FieldValue) {
  3320. continue;
  3321. }
  3322. ast_node(fv, FieldValue, elem);
  3323. if (is_ast_range(fv->field)) {
  3324. ast_node(ie, BinaryExpr, fv->field);
  3325. TypeAndValue lo_tav = ie->left->tav;
  3326. TypeAndValue hi_tav = ie->right->tav;
  3327. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3328. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3329. TokenKind op = ie->op.kind;
  3330. i64 lo = exact_value_to_i64(lo_tav.value);
  3331. i64 hi = exact_value_to_i64(hi_tav.value);
  3332. i64 corrected_index = index;
  3333. if (is_type_enumerated_array(node->tav.type)) {
  3334. Type *bt = base_type(node->tav.type);
  3335. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3336. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  3337. }
  3338. if (op != Token_RangeHalf) {
  3339. if (lo <= corrected_index && corrected_index <= hi) {
  3340. TypeAndValue tav = fv->value->tav;
  3341. if (success_) *success_ = true;
  3342. if (finish_) *finish_ = false;
  3343. return tav.value;
  3344. }
  3345. } else {
  3346. if (lo <= corrected_index && corrected_index < hi) {
  3347. TypeAndValue tav = fv->value->tav;
  3348. if (success_) *success_ = true;
  3349. if (finish_) *finish_ = false;
  3350. return tav.value;
  3351. }
  3352. }
  3353. } else {
  3354. TypeAndValue index_tav = fv->field->tav;
  3355. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3356. ExactValue index_value = index_tav.value;
  3357. if (is_type_enumerated_array(node->tav.type)) {
  3358. Type *bt = base_type(node->tav.type);
  3359. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  3360. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  3361. }
  3362. i64 field_index = exact_value_to_i64(index_value);
  3363. if (index == field_index) {
  3364. TypeAndValue tav = fv->value->tav;
  3365. if (success_) *success_ = true;
  3366. if (finish_) *finish_ = false;
  3367. return tav.value;;
  3368. }
  3369. }
  3370. }
  3371. }
  3372. } else {
  3373. i32 count = (i32)cl->elems.count;
  3374. if (count < index) {
  3375. if (success_) *success_ = false;
  3376. if (finish_) *finish_ = true;
  3377. return empty_exact_value;
  3378. }
  3379. if (cl->elems.count <= index) {
  3380. if (success_) *success_ = false;
  3381. if (finish_) *finish_ = false;
  3382. return value;
  3383. }
  3384. TypeAndValue tav = cl->elems[index]->tav;
  3385. if (tav.mode == Addressing_Constant) {
  3386. if (success_) *success_ = true;
  3387. if (finish_) *finish_ = false;
  3388. return tav.value;
  3389. } else {
  3390. GB_ASSERT(is_type_untyped_nil(tav.type));
  3391. if (success_) *success_ = true;
  3392. if (finish_) *finish_ = false;
  3393. return tav.value;
  3394. }
  3395. }
  3396. case_end;
  3397. default:
  3398. // TODO(bill): Should this be a general fallback?
  3399. if (success_) *success_ = true;
  3400. if (finish_) *finish_ = true;
  3401. return empty_exact_value;
  3402. }
  3403. if (finish_) *finish_ = false;
  3404. return value;
  3405. }
  3406. ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  3407. if (operand->mode != Addressing_Constant) {
  3408. if (success_) *success_ = false;
  3409. return empty_exact_value;
  3410. }
  3411. if (sel.indirect) {
  3412. if (success_) *success_ = false;
  3413. return empty_exact_value;
  3414. }
  3415. if (sel.index.count == 0) {
  3416. if (success_) *success_ = false;
  3417. return empty_exact_value;
  3418. }
  3419. ExactValue value = operand->value;
  3420. if (value.kind == ExactValue_Compound) {
  3421. while (sel.index.count > 0) {
  3422. i32 index = sel.index[0];
  3423. sel = sub_selection(sel, 1);
  3424. bool finish = false;
  3425. value = get_constant_field_single(c, value, index, success_, &finish);
  3426. if (finish) {
  3427. return value;
  3428. }
  3429. }
  3430. if (success_) *success_ = true;
  3431. return value;
  3432. } else if (value.kind == ExactValue_Quaternion) {
  3433. // @QuaternionLayout
  3434. Quaternion256 q = *value.value_quaternion;
  3435. GB_ASSERT(sel.index.count == 1);
  3436. switch (sel.index[0]) {
  3437. case 3: // w
  3438. if (success_) *success_ = true;
  3439. return exact_value_float(q.real);
  3440. case 0: // x
  3441. if (success_) *success_ = true;
  3442. return exact_value_float(q.imag);
  3443. case 1: // y
  3444. if (success_) *success_ = true;
  3445. return exact_value_float(q.jmag);
  3446. case 2: // z
  3447. if (success_) *success_ = true;
  3448. return exact_value_float(q.kmag);
  3449. }
  3450. if (success_) *success_ = false;
  3451. return empty_exact_value;
  3452. } else if (value.kind == ExactValue_Complex) {
  3453. // @QuaternionLayout
  3454. Complex128 c = *value.value_complex;
  3455. GB_ASSERT(sel.index.count == 1);
  3456. switch (sel.index[0]) {
  3457. case 0: // real
  3458. if (success_) *success_ = true;
  3459. return exact_value_float(c.real);
  3460. case 1: // imag
  3461. if (success_) *success_ = true;
  3462. return exact_value_float(c.imag);
  3463. }
  3464. if (success_) *success_ = false;
  3465. return empty_exact_value;
  3466. }
  3467. if (success_) *success_ = true;
  3468. return empty_exact_value;
  3469. }
  3470. void check_did_you_mean_print(DidYouMeanAnswers *d) {
  3471. auto results = did_you_mean_results(d);
  3472. if (results.count != 0) {
  3473. error_line("\tSuggestion: Did you mean?\n");
  3474. for_array(i, results) {
  3475. String const &target = results[i].target;
  3476. error_line("\t\t%.*s\n", LIT(target));
  3477. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  3478. }
  3479. }
  3480. }
  3481. void check_did_you_mean_type(String const &name, Array<Entity *> const &fields) {
  3482. ERROR_BLOCK();
  3483. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  3484. defer (did_you_mean_destroy(&d));
  3485. for_array(i, fields) {
  3486. did_you_mean_append(&d, fields[i]->token.string);
  3487. }
  3488. check_did_you_mean_print(&d);
  3489. }
  3490. void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields) {
  3491. ERROR_BLOCK();
  3492. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  3493. defer (did_you_mean_destroy(&d));
  3494. for_array(i, fields) {
  3495. did_you_mean_append(&d, fields[i]->token.string);
  3496. }
  3497. check_did_you_mean_print(&d);
  3498. }
  3499. void check_did_you_mean_scope(String const &name, Scope *scope) {
  3500. ERROR_BLOCK();
  3501. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.entries.count, name);
  3502. defer (did_you_mean_destroy(&d));
  3503. for_array(i, scope->elements.entries) {
  3504. Entity *e = scope->elements.entries[i].value;
  3505. did_you_mean_append(&d, e->token.string);
  3506. }
  3507. check_did_you_mean_print(&d);
  3508. }
  3509. Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  3510. Type *array_type = base_type(type_deref(original_type));
  3511. GB_ASSERT(array_type->kind == Type_Array);
  3512. Type *elem_type = array_type->Array.elem;
  3513. Type *swizzle_array_type = nullptr;
  3514. Type *bth = base_type(type_deref(type_hint));
  3515. if (bth != nullptr && bth->kind == Type_Array &&
  3516. bth->Array.count == new_count &&
  3517. are_types_identical(bth->Array.elem, elem_type)) {
  3518. swizzle_array_type = type_hint;
  3519. } else {
  3520. i64 max_count = array_type->Array.count;
  3521. if (new_count == max_count) {
  3522. swizzle_array_type = original_type;
  3523. } else {
  3524. swizzle_array_type = alloc_type_array(elem_type, new_count);
  3525. }
  3526. }
  3527. return swizzle_array_type;
  3528. }
  3529. Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  3530. ast_node(se, SelectorExpr, node);
  3531. bool check_op_expr = true;
  3532. Entity *expr_entity = nullptr;
  3533. Entity *entity = nullptr;
  3534. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  3535. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  3536. error(node, "Illegal use of -> selector shorthand outside of a call");
  3537. operand->mode = Addressing_Invalid;
  3538. operand->expr = node;
  3539. return nullptr;
  3540. }
  3541. operand->expr = node;
  3542. Ast *op_expr = se->expr;
  3543. Ast *selector = unparen_expr(se->selector);
  3544. if (selector == nullptr) {
  3545. operand->mode = Addressing_Invalid;
  3546. operand->expr = node;
  3547. return nullptr;
  3548. }
  3549. if (selector->kind != Ast_Ident) {
  3550. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  3551. operand->mode = Addressing_Invalid;
  3552. operand->expr = node;
  3553. return nullptr;
  3554. }
  3555. if (op_expr->kind == Ast_Ident) {
  3556. String op_name = op_expr->Ident.token.string;
  3557. Entity *e = scope_lookup(c->scope, op_name);
  3558. add_entity_use(c, op_expr, e);
  3559. expr_entity = e;
  3560. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  3561. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  3562. // It pretty much needs to be in this order and this way
  3563. // If you can clean this up, please do but be really careful
  3564. String import_name = op_name;
  3565. Scope *import_scope = e->ImportName.scope;
  3566. String entity_name = selector->Ident.token.string;
  3567. check_op_expr = false;
  3568. entity = scope_lookup_current(import_scope, entity_name);
  3569. bool is_declared = entity != nullptr;
  3570. bool allow_builtin = false;
  3571. if (is_declared) {
  3572. if (entity->kind == Entity_Builtin) {
  3573. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  3574. // This means that we should just ignore the found result through it
  3575. allow_builtin = entity->scope == import_scope || entity->scope != builtin_pkg->scope;
  3576. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  3577. is_declared = false;
  3578. }
  3579. }
  3580. if (!is_declared) {
  3581. error(op_expr, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  3582. operand->mode = Addressing_Invalid;
  3583. operand->expr = node;
  3584. check_did_you_mean_scope(entity_name, import_scope);
  3585. return nullptr;
  3586. }
  3587. check_entity_decl(c, entity, nullptr, nullptr);
  3588. if (entity->kind == Entity_ProcGroup) {
  3589. operand->mode = Addressing_ProcGroup;
  3590. operand->proc_group = entity;
  3591. add_type_and_value(c->info, operand->expr, operand->mode, operand->type, operand->value);
  3592. return entity;
  3593. }
  3594. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  3595. if (!is_entity_exported(entity, allow_builtin)) {
  3596. gbString sel_str = expr_to_string(selector);
  3597. error(op_expr, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  3598. gb_string_free(sel_str);
  3599. // NOTE(bill): make the state valid still, even if it's "invalid"
  3600. // operand->mode = Addressing_Invalid;
  3601. // operand->expr = node;
  3602. // return nullptr;
  3603. }
  3604. if (entity->kind == Entity_ProcGroup) {
  3605. Array<Entity *> procs = entity->ProcGroup.entities;
  3606. bool skip = false;
  3607. for_array(i, procs) {
  3608. Entity *p = procs[i];
  3609. Type *t = base_type(p->type);
  3610. if (t == t_invalid) {
  3611. continue;
  3612. }
  3613. Operand x = {};
  3614. x.mode = Addressing_Value;
  3615. x.type = t;
  3616. if (type_hint != nullptr) {
  3617. if (check_is_assignable_to(c, &x, type_hint)) {
  3618. entity = p;
  3619. skip = true;
  3620. break;
  3621. }
  3622. }
  3623. }
  3624. if (!skip) {
  3625. GB_ASSERT(entity != nullptr);
  3626. operand->mode = Addressing_ProcGroup;
  3627. operand->type = t_invalid;
  3628. operand->expr = node;
  3629. operand->proc_group = entity;
  3630. return entity;
  3631. }
  3632. }
  3633. }
  3634. }
  3635. if (check_op_expr) {
  3636. check_expr_base(c, operand, op_expr, nullptr);
  3637. if (operand->mode == Addressing_Invalid) {
  3638. operand->mode = Addressing_Invalid;
  3639. operand->expr = node;
  3640. return nullptr;
  3641. }
  3642. }
  3643. if (entity == nullptr && selector->kind == Ast_Ident) {
  3644. String field_name = selector->Ident.token.string;
  3645. if (is_type_dynamic_array(type_deref(operand->type))) {
  3646. init_mem_allocator(c->checker);
  3647. }
  3648. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  3649. entity = sel.entity;
  3650. // NOTE(bill): Add type info needed for fields like 'names'
  3651. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  3652. add_type_info_type(c, operand->type);
  3653. }
  3654. if (is_type_enum(operand->type)) {
  3655. add_type_info_type(c, operand->type);
  3656. }
  3657. }
  3658. if (entity == nullptr && selector->kind == Ast_Ident && is_type_array(type_deref(operand->type))) {
  3659. // TODO(bill): Simd_Vector swizzling
  3660. String field_name = selector->Ident.token.string;
  3661. if (1 < field_name.len && field_name.len <= 4) {
  3662. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  3663. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  3664. bool found_xyzw = false;
  3665. bool found_rgba = false;
  3666. for (isize i = 0; i < field_name.len; i++) {
  3667. bool valid = false;
  3668. for (isize j = 0; j < 4; j++) {
  3669. if (field_name.text[i] == swizzles_xyzw[j]) {
  3670. found_xyzw = true;
  3671. valid = true;
  3672. break;
  3673. }
  3674. if (field_name.text[i] == swizzles_rgba[j]) {
  3675. found_rgba = true;
  3676. valid = true;
  3677. break;
  3678. }
  3679. }
  3680. if (!valid) {
  3681. goto end_of_array_selector_swizzle;
  3682. }
  3683. }
  3684. u8 *swizzles = nullptr;
  3685. u8 index_count = cast(u8)field_name.len;
  3686. if (found_xyzw && found_rgba) {
  3687. gbString op_str = expr_to_string(op_expr);
  3688. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  3689. gb_string_free(op_str);
  3690. operand->mode = Addressing_Invalid;
  3691. operand->expr = node;
  3692. return nullptr;
  3693. }
  3694. u8 indices = 0;
  3695. if (found_xyzw) {
  3696. swizzles = swizzles_xyzw;
  3697. } else if (found_rgba) {
  3698. swizzles = swizzles_rgba;
  3699. }
  3700. for (isize i = 0; i < field_name.len; i++) {
  3701. for (isize j = 0; j < 4; j++) {
  3702. if (field_name.text[i] == swizzles[j]) {
  3703. indices |= cast(u8)(j)<<(i*2);
  3704. break;
  3705. }
  3706. }
  3707. }
  3708. Type *original_type = operand->type;
  3709. Type *array_type = base_type(type_deref(original_type));
  3710. GB_ASSERT(array_type->kind == Type_Array);
  3711. i64 array_count = array_type->Array.count;
  3712. for (u8 i = 0; i < index_count; i++) {
  3713. u8 idx = indices>>(i*2) & 3;
  3714. if (idx >= array_count) {
  3715. char c = 0;
  3716. if (found_xyzw) {
  3717. c = swizzles_xyzw[idx];
  3718. } else if (found_rgba) {
  3719. c = swizzles_rgba[idx];
  3720. } else {
  3721. GB_PANIC("unknown swizzle kind");
  3722. }
  3723. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  3724. break;
  3725. }
  3726. }
  3727. se->swizzle_count = index_count;
  3728. se->swizzle_indices = indices;
  3729. AddressingMode prev_mode = operand->mode;
  3730. operand->mode = Addressing_SwizzleValue;
  3731. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  3732. operand->expr = node;
  3733. switch (prev_mode) {
  3734. case Addressing_Variable:
  3735. case Addressing_SoaVariable:
  3736. case Addressing_SwizzleVariable:
  3737. operand->mode = Addressing_SwizzleVariable;
  3738. break;
  3739. }
  3740. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  3741. add_type_and_value(c->info, operand->expr, operand->mode, operand->type, operand->value);
  3742. return swizzle_entity;
  3743. }
  3744. end_of_array_selector_swizzle:;
  3745. }
  3746. if (entity == nullptr) {
  3747. gbString op_str = expr_to_string(op_expr);
  3748. gbString type_str = type_to_string(operand->type);
  3749. gbString sel_str = expr_to_string(selector);
  3750. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  3751. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  3752. String const &name = selector->Ident.token.string;
  3753. Type *bt = base_type(operand->type);
  3754. if (bt->kind == Type_Struct) {
  3755. check_did_you_mean_type(name, bt->Struct.fields);
  3756. } else if (bt->kind == Type_Enum) {
  3757. check_did_you_mean_type(name, bt->Enum.fields);
  3758. }
  3759. }
  3760. gb_string_free(sel_str);
  3761. gb_string_free(type_str);
  3762. gb_string_free(op_str);
  3763. operand->mode = Addressing_Invalid;
  3764. operand->expr = node;
  3765. return nullptr;
  3766. }
  3767. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  3768. bool success = false;
  3769. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  3770. if (success) {
  3771. operand->mode = Addressing_Constant;
  3772. operand->expr = node;
  3773. operand->value = field_value;
  3774. operand->type = entity->type;
  3775. add_entity_use(c, selector, entity);
  3776. add_type_and_value(c->info, operand->expr, operand->mode, operand->type, operand->value);
  3777. return entity;
  3778. }
  3779. gbString op_str = expr_to_string(op_expr);
  3780. gbString type_str = type_to_string(operand->type);
  3781. gbString sel_str = expr_to_string(selector);
  3782. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  3783. gb_string_free(sel_str);
  3784. gb_string_free(type_str);
  3785. gb_string_free(op_str);
  3786. operand->mode = Addressing_Invalid;
  3787. operand->expr = node;
  3788. return nullptr;
  3789. }
  3790. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  3791. bool success = false;
  3792. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  3793. if (success) {
  3794. operand->mode = Addressing_Constant;
  3795. operand->expr = node;
  3796. operand->value = field_value;
  3797. operand->type = entity->type;
  3798. add_entity_use(c, selector, entity);
  3799. add_type_and_value(c->info, operand->expr, operand->mode, operand->type, operand->value);
  3800. return entity;
  3801. }
  3802. gbString op_str = expr_to_string(op_expr);
  3803. gbString type_str = type_to_string(operand->type);
  3804. gbString sel_str = expr_to_string(selector);
  3805. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  3806. gb_string_free(sel_str);
  3807. gb_string_free(type_str);
  3808. gb_string_free(op_str);
  3809. operand->mode = Addressing_Invalid;
  3810. operand->expr = node;
  3811. return nullptr;
  3812. }
  3813. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  3814. gbString op_str = expr_to_string(op_expr);
  3815. gbString type_str = type_to_string(operand->type);
  3816. gbString sel_str = expr_to_string(selector);
  3817. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  3818. gb_string_free(sel_str);
  3819. gb_string_free(type_str);
  3820. gb_string_free(op_str);
  3821. operand->mode = Addressing_Invalid;
  3822. operand->expr = node;
  3823. return nullptr;
  3824. }
  3825. add_entity_use(c, selector, entity);
  3826. operand->type = entity->type;
  3827. operand->expr = node;
  3828. switch (entity->kind) {
  3829. case Entity_Constant:
  3830. operand->value = entity->Constant.value;
  3831. operand->mode = Addressing_Constant;
  3832. if (operand->value.kind == ExactValue_Procedure) {
  3833. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  3834. if (proc != nullptr) {
  3835. operand->mode = Addressing_Value;
  3836. operand->type = proc->type;
  3837. }
  3838. }
  3839. break;
  3840. case Entity_Variable:
  3841. if (sel.indirect) {
  3842. operand->mode = Addressing_Variable;
  3843. } else if (operand->mode == Addressing_Context) {
  3844. // Do nothing
  3845. } else if (operand->mode == Addressing_MapIndex) {
  3846. operand->mode = Addressing_Value;
  3847. } else if (entity->flags & EntityFlag_SoaPtrField) {
  3848. operand->mode = Addressing_SoaVariable;
  3849. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  3850. operand->mode = Addressing_Value;
  3851. } else if (operand->mode == Addressing_SoaVariable) {
  3852. operand->mode = Addressing_Variable;
  3853. } else if (operand->mode != Addressing_Value) {
  3854. operand->mode = Addressing_Variable;
  3855. } else {
  3856. operand->mode = Addressing_Value;
  3857. }
  3858. break;
  3859. case Entity_TypeName:
  3860. operand->mode = Addressing_Type;
  3861. break;
  3862. case Entity_Procedure:
  3863. operand->mode = Addressing_Value;
  3864. operand->value = exact_value_procedure(node);
  3865. break;
  3866. case Entity_Builtin:
  3867. operand->mode = Addressing_Builtin;
  3868. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  3869. break;
  3870. case Entity_ProcGroup:
  3871. operand->mode = Addressing_ProcGroup;
  3872. operand->proc_group = entity;
  3873. break;
  3874. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  3875. case Entity_Nil:
  3876. operand->mode = Addressing_Value;
  3877. break;
  3878. }
  3879. add_type_and_value(c->info, operand->expr, operand->mode, operand->type, operand->value);
  3880. return entity;
  3881. }
  3882. bool is_type_normal_pointer(Type *ptr, Type **elem) {
  3883. ptr = base_type(ptr);
  3884. if (is_type_pointer(ptr)) {
  3885. if (is_type_rawptr(ptr)) {
  3886. return false;
  3887. }
  3888. if (elem) *elem = ptr->Pointer.elem;
  3889. return true;
  3890. }
  3891. return false;
  3892. }
  3893. bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  3894. switch (node->kind) {
  3895. case_ast_node(i, Ident, node);
  3896. String name = i->token.string;
  3897. if (nested) {
  3898. Entity *e = scope_lookup_current(s, name);
  3899. if (e != nullptr) {
  3900. if (out_scope) *out_scope = e->scope;
  3901. return true;
  3902. }
  3903. } else {
  3904. Entity *e = scope_lookup(s, name);
  3905. if (e != nullptr) {
  3906. if (out_scope) *out_scope = e->scope;
  3907. return true;
  3908. }
  3909. }
  3910. case_end;
  3911. case_ast_node(se, SelectorExpr, node);
  3912. Ast *lhs = se->expr;
  3913. Ast *rhs = se->selector;
  3914. Scope *lhs_scope = nullptr;
  3915. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  3916. return check_identifier_exists(lhs_scope, rhs, true);
  3917. }
  3918. case_end;
  3919. }
  3920. return false;
  3921. }
  3922. isize add_dependencies_from_unpacking(CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) {
  3923. if (lhs != nullptr && c->decl != nullptr) {
  3924. mutex_lock(&c->info->deps_mutex);
  3925. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  3926. Entity *e = lhs[tuple_index + j];
  3927. if (e != nullptr) {
  3928. DeclInfo *decl = decl_info_of_entity(e);
  3929. if (decl != nullptr) {
  3930. for_array(k, decl->deps.entries) {
  3931. Entity *dep = decl->deps.entries[k].ptr;
  3932. ptr_set_add(&c->decl->deps, dep);
  3933. }
  3934. }
  3935. }
  3936. }
  3937. mutex_unlock(&c->info->deps_mutex);
  3938. }
  3939. return tuple_count;
  3940. }
  3941. bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  3942. bool optional_ok = false;
  3943. isize tuple_index = 0;
  3944. for_array(i, rhs) {
  3945. CheckerContext c_ = *ctx;
  3946. CheckerContext *c = &c_;
  3947. Operand o = {};
  3948. Type *type_hint = nullptr;
  3949. if (tuple_index < lhs.count) {
  3950. type_hint = lhs[tuple_index].type;
  3951. }
  3952. check_expr_base(c, &o, rhs[i], type_hint);
  3953. if (o.mode == Addressing_NoValue) {
  3954. error_operand_no_value(&o);
  3955. o.mode = Addressing_Invalid;
  3956. }
  3957. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  3958. if (lhs.count == 2 && rhs.count == 1 &&
  3959. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  3960. Ast *expr = unparen_expr(o.expr);
  3961. Operand val0 = o;
  3962. Operand val1 = o;
  3963. val0.mode = Addressing_Value;
  3964. val1.mode = Addressing_Value;
  3965. val1.type = t_untyped_bool;
  3966. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  3967. if (expr->kind == Ast_TypeAssertion &&
  3968. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  3969. // NOTE(bill): Used only for optimizations in the backend
  3970. if (is_blank_ident(lhs[0].expr)) {
  3971. expr->TypeAssertion.ignores[0] = true;
  3972. }
  3973. if (is_blank_ident(lhs[1].expr)) {
  3974. expr->TypeAssertion.ignores[1] = true;
  3975. }
  3976. }
  3977. array_add(operands, val0);
  3978. array_add(operands, val1);
  3979. optional_ok = true;
  3980. tuple_index += 2;
  3981. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  3982. Type *tuple = o.type;
  3983. GB_ASSERT(tuple->Tuple.variables.count == 2);
  3984. Ast *expr = unparen_expr(o.expr);
  3985. if (expr->kind == Ast_CallExpr) {
  3986. expr->CallExpr.optional_ok_one = true;
  3987. }
  3988. Operand val = o;
  3989. val.type = tuple->Tuple.variables[0]->type;
  3990. val.mode = Addressing_Value;
  3991. array_add(operands, val);
  3992. tuple_index += tuple->Tuple.variables.count;
  3993. } else {
  3994. array_add(operands, o);
  3995. tuple_index += 1;
  3996. }
  3997. } else {
  3998. TypeTuple *tuple = &o.type->Tuple;
  3999. for_array(j, tuple->variables) {
  4000. o.type = tuple->variables[j]->type;
  4001. array_add(operands, o);
  4002. }
  4003. tuple_index += tuple->variables.count;
  4004. }
  4005. }
  4006. return optional_ok;
  4007. }
  4008. bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs, bool allow_ok, bool is_variadic) {
  4009. bool optional_ok = false;
  4010. isize tuple_index = 0;
  4011. for_array(i, rhs) {
  4012. CheckerContext c_ = *ctx;
  4013. CheckerContext *c = &c_;
  4014. Operand o = {};
  4015. Type *type_hint = nullptr;
  4016. if (lhs != nullptr && tuple_index < lhs_count) {
  4017. // NOTE(bill): override DeclInfo for dependency
  4018. Entity *e = lhs[tuple_index];
  4019. if (e != nullptr) {
  4020. // DeclInfo *decl = decl_info_of_entity(e);
  4021. // if (decl) c->decl = decl;
  4022. type_hint = e->type;
  4023. if (e->flags & EntityFlag_Ellipsis) {
  4024. GB_ASSERT(is_type_slice(e->type));
  4025. GB_ASSERT(e->type->kind == Type_Slice);
  4026. type_hint = e->type->Slice.elem;
  4027. }
  4028. }
  4029. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  4030. // NOTE(bill): override DeclInfo for dependency
  4031. Entity *e = lhs[lhs_count-1];
  4032. if (e != nullptr) {
  4033. // DeclInfo *decl = decl_info_of_entity(e);
  4034. // if (decl) c->decl = decl;
  4035. type_hint = e->type;
  4036. if (e->flags & EntityFlag_Ellipsis) {
  4037. GB_ASSERT(is_type_slice(e->type));
  4038. GB_ASSERT(e->type->kind == Type_Slice);
  4039. type_hint = e->type->Slice.elem;
  4040. }
  4041. }
  4042. }
  4043. check_expr_base(c, &o, rhs[i], type_hint);
  4044. if (o.mode == Addressing_NoValue) {
  4045. error_operand_no_value(&o);
  4046. o.mode = Addressing_Invalid;
  4047. }
  4048. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  4049. if (allow_ok && lhs_count == 2 && rhs.count == 1 &&
  4050. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4051. Ast *expr = unparen_expr(o.expr);
  4052. Operand val0 = o;
  4053. Operand val1 = o;
  4054. val0.mode = Addressing_Value;
  4055. val1.mode = Addressing_Value;
  4056. val1.type = t_untyped_bool;
  4057. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  4058. if (expr->kind == Ast_TypeAssertion &&
  4059. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  4060. // NOTE(bill): Used only for optimizations in the backend
  4061. if (is_blank_ident(lhs[0]->token)) {
  4062. expr->TypeAssertion.ignores[0] = true;
  4063. }
  4064. if (is_blank_ident(lhs[1]->token)) {
  4065. expr->TypeAssertion.ignores[1] = true;
  4066. }
  4067. }
  4068. array_add(operands, val0);
  4069. array_add(operands, val1);
  4070. optional_ok = true;
  4071. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  4072. } else {
  4073. array_add(operands, o);
  4074. tuple_index += 1;
  4075. }
  4076. } else {
  4077. TypeTuple *tuple = &o.type->Tuple;
  4078. for_array(j, tuple->variables) {
  4079. o.type = tuple->variables[j]->type;
  4080. array_add(operands, o);
  4081. }
  4082. isize count = tuple->variables.count;
  4083. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  4084. }
  4085. }
  4086. return optional_ok;
  4087. }
  4088. bool is_expr_constant_zero(Ast *expr) {
  4089. GB_ASSERT(expr != nullptr);
  4090. auto v = exact_value_to_integer(expr->tav.value);
  4091. if (v.kind == ExactValue_Integer) {
  4092. return big_int_cmp_zero(&v.value_integer) == 0;
  4093. }
  4094. return false;
  4095. }
  4096. CALL_ARGUMENT_CHECKER(check_call_arguments_internal) {
  4097. ast_node(ce, CallExpr, call);
  4098. GB_ASSERT(is_type_proc(proc_type));
  4099. proc_type = base_type(proc_type);
  4100. TypeProc *pt = &proc_type->Proc;
  4101. isize param_count = 0;
  4102. isize param_count_excluding_defaults = 0;
  4103. bool variadic = pt->variadic;
  4104. bool vari_expand = (ce->ellipsis.pos.line != 0);
  4105. i64 score = 0;
  4106. bool show_error = show_error_mode == CallArgumentMode_ShowErrors;
  4107. TypeTuple *param_tuple = nullptr;
  4108. if (pt->params != nullptr) {
  4109. param_tuple = &pt->params->Tuple;
  4110. param_count = param_tuple->variables.count;
  4111. if (variadic) {
  4112. for (isize i = param_count-1; i >= 0; i--) {
  4113. Entity *e = param_tuple->variables[i];
  4114. if (e->kind == Entity_TypeName) {
  4115. break;
  4116. }
  4117. if (e->kind == Entity_Variable) {
  4118. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4119. param_count--;
  4120. continue;
  4121. }
  4122. }
  4123. break;
  4124. }
  4125. param_count--;
  4126. }
  4127. }
  4128. param_count_excluding_defaults = param_count;
  4129. if (param_tuple != nullptr) {
  4130. for (isize i = param_count-1; i >= 0; i--) {
  4131. Entity *e = param_tuple->variables[i];
  4132. if (e->kind == Entity_TypeName) {
  4133. break;
  4134. }
  4135. if (e->kind == Entity_Variable) {
  4136. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4137. param_count_excluding_defaults--;
  4138. continue;
  4139. }
  4140. }
  4141. break;
  4142. }
  4143. }
  4144. CallArgumentError err = CallArgumentError_None;
  4145. Type *final_proc_type = proc_type;
  4146. Entity *gen_entity = nullptr;
  4147. if (vari_expand && !variadic) {
  4148. if (show_error) {
  4149. error(ce->ellipsis,
  4150. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  4151. LIT(ce->proc->Ident.token.string));
  4152. }
  4153. err = CallArgumentError_NonVariadicExpand;
  4154. } else if (vari_expand && pt->c_vararg) {
  4155. if (show_error) {
  4156. error(ce->ellipsis,
  4157. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  4158. LIT(ce->proc->Ident.token.string));
  4159. }
  4160. err = CallArgumentError_NonVariadicExpand;
  4161. } else if (operands.count == 0 && param_count_excluding_defaults == 0) {
  4162. err = CallArgumentError_None;
  4163. if (variadic) {
  4164. GB_ASSERT(param_tuple != nullptr && param_tuple->variables.count > 0);
  4165. Type *t = param_tuple->variables[0]->type;
  4166. if (is_type_polymorphic(t)) {
  4167. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  4168. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  4169. }
  4170. }
  4171. } else {
  4172. i32 error_code = 0;
  4173. if (operands.count < param_count_excluding_defaults) {
  4174. error_code = -1;
  4175. } else if (!variadic && operands.count > param_count) {
  4176. error_code = +1;
  4177. }
  4178. if (error_code != 0) {
  4179. err = CallArgumentError_TooManyArguments;
  4180. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  4181. if (error_code < 0) {
  4182. err = CallArgumentError_TooFewArguments;
  4183. err_fmt = "Too few arguments for '%s', expected %td arguments, got %td";
  4184. }
  4185. if (show_error) {
  4186. gbString proc_str = expr_to_string(ce->proc);
  4187. defer (gb_string_free(proc_str));
  4188. error(call, err_fmt, proc_str, param_count_excluding_defaults, operands.count);
  4189. #if 0
  4190. error_line("\t");
  4191. for_array(i, operands) {
  4192. if (i > 0) {
  4193. error_line(", ");
  4194. }
  4195. gbString s = expr_to_string(operands[i].expr);
  4196. error_line("%s", s);
  4197. gb_string_free(s);
  4198. }
  4199. error_line("\n");
  4200. #endif
  4201. }
  4202. } else {
  4203. // NOTE(bill): Generate the procedure type for this generic instance
  4204. if (pt->is_polymorphic && !pt->is_poly_specialized) {
  4205. PolyProcData poly_proc_data = {};
  4206. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &operands, call, &poly_proc_data)) {
  4207. gen_entity = poly_proc_data.gen_entity;
  4208. GB_ASSERT(is_type_proc(gen_entity->type));
  4209. final_proc_type = gen_entity->type;
  4210. } else {
  4211. err = CallArgumentError_WrongTypes;
  4212. }
  4213. }
  4214. GB_ASSERT(is_type_proc(final_proc_type));
  4215. TypeProc *pt = &final_proc_type->Proc;
  4216. GB_ASSERT(pt->params != nullptr);
  4217. auto sig_params = pt->params->Tuple.variables;
  4218. isize operand_index = 0;
  4219. isize max_operand_count = gb_min(param_count, operands.count);
  4220. for (; operand_index < max_operand_count; operand_index++) {
  4221. Entity *e = sig_params[operand_index];
  4222. Type *t = e->type;
  4223. Operand o = operands[operand_index];
  4224. if (o.expr != nullptr) {
  4225. call->viral_state_flags |= o.expr->viral_state_flags;
  4226. }
  4227. if (e->kind == Entity_TypeName) {
  4228. // GB_ASSERT(!variadic);
  4229. if (o.mode == Addressing_Invalid) {
  4230. continue;
  4231. } else if (o.mode != Addressing_Type) {
  4232. if (show_error) {
  4233. error(o.expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  4234. }
  4235. err = CallArgumentError_WrongTypes;
  4236. }
  4237. if (are_types_identical(e->type, o.type)) {
  4238. score += assign_score_function(1);
  4239. } else {
  4240. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  4241. }
  4242. continue;
  4243. }
  4244. bool param_is_variadic = pt->variadic && pt->variadic_index == operand_index;
  4245. i64 s = 0;
  4246. if (!check_is_assignable_to_with_score(c, &o, t, &s, param_is_variadic)) {
  4247. bool ok = false;
  4248. if (e->flags & EntityFlag_AutoCast) {
  4249. ok = check_is_castable_to(c, &o, t);
  4250. } else if (e->flags & EntityFlag_AnyInt) {
  4251. if (is_type_integer(t)) {
  4252. ok = check_is_castable_to(c, &o, t);
  4253. }
  4254. }
  4255. if (ok) {
  4256. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  4257. } else {
  4258. if (show_error) {
  4259. check_assignment(c, &o, t, str_lit("argument"));
  4260. }
  4261. // TODO(bill, 2021-05-05): Is this incorrect logic to only fail if there is ambiguity for definite?
  4262. if (o.mode == Addressing_Invalid) {
  4263. err = CallArgumentError_WrongTypes;
  4264. }
  4265. }
  4266. } else if (show_error) {
  4267. check_assignment(c, &o, t, str_lit("argument"));
  4268. }
  4269. score += s;
  4270. if (e->flags & EntityFlag_ConstInput) {
  4271. if (o.mode != Addressing_Constant) {
  4272. if (show_error) {
  4273. error(o.expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  4274. }
  4275. err = CallArgumentError_NoneConstantParameter;
  4276. }
  4277. }
  4278. if (o.mode == Addressing_Type && is_type_typeid(e->type)) {
  4279. add_type_info_type(c, o.type);
  4280. add_type_and_value(c->info, o.expr, Addressing_Value, e->type, exact_value_typeid(o.type));
  4281. } else if (show_error && is_type_untyped(o.type)) {
  4282. update_untyped_expr_type(c, o.expr, t, true);
  4283. }
  4284. }
  4285. if (variadic) {
  4286. bool variadic_expand = false;
  4287. Type *slice = sig_params[param_count]->type;
  4288. GB_ASSERT(is_type_slice(slice));
  4289. Type *elem = base_type(slice)->Slice.elem;
  4290. Type *t = elem;
  4291. if (is_type_polymorphic(t)) {
  4292. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  4293. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  4294. }
  4295. for (; operand_index < operands.count; operand_index++) {
  4296. Operand o = operands[operand_index];
  4297. if (vari_expand) {
  4298. variadic_expand = true;
  4299. t = slice;
  4300. if (operand_index != param_count) {
  4301. if (show_error) {
  4302. error(o.expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  4303. }
  4304. if (data) {
  4305. data->score = score;
  4306. data->result_type = final_proc_type->Proc.results;
  4307. data->gen_entity = gen_entity;
  4308. }
  4309. return CallArgumentError_MultipleVariadicExpand;
  4310. }
  4311. }
  4312. i64 s = 0;
  4313. if (!check_is_assignable_to_with_score(c, &o, t, &s, true)) {
  4314. if (show_error) {
  4315. check_assignment(c, &o, t, str_lit("argument"));
  4316. }
  4317. err = CallArgumentError_WrongTypes;
  4318. } else if (show_error) {
  4319. check_assignment(c, &o, t, str_lit("argument"));
  4320. }
  4321. score += s;
  4322. if (is_type_any(elem)) {
  4323. add_type_info_type(c, o.type);
  4324. }
  4325. if (o.mode == Addressing_Type && is_type_typeid(t)) {
  4326. add_type_info_type(c, o.type);
  4327. add_type_and_value(c->info, o.expr, Addressing_Value, t, exact_value_typeid(o.type));
  4328. } else if (show_error && is_type_untyped(o.type)) {
  4329. update_untyped_expr_type(c, o.expr, t, true);
  4330. }
  4331. }
  4332. }
  4333. }
  4334. }
  4335. if (data) {
  4336. data->score = score;
  4337. data->result_type = final_proc_type->Proc.results;
  4338. data->gen_entity = gen_entity;
  4339. add_type_and_value(c->info, ce->proc, Addressing_Value, final_proc_type, {});
  4340. }
  4341. return err;
  4342. }
  4343. bool is_call_expr_field_value(AstCallExpr *ce) {
  4344. GB_ASSERT(ce != nullptr);
  4345. if (ce->args.count == 0) {
  4346. return false;
  4347. }
  4348. return ce->args[0]->kind == Ast_FieldValue;
  4349. }
  4350. isize lookup_procedure_parameter(TypeProc *pt, String parameter_name) {
  4351. isize param_count = pt->param_count;
  4352. for (isize i = 0; i < param_count; i++) {
  4353. Entity *e = pt->params->Tuple.variables[i];
  4354. String name = e->token.string;
  4355. if (is_blank_ident(name)) {
  4356. continue;
  4357. }
  4358. if (name == parameter_name) {
  4359. return i;
  4360. }
  4361. }
  4362. return -1;
  4363. }
  4364. isize lookup_procedure_result(TypeProc *pt, String result_name) {
  4365. isize result_count = pt->result_count;
  4366. for (isize i = 0; i < result_count; i++) {
  4367. Entity *e = pt->results->Tuple.variables[i];
  4368. String name = e->token.string;
  4369. if (is_blank_ident(name)) {
  4370. continue;
  4371. }
  4372. if (name == result_name) {
  4373. return i;
  4374. }
  4375. }
  4376. return -1;
  4377. }
  4378. CALL_ARGUMENT_CHECKER(check_named_call_arguments) {
  4379. ast_node(ce, CallExpr, call);
  4380. GB_ASSERT(is_type_proc(proc_type));
  4381. proc_type = base_type(proc_type);
  4382. TypeProc *pt = &proc_type->Proc;
  4383. i64 score = 0;
  4384. bool show_error = show_error_mode == CallArgumentMode_ShowErrors;
  4385. CallArgumentError err = CallArgumentError_None;
  4386. isize param_count = pt->param_count;
  4387. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  4388. auto ordered_operands = array_make<Operand>(temporary_allocator(), param_count);
  4389. defer ({
  4390. for_array(i, ordered_operands) {
  4391. Operand const &o = ordered_operands[i];
  4392. if (o.expr != nullptr) {
  4393. call->viral_state_flags |= o.expr->viral_state_flags;
  4394. }
  4395. }
  4396. });
  4397. for_array(i, ce->args) {
  4398. Ast *arg = ce->args[i];
  4399. ast_node(fv, FieldValue, arg);
  4400. if (fv->field->kind != Ast_Ident) {
  4401. if (show_error) {
  4402. gbString expr_str = expr_to_string(fv->field);
  4403. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  4404. gb_string_free(expr_str);
  4405. }
  4406. err = CallArgumentError_InvalidFieldValue;
  4407. continue;
  4408. }
  4409. String name = fv->field->Ident.token.string;
  4410. isize index = lookup_procedure_parameter(pt, name);
  4411. if (index < 0) {
  4412. if (show_error) {
  4413. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  4414. }
  4415. err = CallArgumentError_ParameterNotFound;
  4416. continue;
  4417. }
  4418. if (visited[index]) {
  4419. if (show_error) {
  4420. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  4421. }
  4422. err = CallArgumentError_DuplicateParameter;
  4423. continue;
  4424. }
  4425. visited[index] = true;
  4426. ordered_operands[index] = operands[i];
  4427. }
  4428. // NOTE(bill): Check for default values and missing parameters
  4429. isize param_count_to_check = param_count;
  4430. if (pt->variadic) {
  4431. param_count_to_check--;
  4432. }
  4433. for (isize i = 0; i < param_count_to_check; i++) {
  4434. if (!visited[i]) {
  4435. Entity *e = pt->params->Tuple.variables[i];
  4436. if (is_blank_ident(e->token)) {
  4437. continue;
  4438. }
  4439. if (e->kind == Entity_Variable) {
  4440. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  4441. score += assign_score_function(1);
  4442. continue;
  4443. }
  4444. }
  4445. if (show_error) {
  4446. if (e->kind == Entity_TypeName) {
  4447. error(call, "Type parameter '%.*s' is missing in procedure call",
  4448. LIT(e->token.string));
  4449. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  4450. // Ignore
  4451. } else {
  4452. gbString str = type_to_string(e->type);
  4453. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  4454. LIT(e->token.string), str);
  4455. gb_string_free(str);
  4456. }
  4457. }
  4458. err = CallArgumentError_ParameterMissing;
  4459. }
  4460. }
  4461. Entity *gen_entity = nullptr;
  4462. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  4463. PolyProcData poly_proc_data = {};
  4464. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  4465. gen_entity = poly_proc_data.gen_entity;
  4466. Type *gept = base_type(gen_entity->type);
  4467. GB_ASSERT(is_type_proc(gept));
  4468. proc_type = gept;
  4469. pt = &gept->Proc;
  4470. }
  4471. }
  4472. for (isize i = 0; i < param_count; i++) {
  4473. Entity *e = pt->params->Tuple.variables[i];
  4474. Operand *o = &ordered_operands[i];
  4475. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  4476. if (o->mode == Addressing_Invalid) {
  4477. if (param_is_variadic) {
  4478. Type *slice = e->type;
  4479. GB_ASSERT(is_type_slice(slice));
  4480. Type *elem = base_type(slice)->Slice.elem;
  4481. if (is_type_polymorphic(elem)) {
  4482. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  4483. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  4484. return err;
  4485. }
  4486. }
  4487. continue;
  4488. }
  4489. if (e->kind == Entity_TypeName) {
  4490. GB_ASSERT(pt->is_polymorphic);
  4491. if (o->mode != Addressing_Type) {
  4492. if (show_error) {
  4493. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  4494. }
  4495. err = CallArgumentError_WrongTypes;
  4496. }
  4497. if (are_types_identical(e->type, o->type)) {
  4498. score += assign_score_function(1);
  4499. } else {
  4500. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  4501. }
  4502. } else {
  4503. i64 s = 0;
  4504. if (!check_is_assignable_to_with_score(c, o, e->type, &s, param_is_variadic)) {
  4505. bool ok = false;
  4506. if (e->flags & EntityFlag_AutoCast) {
  4507. ok = check_is_castable_to(c, o, e->type);
  4508. }
  4509. if (ok) {
  4510. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  4511. } else {
  4512. if (show_error) {
  4513. check_assignment(c, o, e->type, str_lit("procedure argument"));
  4514. }
  4515. err = CallArgumentError_WrongTypes;
  4516. }
  4517. if (e->flags & EntityFlag_ConstInput) {
  4518. if (o->mode != Addressing_Constant) {
  4519. if (show_error) {
  4520. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  4521. }
  4522. err = CallArgumentError_NoneConstantParameter;
  4523. }
  4524. }
  4525. } else if (show_error) {
  4526. check_assignment(c, o, e->type, str_lit("procedure argument"));
  4527. }
  4528. score += s;
  4529. }
  4530. if (o->mode == Addressing_Type && is_type_typeid(e->type)) {
  4531. add_type_info_type(c, o->type);
  4532. add_type_and_value(c->info, o->expr, Addressing_Value, e->type, exact_value_typeid(o->type));
  4533. }
  4534. }
  4535. if (data) {
  4536. data->score = score;
  4537. data->result_type = pt->results;
  4538. data->gen_entity = gen_entity;
  4539. add_type_and_value(c->info, ce->proc, Addressing_Value, proc_type, {});
  4540. }
  4541. return err;
  4542. }
  4543. Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  4544. Entity **lhs = nullptr;
  4545. isize lhs_count = -1;
  4546. if (proc_type == nullptr) {
  4547. return nullptr;
  4548. }
  4549. GB_ASSERT(is_type_proc(proc_type));
  4550. TypeProc *pt = &base_type(proc_type)->Proc;
  4551. *is_variadic = pt->variadic;
  4552. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  4553. if (pt->params != nullptr) {
  4554. lhs = pt->params->Tuple.variables.data;
  4555. lhs_count = pt->params->Tuple.variables.count;
  4556. }
  4557. } else {
  4558. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  4559. if (pt->params == nullptr) {
  4560. lhs_count = 0;
  4561. } else {
  4562. lhs_count = pt->params->Tuple.variables.count;
  4563. }
  4564. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  4565. for (isize i = 0; i < lhs_count; i++) {
  4566. Entity *e = pt->params->Tuple.variables[i];
  4567. if (!is_type_polymorphic(e->type)) {
  4568. lhs[i] = e;
  4569. }
  4570. }
  4571. }
  4572. if (lhs_count_) *lhs_count_ = lhs_count;
  4573. return lhs;
  4574. }
  4575. bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  4576. if (clauses != nullptr) {
  4577. for_array(i, *clauses) {
  4578. Ast *clause = (*clauses)[i];
  4579. Operand o = {};
  4580. check_expr(ctx, &o, clause);
  4581. if (o.mode != Addressing_Constant) {
  4582. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  4583. if (print_err && call_expr) error(call_expr, "at caller location");
  4584. return false;
  4585. } else if (o.value.kind != ExactValue_Bool) {
  4586. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  4587. if (print_err && call_expr) error(call_expr, "at caller location");
  4588. return false;
  4589. } else if (!o.value.value_bool) {
  4590. if (print_err) {
  4591. ERROR_BLOCK();
  4592. gbString str = expr_to_string(clause);
  4593. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  4594. gb_string_free(str);
  4595. if (scope != nullptr) {
  4596. isize print_count = 0;
  4597. for_array(j, scope->elements.entries) {
  4598. Entity *e = scope->elements.entries[j].value;
  4599. switch (e->kind) {
  4600. case Entity_TypeName: {
  4601. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  4602. gbString str = type_to_string(e->type);
  4603. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  4604. gb_string_free(str);
  4605. print_count += 1;
  4606. break;
  4607. }
  4608. case Entity_Constant: {
  4609. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  4610. gbString str = exact_value_to_string(e->Constant.value);
  4611. if (is_type_untyped(e->type)) {
  4612. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  4613. } else {
  4614. gbString t = type_to_string(e->type);
  4615. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  4616. gb_string_free(t);
  4617. }
  4618. gb_string_free(str);
  4619. print_count += 1;
  4620. break;
  4621. }
  4622. }
  4623. }
  4624. }
  4625. if (call_expr) error(call_expr, "at caller location");
  4626. }
  4627. return false;
  4628. }
  4629. }
  4630. }
  4631. return true;
  4632. }
  4633. CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Type *proc_type, Ast *call, Slice<Ast *> const &args) {
  4634. ast_node(ce, CallExpr, call);
  4635. CallArgumentCheckerType *call_checker = check_call_arguments_internal;
  4636. Array<Operand> operands = {};
  4637. defer (array_free(&operands));
  4638. Type *result_type = t_invalid;
  4639. if (is_call_expr_field_value(ce)) {
  4640. call_checker = check_named_call_arguments;
  4641. operands = array_make<Operand>(heap_allocator(), args.count);
  4642. // NOTE(bill): This is give type hints for the named parameters
  4643. // in order to improve the type inference system
  4644. StringMap<Type *> type_hint_map = {}; // Key: String
  4645. string_map_init(&type_hint_map, heap_allocator(), 2*args.count);
  4646. defer (string_map_destroy(&type_hint_map));
  4647. Type *ptype = nullptr;
  4648. bool single_case = true;
  4649. if (operand->mode == Addressing_ProcGroup) {
  4650. single_case = false;
  4651. Array<Entity *> procs = proc_group_entities(c, *operand);
  4652. if (procs.count == 1) {
  4653. ptype = procs[0]->type;
  4654. single_case = true;
  4655. }
  4656. } else {
  4657. ptype = proc_type;
  4658. }
  4659. if (single_case) {
  4660. Type *bptype = base_type(ptype);
  4661. if (is_type_proc(bptype)) {
  4662. TypeProc *pt = &bptype->Proc;
  4663. TypeTuple *param_tuple = nullptr;
  4664. if (pt->params != nullptr) {
  4665. param_tuple = &pt->params->Tuple;
  4666. }
  4667. if (param_tuple != nullptr) {
  4668. for_array(i, param_tuple->variables) {
  4669. Entity *e = param_tuple->variables[i];
  4670. if (is_blank_ident(e->token)) {
  4671. continue;
  4672. }
  4673. string_map_set(&type_hint_map, e->token.string, e->type);
  4674. }
  4675. }
  4676. }
  4677. } else {
  4678. Array<Entity *> procs = proc_group_entities(c, *operand);
  4679. for_array(j, procs) {
  4680. Type *proc_type = base_type(procs[j]->type);
  4681. if (is_type_proc(proc_type)) {
  4682. TypeProc *pt = &proc_type->Proc;
  4683. TypeTuple *param_tuple = nullptr;
  4684. if (pt->params != nullptr) {
  4685. param_tuple = &pt->params->Tuple;
  4686. }
  4687. if (param_tuple == nullptr) {
  4688. continue;
  4689. }
  4690. for_array(i, param_tuple->variables) {
  4691. Entity *e = param_tuple->variables[i];
  4692. if (is_blank_ident(e->token)) {
  4693. continue;
  4694. }
  4695. StringHashKey key = string_hash_string(e->token.string);
  4696. Type **found = string_map_get(&type_hint_map, key);
  4697. if (found) {
  4698. Type *t = *found;
  4699. if (t == nullptr) {
  4700. // NOTE(bill): Ambiguous named parameter across all types
  4701. continue;
  4702. }
  4703. if (are_types_identical(t, e->type)) {
  4704. // NOTE(bill): No need to set again
  4705. } else {
  4706. // NOTE(bill): Ambiguous named parameter across all types so set it to a nullptr
  4707. string_map_set(&type_hint_map, key, cast(Type *)nullptr);
  4708. }
  4709. } else {
  4710. string_map_set(&type_hint_map, key, e->type);
  4711. }
  4712. }
  4713. }
  4714. }
  4715. }
  4716. for_array(i, args) {
  4717. Ast *arg = args[i];
  4718. ast_node(fv, FieldValue, arg);
  4719. Ast *field = fv->field;
  4720. Type *type_hint = nullptr;
  4721. if (field != nullptr && field->kind == Ast_Ident) {
  4722. String key = field->Ident.token.string;
  4723. Type **found = string_map_get(&type_hint_map, key);
  4724. if (found) {
  4725. type_hint = *found;
  4726. }
  4727. }
  4728. check_expr_or_type(c, &operands[i], fv->value, type_hint);
  4729. }
  4730. } else {
  4731. operands = array_make<Operand>(heap_allocator(), 0, 2*args.count);
  4732. Entity **lhs = nullptr;
  4733. isize lhs_count = -1;
  4734. bool is_variadic = false;
  4735. if (proc_type != nullptr && is_type_proc(proc_type)) {
  4736. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  4737. }
  4738. if (operand->mode != Addressing_ProcGroup) {
  4739. check_unpack_arguments(c, lhs, lhs_count, &operands, args, false, is_variadic);
  4740. }
  4741. }
  4742. if (operand->mode == Addressing_ProcGroup) {
  4743. check_entity_decl(c, operand->proc_group, nullptr, nullptr);
  4744. Array<Entity *> procs = proc_group_entities(c, *operand);
  4745. if (procs.count == 1) {
  4746. Ast *ident = operand->expr;
  4747. while (ident->kind == Ast_SelectorExpr) {
  4748. Ast *s = ident->SelectorExpr.selector;
  4749. ident = s;
  4750. }
  4751. Entity *e = procs[0];
  4752. Entity **lhs = nullptr;
  4753. isize lhs_count = -1;
  4754. bool is_variadic = false;
  4755. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  4756. check_unpack_arguments(c, lhs, lhs_count, &operands, args, false, is_variadic);
  4757. CallArgumentData data = {};
  4758. CallArgumentError err = call_checker(c, call, e->type, e, operands, CallArgumentMode_ShowErrors, &data);
  4759. if (err != CallArgumentError_None) {
  4760. // handle error
  4761. }
  4762. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  4763. add_entity_use(c, ident, entity_to_use);
  4764. if (entity_to_use != nullptr) {
  4765. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  4766. }
  4767. return data;
  4768. }
  4769. Entity **lhs = nullptr;
  4770. isize lhs_count = -1;
  4771. {
  4772. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  4773. // where the same positional parameter has the same type value (and ellipsis)
  4774. bool proc_arg_count_all_equal = true;
  4775. isize proc_arg_count = -1;
  4776. for_array(i, procs) {
  4777. Entity *p = procs[i];
  4778. Type *pt = base_type(p->type);
  4779. if (pt != nullptr && is_type_proc(pt)) {
  4780. if (proc_arg_count < 0) {
  4781. proc_arg_count = pt->Proc.param_count;
  4782. } else {
  4783. if (proc_arg_count != pt->Proc.param_count) {
  4784. proc_arg_count_all_equal = false;
  4785. break;
  4786. }
  4787. }
  4788. }
  4789. }
  4790. if (proc_arg_count >= 0 && proc_arg_count_all_equal) {
  4791. lhs_count = proc_arg_count;
  4792. if (lhs_count > 0) {
  4793. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  4794. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  4795. Entity *e = nullptr;
  4796. for_array(j, procs) {
  4797. Entity *p = procs[j];
  4798. Type *pt = base_type(p->type);
  4799. if (pt != nullptr && is_type_proc(pt)) {
  4800. if (e == nullptr) {
  4801. e = pt->Proc.params->Tuple.variables[param_index];
  4802. } else {
  4803. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  4804. if (e == f) {
  4805. continue;
  4806. }
  4807. if (are_types_identical(e->type, f->type)) {
  4808. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  4809. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  4810. if (ee == fe) {
  4811. continue;
  4812. }
  4813. }
  4814. // NOTE(bill): Entities are not close enough to be used
  4815. e = nullptr;
  4816. break;
  4817. }
  4818. }
  4819. }
  4820. lhs[param_index] = e;
  4821. }
  4822. }
  4823. }
  4824. }
  4825. check_unpack_arguments(c, lhs, lhs_count, &operands, args, false, false);
  4826. if (lhs != nullptr) {
  4827. gb_free(heap_allocator(), lhs);
  4828. }
  4829. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  4830. defer (array_free(&valids));
  4831. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  4832. defer (array_free(&proc_entities));
  4833. for_array(i, procs) {
  4834. array_add(&proc_entities, procs[i]);
  4835. }
  4836. gbString expr_name = expr_to_string(operand->expr);
  4837. defer (gb_string_free(expr_name));
  4838. for_array(i, procs) {
  4839. Entity *p = procs[i];
  4840. Type *pt = base_type(p->type);
  4841. if (pt != nullptr && is_type_proc(pt)) {
  4842. CallArgumentError err = CallArgumentError_None;
  4843. CallArgumentData data = {};
  4844. CheckerContext ctx = *c;
  4845. ctx.no_polymorphic_errors = true;
  4846. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  4847. ctx.hide_polymorphic_errors = true;
  4848. err = call_checker(&ctx, call, pt, p, operands, CallArgumentMode_NoErrors, &data);
  4849. if (err != CallArgumentError_None) {
  4850. continue;
  4851. }
  4852. isize index = i;
  4853. if (data.gen_entity != nullptr) {
  4854. Entity *e = data.gen_entity;
  4855. DeclInfo *decl = data.gen_entity->decl_info;
  4856. ctx.scope = decl->scope;
  4857. ctx.decl = decl;
  4858. ctx.proc_name = e->token.string;
  4859. ctx.curr_proc_decl = decl;
  4860. ctx.curr_proc_sig = e->type;
  4861. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  4862. if (!evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, false)) {
  4863. continue;
  4864. }
  4865. array_add(&proc_entities, data.gen_entity);
  4866. index = proc_entities.count-1;
  4867. }
  4868. ValidIndexAndScore item = {};
  4869. item.index = index;
  4870. item.score = data.score;
  4871. array_add(&valids, item);
  4872. }
  4873. }
  4874. if (valids.count > 1) {
  4875. gb_sort_array(valids.data, valids.count, valid_index_and_score_cmp);
  4876. i64 best_score = valids[0].score;
  4877. Entity *best_entity = proc_entities[valids[0].index];
  4878. GB_ASSERT(best_entity != nullptr);
  4879. for (isize i = 1; i < valids.count; i++) {
  4880. if (best_score > valids[i].score) {
  4881. valids.count = i;
  4882. break;
  4883. }
  4884. if (best_entity == proc_entities[valids[i].index]) {
  4885. valids.count = i;
  4886. break;
  4887. }
  4888. }
  4889. }
  4890. if (valids.count == 0) {
  4891. begin_error_block();
  4892. defer (end_error_block());
  4893. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  4894. if (operands.count == 0) {
  4895. error_line("\tNo given arguments\n");
  4896. } else {
  4897. error_line("\tGiven argument types: (");
  4898. for_array(i, operands) {
  4899. Operand o = operands[i];
  4900. if (i > 0) error_line(", ");
  4901. gbString type = type_to_string(o.type);
  4902. defer (gb_string_free(type));
  4903. error_line("%s", type);
  4904. }
  4905. error_line(")\n");
  4906. }
  4907. if (procs.count > 0) {
  4908. error_line("Did you mean to use one of the following:\n");
  4909. }
  4910. for_array(i, procs) {
  4911. Entity *proc = procs[i];
  4912. TokenPos pos = proc->token.pos;
  4913. Type *t = base_type(proc->type);
  4914. if (t == t_invalid) continue;
  4915. GB_ASSERT(t->kind == Type_Proc);
  4916. gbString pt;
  4917. defer (gb_string_free(pt));
  4918. if (t->Proc.node != nullptr) {
  4919. pt = expr_to_string(t->Proc.node);
  4920. } else {
  4921. pt = type_to_string(t);
  4922. }
  4923. String prefix = {};
  4924. String prefix_sep = {};
  4925. if (proc->pkg) {
  4926. prefix = proc->pkg->name;
  4927. prefix_sep = str_lit(".");
  4928. }
  4929. String name = proc->token.string;
  4930. char const *sep = "::";
  4931. if (proc->kind == Entity_Variable) {
  4932. sep = ":=";
  4933. }
  4934. 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));
  4935. }
  4936. if (procs.count > 0) {
  4937. error_line("\n");
  4938. }
  4939. result_type = t_invalid;
  4940. } else if (valids.count > 1) {
  4941. begin_error_block();
  4942. defer (end_error_block());
  4943. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  4944. error_line("\tGiven argument types: (");
  4945. for_array(i, operands) {
  4946. Operand o = operands[i];
  4947. if (i > 0) error_line(", ");
  4948. gbString type = type_to_string(o.type);
  4949. defer (gb_string_free(type));
  4950. error_line("%s", type);
  4951. }
  4952. error_line(")\n");
  4953. for (isize i = 0; i < valids.count; i++) {
  4954. Entity *proc = proc_entities[valids[i].index];
  4955. GB_ASSERT(proc != nullptr);
  4956. TokenPos pos = proc->token.pos;
  4957. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  4958. gbString pt = nullptr;
  4959. defer (gb_string_free(pt));
  4960. if (t->Proc.node != nullptr) {
  4961. pt = expr_to_string(t->Proc.node);
  4962. } else {
  4963. pt = type_to_string(t);
  4964. }
  4965. String name = proc->token.string;
  4966. char const *sep = "::";
  4967. if (proc->kind == Entity_Variable) {
  4968. sep = ":=";
  4969. }
  4970. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  4971. if (proc->decl_info->proc_lit != nullptr) {
  4972. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  4973. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  4974. if (pl->where_token.kind != Token_Invalid) {
  4975. error_line("\n\t\twhere ");
  4976. for_array(j, pl->where_clauses) {
  4977. Ast *clause = pl->where_clauses[j];
  4978. if (j != 0) {
  4979. error_line("\t\t ");
  4980. }
  4981. gbString str = expr_to_string(clause);
  4982. error_line("%s", str);
  4983. gb_string_free(str);
  4984. if (j != pl->where_clauses.count-1) {
  4985. error_line(",");
  4986. }
  4987. }
  4988. error_line("\n\t");
  4989. }
  4990. }
  4991. error_line("at %s\n", token_pos_to_string(pos));
  4992. }
  4993. result_type = t_invalid;
  4994. } else {
  4995. Ast *ident = operand->expr;
  4996. while (ident->kind == Ast_SelectorExpr) {
  4997. Ast *s = ident->SelectorExpr.selector;
  4998. ident = s;
  4999. }
  5000. Entity *e = proc_entities[valids[0].index];
  5001. GB_ASSERT(e != nullptr);
  5002. proc_type = e->type;
  5003. CallArgumentData data = {};
  5004. CallArgumentError err = call_checker(c, call, proc_type, e, operands, CallArgumentMode_ShowErrors, &data);
  5005. gb_unused(err);
  5006. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  5007. add_entity_use(c, ident, entity_to_use);
  5008. if (entity_to_use != nullptr) {
  5009. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5010. }
  5011. if (data.gen_entity != nullptr) {
  5012. Entity *e = data.gen_entity;
  5013. DeclInfo *decl = data.gen_entity->decl_info;
  5014. CheckerContext ctx = *c;
  5015. ctx.scope = decl->scope;
  5016. ctx.decl = decl;
  5017. ctx.proc_name = e->token.string;
  5018. ctx.curr_proc_decl = decl;
  5019. ctx.curr_proc_sig = e->type;
  5020. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5021. evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, true);
  5022. decl->where_clauses_evaluated = true;
  5023. }
  5024. return data;
  5025. }
  5026. } else {
  5027. Ast *ident = operand->expr;
  5028. while (ident->kind == Ast_SelectorExpr) {
  5029. Ast *s = ident->SelectorExpr.selector;
  5030. ident = s;
  5031. }
  5032. Entity *e = entity_of_node(ident);
  5033. CallArgumentData data = {};
  5034. CallArgumentError err = call_checker(c, call, proc_type, e, operands, CallArgumentMode_ShowErrors, &data);
  5035. gb_unused(err);
  5036. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  5037. add_entity_use(c, ident, entity_to_use);
  5038. if (entity_to_use != nullptr) {
  5039. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5040. }
  5041. if (data.gen_entity != nullptr) {
  5042. Entity *e = data.gen_entity;
  5043. DeclInfo *decl = data.gen_entity->decl_info;
  5044. CheckerContext ctx = *c;
  5045. ctx.scope = decl->scope;
  5046. ctx.decl = decl;
  5047. ctx.proc_name = e->token.string;
  5048. ctx.curr_proc_decl = decl;
  5049. ctx.curr_proc_sig = e->type;
  5050. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5051. evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, true);
  5052. decl->where_clauses_evaluated = true;
  5053. }
  5054. return data;
  5055. }
  5056. CallArgumentData data = {};
  5057. data.result_type = t_invalid;
  5058. return data;
  5059. }
  5060. isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  5061. if (!is_type_polymorphic_record(t)) {
  5062. return -1;
  5063. }
  5064. TypeTuple *params = get_record_polymorphic_params(t);
  5065. if (params == nullptr) {
  5066. return -1;
  5067. }
  5068. for_array(i, params->variables) {
  5069. Entity *e = params->variables[i];
  5070. String name = e->token.string;
  5071. if (is_blank_ident(name)) {
  5072. continue;
  5073. }
  5074. if (name == parameter_name) {
  5075. return i;
  5076. }
  5077. }
  5078. return -1;
  5079. }
  5080. CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  5081. ast_node(ce, CallExpr, call);
  5082. Type *original_type = operand->type;
  5083. GB_ASSERT(is_type_polymorphic_record(original_type));
  5084. bool show_error = true;
  5085. Array<Operand> operands = {};
  5086. defer (array_free(&operands));
  5087. bool named_fields = false;
  5088. {
  5089. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  5090. auto prev_type_path = c->type_path;
  5091. c->type_path = new_checker_type_path();
  5092. defer ({
  5093. destroy_checker_type_path(c->type_path);
  5094. c->type_path = prev_type_path;
  5095. });
  5096. if (is_call_expr_field_value(ce)) {
  5097. named_fields = true;
  5098. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  5099. for_array(i, ce->args) {
  5100. Ast *arg = ce->args[i];
  5101. ast_node(fv, FieldValue, arg);
  5102. if (fv->field->kind == Ast_Ident) {
  5103. String name = fv->field->Ident.token.string;
  5104. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5105. if (index >= 0) {
  5106. TypeTuple *params = get_record_polymorphic_params(original_type);
  5107. Entity *e = params->variables[i];
  5108. if (e->kind == Entity_Constant) {
  5109. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  5110. continue;
  5111. }
  5112. }
  5113. }
  5114. check_expr_or_type(c, &operands[i], fv->value);
  5115. }
  5116. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5117. if (vari_expand) {
  5118. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  5119. }
  5120. } else {
  5121. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  5122. Entity **lhs = nullptr;
  5123. isize lhs_count = -1;
  5124. TypeTuple *params = get_record_polymorphic_params(original_type);
  5125. if (params != nullptr) {
  5126. lhs = params->variables.data;
  5127. lhs_count = params->variables.count;
  5128. }
  5129. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, false, false);
  5130. }
  5131. }
  5132. CallArgumentError err = CallArgumentError_None;
  5133. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  5134. isize param_count = tuple->variables.count;
  5135. isize minimum_param_count = param_count;
  5136. for (; minimum_param_count > 0; minimum_param_count--) {
  5137. Entity *e = tuple->variables[minimum_param_count-1];
  5138. if (e->kind != Entity_Constant) {
  5139. break;
  5140. }
  5141. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  5142. break;
  5143. }
  5144. }
  5145. Array<Operand> ordered_operands = operands;
  5146. if (!named_fields) {
  5147. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5148. array_copy(&ordered_operands, operands, 0);
  5149. } else {
  5150. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  5151. // LEAK(bill)
  5152. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5153. for_array(i, ce->args) {
  5154. Ast *arg = ce->args[i];
  5155. ast_node(fv, FieldValue, arg);
  5156. if (fv->field->kind != Ast_Ident) {
  5157. if (show_error) {
  5158. gbString expr_str = expr_to_string(fv->field);
  5159. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  5160. gb_string_free(expr_str);
  5161. }
  5162. err = CallArgumentError_InvalidFieldValue;
  5163. continue;
  5164. }
  5165. String name = fv->field->Ident.token.string;
  5166. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5167. if (index < 0) {
  5168. if (show_error) {
  5169. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  5170. }
  5171. err = CallArgumentError_ParameterNotFound;
  5172. continue;
  5173. }
  5174. if (visited[index]) {
  5175. if (show_error) {
  5176. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  5177. }
  5178. err = CallArgumentError_DuplicateParameter;
  5179. continue;
  5180. }
  5181. visited[index] = true;
  5182. ordered_operands[index] = operands[i];
  5183. }
  5184. for (isize i = 0; i < param_count; i++) {
  5185. if (!visited[i]) {
  5186. Entity *e = tuple->variables[i];
  5187. if (is_blank_ident(e->token)) {
  5188. continue;
  5189. }
  5190. if (show_error) {
  5191. if (e->kind == Entity_TypeName) {
  5192. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  5193. LIT(e->token.string));
  5194. } else {
  5195. gbString str = type_to_string(e->type);
  5196. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  5197. LIT(e->token.string), str);
  5198. gb_string_free(str);
  5199. }
  5200. }
  5201. err = CallArgumentError_ParameterMissing;
  5202. }
  5203. }
  5204. }
  5205. if (err != 0) {
  5206. operand->mode = Addressing_Invalid;
  5207. return err;
  5208. }
  5209. while (ordered_operands.count > 0) {
  5210. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  5211. break;
  5212. }
  5213. array_pop(&ordered_operands);
  5214. }
  5215. if (minimum_param_count != param_count) {
  5216. if (param_count < ordered_operands.count) {
  5217. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  5218. err = CallArgumentError_TooManyArguments;
  5219. } else if (minimum_param_count > ordered_operands.count) {
  5220. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  5221. err = CallArgumentError_TooFewArguments;
  5222. }
  5223. } else {
  5224. if (param_count < ordered_operands.count) {
  5225. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  5226. err = CallArgumentError_TooManyArguments;
  5227. } else if (param_count > ordered_operands.count) {
  5228. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  5229. err = CallArgumentError_TooFewArguments;
  5230. }
  5231. }
  5232. if (err != 0) {
  5233. return err;
  5234. }
  5235. if (minimum_param_count != param_count) {
  5236. array_resize(&ordered_operands, param_count);
  5237. isize missing_count = 0;
  5238. // NOTE(bill): Replace missing operands with the default values (if possible)
  5239. for_array(i, ordered_operands) {
  5240. Operand *o = &ordered_operands[i];
  5241. if (o->expr == nullptr) {
  5242. Entity *e = tuple->variables[i];
  5243. if (e->kind == Entity_Constant) {
  5244. missing_count += 1;
  5245. o->mode = Addressing_Constant;
  5246. o->type = default_type(e->type);
  5247. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  5248. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  5249. o->value = e->Constant.param_value.value;
  5250. }
  5251. } else if (e->kind == Entity_TypeName) {
  5252. missing_count += 1;
  5253. o->mode = Addressing_Type;
  5254. o->type = e->type;
  5255. o->expr = e->identifier;
  5256. }
  5257. }
  5258. }
  5259. }
  5260. isize oo_count = gb_min(param_count, ordered_operands.count);
  5261. i64 score = 0;
  5262. for (isize i = 0; i < oo_count; i++) {
  5263. Entity *e = tuple->variables[i];
  5264. Operand *o = &ordered_operands[i];
  5265. if (o->mode == Addressing_Invalid) {
  5266. continue;
  5267. }
  5268. if (e->kind == Entity_TypeName) {
  5269. if (o->mode != Addressing_Type) {
  5270. if (show_error) {
  5271. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5272. }
  5273. err = CallArgumentError_WrongTypes;
  5274. }
  5275. if (are_types_identical(e->type, o->type)) {
  5276. score += assign_score_function(1);
  5277. } else {
  5278. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5279. }
  5280. } else {
  5281. i64 s = 0;
  5282. if (o->type->kind == Type_Generic) {
  5283. // Polymorphic name!
  5284. score += assign_score_function(1);
  5285. continue;
  5286. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  5287. if (show_error) {
  5288. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  5289. }
  5290. err = CallArgumentError_WrongTypes;
  5291. }
  5292. o->type = e->type;
  5293. if (o->mode != Addressing_Constant) {
  5294. bool valid = false;
  5295. if (is_type_proc(o->type)) {
  5296. Entity *proc_entity = entity_from_expr(o->expr);
  5297. valid = proc_entity != nullptr;
  5298. }
  5299. if (!valid) {
  5300. if (show_error) {
  5301. error(o->expr, "Expected a constant value for this polymorphic type argument");
  5302. }
  5303. err = CallArgumentError_NoneConstantParameter;
  5304. }
  5305. }
  5306. score += s;
  5307. }
  5308. // NOTE(bill): Add type info the parameters
  5309. add_type_info_type(c, o->type);
  5310. }
  5311. {
  5312. bool failure = false;
  5313. Entity *found_entity = find_polymorphic_record_entity(c, original_type, param_count, ordered_operands, &failure);
  5314. if (found_entity) {
  5315. operand->mode = Addressing_Type;
  5316. operand->type = found_entity->type;
  5317. return err;
  5318. }
  5319. String generated_name = make_string_c(expr_to_string(call));
  5320. CheckerContext ctx = *c;
  5321. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  5322. ctx.scope = polymorphic_record_parent_scope(original_type);
  5323. GB_ASSERT(ctx.scope != nullptr);
  5324. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  5325. Type *bt = base_type(original_type);
  5326. if (bt->kind == Type_Struct) {
  5327. Ast *node = clone_ast(bt->Struct.node);
  5328. Type *struct_type = alloc_type_struct();
  5329. struct_type->Struct.node = node;
  5330. struct_type->Struct.polymorphic_parent = original_type;
  5331. set_base_type(named_type, struct_type);
  5332. check_open_scope(&ctx, node);
  5333. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  5334. check_close_scope(&ctx);
  5335. } else if (bt->kind == Type_Union) {
  5336. Ast *node = clone_ast(bt->Union.node);
  5337. Type *union_type = alloc_type_union();
  5338. union_type->Union.node = node;
  5339. union_type->Union.polymorphic_parent = original_type;
  5340. set_base_type(named_type, union_type);
  5341. check_open_scope(&ctx, node);
  5342. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  5343. check_close_scope(&ctx);
  5344. } else {
  5345. GB_PANIC("Unsupported parametric polymorphic record type");
  5346. }
  5347. operand->mode = Addressing_Type;
  5348. operand->type = named_type;
  5349. }
  5350. return err;
  5351. }
  5352. ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  5353. if (proc != nullptr &&
  5354. proc->kind == Ast_BasicDirective) {
  5355. ast_node(bd, BasicDirective, proc);
  5356. String name = bd->name.string;
  5357. if (
  5358. name == "location" ||
  5359. name == "assert" ||
  5360. name == "panic" ||
  5361. name == "defined" ||
  5362. name == "config" ||
  5363. name == "load" ||
  5364. name == "load_hash" ||
  5365. name == "load_or"
  5366. ) {
  5367. operand->mode = Addressing_Builtin;
  5368. operand->builtin_id = BuiltinProc_DIRECTIVE;
  5369. operand->expr = proc;
  5370. operand->type = t_invalid;
  5371. add_type_and_value(c->info, proc, operand->mode, operand->type, operand->value);
  5372. } else {
  5373. error(proc, "Unknown directive: #%.*s", LIT(name));
  5374. operand->expr = proc;
  5375. operand->type = t_invalid;
  5376. operand->mode = Addressing_Invalid;
  5377. return Expr_Expr;
  5378. }
  5379. if (inlining != ProcInlining_none) {
  5380. error(call, "Inlining operators are not allowed on built-in procedures");
  5381. }
  5382. } else {
  5383. if (proc != nullptr) {
  5384. check_expr_or_type(c, operand, proc);
  5385. } else {
  5386. GB_ASSERT(operand->expr != nullptr);
  5387. }
  5388. }
  5389. if (args.count > 0) {
  5390. bool fail = false;
  5391. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  5392. for_array(i, args) {
  5393. Ast *arg = args[i];
  5394. bool mix = false;
  5395. if (first_is_field_value) {
  5396. mix = arg->kind != Ast_FieldValue;
  5397. } else {
  5398. mix = arg->kind == Ast_FieldValue;
  5399. }
  5400. if (mix) {
  5401. error(arg, "Mixture of 'field = value' and value elements in a procedure call is not allowed");
  5402. fail = true;
  5403. }
  5404. }
  5405. if (fail) {
  5406. operand->mode = Addressing_Invalid;
  5407. operand->expr = call;
  5408. return Expr_Stmt;
  5409. }
  5410. }
  5411. if (operand->mode == Addressing_Invalid) {
  5412. for_array(i, args) {
  5413. Ast *arg = args[i];
  5414. if (arg->kind == Ast_FieldValue) {
  5415. arg = arg->FieldValue.value;
  5416. }
  5417. check_expr_base(c, operand, arg, nullptr);
  5418. }
  5419. operand->mode = Addressing_Invalid;
  5420. operand->expr = call;
  5421. return Expr_Stmt;
  5422. }
  5423. if (operand->mode == Addressing_Type) {
  5424. Type *t = operand->type;
  5425. if (is_type_polymorphic_record(t)) {
  5426. if (!is_type_named(t)) {
  5427. gbString s = expr_to_string(operand->expr);
  5428. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  5429. gb_string_free(s);
  5430. operand->mode = Addressing_Invalid;
  5431. operand->type = t_invalid;;
  5432. return Expr_Expr;
  5433. }
  5434. auto err = check_polymorphic_record_type(c, operand, call);
  5435. if (err == 0) {
  5436. Ast *ident = operand->expr;
  5437. while (ident->kind == Ast_SelectorExpr) {
  5438. Ast *s = ident->SelectorExpr.selector;
  5439. ident = s;
  5440. }
  5441. Type *ot = operand->type;
  5442. GB_ASSERT(ot->kind == Type_Named);
  5443. Entity *e = ot->Named.type_name;
  5444. add_entity_use(c, ident, e);
  5445. add_type_and_value(c->info, call, Addressing_Type, ot, empty_exact_value);
  5446. } else {
  5447. operand->mode = Addressing_Invalid;
  5448. operand->type = t_invalid;
  5449. }
  5450. } else {
  5451. gbString str = type_to_string(t);
  5452. defer (gb_string_free(str));
  5453. operand->mode = Addressing_Invalid;
  5454. isize arg_count = args.count;
  5455. switch (arg_count) {
  5456. case 0: error(call, "Missing argument in conversion to '%s'", str); break;
  5457. default: error(call, "Too many arguments in conversion to '%s'", str); break;
  5458. case 1: {
  5459. Ast *arg = args[0];
  5460. if (arg->kind == Ast_FieldValue) {
  5461. error(call, "'field = value' cannot be used in a type conversion");
  5462. arg = arg->FieldValue.value;
  5463. // NOTE(bill): Carry on the cast regardless
  5464. }
  5465. check_expr_with_type_hint(c, operand, arg, t);
  5466. if (operand->mode != Addressing_Invalid) {
  5467. if (is_type_polymorphic(t)) {
  5468. error(call, "A polymorphic type cannot be used in a type conversion");
  5469. } else {
  5470. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  5471. // as it assumes it is determining the type
  5472. check_cast(c, operand, t);
  5473. }
  5474. }
  5475. operand->type = t;
  5476. operand->expr = call;
  5477. if (operand->mode != Addressing_Invalid) {
  5478. update_untyped_expr_type(c, arg, t, false);
  5479. }
  5480. break;
  5481. }
  5482. }
  5483. }
  5484. return Expr_Expr;
  5485. }
  5486. if (operand->mode == Addressing_Builtin) {
  5487. i32 id = operand->builtin_id;
  5488. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  5489. operand->mode = Addressing_Invalid;
  5490. operand->type = t_invalid;
  5491. }
  5492. operand->expr = call;
  5493. return builtin_procs[id].kind;
  5494. }
  5495. Entity *e = entity_of_node(operand->expr);
  5496. if (e != nullptr && e->kind == Entity_Procedure) {
  5497. if (e->Procedure.deferred_procedure.entity != nullptr) {
  5498. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  5499. }
  5500. }
  5501. Type *proc_type = base_type(operand->type);
  5502. if (operand->mode != Addressing_ProcGroup) {
  5503. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  5504. bool valid_mode = is_operand_value(*operand);
  5505. if (!valid_type || !valid_mode) {
  5506. Ast *e = operand->expr;
  5507. gbString str = expr_to_string(e);
  5508. gbString type_str = type_to_string(operand->type);
  5509. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  5510. gb_string_free(type_str);
  5511. gb_string_free(str);
  5512. operand->mode = Addressing_Invalid;
  5513. operand->expr = call;
  5514. return Expr_Stmt;
  5515. }
  5516. }
  5517. CallArgumentData data = check_call_arguments(c, operand, proc_type, call, args);
  5518. Type *result_type = data.result_type;
  5519. gb_zero_item(operand);
  5520. operand->expr = call;
  5521. if (result_type == t_invalid) {
  5522. operand->mode = Addressing_Invalid;
  5523. operand->type = t_invalid;
  5524. return Expr_Stmt;
  5525. }
  5526. Type *pt = base_type(proc_type);
  5527. if (pt == t_invalid) {
  5528. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  5529. pt = type_of_expr(operand->expr->CallExpr.proc);
  5530. }
  5531. if (pt == t_invalid && data.gen_entity) {
  5532. pt = data.gen_entity->type;
  5533. }
  5534. }
  5535. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  5536. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  5537. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  5538. }
  5539. }
  5540. if (result_type == nullptr) {
  5541. operand->mode = Addressing_NoValue;
  5542. } else {
  5543. GB_ASSERT(is_type_tuple(result_type));
  5544. isize count = result_type->Tuple.variables.count;
  5545. switch (count) {
  5546. case 0:
  5547. operand->mode = Addressing_NoValue;
  5548. break;
  5549. case 1:
  5550. operand->mode = Addressing_Value;
  5551. operand->type = result_type->Tuple.variables[0]->type;
  5552. break;
  5553. default:
  5554. operand->mode = Addressing_Value;
  5555. operand->type = result_type;
  5556. break;
  5557. }
  5558. }
  5559. switch (inlining) {
  5560. case ProcInlining_inline:
  5561. if (proc != nullptr) {
  5562. Entity *e = entity_from_expr(proc);
  5563. if (e != nullptr && e->kind == Entity_Procedure) {
  5564. DeclInfo *decl = e->decl_info;
  5565. if (decl->proc_lit) {
  5566. ast_node(pl, ProcLit, decl->proc_lit);
  5567. if (pl->inlining == ProcInlining_no_inline) {
  5568. error(call, "'inline' cannot be applied to a procedure that has be marked as 'no_inline'");
  5569. }
  5570. }
  5571. }
  5572. }
  5573. break;
  5574. case ProcInlining_no_inline:
  5575. break;
  5576. }
  5577. operand->expr = call;
  5578. {
  5579. if (proc_type == t_invalid) {
  5580. // gb_printf_err("%s\n", expr_to_string(operand->expr));
  5581. }
  5582. Type *type = nullptr;
  5583. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  5584. type = type_of_expr(operand->expr->CallExpr.proc);
  5585. }
  5586. if (type == nullptr) {
  5587. type = pt;
  5588. }
  5589. type = base_type(type);
  5590. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  5591. operand->mode = Addressing_OptionalOk;
  5592. operand->type = type->Proc.results->Tuple.variables[0]->type;
  5593. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  5594. operand->expr->CallExpr.optional_ok_one = true;
  5595. }
  5596. }
  5597. }
  5598. // add_type_and_value(c->info, operand->expr, operand->mode, operand->type, operand->value);
  5599. return Expr_Expr;
  5600. }
  5601. void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  5602. check_expr_base(c, o, e, t);
  5603. check_not_tuple(c, o);
  5604. char const *err_str = nullptr;
  5605. switch (o->mode) {
  5606. case Addressing_NoValue:
  5607. err_str = "used as a value";
  5608. break;
  5609. case Addressing_Type:
  5610. if (t == nullptr || !is_type_typeid(t)) {
  5611. err_str = "is not an expression but a type, in this context it is ambiguous";
  5612. }
  5613. break;
  5614. case Addressing_Builtin:
  5615. err_str = "must be called";
  5616. break;
  5617. }
  5618. if (err_str != nullptr) {
  5619. gbString str = expr_to_string(e);
  5620. error(e, "'%s' %s", str, err_str);
  5621. gb_string_free(str);
  5622. o->mode = Addressing_Invalid;
  5623. }
  5624. }
  5625. bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  5626. switch (t->kind) {
  5627. case Type_Basic:
  5628. if (t->Basic.kind == Basic_string) {
  5629. if (o->mode == Addressing_Constant) {
  5630. *max_count = o->value.value_string.len;
  5631. }
  5632. if (o->mode != Addressing_Constant) {
  5633. o->mode = Addressing_Value;
  5634. }
  5635. o->type = t_u8;
  5636. return true;
  5637. } else if (t->Basic.kind == Basic_UntypedString) {
  5638. if (o->mode == Addressing_Constant) {
  5639. *max_count = o->value.value_string.len;
  5640. o->type = t_u8;
  5641. return true;
  5642. }
  5643. return false;
  5644. }
  5645. break;
  5646. case Type_MultiPointer:
  5647. o->type = t->MultiPointer.elem;
  5648. if (o->mode != Addressing_Constant) {
  5649. o->mode = Addressing_Variable;
  5650. }
  5651. return true;
  5652. case Type_Array:
  5653. *max_count = t->Array.count;
  5654. if (indirection) {
  5655. o->mode = Addressing_Variable;
  5656. } else if (o->mode != Addressing_Variable &&
  5657. o->mode != Addressing_Constant) {
  5658. o->mode = Addressing_Value;
  5659. }
  5660. o->type = t->Array.elem;
  5661. return true;
  5662. case Type_EnumeratedArray:
  5663. *max_count = t->EnumeratedArray.count;
  5664. if (indirection) {
  5665. o->mode = Addressing_Variable;
  5666. } else if (o->mode != Addressing_Variable &&
  5667. o->mode != Addressing_Constant) {
  5668. o->mode = Addressing_Value;
  5669. }
  5670. o->type = t->EnumeratedArray.elem;
  5671. return true;
  5672. case Type_Matrix:
  5673. *max_count = t->Matrix.column_count;
  5674. if (indirection) {
  5675. o->mode = Addressing_Variable;
  5676. } else if (o->mode != Addressing_Variable) {
  5677. o->mode = Addressing_Value;
  5678. }
  5679. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  5680. return true;
  5681. case Type_Slice:
  5682. o->type = t->Slice.elem;
  5683. if (o->mode != Addressing_Constant) {
  5684. o->mode = Addressing_Variable;
  5685. }
  5686. return true;
  5687. case Type_RelativeSlice:
  5688. {
  5689. Type *slice_type = base_type(t->RelativeSlice.slice_type);
  5690. GB_ASSERT(slice_type->kind == Type_Slice);
  5691. o->type = slice_type->Slice.elem;
  5692. if (o->mode != Addressing_Constant) {
  5693. o->mode = Addressing_Variable;
  5694. }
  5695. }
  5696. return true;
  5697. case Type_DynamicArray:
  5698. o->type = t->DynamicArray.elem;
  5699. if (o->mode != Addressing_Constant) {
  5700. o->mode = Addressing_Variable;
  5701. }
  5702. return true;
  5703. case Type_Struct:
  5704. if (t->Struct.soa_kind != StructSoa_None) {
  5705. if (t->Struct.soa_kind == StructSoa_Fixed) {
  5706. *max_count = t->Struct.soa_count;
  5707. }
  5708. o->type = t->Struct.soa_elem;
  5709. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable) {
  5710. o->mode = Addressing_SoaVariable;
  5711. } else {
  5712. o->mode = Addressing_Value;
  5713. }
  5714. return true;
  5715. }
  5716. return false;
  5717. }
  5718. if (is_type_pointer(original_type) && indirection) {
  5719. Type *ptr = base_type(original_type);
  5720. if (ptr->kind == Type_Pointer && o->mode == Addressing_SoaVariable) {
  5721. o->type = ptr->Pointer.elem;
  5722. o->mode = Addressing_Value;
  5723. return true;
  5724. }
  5725. }
  5726. return false;
  5727. }
  5728. bool ternary_compare_types(Type *x, Type *y) {
  5729. if (is_type_untyped_undef(x) && type_has_undef(y)) {
  5730. return true;
  5731. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  5732. return true;
  5733. } else if (is_type_untyped_undef(y) && type_has_undef(x)) {
  5734. return true;
  5735. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  5736. return true;
  5737. }
  5738. return are_types_identical(x, y);
  5739. }
  5740. bool check_range(CheckerContext *c, Ast *node, Operand *x, Operand *y, ExactValue *inline_for_depth_, Type *type_hint=nullptr) {
  5741. if (!is_ast_range(node)) {
  5742. return false;
  5743. }
  5744. ast_node(ie, BinaryExpr, node);
  5745. check_expr_with_type_hint(c, x, ie->left, type_hint);
  5746. if (x->mode == Addressing_Invalid) {
  5747. return false;
  5748. }
  5749. check_expr_with_type_hint(c, y, ie->right, type_hint);
  5750. if (y->mode == Addressing_Invalid) {
  5751. return false;
  5752. }
  5753. convert_to_typed(c, x, y->type);
  5754. if (x->mode == Addressing_Invalid) {
  5755. return false;
  5756. }
  5757. convert_to_typed(c, y, x->type);
  5758. if (y->mode == Addressing_Invalid) {
  5759. return false;
  5760. }
  5761. convert_to_typed(c, x, default_type(y->type));
  5762. if (x->mode == Addressing_Invalid) {
  5763. return false;
  5764. }
  5765. convert_to_typed(c, y, default_type(x->type));
  5766. if (y->mode == Addressing_Invalid) {
  5767. return false;
  5768. }
  5769. if (!are_types_identical(x->type, y->type)) {
  5770. if (x->type != t_invalid &&
  5771. y->type != t_invalid) {
  5772. gbString xt = type_to_string(x->type);
  5773. gbString yt = type_to_string(y->type);
  5774. gbString expr_str = expr_to_string(x->expr);
  5775. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  5776. gb_string_free(expr_str);
  5777. gb_string_free(yt);
  5778. gb_string_free(xt);
  5779. }
  5780. return false;
  5781. }
  5782. Type *type = x->type;
  5783. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  5784. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  5785. return false;
  5786. }
  5787. if (x->mode == Addressing_Constant &&
  5788. y->mode == Addressing_Constant) {
  5789. ExactValue a = x->value;
  5790. ExactValue b = y->value;
  5791. GB_ASSERT(are_types_identical(x->type, y->type));
  5792. TokenKind op = Token_Lt;
  5793. switch (ie->op.kind) {
  5794. case Token_Ellipsis: op = Token_LtEq; break; // ..
  5795. case Token_RangeFull: op = Token_LtEq; break; // ..=
  5796. case Token_RangeHalf: op = Token_Lt; break; // ..<
  5797. default: error(ie->op, "Invalid range operator"); break;
  5798. }
  5799. bool ok = compare_exact_values(op, a, b);
  5800. if (!ok) {
  5801. // TODO(bill): Better error message
  5802. error(ie->op, "Invalid interval range");
  5803. return false;
  5804. }
  5805. ExactValue inline_for_depth = exact_value_sub(b, a);
  5806. if (ie->op.kind != Token_RangeHalf) {
  5807. inline_for_depth = exact_value_increment_one(inline_for_depth);
  5808. }
  5809. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  5810. } else if (inline_for_depth_ != nullptr) {
  5811. error(ie->op, "Interval expressions must be constant");
  5812. return false;
  5813. }
  5814. add_type_and_value(c->info, ie->left, x->mode, x->type, x->value);
  5815. add_type_and_value(c->info, ie->right, y->mode, y->type, y->value);
  5816. return true;
  5817. }
  5818. bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  5819. if (is_operand_nil(*o)) {
  5820. return true;
  5821. }
  5822. Ast *expr = unparen_expr(o->expr);
  5823. if (expr != nullptr) {
  5824. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  5825. if (e != nullptr && e->kind == Entity_Procedure) {
  5826. return true;
  5827. }
  5828. if (expr->kind == Ast_ProcLit) {
  5829. add_type_and_value(c->info, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  5830. return true;
  5831. }
  5832. }
  5833. return o->mode == Addressing_Constant;
  5834. }
  5835. bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  5836. if (is_type_enum(th)) {
  5837. Type *enum_type = base_type(th);
  5838. GB_ASSERT(enum_type->kind == Type_Enum);
  5839. String name = ise->selector->Ident.token.string;
  5840. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  5841. if (e == nullptr) {
  5842. return false;
  5843. }
  5844. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  5845. GB_ASSERT(e->kind == Entity_Constant);
  5846. o->value = e->Constant.value;
  5847. o->mode = Addressing_Constant;
  5848. o->type = e->type;
  5849. return true;
  5850. }
  5851. if (is_type_union(th)) {
  5852. Type *union_type = base_type(th);
  5853. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  5854. for_array(i, union_type->Union.variants) {
  5855. Type *vt = union_type->Union.variants[i];
  5856. Operand x = {};
  5857. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  5858. array_add(&operands, x);
  5859. }
  5860. }
  5861. if (operands.count == 1) {
  5862. *o = operands[0];
  5863. return true;
  5864. }
  5865. }
  5866. return false;
  5867. }
  5868. ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  5869. ast_node(ise, ImplicitSelectorExpr, node);
  5870. o->type = t_invalid;
  5871. o->expr = node;
  5872. o->mode = Addressing_Invalid;
  5873. Type *th = type_hint;
  5874. if (th == nullptr) {
  5875. gbString str = expr_to_string(node);
  5876. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  5877. gb_string_free(str);
  5878. return Expr_Expr;
  5879. }
  5880. o->type = th;
  5881. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  5882. if (!ok) {
  5883. String name = ise->selector->Ident.token.string;
  5884. if (is_type_enum(th)) {
  5885. Type *bt = base_type(th);
  5886. GB_ASSERT(bt->kind == Type_Enum);
  5887. gbString typ = type_to_string(th);
  5888. defer (gb_string_free(typ));
  5889. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  5890. check_did_you_mean_type(name, bt->Enum.fields);
  5891. } else {
  5892. gbString typ = type_to_string(th);
  5893. gbString str = expr_to_string(node);
  5894. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  5895. gb_string_free(str);
  5896. gb_string_free(typ);
  5897. }
  5898. }
  5899. o->expr = node;
  5900. return Expr_Expr;
  5901. }
  5902. void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_) {
  5903. switch (x->mode) {
  5904. case Addressing_MapIndex:
  5905. case Addressing_OptionalOk:
  5906. case Addressing_OptionalOkPtr:
  5907. if (val_type_) *val_type_ = x->type;
  5908. break;
  5909. default:
  5910. if (ok_type_) *ok_type_ = x->type;
  5911. return;
  5912. }
  5913. Ast *expr = unparen_expr(x->expr);
  5914. if (expr->kind == Ast_CallExpr) {
  5915. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  5916. if (is_type_proc(pt)) {
  5917. Type *tuple = pt->Proc.results;
  5918. add_type_and_value(c->info, x->expr, x->mode, tuple, x->value);
  5919. if (pt->Proc.result_count >= 2) {
  5920. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  5921. }
  5922. expr->CallExpr.optional_ok_one = false;
  5923. x->type = tuple;
  5924. return;
  5925. }
  5926. }
  5927. Type *tuple = make_optional_ok_type(x->type);
  5928. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  5929. add_type_and_value(c->info, x->expr, x->mode, tuple, x->value);
  5930. x->type = tuple;
  5931. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  5932. }
  5933. void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  5934. ast_node(ie, MatrixIndexExpr, node);
  5935. check_expr(c, o, ie->expr);
  5936. node->viral_state_flags |= ie->expr->viral_state_flags;
  5937. if (o->mode == Addressing_Invalid) {
  5938. o->expr = node;
  5939. return;
  5940. }
  5941. Type *t = base_type(type_deref(o->type));
  5942. bool is_ptr = is_type_pointer(o->type);
  5943. bool is_const = o->mode == Addressing_Constant;
  5944. if (t->kind != Type_Matrix) {
  5945. gbString str = expr_to_string(o->expr);
  5946. gbString type_str = type_to_string(o->type);
  5947. defer (gb_string_free(str));
  5948. defer (gb_string_free(type_str));
  5949. if (is_const) {
  5950. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  5951. } else {
  5952. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  5953. }
  5954. o->mode = Addressing_Invalid;
  5955. o->expr = node;
  5956. return;
  5957. }
  5958. o->type = t->Matrix.elem;
  5959. if (is_ptr) {
  5960. o->mode = Addressing_Variable;
  5961. } else if (o->mode != Addressing_Variable) {
  5962. o->mode = Addressing_Value;
  5963. }
  5964. if (ie->row_index == nullptr) {
  5965. gbString str = expr_to_string(o->expr);
  5966. error(o->expr, "Missing row index for '%s'", str);
  5967. gb_string_free(str);
  5968. o->mode = Addressing_Invalid;
  5969. o->expr = node;
  5970. return;
  5971. }
  5972. if (ie->column_index == nullptr) {
  5973. gbString str = expr_to_string(o->expr);
  5974. error(o->expr, "Missing column index for '%s'", str);
  5975. gb_string_free(str);
  5976. o->mode = Addressing_Invalid;
  5977. o->expr = node;
  5978. return;
  5979. }
  5980. i64 row_count = t->Matrix.row_count;
  5981. i64 column_count = t->Matrix.column_count;
  5982. i64 row_index = 0;
  5983. i64 column_index = 0;
  5984. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  5985. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  5986. gb_unused(row_ok);
  5987. gb_unused(column_ok);
  5988. }
  5989. ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  5990. u32 prev_state_flags = c->state_flags;
  5991. defer (c->state_flags = prev_state_flags);
  5992. if (node->state_flags != 0) {
  5993. u32 in = node->state_flags;
  5994. u32 out = c->state_flags;
  5995. if (in & StateFlag_no_bounds_check) {
  5996. out |= StateFlag_no_bounds_check;
  5997. out &= ~StateFlag_bounds_check;
  5998. } else if (in & StateFlag_bounds_check) {
  5999. out |= StateFlag_bounds_check;
  6000. out &= ~StateFlag_no_bounds_check;
  6001. }
  6002. c->state_flags = out;
  6003. }
  6004. ExprKind kind = Expr_Stmt;
  6005. o->mode = Addressing_Invalid;
  6006. o->type = t_invalid;
  6007. switch (node->kind) {
  6008. default:
  6009. return kind;
  6010. case_ast_node(be, BadExpr, node)
  6011. return kind;
  6012. case_end;
  6013. case_ast_node(i, Implicit, node)
  6014. switch (i->kind) {
  6015. case Token_context:
  6016. {
  6017. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  6018. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  6019. return kind;
  6020. }
  6021. if (unparen_expr(c->assignment_lhs_hint) == node) {
  6022. c->scope->flags |= ScopeFlag_ContextDefined;
  6023. }
  6024. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  6025. error(node, "'context' has not been defined within this scope");
  6026. // Continue with value
  6027. }
  6028. init_core_context(c->checker);
  6029. o->mode = Addressing_Context;
  6030. o->type = t_context;
  6031. }
  6032. break;
  6033. default:
  6034. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  6035. return kind;
  6036. }
  6037. case_end;
  6038. case_ast_node(i, Ident, node);
  6039. check_ident(c, o, node, nullptr, type_hint, false);
  6040. case_end;
  6041. case_ast_node(u, Undef, node);
  6042. o->mode = Addressing_Value;
  6043. o->type = t_untyped_undef;
  6044. case_end;
  6045. case_ast_node(bl, BasicLit, node);
  6046. Type *t = t_invalid;
  6047. switch (node->tav.value.kind) {
  6048. case ExactValue_String: t = t_untyped_string; break;
  6049. case ExactValue_Float: t = t_untyped_float; break;
  6050. case ExactValue_Complex: t = t_untyped_complex; break;
  6051. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  6052. case ExactValue_Integer:
  6053. t = t_untyped_integer;
  6054. if (bl->token.kind == Token_Rune) {
  6055. t = t_untyped_rune;
  6056. }
  6057. break;
  6058. default:
  6059. GB_PANIC("Unhandled value type for basic literal");
  6060. break;
  6061. }
  6062. o->mode = Addressing_Constant;
  6063. o->type = t;
  6064. o->value = node->tav.value;
  6065. case_end;
  6066. case_ast_node(bd, BasicDirective, node);
  6067. o->mode = Addressing_Constant;
  6068. String name = bd->name.string;
  6069. if (name == "file") {
  6070. o->type = t_untyped_string;
  6071. o->value = exact_value_string(get_file_path_string(bd->token.pos.file_id));
  6072. } else if (name == "line") {
  6073. o->type = t_untyped_integer;
  6074. o->value = exact_value_i64(bd->token.pos.line);
  6075. } else if (name == "procedure") {
  6076. if (c->curr_proc_decl == nullptr) {
  6077. error(node, "#procedure may only be used within procedures");
  6078. o->type = t_untyped_string;
  6079. o->value = exact_value_string(str_lit(""));
  6080. } else {
  6081. o->type = t_untyped_string;
  6082. o->value = exact_value_string(c->proc_name);
  6083. }
  6084. } else if (name == "caller_location") {
  6085. init_core_source_code_location(c->checker);
  6086. error(node, "#caller_location may only be used as a default argument parameter");
  6087. o->type = t_source_code_location;
  6088. o->mode = Addressing_Value;
  6089. } else {
  6090. if (name == "location") {
  6091. init_core_source_code_location(c->checker);
  6092. error(node, "'#%.*s' must be used in a call expression", LIT(name));
  6093. o->type = t_source_code_location;
  6094. o->mode = Addressing_Value;
  6095. } else if (
  6096. name == "assert" ||
  6097. name == "defined" ||
  6098. name == "config" ||
  6099. name == "load" ||
  6100. name == "load_hash" ||
  6101. name == "load_or"
  6102. ) {
  6103. error(node, "'#%.*s' must be used as a call", LIT(name));
  6104. o->type = t_invalid;
  6105. o->mode = Addressing_Invalid;
  6106. } else {
  6107. error(node, "Unknown directive: #%.*s", LIT(name));
  6108. o->type = t_invalid;
  6109. o->mode = Addressing_Invalid;
  6110. }
  6111. }
  6112. case_end;
  6113. case_ast_node(pg, ProcGroup, node);
  6114. error(node, "Illegal use of a procedure group");
  6115. o->mode = Addressing_Invalid;
  6116. case_end;
  6117. case_ast_node(pl, ProcLit, node);
  6118. CheckerContext ctx = *c;
  6119. DeclInfo *decl = nullptr;
  6120. Type *type = alloc_type(Type_Proc);
  6121. check_open_scope(&ctx, pl->type);
  6122. {
  6123. decl = make_decl_info(ctx.scope, ctx.decl);
  6124. decl->proc_lit = node;
  6125. ctx.decl = decl;
  6126. defer (ctx.decl = ctx.decl->parent);
  6127. if (pl->tags != 0) {
  6128. error(node, "A procedure literal cannot have tags");
  6129. pl->tags = 0; // TODO(bill): Should I zero this?!
  6130. }
  6131. check_procedure_type(&ctx, type, pl->type);
  6132. if (!is_type_proc(type)) {
  6133. gbString str = expr_to_string(node);
  6134. error(node, "Invalid procedure literal '%s'", str);
  6135. gb_string_free(str);
  6136. check_close_scope(&ctx);
  6137. return kind;
  6138. }
  6139. if (pl->body == nullptr) {
  6140. error(node, "A procedure literal must have a body");
  6141. return kind;
  6142. }
  6143. pl->decl = decl;
  6144. check_procedure_later(&ctx, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  6145. }
  6146. check_close_scope(&ctx);
  6147. o->mode = Addressing_Value;
  6148. o->type = type;
  6149. case_end;
  6150. case_ast_node(te, TernaryIfExpr, node);
  6151. Operand cond = {Addressing_Invalid};
  6152. check_expr(c, &cond, te->cond);
  6153. node->viral_state_flags |= te->cond->viral_state_flags;
  6154. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  6155. error(te->cond, "Non-boolean condition in ternary if expression");
  6156. }
  6157. Operand x = {Addressing_Invalid};
  6158. Operand y = {Addressing_Invalid};
  6159. check_expr_or_type(c, &x, te->x, type_hint);
  6160. node->viral_state_flags |= te->x->viral_state_flags;
  6161. if (te->y != nullptr) {
  6162. check_expr_or_type(c, &y, te->y, type_hint);
  6163. node->viral_state_flags |= te->y->viral_state_flags;
  6164. } else {
  6165. error(node, "A ternary expression must have an else clause");
  6166. return kind;
  6167. }
  6168. if (x.type == nullptr || x.type == t_invalid ||
  6169. y.type == nullptr || y.type == t_invalid) {
  6170. return kind;
  6171. }
  6172. convert_to_typed(c, &x, y.type);
  6173. if (x.mode == Addressing_Invalid) {
  6174. return kind;
  6175. }
  6176. convert_to_typed(c, &y, x.type);
  6177. if (y.mode == Addressing_Invalid) {
  6178. x.mode = Addressing_Invalid;
  6179. return kind;
  6180. }
  6181. if (!ternary_compare_types(x.type, y.type)) {
  6182. gbString its = type_to_string(x.type);
  6183. gbString ets = type_to_string(y.type);
  6184. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  6185. gb_string_free(ets);
  6186. gb_string_free(its);
  6187. return kind;
  6188. }
  6189. o->type = x.type;
  6190. if (is_type_untyped_nil(o->type) || is_type_untyped_undef(o->type)) {
  6191. o->type = y.type;
  6192. }
  6193. o->mode = Addressing_Value;
  6194. o->expr = node;
  6195. if (type_hint != nullptr && is_type_untyped(o->type)) {
  6196. if (check_cast_internal(c, &x, type_hint) &&
  6197. check_cast_internal(c, &y, type_hint)) {
  6198. convert_to_typed(c, o, type_hint);
  6199. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  6200. }
  6201. }
  6202. case_end;
  6203. case_ast_node(te, TernaryWhenExpr, node);
  6204. Operand cond = {};
  6205. check_expr(c, &cond, te->cond);
  6206. node->viral_state_flags |= te->cond->viral_state_flags;
  6207. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  6208. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  6209. return kind;
  6210. }
  6211. if (cond.value.value_bool) {
  6212. check_expr_or_type(c, o, te->x, type_hint);
  6213. node->viral_state_flags |= te->x->viral_state_flags;
  6214. } else {
  6215. if (te->y != nullptr) {
  6216. check_expr_or_type(c, o, te->y, type_hint);
  6217. node->viral_state_flags |= te->y->viral_state_flags;
  6218. } else {
  6219. error(node, "A ternary when expression must have an else clause");
  6220. return kind;
  6221. }
  6222. }
  6223. case_end;
  6224. case_ast_node(oe, OrElseExpr, node);
  6225. String name = oe->token.string;
  6226. Ast *arg = oe->x;
  6227. Ast *default_value = oe->y;
  6228. Operand x = {};
  6229. Operand y = {};
  6230. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  6231. if (x.mode == Addressing_Invalid) {
  6232. o->mode = Addressing_Value;
  6233. o->type = t_invalid;
  6234. o->expr = node;
  6235. return Expr_Expr;
  6236. }
  6237. check_multi_expr_with_type_hint(c, &y, default_value, x.type);
  6238. error_operand_no_value(&y);
  6239. if (y.mode == Addressing_Invalid) {
  6240. o->mode = Addressing_Value;
  6241. o->type = t_invalid;
  6242. o->expr = node;
  6243. return Expr_Expr;
  6244. }
  6245. Type *left_type = nullptr;
  6246. Type *right_type = nullptr;
  6247. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  6248. add_type_and_value(&c->checker->info, arg, x.mode, x.type, x.value);
  6249. if (left_type != nullptr) {
  6250. check_assignment(c, &y, left_type, name);
  6251. } else {
  6252. check_or_else_expr_no_value_error(c, name, x, type_hint);
  6253. }
  6254. if (left_type == nullptr) {
  6255. left_type = t_invalid;
  6256. }
  6257. o->mode = Addressing_Value;
  6258. o->type = left_type;
  6259. o->expr = node;
  6260. return Expr_Expr;
  6261. case_end;
  6262. case_ast_node(re, OrReturnExpr, node);
  6263. String name = re->token.string;
  6264. Operand x = {};
  6265. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  6266. if (x.mode == Addressing_Invalid) {
  6267. o->mode = Addressing_Value;
  6268. o->type = t_invalid;
  6269. o->expr = node;
  6270. return Expr_Expr;
  6271. }
  6272. Type *left_type = nullptr;
  6273. Type *right_type = nullptr;
  6274. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  6275. add_type_and_value(&c->checker->info, re->expr, x.mode, x.type, x.value);
  6276. if (right_type == nullptr) {
  6277. check_or_else_expr_no_value_error(c, name, x, type_hint);
  6278. } else {
  6279. Type *proc_type = base_type(c->curr_proc_sig);
  6280. GB_ASSERT(proc_type->kind == Type_Proc);
  6281. Type *result_type = proc_type->Proc.results;
  6282. if (result_type == nullptr) {
  6283. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  6284. } else {
  6285. GB_ASSERT(result_type->kind == Type_Tuple);
  6286. auto const &vars = result_type->Tuple.variables;
  6287. Type *end_type = vars[vars.count-1]->type;
  6288. if (vars.count > 1) {
  6289. if (!proc_type->Proc.has_named_results) {
  6290. 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));
  6291. }
  6292. }
  6293. Operand rhs = {};
  6294. rhs.type = right_type;
  6295. rhs.mode = Addressing_Value;
  6296. // TODO(bill): better error message
  6297. if (!check_is_assignable_to(c, &rhs, end_type)) {
  6298. gbString a = type_to_string(right_type);
  6299. gbString b = type_to_string(end_type);
  6300. gbString ret_type = type_to_string(result_type);
  6301. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  6302. if (vars.count == 1) {
  6303. error_line("\tProcedure return value type: %s\n", ret_type);
  6304. } else {
  6305. error_line("\tProcedure return value types: (%s)\n", ret_type);
  6306. }
  6307. gb_string_free(ret_type);
  6308. gb_string_free(b);
  6309. gb_string_free(a);
  6310. }
  6311. }
  6312. }
  6313. o->expr = node;
  6314. o->type = left_type;
  6315. if (left_type != nullptr) {
  6316. o->mode = Addressing_Value;
  6317. } else {
  6318. o->mode = Addressing_NoValue;
  6319. }
  6320. if (c->curr_proc_sig == nullptr) {
  6321. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  6322. }
  6323. if (c->in_defer) {
  6324. error(node, "'or_return' cannot be used within a defer statement");
  6325. }
  6326. return Expr_Expr;
  6327. case_end;
  6328. case_ast_node(cl, CompoundLit, node);
  6329. Type *type = type_hint;
  6330. if (type != nullptr && is_type_untyped(type)) {
  6331. type = nullptr;
  6332. }
  6333. bool is_to_be_determined_array_count = false;
  6334. bool is_constant = true;
  6335. if (cl->type != nullptr) {
  6336. type = nullptr;
  6337. // [?]Type
  6338. if (cl->type->kind == Ast_ArrayType && cl->type->ArrayType.count != nullptr) {
  6339. Ast *count = cl->type->ArrayType.count;
  6340. if (count->kind == Ast_UnaryExpr &&
  6341. count->UnaryExpr.op.kind == Token_Question) {
  6342. type = alloc_type_array(check_type(c, cl->type->ArrayType.elem), -1);
  6343. is_to_be_determined_array_count = true;
  6344. }
  6345. if (cl->elems.count > 0) {
  6346. if (cl->type->ArrayType.tag != nullptr) {
  6347. Ast *tag = cl->type->ArrayType.tag;
  6348. GB_ASSERT(tag->kind == Ast_BasicDirective);
  6349. String name = tag->BasicDirective.name.string;
  6350. if (name == "soa") {
  6351. error(node, "#soa arrays are not supported for compound literals");
  6352. return kind;
  6353. }
  6354. }
  6355. }
  6356. }
  6357. if (cl->type->kind == Ast_DynamicArrayType && cl->type->DynamicArrayType.tag != nullptr) {
  6358. if (cl->elems.count > 0) {
  6359. Ast *tag = cl->type->DynamicArrayType.tag;
  6360. GB_ASSERT(tag->kind == Ast_BasicDirective);
  6361. String name = tag->BasicDirective.name.string;
  6362. if (name == "soa") {
  6363. error(node, "#soa arrays are not supported for compound literals");
  6364. return kind;
  6365. }
  6366. }
  6367. }
  6368. if (type == nullptr) {
  6369. type = check_type(c, cl->type);
  6370. }
  6371. }
  6372. if (type == nullptr) {
  6373. error(node, "Missing type in compound literal");
  6374. return kind;
  6375. }
  6376. Type *t = base_type(type);
  6377. if (is_type_polymorphic(t)) {
  6378. gbString str = type_to_string(type);
  6379. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  6380. o->expr = node;
  6381. o->type = type;
  6382. gb_string_free(str);
  6383. return kind;
  6384. }
  6385. switch (t->kind) {
  6386. case Type_Struct: {
  6387. if (cl->elems.count == 0) {
  6388. break; // NOTE(bill): No need to init
  6389. }
  6390. if (t->Struct.is_raw_union) {
  6391. if (cl->elems.count > 0) {
  6392. // NOTE: unions cannot be constant
  6393. is_constant = false;
  6394. if (cl->elems[0]->kind != Ast_FieldValue) {
  6395. gbString type_str = type_to_string(type);
  6396. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  6397. gb_string_free(type_str);
  6398. } else {
  6399. if (cl->elems.count != 1) {
  6400. gbString type_str = type_to_string(type);
  6401. 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);
  6402. gb_string_free(type_str);
  6403. } else {
  6404. Ast *elem = cl->elems[0];
  6405. ast_node(fv, FieldValue, elem);
  6406. if (fv->field->kind != Ast_Ident) {
  6407. gbString expr_str = expr_to_string(fv->field);
  6408. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  6409. gb_string_free(expr_str);
  6410. break;
  6411. }
  6412. String name = fv->field->Ident.token.string;
  6413. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  6414. bool is_unknown = sel.entity == nullptr;
  6415. if (is_unknown) {
  6416. error(elem, "Unknown field '%.*s' in structure literal", LIT(name));
  6417. break;
  6418. }
  6419. if (sel.index.count > 1) {
  6420. error(elem, "Cannot assign to an anonymous field '%.*s' in a structure literal (at the moment)", LIT(name));
  6421. break;
  6422. }
  6423. Entity *field = t->Struct.fields[sel.index[0]];
  6424. add_entity_use(c, fv->field, field);
  6425. Operand o = {};
  6426. check_expr_or_type(c, &o, fv->value, field->type);
  6427. check_assignment(c, &o, field->type, str_lit("structure literal"));
  6428. }
  6429. }
  6430. }
  6431. break;
  6432. }
  6433. isize field_count = t->Struct.fields.count;
  6434. isize min_field_count = t->Struct.fields.count;
  6435. for (isize i = min_field_count-1; i >= 0; i--) {
  6436. Entity *e = t->Struct.fields[i];
  6437. GB_ASSERT(e->kind == Entity_Variable);
  6438. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  6439. min_field_count--;
  6440. } else {
  6441. break;
  6442. }
  6443. }
  6444. if (cl->elems[0]->kind == Ast_FieldValue) {
  6445. bool *fields_visited = gb_alloc_array(temporary_allocator(), bool, field_count);
  6446. for_array(i, cl->elems) {
  6447. Ast *elem = cl->elems[i];
  6448. if (elem->kind != Ast_FieldValue) {
  6449. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  6450. continue;
  6451. }
  6452. ast_node(fv, FieldValue, elem);
  6453. if (fv->field->kind != Ast_Ident) {
  6454. gbString expr_str = expr_to_string(fv->field);
  6455. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  6456. gb_string_free(expr_str);
  6457. continue;
  6458. }
  6459. String name = fv->field->Ident.token.string;
  6460. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  6461. bool is_unknown = sel.entity == nullptr;
  6462. if (is_unknown) {
  6463. error(elem, "Unknown field '%.*s' in structure literal", LIT(name));
  6464. continue;
  6465. }
  6466. if (sel.index.count > 1) {
  6467. error(elem, "Cannot assign to an anonymous field '%.*s' in a structure literal (at the moment)", LIT(name));
  6468. continue;
  6469. }
  6470. Entity *field = t->Struct.fields[sel.index[0]];
  6471. add_entity_use(c, fv->field, field);
  6472. if (fields_visited[sel.index[0]]) {
  6473. error(elem, "Duplicate field '%.*s' in structure literal", LIT(name));
  6474. continue;
  6475. }
  6476. fields_visited[sel.index[0]] = true;
  6477. Operand o = {};
  6478. check_expr_or_type(c, &o, fv->value, field->type);
  6479. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  6480. is_constant = false;
  6481. }
  6482. if (is_constant) {
  6483. is_constant = check_is_operand_compound_lit_constant(c, &o);
  6484. }
  6485. check_assignment(c, &o, field->type, str_lit("structure literal"));
  6486. }
  6487. } else {
  6488. bool seen_field_value = false;
  6489. for_array(index, cl->elems) {
  6490. Entity *field = nullptr;
  6491. Ast *elem = cl->elems[index];
  6492. if (elem->kind == Ast_FieldValue) {
  6493. seen_field_value = true;
  6494. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  6495. continue;
  6496. } else if (seen_field_value) {
  6497. error(elem, "Value elements cannot be used after a 'field = value'");
  6498. continue;
  6499. }
  6500. if (index >= field_count) {
  6501. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  6502. break;
  6503. }
  6504. if (field == nullptr) {
  6505. field = t->Struct.fields[index];
  6506. }
  6507. Operand o = {};
  6508. check_expr_or_type(c, &o, elem, field->type);
  6509. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  6510. is_constant = false;
  6511. }
  6512. if (is_constant) {
  6513. is_constant = check_is_operand_compound_lit_constant(c, &o);
  6514. }
  6515. check_assignment(c, &o, field->type, str_lit("structure literal"));
  6516. }
  6517. if (cl->elems.count < field_count) {
  6518. if (min_field_count < field_count) {
  6519. if (cl->elems.count < min_field_count) {
  6520. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  6521. }
  6522. } else {
  6523. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  6524. }
  6525. }
  6526. }
  6527. break;
  6528. }
  6529. case Type_Slice:
  6530. case Type_Array:
  6531. case Type_DynamicArray:
  6532. case Type_SimdVector:
  6533. case Type_Matrix:
  6534. {
  6535. Type *elem_type = nullptr;
  6536. String context_name = {};
  6537. i64 max_type_count = -1;
  6538. if (t->kind == Type_Slice) {
  6539. elem_type = t->Slice.elem;
  6540. context_name = str_lit("slice literal");
  6541. } else if (t->kind == Type_Array) {
  6542. elem_type = t->Array.elem;
  6543. context_name = str_lit("array literal");
  6544. if (!is_to_be_determined_array_count) {
  6545. max_type_count = t->Array.count;
  6546. }
  6547. } else if (t->kind == Type_DynamicArray) {
  6548. elem_type = t->DynamicArray.elem;
  6549. context_name = str_lit("dynamic array literal");
  6550. is_constant = false;
  6551. if (!build_context.no_dynamic_literals) {
  6552. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  6553. add_package_dependency(c, "runtime", "__dynamic_array_append");
  6554. }
  6555. } else if (t->kind == Type_SimdVector) {
  6556. elem_type = t->SimdVector.elem;
  6557. context_name = str_lit("simd vector literal");
  6558. max_type_count = t->SimdVector.count;
  6559. } else if (t->kind == Type_Matrix) {
  6560. elem_type = t->Matrix.elem;
  6561. context_name = str_lit("matrix literal");
  6562. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  6563. } else {
  6564. GB_PANIC("unreachable");
  6565. }
  6566. i64 max = 0;
  6567. Type *bet = base_type(elem_type);
  6568. if (!elem_type_can_be_constant(bet)) {
  6569. is_constant = false;
  6570. }
  6571. if (bet == t_invalid) {
  6572. break;
  6573. }
  6574. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  6575. if (is_type_simd_vector(t)) {
  6576. error(cl->elems[0], "'field = value' is not allowed for SIMD vector literals");
  6577. } else {
  6578. RangeCache rc = range_cache_make(heap_allocator());
  6579. defer (range_cache_destroy(&rc));
  6580. for_array(i, cl->elems) {
  6581. Ast *elem = cl->elems[i];
  6582. if (elem->kind != Ast_FieldValue) {
  6583. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  6584. continue;
  6585. }
  6586. ast_node(fv, FieldValue, elem);
  6587. if (is_ast_range(fv->field)) {
  6588. Token op = fv->field->BinaryExpr.op;
  6589. Operand x = {};
  6590. Operand y = {};
  6591. bool ok = check_range(c, fv->field, &x, &y, nullptr);
  6592. if (!ok) {
  6593. continue;
  6594. }
  6595. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  6596. error(x.expr, "Expected a constant integer as an array field");
  6597. continue;
  6598. }
  6599. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  6600. error(y.expr, "Expected a constant integer as an array field");
  6601. continue;
  6602. }
  6603. i64 lo = exact_value_to_i64(x.value);
  6604. i64 hi = exact_value_to_i64(y.value);
  6605. i64 max_index = hi;
  6606. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  6607. hi -= 1;
  6608. } else { // .. (inclusive)
  6609. max_index += 1;
  6610. }
  6611. bool new_range = range_cache_add_range(&rc, lo, hi);
  6612. if (!new_range) {
  6613. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  6614. continue;
  6615. }
  6616. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  6617. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  6618. continue;
  6619. }
  6620. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  6621. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  6622. continue;
  6623. }
  6624. if (max < hi) {
  6625. max = max_index;
  6626. }
  6627. Operand operand = {};
  6628. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  6629. check_assignment(c, &operand, elem_type, context_name);
  6630. is_constant = is_constant && operand.mode == Addressing_Constant;
  6631. } else {
  6632. Operand op_index = {};
  6633. check_expr(c, &op_index, fv->field);
  6634. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  6635. error(elem, "Expected a constant integer as an array field");
  6636. continue;
  6637. }
  6638. // add_type_and_value(c->info, op_index.expr, op_index.mode, op_index.type, op_index.value);
  6639. i64 index = exact_value_to_i64(op_index.value);
  6640. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  6641. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  6642. continue;
  6643. }
  6644. bool new_index = range_cache_add_index(&rc, index);
  6645. if (!new_index) {
  6646. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  6647. continue;
  6648. }
  6649. if (max < index+1) {
  6650. max = index+1;
  6651. }
  6652. Operand operand = {};
  6653. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  6654. check_assignment(c, &operand, elem_type, context_name);
  6655. is_constant = is_constant && operand.mode == Addressing_Constant;
  6656. }
  6657. }
  6658. cl->max_count = max;
  6659. }
  6660. } else {
  6661. isize index = 0;
  6662. for (; index < cl->elems.count; index++) {
  6663. Ast *e = cl->elems[index];
  6664. if (e == nullptr) {
  6665. error(node, "Invalid literal element");
  6666. continue;
  6667. }
  6668. if (e->kind == Ast_FieldValue) {
  6669. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  6670. continue;
  6671. }
  6672. if (0 <= max_type_count && max_type_count <= index) {
  6673. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  6674. }
  6675. Operand operand = {};
  6676. check_expr_with_type_hint(c, &operand, e, elem_type);
  6677. check_assignment(c, &operand, elem_type, context_name);
  6678. is_constant = is_constant && operand.mode == Addressing_Constant;
  6679. }
  6680. if (max < index) {
  6681. max = index;
  6682. }
  6683. }
  6684. if (t->kind == Type_Array) {
  6685. if (is_to_be_determined_array_count) {
  6686. t->Array.count = max;
  6687. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  6688. if (0 < max && max < t->Array.count) {
  6689. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  6690. }
  6691. }
  6692. }
  6693. if (t->kind == Type_SimdVector) {
  6694. if (!is_constant) {
  6695. error(node, "Expected all constant elements for a simd vector");
  6696. }
  6697. }
  6698. if (t->kind == Type_DynamicArray) {
  6699. if (build_context.no_dynamic_literals && cl->elems.count) {
  6700. error(node, "Compound literals of dynamic types have been disabled");
  6701. }
  6702. }
  6703. break;
  6704. }
  6705. case Type_EnumeratedArray:
  6706. {
  6707. Type *elem_type = t->EnumeratedArray.elem;
  6708. Type *index_type = t->EnumeratedArray.index;
  6709. String context_name = str_lit("enumerated array literal");
  6710. i64 max_type_count = t->EnumeratedArray.count;
  6711. gbString index_type_str = type_to_string(index_type);
  6712. defer (gb_string_free(index_type_str));
  6713. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  6714. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  6715. String total_lo_string = {};
  6716. String total_hi_string = {};
  6717. GB_ASSERT(is_type_enum(index_type));
  6718. {
  6719. Type *bt = base_type(index_type);
  6720. GB_ASSERT(bt->kind == Type_Enum);
  6721. for_array(i, bt->Enum.fields) {
  6722. Entity *f = bt->Enum.fields[i];
  6723. if (f->kind != Entity_Constant) {
  6724. continue;
  6725. }
  6726. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  6727. total_lo_string = f->token.string;
  6728. }
  6729. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  6730. total_hi_string = f->token.string;
  6731. }
  6732. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  6733. break;
  6734. }
  6735. }
  6736. }
  6737. i64 max = 0;
  6738. Type *bet = base_type(elem_type);
  6739. if (!elem_type_can_be_constant(bet)) {
  6740. is_constant = false;
  6741. }
  6742. if (bet == t_invalid) {
  6743. break;
  6744. }
  6745. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  6746. RangeCache rc = range_cache_make(heap_allocator());
  6747. defer (range_cache_destroy(&rc));
  6748. for_array(i, cl->elems) {
  6749. Ast *elem = cl->elems[i];
  6750. if (elem->kind != Ast_FieldValue) {
  6751. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  6752. continue;
  6753. }
  6754. ast_node(fv, FieldValue, elem);
  6755. if (is_ast_range(fv->field)) {
  6756. Token op = fv->field->BinaryExpr.op;
  6757. Operand x = {};
  6758. Operand y = {};
  6759. bool ok = check_range(c, fv->field, &x, &y, nullptr, index_type);
  6760. if (!ok) {
  6761. continue;
  6762. }
  6763. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  6764. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  6765. continue;
  6766. }
  6767. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  6768. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  6769. continue;
  6770. }
  6771. i64 lo = exact_value_to_i64(x.value);
  6772. i64 hi = exact_value_to_i64(y.value);
  6773. i64 max_index = hi;
  6774. if (op.kind == Token_RangeHalf) {
  6775. hi -= 1;
  6776. }
  6777. bool new_range = range_cache_add_range(&rc, lo, hi);
  6778. if (!new_range) {
  6779. gbString lo_str = expr_to_string(x.expr);
  6780. gbString hi_str = expr_to_string(y.expr);
  6781. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  6782. gb_string_free(hi_str);
  6783. gb_string_free(lo_str);
  6784. continue;
  6785. }
  6786. // NOTE(bill): These are sanity checks for invalid enum values
  6787. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  6788. gbString lo_str = expr_to_string(x.expr);
  6789. 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));
  6790. gb_string_free(lo_str);
  6791. continue;
  6792. }
  6793. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  6794. gbString hi_str = expr_to_string(y.expr);
  6795. 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));
  6796. gb_string_free(hi_str);
  6797. continue;
  6798. }
  6799. if (max < hi) {
  6800. max = max_index;
  6801. }
  6802. Operand operand = {};
  6803. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  6804. check_assignment(c, &operand, elem_type, context_name);
  6805. is_constant = is_constant && operand.mode == Addressing_Constant;
  6806. } else {
  6807. Operand op_index = {};
  6808. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  6809. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  6810. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  6811. continue;
  6812. }
  6813. i64 index = exact_value_to_i64(op_index.value);
  6814. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  6815. gbString idx_str = expr_to_string(op_index.expr);
  6816. 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));
  6817. gb_string_free(idx_str);
  6818. continue;
  6819. }
  6820. bool new_index = range_cache_add_index(&rc, index);
  6821. if (!new_index) {
  6822. gbString idx_str = expr_to_string(op_index.expr);
  6823. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  6824. gb_string_free(idx_str);
  6825. continue;
  6826. }
  6827. if (max < index+1) {
  6828. max = index+1;
  6829. }
  6830. Operand operand = {};
  6831. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  6832. check_assignment(c, &operand, elem_type, context_name);
  6833. is_constant = is_constant && operand.mode == Addressing_Constant;
  6834. }
  6835. }
  6836. cl->max_count = max;
  6837. } else {
  6838. isize index = 0;
  6839. for (; index < cl->elems.count; index++) {
  6840. Ast *e = cl->elems[index];
  6841. if (e == nullptr) {
  6842. error(node, "Invalid literal element");
  6843. continue;
  6844. }
  6845. if (e->kind == Ast_FieldValue) {
  6846. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  6847. continue;
  6848. }
  6849. if (0 <= max_type_count && max_type_count <= index) {
  6850. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  6851. }
  6852. Operand operand = {};
  6853. check_expr_with_type_hint(c, &operand, e, elem_type);
  6854. check_assignment(c, &operand, elem_type, context_name);
  6855. is_constant = is_constant && operand.mode == Addressing_Constant;
  6856. }
  6857. if (max < index) {
  6858. max = index;
  6859. }
  6860. }
  6861. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  6862. if (0 < max && max < t->EnumeratedArray.count) {
  6863. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  6864. } else {
  6865. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  6866. }
  6867. }
  6868. break;
  6869. }
  6870. case Type_Basic: {
  6871. if (!is_type_any(t)) {
  6872. if (cl->elems.count != 0) {
  6873. error(node, "Illegal compound literal");
  6874. }
  6875. break;
  6876. }
  6877. if (cl->elems.count == 0) {
  6878. break; // NOTE(bill): No need to init
  6879. }
  6880. { // Checker values
  6881. Type *field_types[2] = {t_rawptr, t_typeid};
  6882. isize field_count = 2;
  6883. if (cl->elems[0]->kind == Ast_FieldValue) {
  6884. bool fields_visited[2] = {};
  6885. for_array(i, cl->elems) {
  6886. Ast *elem = cl->elems[i];
  6887. if (elem->kind != Ast_FieldValue) {
  6888. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  6889. continue;
  6890. }
  6891. ast_node(fv, FieldValue, elem);
  6892. if (fv->field->kind != Ast_Ident) {
  6893. gbString expr_str = expr_to_string(fv->field);
  6894. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  6895. gb_string_free(expr_str);
  6896. continue;
  6897. }
  6898. String name = fv->field->Ident.token.string;
  6899. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  6900. if (sel.entity == nullptr) {
  6901. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  6902. continue;
  6903. }
  6904. isize index = sel.index[0];
  6905. if (fields_visited[index]) {
  6906. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  6907. continue;
  6908. }
  6909. fields_visited[index] = true;
  6910. check_expr(c, o, fv->value);
  6911. // NOTE(bill): 'any' literals can never be constant
  6912. is_constant = false;
  6913. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  6914. }
  6915. } else {
  6916. for_array(index, cl->elems) {
  6917. Ast *elem = cl->elems[index];
  6918. if (elem->kind == Ast_FieldValue) {
  6919. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  6920. continue;
  6921. }
  6922. check_expr(c, o, elem);
  6923. if (index >= field_count) {
  6924. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  6925. break;
  6926. }
  6927. // NOTE(bill): 'any' literals can never be constant
  6928. is_constant = false;
  6929. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  6930. }
  6931. if (cl->elems.count < field_count) {
  6932. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  6933. }
  6934. }
  6935. }
  6936. break;
  6937. }
  6938. case Type_Map: {
  6939. if (cl->elems.count == 0) {
  6940. break;
  6941. }
  6942. is_constant = false;
  6943. { // Checker values
  6944. bool key_is_typeid = is_type_typeid(t->Map.key);
  6945. bool value_is_typeid = is_type_typeid(t->Map.value);
  6946. for_array(i, cl->elems) {
  6947. Ast *elem = cl->elems[i];
  6948. if (elem->kind != Ast_FieldValue) {
  6949. error(elem, "Only 'field = value' elements are allowed in a map literal");
  6950. continue;
  6951. }
  6952. ast_node(fv, FieldValue, elem);
  6953. if (key_is_typeid) {
  6954. check_expr_or_type(c, o, fv->field, t->Map.key);
  6955. } else {
  6956. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  6957. }
  6958. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  6959. if (o->mode == Addressing_Invalid) {
  6960. continue;
  6961. }
  6962. if (value_is_typeid) {
  6963. check_expr_or_type(c, o, fv->value, t->Map.value);
  6964. } else {
  6965. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  6966. }
  6967. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  6968. }
  6969. }
  6970. if (build_context.no_dynamic_literals && cl->elems.count) {
  6971. error(node, "Compound literals of dynamic types have been disabled");
  6972. } else {
  6973. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  6974. add_package_dependency(c, "runtime", "__dynamic_map_set");
  6975. }
  6976. break;
  6977. }
  6978. case Type_BitSet: {
  6979. if (cl->elems.count == 0) {
  6980. break; // NOTE(bill): No need to init
  6981. }
  6982. Type *et = base_type(t->BitSet.elem);
  6983. isize field_count = 0;
  6984. if (et->kind == Type_Enum) {
  6985. field_count = et->Enum.fields.count;
  6986. }
  6987. if (cl->elems[0]->kind == Ast_FieldValue) {
  6988. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  6989. is_constant = false;
  6990. } else {
  6991. for_array(index, cl->elems) {
  6992. Ast *elem = cl->elems[index];
  6993. if (elem->kind == Ast_FieldValue) {
  6994. error(elem, "'field = value' in a bit_set a literal is not allowed");
  6995. continue;
  6996. }
  6997. check_expr_with_type_hint(c, o, elem, et);
  6998. if (is_constant) {
  6999. is_constant = o->mode == Addressing_Constant;
  7000. }
  7001. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  7002. if (o->mode == Addressing_Constant) {
  7003. i64 lower = t->BitSet.lower;
  7004. i64 upper = t->BitSet.upper;
  7005. i64 v = exact_value_to_i64(o->value);
  7006. if (lower <= v && v <= upper) {
  7007. // okay
  7008. } else {
  7009. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  7010. continue;
  7011. }
  7012. }
  7013. }
  7014. }
  7015. break;
  7016. }
  7017. default: {
  7018. if (cl->elems.count == 0) {
  7019. break; // NOTE(bill): No need to init
  7020. }
  7021. gbString str = type_to_string(type);
  7022. error(node, "Invalid compound literal type '%s'", str);
  7023. gb_string_free(str);
  7024. return kind;
  7025. }
  7026. }
  7027. if (is_constant) {
  7028. o->mode = Addressing_Constant;
  7029. if (is_type_bit_set(type)) {
  7030. // NOTE(bill): Encode as an integer
  7031. i64 lower = base_type(type)->BitSet.lower;
  7032. u64 bits = 0;
  7033. for_array(index, cl->elems) {
  7034. Ast *elem = cl->elems[index];
  7035. GB_ASSERT(elem->kind != Ast_FieldValue);
  7036. TypeAndValue tav = elem->tav;
  7037. ExactValue i = exact_value_to_integer(tav.value);
  7038. if (i.kind != ExactValue_Integer) {
  7039. continue;
  7040. }
  7041. i64 val = big_int_to_i64(&i.value_integer);
  7042. val -= lower;
  7043. u64 bit = u64(1ll<<val);
  7044. bits |= bit;
  7045. }
  7046. o->value = exact_value_u64(bits);
  7047. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  7048. ExactValue value = exact_value_compound(node);
  7049. Type *bt = core_type(type);
  7050. if (bt->kind == Type_Basic) {
  7051. if (bt->Basic.flags & BasicFlag_Boolean) {
  7052. value = exact_value_bool(false);
  7053. } else if (bt->Basic.flags & BasicFlag_Integer) {
  7054. value = exact_value_i64(0);
  7055. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  7056. value = exact_value_i64(0);
  7057. } else if (bt->Basic.flags & BasicFlag_Float) {
  7058. value = exact_value_float(0);
  7059. } else if (bt->Basic.flags & BasicFlag_Complex) {
  7060. value = exact_value_complex(0, 0);
  7061. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  7062. value = exact_value_quaternion(0, 0, 0, 0);
  7063. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  7064. value = exact_value_pointer(0);
  7065. } else if (bt->Basic.flags & BasicFlag_String) {
  7066. String empty_string = {};
  7067. value = exact_value_string(empty_string);
  7068. } else if (bt->Basic.flags & BasicFlag_Rune) {
  7069. value = exact_value_i64(0);
  7070. }
  7071. }
  7072. o->value = value;
  7073. } else {
  7074. o->value = exact_value_compound(node);
  7075. }
  7076. } else {
  7077. o->mode = Addressing_Value;
  7078. }
  7079. o->type = type;
  7080. case_end;
  7081. case_ast_node(pe, ParenExpr, node);
  7082. kind = check_expr_base(c, o, pe->expr, type_hint);
  7083. node->viral_state_flags |= pe->expr->viral_state_flags;
  7084. o->expr = node;
  7085. case_end;
  7086. case_ast_node(te, TagExpr, node);
  7087. String name = te->name.string;
  7088. error(node, "Unknown tag expression, #%.*s", LIT(name));
  7089. if (te->expr) {
  7090. kind = check_expr_base(c, o, te->expr, type_hint);
  7091. node->viral_state_flags |= te->expr->viral_state_flags;
  7092. }
  7093. o->expr = node;
  7094. case_end;
  7095. case_ast_node(ta, TypeAssertion, node);
  7096. check_expr(c, o, ta->expr);
  7097. node->viral_state_flags |= ta->expr->viral_state_flags;
  7098. if (o->mode == Addressing_Invalid) {
  7099. o->expr = node;
  7100. return kind;
  7101. }
  7102. if (o->mode == Addressing_Constant) {
  7103. gbString expr_str = expr_to_string(o->expr);
  7104. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  7105. gb_string_free(expr_str);
  7106. o->mode = Addressing_Invalid;
  7107. o->expr = node;
  7108. return kind;
  7109. }
  7110. if (is_type_untyped(o->type)) {
  7111. gbString expr_str = expr_to_string(o->expr);
  7112. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  7113. gb_string_free(expr_str);
  7114. o->mode = Addressing_Invalid;
  7115. o->expr = node;
  7116. return kind;
  7117. }
  7118. Type *src = type_deref(o->type);
  7119. Type *bsrc = base_type(src);
  7120. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  7121. if (!is_type_union(src)) {
  7122. gbString str = type_to_string(o->type);
  7123. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  7124. gb_string_free(str);
  7125. o->mode = Addressing_Invalid;
  7126. o->expr = node;
  7127. return kind;
  7128. }
  7129. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  7130. bool allowed = false;
  7131. for_array(i, bsrc->Union.variants) {
  7132. Type *vt = bsrc->Union.variants[i];
  7133. if (are_types_identical(vt, type_hint)) {
  7134. allowed = true;
  7135. add_type_info_type(c, vt);
  7136. break;
  7137. }
  7138. }
  7139. if (allowed) {
  7140. add_type_info_type(c, o->type);
  7141. o->type = type_hint;
  7142. o->mode = Addressing_OptionalOk;
  7143. return kind;
  7144. }
  7145. }
  7146. if (bsrc->Union.variants.count != 1) {
  7147. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  7148. o->mode = Addressing_Invalid;
  7149. o->expr = node;
  7150. return kind;
  7151. }
  7152. add_type_info_type(c, o->type);
  7153. add_type_info_type(c, bsrc->Union.variants[0]);
  7154. o->type = bsrc->Union.variants[0];
  7155. o->mode = Addressing_OptionalOk;
  7156. } else {
  7157. Type *t = check_type(c, ta->type);
  7158. Type *dst = t;
  7159. if (is_type_union(src)) {
  7160. bool ok = false;
  7161. for_array(i, bsrc->Union.variants) {
  7162. Type *vt = bsrc->Union.variants[i];
  7163. if (are_types_identical(vt, dst)) {
  7164. ok = true;
  7165. break;
  7166. }
  7167. }
  7168. if (!ok) {
  7169. gbString expr_str = expr_to_string(o->expr);
  7170. gbString dst_type_str = type_to_string(t);
  7171. defer (gb_string_free(expr_str));
  7172. defer (gb_string_free(dst_type_str));
  7173. if (bsrc->Union.variants.count == 0) {
  7174. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  7175. } else {
  7176. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  7177. }
  7178. o->mode = Addressing_Invalid;
  7179. o->expr = node;
  7180. return kind;
  7181. }
  7182. add_type_info_type(c, o->type);
  7183. add_type_info_type(c, t);
  7184. o->type = t;
  7185. o->mode = Addressing_OptionalOk;
  7186. } else if (is_type_any(src)) {
  7187. o->type = t;
  7188. o->mode = Addressing_OptionalOk;
  7189. add_type_info_type(c, o->type);
  7190. add_type_info_type(c, t);
  7191. } else {
  7192. gbString str = type_to_string(o->type);
  7193. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  7194. gb_string_free(str);
  7195. o->mode = Addressing_Invalid;
  7196. o->expr = node;
  7197. return kind;
  7198. }
  7199. }
  7200. add_package_dependency(c, "runtime", "type_assertion_check");
  7201. add_package_dependency(c, "runtime", "type_assertion_check2");
  7202. case_end;
  7203. case_ast_node(tc, TypeCast, node);
  7204. check_expr_or_type(c, o, tc->type);
  7205. if (o->mode != Addressing_Type) {
  7206. gbString str = expr_to_string(tc->type);
  7207. error(tc->type, "Expected a type, got %s", str);
  7208. gb_string_free(str);
  7209. o->mode = Addressing_Invalid;
  7210. }
  7211. if (o->mode == Addressing_Invalid) {
  7212. o->expr = node;
  7213. return kind;
  7214. }
  7215. Type *type = o->type;
  7216. check_expr_base(c, o, tc->expr, type);
  7217. node->viral_state_flags |= tc->expr->viral_state_flags;
  7218. if (o->mode != Addressing_Invalid) {
  7219. switch (tc->token.kind) {
  7220. case Token_transmute:
  7221. check_transmute(c, node, o, type);
  7222. break;
  7223. case Token_cast:
  7224. check_cast(c, o, type);
  7225. break;
  7226. default:
  7227. error(node, "Invalid AST: Invalid casting expression");
  7228. o->mode = Addressing_Invalid;
  7229. break;
  7230. }
  7231. }
  7232. return Expr_Expr;
  7233. case_end;
  7234. case_ast_node(ac, AutoCast, node);
  7235. check_expr_base(c, o, ac->expr, type_hint);
  7236. node->viral_state_flags |= ac->expr->viral_state_flags;
  7237. if (o->mode == Addressing_Invalid) {
  7238. o->expr = node;
  7239. return kind;
  7240. }
  7241. if (type_hint) {
  7242. Type *type = type_of_expr(ac->expr);
  7243. check_cast(c, o, type_hint);
  7244. if (is_type_typed(type) && are_types_identical(type, type_hint)) {
  7245. if (build_context.vet_extra) {
  7246. error(node, "Redundant 'auto_cast' applied to expression");
  7247. }
  7248. }
  7249. }
  7250. o->expr = node;
  7251. return Expr_Expr;
  7252. case_end;
  7253. case_ast_node(ue, UnaryExpr, node);
  7254. Type *th = type_hint;
  7255. if (ue->op.kind == Token_And) {
  7256. th = type_deref(th);
  7257. }
  7258. check_expr_base(c, o, ue->expr, th);
  7259. node->viral_state_flags |= ue->expr->viral_state_flags;
  7260. if (o->mode != Addressing_Invalid) {
  7261. check_unary_expr(c, o, ue->op, node);
  7262. }
  7263. o->expr = node;
  7264. return kind;
  7265. case_end;
  7266. case_ast_node(be, BinaryExpr, node);
  7267. check_binary_expr(c, o, node, type_hint, true);
  7268. if (o->mode == Addressing_Invalid) {
  7269. o->expr = node;
  7270. return kind;
  7271. }
  7272. case_end;
  7273. case_ast_node(se, SelectorExpr, node);
  7274. check_selector(c, o, node, type_hint);
  7275. node->viral_state_flags |= se->expr->viral_state_flags;
  7276. case_end;
  7277. case_ast_node(se, SelectorCallExpr, node);
  7278. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  7279. // COM APIs is a great example of where this kind of thing is extremely useful
  7280. // General idea:
  7281. //
  7282. // x->y(123) == x.y(x, 123)
  7283. //
  7284. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  7285. // Just regenerating a new AST aids things
  7286. //
  7287. // TODO(bill): Is this a good hack or not?
  7288. //
  7289. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  7290. if (se->modified_call) {
  7291. // Prevent double evaluation
  7292. o->expr = node;
  7293. o->type = node->tav.type;
  7294. o->value = node->tav.value;
  7295. o->mode = node->tav.mode;
  7296. return Expr_Expr;
  7297. }
  7298. bool allow_arrow_right_selector_expr;
  7299. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  7300. c->allow_arrow_right_selector_expr = true;
  7301. Operand x = {};
  7302. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  7303. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  7304. if (x.mode == Addressing_Invalid || x.type == t_invalid) {
  7305. o->mode = Addressing_Invalid;
  7306. o->type = t_invalid;
  7307. o->expr = node;
  7308. return kind;
  7309. }
  7310. if (!is_type_proc(x.type)) {
  7311. gbString type_str = type_to_string(x.type);
  7312. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  7313. gb_string_free(type_str);
  7314. o->mode = Addressing_Invalid;
  7315. o->type = t_invalid;
  7316. o->expr = node;
  7317. return Expr_Stmt;
  7318. }
  7319. ast_node(ce, CallExpr, se->call);
  7320. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  7321. Ast *first_arg = x.expr->SelectorExpr.expr;
  7322. GB_ASSERT(first_arg != nullptr);
  7323. Type *pt = base_type(x.type);
  7324. GB_ASSERT(pt->kind == Type_Proc);
  7325. Type *first_type = nullptr;
  7326. String first_arg_name = {};
  7327. if (pt->Proc.param_count > 0) {
  7328. Entity *f = pt->Proc.params->Tuple.variables[0];
  7329. first_type = f->type;
  7330. first_arg_name = f->token.string;
  7331. }
  7332. if (first_arg_name.len == 0) {
  7333. first_arg_name = str_lit("_");
  7334. }
  7335. if (first_type == nullptr) {
  7336. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  7337. o->mode = Addressing_Invalid;
  7338. o->type = t_invalid;
  7339. o->expr = node;
  7340. return Expr_Stmt;
  7341. }
  7342. Operand y = {};
  7343. y.mode = first_arg->tav.mode;
  7344. y.type = first_arg->tav.type;
  7345. y.value = first_arg->tav.value;
  7346. if (check_is_assignable_to(c, &y, first_type)) {
  7347. // Do nothing, it's valid
  7348. } else {
  7349. Operand z = y;
  7350. z.type = type_deref(y.type);
  7351. if (check_is_assignable_to(c, &z, first_type)) {
  7352. // NOTE(bill): AST GENERATION HACK!
  7353. Token op = {Token_Pointer};
  7354. first_arg = ast_deref_expr(first_arg->file, first_arg, op);
  7355. } else if (y.mode == Addressing_Variable) {
  7356. Operand w = y;
  7357. w.type = alloc_type_pointer(y.type);
  7358. if (check_is_assignable_to(c, &w, first_type)) {
  7359. // NOTE(bill): AST GENERATION HACK!
  7360. Token op = {Token_And};
  7361. first_arg = ast_unary_expr(first_arg->file, op, first_arg);
  7362. }
  7363. }
  7364. }
  7365. if (ce->args.count > 0) {
  7366. bool fail = false;
  7367. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  7368. for_array(i, ce->args) {
  7369. Ast *arg = ce->args[i];
  7370. bool mix = false;
  7371. if (first_is_field_value) {
  7372. mix = arg->kind != Ast_FieldValue;
  7373. } else {
  7374. mix = arg->kind == Ast_FieldValue;
  7375. }
  7376. if (mix) {
  7377. fail = true;
  7378. break;
  7379. }
  7380. }
  7381. if (!fail && first_is_field_value) {
  7382. Token op = {Token_Eq};
  7383. AstFile *f = first_arg->file;
  7384. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  7385. }
  7386. }
  7387. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  7388. modified_args[0] = first_arg;
  7389. slice_copy(&modified_args, ce->args, 1);
  7390. ce->args = modified_args;
  7391. se->modified_call = true;
  7392. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  7393. c->allow_arrow_right_selector_expr = true;
  7394. check_expr_base(c, o, se->call, type_hint);
  7395. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  7396. o->expr = node;
  7397. return Expr_Expr;
  7398. case_end;
  7399. case_ast_node(ise, ImplicitSelectorExpr, node);
  7400. return check_implicit_selector_expr(c, o, node, type_hint);
  7401. case_end;
  7402. case_ast_node(ie, IndexExpr, node);
  7403. check_expr(c, o, ie->expr);
  7404. node->viral_state_flags |= ie->expr->viral_state_flags;
  7405. if (o->mode == Addressing_Invalid) {
  7406. o->expr = node;
  7407. return kind;
  7408. }
  7409. Type *t = base_type(type_deref(o->type));
  7410. bool is_ptr = is_type_pointer(o->type);
  7411. bool is_const = o->mode == Addressing_Constant;
  7412. if (is_type_map(t)) {
  7413. Operand key = {};
  7414. if (is_type_typeid(t->Map.key)) {
  7415. check_expr_or_type(c, &key, ie->index, t->Map.key);
  7416. } else {
  7417. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  7418. }
  7419. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  7420. if (key.mode == Addressing_Invalid) {
  7421. o->mode = Addressing_Invalid;
  7422. o->expr = node;
  7423. return kind;
  7424. }
  7425. o->mode = Addressing_MapIndex;
  7426. o->type = t->Map.value;
  7427. o->expr = node;
  7428. add_package_dependency(c, "runtime", "__dynamic_map_get");
  7429. add_package_dependency(c, "runtime", "__dynamic_map_set");
  7430. return Expr_Expr;
  7431. }
  7432. i64 max_count = -1;
  7433. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  7434. if (is_const) {
  7435. if (is_type_array(t)) {
  7436. // OKay
  7437. } else if (is_type_slice(t)) {
  7438. // Okay
  7439. } else if (is_type_enumerated_array(t)) {
  7440. // Okay
  7441. } else if (is_type_string(t)) {
  7442. // Okay
  7443. } else if (is_type_relative_slice(t)) {
  7444. // Okay
  7445. } else if (is_type_matrix(t)) {
  7446. // Okay
  7447. } else {
  7448. valid = false;
  7449. }
  7450. }
  7451. if (!valid) {
  7452. gbString str = expr_to_string(o->expr);
  7453. gbString type_str = type_to_string(o->type);
  7454. defer (gb_string_free(str));
  7455. defer (gb_string_free(type_str));
  7456. if (is_const) {
  7457. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  7458. } else {
  7459. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  7460. }
  7461. o->mode = Addressing_Invalid;
  7462. o->expr = node;
  7463. return kind;
  7464. }
  7465. if (ie->index == nullptr) {
  7466. gbString str = expr_to_string(o->expr);
  7467. error(o->expr, "Missing index for '%s'", str);
  7468. gb_string_free(str);
  7469. o->mode = Addressing_Invalid;
  7470. o->expr = node;
  7471. return kind;
  7472. }
  7473. Type *index_type_hint = nullptr;
  7474. if (is_type_enumerated_array(t)) {
  7475. Type *bt = base_type(t);
  7476. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  7477. index_type_hint = bt->EnumeratedArray.index;
  7478. }
  7479. i64 index = 0;
  7480. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  7481. if (is_const) {
  7482. if (index < 0) {
  7483. gbString str = expr_to_string(o->expr);
  7484. error(o->expr, "Cannot index a constant '%s'", str);
  7485. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  7486. gb_string_free(str);
  7487. o->mode = Addressing_Invalid;
  7488. o->expr = node;
  7489. return kind;
  7490. } else if (ok) {
  7491. ExactValue value = type_and_value_of_expr(ie->expr).value;
  7492. o->mode = Addressing_Constant;
  7493. bool success = false;
  7494. bool finish = false;
  7495. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  7496. if (!success) {
  7497. gbString str = expr_to_string(o->expr);
  7498. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  7499. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  7500. gb_string_free(str);
  7501. o->mode = Addressing_Invalid;
  7502. o->expr = node;
  7503. return kind;
  7504. }
  7505. }
  7506. }
  7507. if (type_hint != nullptr && is_type_matrix(t)) {
  7508. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  7509. // if a type hint exists
  7510. }
  7511. case_end;
  7512. case_ast_node(se, SliceExpr, node);
  7513. check_expr(c, o, se->expr);
  7514. node->viral_state_flags |= se->expr->viral_state_flags;
  7515. if (o->mode == Addressing_Invalid) {
  7516. o->mode = Addressing_Invalid;
  7517. o->expr = node;
  7518. return kind;
  7519. }
  7520. bool valid = false;
  7521. i64 max_count = -1;
  7522. Type *t = base_type(type_deref(o->type));
  7523. switch (t->kind) {
  7524. case Type_Basic:
  7525. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  7526. valid = true;
  7527. if (o->mode == Addressing_Constant) {
  7528. max_count = o->value.value_string.len;
  7529. }
  7530. o->type = type_deref(o->type);
  7531. }
  7532. break;
  7533. case Type_Array:
  7534. valid = true;
  7535. max_count = t->Array.count;
  7536. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  7537. gbString str = expr_to_string(node);
  7538. error(node, "Cannot slice array '%s', value is not addressable", str);
  7539. gb_string_free(str);
  7540. o->mode = Addressing_Invalid;
  7541. o->expr = node;
  7542. return kind;
  7543. }
  7544. o->type = alloc_type_slice(t->Array.elem);
  7545. break;
  7546. case Type_MultiPointer:
  7547. valid = true;
  7548. o->type = type_deref(o->type);
  7549. break;
  7550. case Type_Slice:
  7551. valid = true;
  7552. o->type = type_deref(o->type);
  7553. break;
  7554. case Type_DynamicArray:
  7555. valid = true;
  7556. o->type = alloc_type_slice(t->DynamicArray.elem);
  7557. break;
  7558. case Type_Struct:
  7559. if (is_type_soa_struct(t)) {
  7560. valid = true;
  7561. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  7562. }
  7563. break;
  7564. case Type_RelativeSlice:
  7565. valid = true;
  7566. o->type = t->RelativeSlice.slice_type;
  7567. if (o->mode != Addressing_Variable) {
  7568. gbString str = expr_to_string(node);
  7569. error(node, "Cannot relative slice '%s', value is not addressable", str);
  7570. gb_string_free(str);
  7571. o->mode = Addressing_Invalid;
  7572. o->expr = node;
  7573. return kind;
  7574. }
  7575. break;
  7576. }
  7577. if (!valid) {
  7578. gbString str = expr_to_string(o->expr);
  7579. gbString type_str = type_to_string(o->type);
  7580. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  7581. gb_string_free(type_str);
  7582. gb_string_free(str);
  7583. o->mode = Addressing_Invalid;
  7584. o->expr = node;
  7585. return kind;
  7586. }
  7587. if (se->low == nullptr && se->high != nullptr) {
  7588. // It is okay to continue as it will assume the 1st index is zero
  7589. }
  7590. i64 indices[2] = {};
  7591. Ast *nodes[2] = {se->low, se->high};
  7592. for (isize i = 0; i < gb_count_of(nodes); i++) {
  7593. i64 index = max_count;
  7594. if (nodes[i] != nullptr) {
  7595. i64 capacity = -1;
  7596. if (max_count >= 0) {
  7597. capacity = max_count;
  7598. }
  7599. i64 j = 0;
  7600. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  7601. index = j;
  7602. }
  7603. node->viral_state_flags |= nodes[i]->viral_state_flags;
  7604. } else if (i == 0) {
  7605. index = 0;
  7606. }
  7607. indices[i] = index;
  7608. }
  7609. for (isize i = 0; i < gb_count_of(indices); i++) {
  7610. i64 a = indices[i];
  7611. for (isize j = i+1; j < gb_count_of(indices); j++) {
  7612. i64 b = indices[j];
  7613. if (a > b && b >= 0) {
  7614. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  7615. }
  7616. }
  7617. }
  7618. if (max_count < 0) {
  7619. if (o->mode == Addressing_Constant) {
  7620. gbString s = expr_to_string(se->expr);
  7621. error(se->expr, "Cannot slice constant value '%s'", s);
  7622. gb_string_free(s);
  7623. }
  7624. }
  7625. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  7626. /*
  7627. x[:] -> [^]T
  7628. x[i:] -> [^]T
  7629. x[:n] -> []T
  7630. x[i:n] -> []T
  7631. */
  7632. o->type = alloc_type_slice(t->MultiPointer.elem);
  7633. }
  7634. o->mode = Addressing_Value;
  7635. if (is_type_string(t) && max_count >= 0) {
  7636. bool all_constant = true;
  7637. for (isize i = 0; i < gb_count_of(nodes); i++) {
  7638. if (nodes[i] != nullptr) {
  7639. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  7640. if (tav.mode != Addressing_Constant) {
  7641. all_constant = false;
  7642. break;
  7643. }
  7644. }
  7645. }
  7646. if (!all_constant) {
  7647. gbString str = expr_to_string(o->expr);
  7648. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  7649. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  7650. gb_string_free(str);
  7651. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  7652. o->expr = node;
  7653. return kind;
  7654. }
  7655. String s = {};
  7656. if (o->value.kind == ExactValue_String) {
  7657. s = o->value.value_string;
  7658. }
  7659. o->mode = Addressing_Constant;
  7660. o->type = t;
  7661. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  7662. }
  7663. case_end;
  7664. case_ast_node(mie, MatrixIndexExpr, node);
  7665. check_matrix_index_expr(c, o, node, type_hint);
  7666. o->expr = node;
  7667. return Expr_Expr;
  7668. case_end;
  7669. case_ast_node(ce, CallExpr, node);
  7670. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  7671. case_end;
  7672. case_ast_node(de, DerefExpr, node);
  7673. check_expr_or_type(c, o, de->expr);
  7674. node->viral_state_flags |= de->expr->viral_state_flags;
  7675. if (o->mode == Addressing_Invalid) {
  7676. o->mode = Addressing_Invalid;
  7677. o->expr = node;
  7678. return kind;
  7679. } else {
  7680. Type *t = base_type(o->type);
  7681. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  7682. o->mode = Addressing_Variable;
  7683. o->type = t->Pointer.elem;
  7684. } else if (t->kind == Type_RelativePointer) {
  7685. if (o->mode != Addressing_Variable) {
  7686. gbString str = expr_to_string(o->expr);
  7687. gbString typ = type_to_string(o->type);
  7688. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  7689. gb_string_free(typ);
  7690. gb_string_free(str);
  7691. }
  7692. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  7693. add_type_info_type(c, o->type);
  7694. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  7695. GB_ASSERT(ptr_type->kind == Type_Pointer);
  7696. o->mode = Addressing_Variable;
  7697. o->type = ptr_type->Pointer.elem;
  7698. } else {
  7699. gbString str = expr_to_string(o->expr);
  7700. gbString typ = type_to_string(o->type);
  7701. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  7702. gb_string_free(typ);
  7703. gb_string_free(str);
  7704. o->mode = Addressing_Invalid;
  7705. o->expr = node;
  7706. return kind;
  7707. }
  7708. }
  7709. case_end;
  7710. case_ast_node(ia, InlineAsmExpr, node);
  7711. if (c->curr_proc_decl == nullptr) {
  7712. error(node, "Inline asm expressions are only allowed within a procedure body");
  7713. }
  7714. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  7715. Type *return_type = nullptr;
  7716. for_array(i, ia->param_types) {
  7717. param_types[i] = check_type(c, ia->param_types[i]);
  7718. }
  7719. if (ia->return_type != nullptr) {
  7720. return_type = check_type(c, ia->return_type);
  7721. }
  7722. Operand x = {};
  7723. check_expr(c, &x, ia->asm_string);
  7724. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  7725. error(x.expr, "Expected a constant string for the inline asm main parameter");
  7726. }
  7727. check_expr(c, &x, ia->constraints_string);
  7728. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  7729. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  7730. }
  7731. Scope *scope = create_scope(c->info, c->scope);
  7732. scope->flags |= ScopeFlag_Proc;
  7733. Type *params = alloc_type_tuple();
  7734. Type *results = alloc_type_tuple();
  7735. if (param_types.count != 0) {
  7736. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  7737. for_array(i, param_types) {
  7738. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  7739. }
  7740. }
  7741. if (return_type != nullptr) {
  7742. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  7743. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  7744. }
  7745. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  7746. o->type = pt;
  7747. o->mode = Addressing_Value;
  7748. o->expr = node;
  7749. return Expr_Expr;
  7750. case_end;
  7751. case Ast_TypeidType:
  7752. case Ast_PolyType:
  7753. case Ast_ProcType:
  7754. case Ast_PointerType:
  7755. case Ast_MultiPointerType:
  7756. case Ast_ArrayType:
  7757. case Ast_DynamicArrayType:
  7758. case Ast_StructType:
  7759. case Ast_UnionType:
  7760. case Ast_EnumType:
  7761. case Ast_MapType:
  7762. case Ast_BitSetType:
  7763. case Ast_MatrixType:
  7764. o->mode = Addressing_Type;
  7765. o->type = check_type(c, node);
  7766. break;
  7767. }
  7768. kind = Expr_Expr;
  7769. o->expr = node;
  7770. return kind;
  7771. }
  7772. ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7773. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  7774. if (o->type != nullptr && core_type(o->type) == nullptr) {
  7775. o->type = t_invalid;
  7776. gbString xs = expr_to_string(o->expr);
  7777. if (o->mode == Addressing_Type) {
  7778. error(o->expr, "Invalid type usage '%s'", xs);
  7779. } else {
  7780. error(o->expr, "Invalid expression '%s'", xs);
  7781. }
  7782. gb_string_free(xs);
  7783. }
  7784. if (o->type != nullptr && is_type_untyped(o->type)) {
  7785. add_untyped(c, node, o->mode, o->type, o->value);
  7786. }
  7787. add_type_and_value(c->info, node, o->mode, o->type, o->value);
  7788. return kind;
  7789. }
  7790. void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  7791. check_expr_base(c, o, e, nullptr);
  7792. switch (o->mode) {
  7793. default:
  7794. return; // NOTE(bill): Valid
  7795. case Addressing_NoValue:
  7796. error_operand_no_value(o);
  7797. break;
  7798. }
  7799. o->mode = Addressing_Invalid;
  7800. }
  7801. void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  7802. check_expr_base(c, o, e, nullptr);
  7803. switch (o->mode) {
  7804. default:
  7805. return; // NOTE(bill): Valid
  7806. case Addressing_NoValue:
  7807. error_operand_no_value(o);
  7808. break;
  7809. case Addressing_Type:
  7810. error_operand_not_expression(o);
  7811. break;
  7812. }
  7813. o->mode = Addressing_Invalid;
  7814. }
  7815. void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  7816. check_expr_base(c, o, e, type_hint);
  7817. switch (o->mode) {
  7818. default:
  7819. return; // NOTE(bill): Valid
  7820. case Addressing_NoValue:
  7821. error_operand_no_value(o);
  7822. break;
  7823. case Addressing_Type:
  7824. error_operand_not_expression(o);
  7825. break;
  7826. }
  7827. o->mode = Addressing_Invalid;
  7828. }
  7829. void check_not_tuple(CheckerContext *c, Operand *o) {
  7830. if (o->mode == Addressing_Value) {
  7831. // NOTE(bill): Tuples are not first class thus never named
  7832. if (o->type->kind == Type_Tuple) {
  7833. isize count = o->type->Tuple.variables.count;
  7834. error(o->expr,
  7835. "%td-valued expression found where single value expected", count);
  7836. o->mode = Addressing_Invalid;
  7837. GB_ASSERT(count != 1);
  7838. }
  7839. }
  7840. }
  7841. void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  7842. check_multi_expr(c, o, e);
  7843. check_not_tuple(c, o);
  7844. }
  7845. void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  7846. check_expr_base(c, o, e, type_hint);
  7847. check_not_tuple(c, o);
  7848. error_operand_no_value(o);
  7849. }
  7850. bool is_exact_value_zero(ExactValue const &v) {
  7851. switch (v.kind) {
  7852. case ExactValue_Invalid:
  7853. return true;
  7854. case ExactValue_Bool:
  7855. return !v.value_bool;
  7856. case ExactValue_String:
  7857. return v.value_string.len == 0;
  7858. case ExactValue_Integer:
  7859. return big_int_is_zero(&v.value_integer);
  7860. case ExactValue_Float:
  7861. return v.value_float == 0.0;
  7862. case ExactValue_Complex:
  7863. if (v.value_complex) {
  7864. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  7865. }
  7866. return true;
  7867. case ExactValue_Quaternion:
  7868. if (v.value_quaternion) {
  7869. return v.value_quaternion->real == 0.0 &&
  7870. v.value_quaternion->imag == 0.0 &&
  7871. v.value_quaternion->jmag == 0.0 &&
  7872. v.value_quaternion->kmag == 0.0;
  7873. }
  7874. return true;
  7875. case ExactValue_Pointer:
  7876. return v.value_pointer == 0;
  7877. case ExactValue_Compound:
  7878. if (v.value_compound == nullptr) {
  7879. return true;
  7880. } else {
  7881. ast_node(cl, CompoundLit, v.value_compound);
  7882. if (cl->elems.count == 0) {
  7883. return true;
  7884. } else {
  7885. for_array(i, cl->elems) {
  7886. Ast *elem = cl->elems[i];
  7887. if (elem->tav.mode != Addressing_Constant) {
  7888. // if (elem->tav.value.kind != ExactValue_Invalid) {
  7889. return false;
  7890. // }
  7891. }
  7892. if (!is_exact_value_zero(elem->tav.value)) {
  7893. return false;
  7894. }
  7895. }
  7896. return true;
  7897. }
  7898. }
  7899. case ExactValue_Procedure:
  7900. return v.value_procedure == nullptr;
  7901. case ExactValue_Typeid:
  7902. return v.value_typeid == nullptr;
  7903. }
  7904. return true;
  7905. }
  7906. gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  7907. gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  7908. for_array(i, params) {
  7909. if (i > 0) {
  7910. str = gb_string_appendc(str, ", ");
  7911. }
  7912. str = write_expr_to_string(str, params[i], false);
  7913. }
  7914. return str;
  7915. }
  7916. gbString string_append_string(gbString str, String string) {
  7917. if (string.len > 0) {
  7918. return gb_string_append_length(str, &string[0], string.len);
  7919. }
  7920. return str;
  7921. }
  7922. gbString string_append_token(gbString str, Token token) {
  7923. if (token.kind == Token_String) {
  7924. str = gb_string_append_rune(str, '"');
  7925. } else if (token.kind == Token_Rune) {
  7926. str = gb_string_append_rune(str, '\'');
  7927. }
  7928. str = string_append_string(str, token.string);
  7929. if (token.kind == Token_String) {
  7930. str = gb_string_append_rune(str, '"');
  7931. } else if (token.kind == Token_Rune) {
  7932. str = gb_string_append_rune(str, '\'');
  7933. }
  7934. return str;
  7935. }
  7936. gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  7937. if (node == nullptr)
  7938. return str;
  7939. if (is_ast_stmt(node)) {
  7940. GB_ASSERT("stmt passed to write_expr_to_string");
  7941. }
  7942. switch (node->kind) {
  7943. default:
  7944. str = gb_string_appendc(str, "(BadExpr)");
  7945. break;
  7946. case_ast_node(i, Ident, node);
  7947. str = string_append_token(str, i->token);
  7948. case_end;
  7949. case_ast_node(i, Implicit, node);
  7950. str = string_append_token(str, *i);
  7951. case_end;
  7952. case_ast_node(bl, BasicLit, node);
  7953. str = string_append_token(str, bl->token);
  7954. case_end;
  7955. case_ast_node(bd, BasicDirective, node);
  7956. str = gb_string_append_rune(str, '#');
  7957. str = string_append_string(str, bd->name.string);
  7958. case_end;
  7959. case_ast_node(ud, Undef, node);
  7960. str = gb_string_appendc(str, "---");
  7961. case_end;
  7962. case_ast_node(pg, ProcGroup, node);
  7963. str = gb_string_appendc(str, "proc{");
  7964. for_array(i, pg->args) {
  7965. if (i > 0) str = gb_string_appendc(str, ", ");
  7966. str = write_expr_to_string(str, pg->args[i], shorthand);
  7967. }
  7968. str = gb_string_append_rune(str, '}');
  7969. case_end;
  7970. case_ast_node(pl, ProcLit, node);
  7971. str = write_expr_to_string(str, pl->type, shorthand);
  7972. if (pl->body) {
  7973. str = gb_string_appendc(str, " {...}");
  7974. } else {
  7975. str = gb_string_appendc(str, " ---");
  7976. }
  7977. case_end;
  7978. case_ast_node(cl, CompoundLit, node);
  7979. str = write_expr_to_string(str, cl->type, shorthand);
  7980. str = gb_string_append_rune(str, '{');
  7981. if (shorthand) {
  7982. str = gb_string_appendc(str, "...");
  7983. } else {
  7984. for_array(i, cl->elems) {
  7985. if (i > 0) str = gb_string_appendc(str, ", ");
  7986. str = write_expr_to_string(str, cl->elems[i], shorthand);
  7987. }
  7988. }
  7989. str = gb_string_append_rune(str, '}');
  7990. case_end;
  7991. case_ast_node(te, TagExpr, node);
  7992. str = gb_string_append_rune(str, '#');
  7993. str = string_append_token(str, te->name);
  7994. str = write_expr_to_string(str, te->expr, shorthand);
  7995. case_end;
  7996. case_ast_node(ue, UnaryExpr, node);
  7997. str = string_append_token(str, ue->op);
  7998. str = write_expr_to_string(str, ue->expr, shorthand);
  7999. case_end;
  8000. case_ast_node(de, DerefExpr, node);
  8001. str = write_expr_to_string(str, de->expr, shorthand);
  8002. str = gb_string_append_rune(str, '^');
  8003. case_end;
  8004. case_ast_node(be, BinaryExpr, node);
  8005. str = write_expr_to_string(str, be->left, shorthand);
  8006. str = gb_string_append_rune(str, ' ');
  8007. str = string_append_token(str, be->op);
  8008. str = gb_string_append_rune(str, ' ');
  8009. str = write_expr_to_string(str, be->right, shorthand);
  8010. case_end;
  8011. case_ast_node(te, TernaryIfExpr, node);
  8012. TokenPos x = ast_token(te->x).pos;
  8013. TokenPos cond = ast_token(te->cond).pos;
  8014. if (x < cond) {
  8015. str = write_expr_to_string(str, te->x, shorthand);
  8016. str = gb_string_appendc(str, " if ");
  8017. str = write_expr_to_string(str, te->cond, shorthand);
  8018. str = gb_string_appendc(str, " else ");
  8019. str = write_expr_to_string(str, te->y, shorthand);
  8020. } else {
  8021. str = write_expr_to_string(str, te->cond, shorthand);
  8022. str = gb_string_appendc(str, " ? ");
  8023. str = write_expr_to_string(str, te->x, shorthand);
  8024. str = gb_string_appendc(str, " : ");
  8025. str = write_expr_to_string(str, te->y, shorthand);
  8026. }
  8027. case_end;
  8028. case_ast_node(te, TernaryWhenExpr, node);
  8029. str = write_expr_to_string(str, te->x, shorthand);
  8030. str = gb_string_appendc(str, " when ");
  8031. str = write_expr_to_string(str, te->cond, shorthand);
  8032. str = gb_string_appendc(str, " else ");
  8033. str = write_expr_to_string(str, te->y, shorthand);
  8034. case_end;
  8035. case_ast_node(oe, OrElseExpr, node);
  8036. str = write_expr_to_string(str, oe->x, shorthand);
  8037. str = gb_string_appendc(str, " or_else ");
  8038. str = write_expr_to_string(str, oe->y, shorthand);
  8039. case_end;
  8040. case_ast_node(oe, OrReturnExpr, node);
  8041. str = write_expr_to_string(str, oe->expr, shorthand);
  8042. str = gb_string_appendc(str, " or_return");
  8043. case_end;
  8044. case_ast_node(pe, ParenExpr, node);
  8045. str = gb_string_append_rune(str, '(');
  8046. str = write_expr_to_string(str, pe->expr, shorthand);
  8047. str = gb_string_append_rune(str, ')');
  8048. case_end;
  8049. case_ast_node(se, SelectorExpr, node);
  8050. str = write_expr_to_string(str, se->expr, shorthand);
  8051. str = string_append_token(str, se->token);
  8052. str = write_expr_to_string(str, se->selector, shorthand);
  8053. case_end;
  8054. case_ast_node(se, ImplicitSelectorExpr, node);
  8055. str = gb_string_append_rune(str, '.');
  8056. str = write_expr_to_string(str, se->selector, shorthand);
  8057. case_end;
  8058. case_ast_node(se, SelectorCallExpr, node);
  8059. str = write_expr_to_string(str, se->expr, shorthand);
  8060. str = gb_string_appendc(str, "(");
  8061. ast_node(ce, CallExpr, se->call);
  8062. isize start = se->modified_call ? 1 : 0;
  8063. for (isize i = start; i < ce->args.count; i++) {
  8064. Ast *arg = ce->args[i];
  8065. if (i > start) {
  8066. str = gb_string_appendc(str, ", ");
  8067. }
  8068. str = write_expr_to_string(str, arg, shorthand);
  8069. }
  8070. str = gb_string_appendc(str, ")");
  8071. case_end;
  8072. case_ast_node(ta, TypeAssertion, node);
  8073. str = write_expr_to_string(str, ta->expr, shorthand);
  8074. if (ta->type != nullptr &&
  8075. ta->type->kind == Ast_UnaryExpr &&
  8076. ta->type->UnaryExpr.op.kind == Token_Question) {
  8077. str = gb_string_appendc(str, ".?");
  8078. } else {
  8079. str = gb_string_appendc(str, ".(");
  8080. str = write_expr_to_string(str, ta->type, shorthand);
  8081. str = gb_string_append_rune(str, ')');
  8082. }
  8083. case_end;
  8084. case_ast_node(tc, TypeCast, node);
  8085. str = string_append_token(str, tc->token);
  8086. str = gb_string_append_rune(str, '(');
  8087. str = write_expr_to_string(str, tc->type, shorthand);
  8088. str = gb_string_append_rune(str, ')');
  8089. str = write_expr_to_string(str, tc->expr, shorthand);
  8090. case_end;
  8091. case_ast_node(ac, AutoCast, node);
  8092. str = string_append_token(str, ac->token);
  8093. str = gb_string_append_rune(str, ' ');
  8094. str = write_expr_to_string(str, ac->expr, shorthand);
  8095. case_end;
  8096. case_ast_node(ie, IndexExpr, node);
  8097. str = write_expr_to_string(str, ie->expr, shorthand);
  8098. str = gb_string_append_rune(str, '[');
  8099. str = write_expr_to_string(str, ie->index, shorthand);
  8100. str = gb_string_append_rune(str, ']');
  8101. case_end;
  8102. case_ast_node(se, SliceExpr, node);
  8103. str = write_expr_to_string(str, se->expr, shorthand);
  8104. str = gb_string_append_rune(str, '[');
  8105. str = write_expr_to_string(str, se->low, shorthand);
  8106. str = string_append_token(str, se->interval);
  8107. str = write_expr_to_string(str, se->high, shorthand);
  8108. str = gb_string_append_rune(str, ']');
  8109. case_end;
  8110. case_ast_node(mie, MatrixIndexExpr, node);
  8111. str = write_expr_to_string(str, mie->expr, shorthand);
  8112. str = gb_string_append_rune(str, '[');
  8113. str = write_expr_to_string(str, mie->row_index, shorthand);
  8114. str = gb_string_appendc(str, ", ");
  8115. str = write_expr_to_string(str, mie->column_index, shorthand);
  8116. str = gb_string_append_rune(str, ']');
  8117. case_end;
  8118. case_ast_node(e, Ellipsis, node);
  8119. str = gb_string_appendc(str, "..");
  8120. str = write_expr_to_string(str, e->expr, shorthand);
  8121. case_end;
  8122. case_ast_node(fv, FieldValue, node);
  8123. str = write_expr_to_string(str, fv->field, shorthand);
  8124. str = gb_string_appendc(str, " = ");
  8125. str = write_expr_to_string(str, fv->value, shorthand);
  8126. case_end;
  8127. case_ast_node(ht, HelperType, node);
  8128. str = gb_string_appendc(str, "#type ");
  8129. str = write_expr_to_string(str, ht->type, shorthand);
  8130. case_end;
  8131. case_ast_node(ht, DistinctType, node);
  8132. str = gb_string_appendc(str, "distinct ");
  8133. str = write_expr_to_string(str, ht->type, shorthand);
  8134. case_end;
  8135. case_ast_node(pt, PolyType, node);
  8136. str = gb_string_append_rune(str, '$');
  8137. str = write_expr_to_string(str, pt->type, shorthand);
  8138. if (pt->specialization != nullptr) {
  8139. str = gb_string_append_rune(str, '/');
  8140. str = write_expr_to_string(str, pt->specialization, shorthand);
  8141. }
  8142. case_end;
  8143. case_ast_node(pt, PointerType, node);
  8144. str = gb_string_append_rune(str, '^');
  8145. str = write_expr_to_string(str, pt->type, shorthand);
  8146. case_end;
  8147. case_ast_node(pt, MultiPointerType, node);
  8148. str = gb_string_appendc(str, "[^]");
  8149. str = write_expr_to_string(str, pt->type, shorthand);
  8150. case_end;
  8151. case_ast_node(at, ArrayType, node);
  8152. str = gb_string_append_rune(str, '[');
  8153. if (at->count != nullptr &&
  8154. at->count->kind == Ast_UnaryExpr &&
  8155. at->count->UnaryExpr.op.kind == Token_Question) {
  8156. str = gb_string_appendc(str, "?");
  8157. } else {
  8158. str = write_expr_to_string(str, at->count, shorthand);
  8159. }
  8160. str = gb_string_append_rune(str, ']');
  8161. str = write_expr_to_string(str, at->elem, shorthand);
  8162. case_end;
  8163. case_ast_node(at, DynamicArrayType, node);
  8164. str = gb_string_appendc(str, "[dynamic]");
  8165. str = write_expr_to_string(str, at->elem, shorthand);
  8166. case_end;
  8167. case_ast_node(bs, BitSetType, node);
  8168. str = gb_string_appendc(str, "bit_set[");
  8169. str = write_expr_to_string(str, bs->elem, shorthand);
  8170. str = gb_string_appendc(str, "]");
  8171. case_end;
  8172. case_ast_node(mt, MapType, node);
  8173. str = gb_string_appendc(str, "map[");
  8174. str = write_expr_to_string(str, mt->key, shorthand);
  8175. str = gb_string_append_rune(str, ']');
  8176. str = write_expr_to_string(str, mt->value, shorthand);
  8177. case_end;
  8178. case_ast_node(mt, MatrixType, node);
  8179. str = gb_string_appendc(str, "matrix[");
  8180. str = write_expr_to_string(str, mt->row_count, shorthand);
  8181. str = gb_string_appendc(str, ", ");
  8182. str = write_expr_to_string(str, mt->column_count, shorthand);
  8183. str = gb_string_append_rune(str, ']');
  8184. str = write_expr_to_string(str, mt->elem, shorthand);
  8185. case_end;
  8186. case_ast_node(f, Field, node);
  8187. if (f->flags&FieldFlag_using) {
  8188. str = gb_string_appendc(str, "using ");
  8189. }
  8190. if (f->flags&FieldFlag_no_alias) {
  8191. str = gb_string_appendc(str, "#no_alias ");
  8192. }
  8193. if (f->flags&FieldFlag_c_vararg) {
  8194. str = gb_string_appendc(str, "#c_vararg ");
  8195. }
  8196. if (f->flags&FieldFlag_auto_cast) {
  8197. str = gb_string_appendc(str, "auto_cast ");
  8198. }
  8199. if (f->flags&FieldFlag_any_int) {
  8200. str = gb_string_appendc(str, "#any_int ");
  8201. }
  8202. if (f->flags&FieldFlag_const) {
  8203. str = gb_string_appendc(str, "#const ");
  8204. }
  8205. for_array(i, f->names) {
  8206. Ast *name = f->names[i];
  8207. if (i > 0) str = gb_string_appendc(str, ", ");
  8208. str = write_expr_to_string(str, name, shorthand);
  8209. }
  8210. if (f->names.count > 0) {
  8211. if (f->type == nullptr && f->default_value != nullptr) {
  8212. str = gb_string_append_rune(str, ' ');
  8213. }
  8214. str = gb_string_appendc(str, ":");
  8215. }
  8216. if (f->type != nullptr) {
  8217. str = gb_string_append_rune(str, ' ');
  8218. str = write_expr_to_string(str, f->type, shorthand);
  8219. }
  8220. if (f->default_value != nullptr) {
  8221. if (f->type != nullptr) {
  8222. str = gb_string_append_rune(str, ' ');
  8223. }
  8224. str = gb_string_appendc(str, "= ");
  8225. str = write_expr_to_string(str, f->default_value, shorthand);
  8226. }
  8227. case_end;
  8228. case_ast_node(f, FieldList, node);
  8229. bool has_name = false;
  8230. for_array(i, f->list) {
  8231. ast_node(field, Field, f->list[i]);
  8232. if (field->names.count > 1) {
  8233. has_name = true;
  8234. break;
  8235. }
  8236. if (field->names.count == 0) {
  8237. continue;
  8238. }
  8239. if (!is_blank_ident(field->names[0])) {
  8240. has_name = true;
  8241. break;
  8242. }
  8243. }
  8244. for_array(i, f->list) {
  8245. if (i > 0) str = gb_string_appendc(str, ", ");
  8246. if (has_name) {
  8247. str = write_expr_to_string(str, f->list[i], shorthand);
  8248. } else {
  8249. ast_node(field, Field, f->list[i]);
  8250. if (field->flags&FieldFlag_using) {
  8251. str = gb_string_appendc(str, "using ");
  8252. }
  8253. if (field->flags&FieldFlag_no_alias) {
  8254. str = gb_string_appendc(str, "#no_alias ");
  8255. }
  8256. if (field->flags&FieldFlag_c_vararg) {
  8257. str = gb_string_appendc(str, "#c_vararg ");
  8258. }
  8259. str = write_expr_to_string(str, field->type, shorthand);
  8260. }
  8261. }
  8262. case_end;
  8263. case_ast_node(ce, CallExpr, node);
  8264. switch (ce->inlining) {
  8265. case ProcInlining_inline:
  8266. str = gb_string_appendc(str, "#force_inline ");
  8267. break;
  8268. case ProcInlining_no_inline:
  8269. str = gb_string_appendc(str, "#force_no_inline ");
  8270. break;
  8271. }
  8272. str = write_expr_to_string(str, ce->proc, shorthand);
  8273. str = gb_string_appendc(str, "(");
  8274. for_array(i, ce->args) {
  8275. Ast *arg = ce->args[i];
  8276. if (i > 0) {
  8277. str = gb_string_appendc(str, ", ");
  8278. }
  8279. str = write_expr_to_string(str, arg, shorthand);
  8280. }
  8281. str = gb_string_appendc(str, ")");
  8282. case_end;
  8283. case_ast_node(tt, TypeidType, node);
  8284. str = gb_string_appendc(str, "typeid");
  8285. if (tt->specialization) {
  8286. str = gb_string_appendc(str, "/");
  8287. str = write_expr_to_string(str, tt->specialization, shorthand);
  8288. }
  8289. case_end;
  8290. case_ast_node(pt, ProcType, node);
  8291. str = gb_string_appendc(str, "proc(");
  8292. str = write_expr_to_string(str, pt->params, shorthand);
  8293. str = gb_string_appendc(str, ")");
  8294. if (pt->results != nullptr) {
  8295. str = gb_string_appendc(str, " -> ");
  8296. bool parens_needed = false;
  8297. if (pt->results && pt->results->kind == Ast_FieldList) {
  8298. for_array(i, pt->results->FieldList.list) {
  8299. Ast *field = pt->results->FieldList.list[i];
  8300. ast_node(f, Field, field);
  8301. if (f->names.count != 0) {
  8302. parens_needed = true;
  8303. break;
  8304. }
  8305. }
  8306. }
  8307. if (parens_needed) {
  8308. str = gb_string_append_rune(str, '(');
  8309. }
  8310. str = write_expr_to_string(str, pt->results, shorthand);
  8311. if (parens_needed) {
  8312. str = gb_string_append_rune(str, ')');
  8313. }
  8314. }
  8315. case_end;
  8316. case_ast_node(st, StructType, node);
  8317. str = gb_string_appendc(str, "struct ");
  8318. if (st->polymorphic_params) {
  8319. str = gb_string_append_rune(str, '(');
  8320. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  8321. str = gb_string_appendc(str, ") ");
  8322. }
  8323. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  8324. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  8325. if (st->align) {
  8326. str = gb_string_appendc(str, "#align ");
  8327. str = write_expr_to_string(str, st->align, shorthand);
  8328. str = gb_string_append_rune(str, ' ');
  8329. }
  8330. str = gb_string_append_rune(str, '{');
  8331. if (shorthand) {
  8332. str = gb_string_appendc(str, "...");
  8333. } else {
  8334. str = write_struct_fields_to_string(str, st->fields);
  8335. }
  8336. str = gb_string_append_rune(str, '}');
  8337. case_end;
  8338. case_ast_node(st, UnionType, node);
  8339. str = gb_string_appendc(str, "union ");
  8340. if (st->polymorphic_params) {
  8341. str = gb_string_append_rune(str, '(');
  8342. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  8343. str = gb_string_appendc(str, ") ");
  8344. }
  8345. if (st->no_nil) str = gb_string_appendc(str, "#no_nil ");
  8346. if (st->maybe) str = gb_string_appendc(str, "#maybe ");
  8347. if (st->align) {
  8348. str = gb_string_appendc(str, "#align ");
  8349. str = write_expr_to_string(str, st->align, shorthand);
  8350. str = gb_string_append_rune(str, ' ');
  8351. }
  8352. str = gb_string_append_rune(str, '{');
  8353. if (shorthand) {
  8354. str = gb_string_appendc(str, "...");
  8355. } else {
  8356. str = write_struct_fields_to_string(str, st->variants);
  8357. }
  8358. str = gb_string_append_rune(str, '}');
  8359. case_end;
  8360. case_ast_node(et, EnumType, node);
  8361. str = gb_string_appendc(str, "enum ");
  8362. if (et->base_type != nullptr) {
  8363. str = write_expr_to_string(str, et->base_type, shorthand);
  8364. str = gb_string_append_rune(str, ' ');
  8365. }
  8366. str = gb_string_append_rune(str, '{');
  8367. if (shorthand) {
  8368. str = gb_string_appendc(str, "...");
  8369. } else {
  8370. for_array(i, et->fields) {
  8371. if (i > 0) {
  8372. str = gb_string_appendc(str, ", ");
  8373. }
  8374. str = write_expr_to_string(str, et->fields[i], shorthand);
  8375. }
  8376. }
  8377. str = gb_string_append_rune(str, '}');
  8378. case_end;
  8379. case_ast_node(rt, RelativeType, node);
  8380. str = write_expr_to_string(str, rt->tag, shorthand);
  8381. str = gb_string_appendc(str, "" );
  8382. str = write_expr_to_string(str, rt->type, shorthand);
  8383. case_end;
  8384. case_ast_node(ia, InlineAsmExpr, node);
  8385. str = gb_string_appendc(str, "asm(");
  8386. for_array(i, ia->param_types) {
  8387. if (i > 0) {
  8388. str = gb_string_appendc(str, ", ");
  8389. }
  8390. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  8391. }
  8392. str = gb_string_appendc(str, ")");
  8393. if (ia->return_type != nullptr) {
  8394. str = gb_string_appendc(str, " -> ");
  8395. str = write_expr_to_string(str, ia->return_type, shorthand);
  8396. }
  8397. if (ia->has_side_effects) {
  8398. str = gb_string_appendc(str, " #side_effects");
  8399. }
  8400. if (ia->is_align_stack) {
  8401. str = gb_string_appendc(str, " #stack_align");
  8402. }
  8403. if (ia->dialect) {
  8404. str = gb_string_appendc(str, " #");
  8405. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  8406. }
  8407. str = gb_string_appendc(str, " {");
  8408. if (shorthand) {
  8409. str = gb_string_appendc(str, "...");
  8410. } else {
  8411. str = write_expr_to_string(str, ia->asm_string, shorthand);
  8412. str = gb_string_appendc(str, ", ");
  8413. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  8414. }
  8415. str = gb_string_appendc(str, "}");
  8416. case_end;
  8417. }
  8418. return str;
  8419. }
  8420. gbString expr_to_string(Ast *expression) {
  8421. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  8422. }
  8423. gbString expr_to_string_shorthand(Ast *expression) {
  8424. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  8425. }