check_expr.cpp 286 KB

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