check_expr.cpp 352 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123
  1. enum CallArgumentError {
  2. CallArgumentError_None,
  3. CallArgumentError_NoneProcedureType,
  4. CallArgumentError_WrongTypes,
  5. CallArgumentError_NonVariadicExpand,
  6. CallArgumentError_VariadicTuple,
  7. CallArgumentError_MultipleVariadicExpand,
  8. CallArgumentError_AmbiguousPolymorphicVariadic,
  9. CallArgumentError_ArgumentCount,
  10. CallArgumentError_TooFewArguments,
  11. CallArgumentError_TooManyArguments,
  12. CallArgumentError_InvalidFieldValue,
  13. CallArgumentError_ParameterNotFound,
  14. CallArgumentError_ParameterMissing,
  15. CallArgumentError_DuplicateParameter,
  16. CallArgumentError_NoneConstantParameter,
  17. CallArgumentError_OutOfOrderParameters,
  18. CallArgumentError_MAX,
  19. };
  20. gb_global char const *CallArgumentError_strings[CallArgumentError_MAX] = {
  21. "None",
  22. "NoneProcedureType",
  23. "WrongTypes",
  24. "NonVariadicExpand",
  25. "VariadicTuple",
  26. "MultipleVariadicExpand",
  27. "AmbiguousPolymorphicVariadic",
  28. "ArgumentCount",
  29. "TooFewArguments",
  30. "TooManyArguments",
  31. "InvalidFieldValue",
  32. "ParameterNotFound",
  33. "ParameterMissing",
  34. "DuplicateParameter",
  35. "NoneConstantParameter",
  36. "OutOfOrderParameters",
  37. };
  38. enum struct CallArgumentErrorMode {
  39. NoErrors,
  40. ShowErrors,
  41. };
  42. struct CallArgumentData {
  43. Entity *gen_entity;
  44. i64 score;
  45. Type * result_type;
  46. };
  47. struct PolyProcData {
  48. Entity * gen_entity;
  49. ProcInfo *proc_info;
  50. };
  51. struct ValidIndexAndScore {
  52. isize index;
  53. i64 score;
  54. };
  55. gb_internal int valid_index_and_score_cmp(void const *a, void const *b) {
  56. i64 si = (cast(ValidIndexAndScore const *)a)->score;
  57. i64 sj = (cast(ValidIndexAndScore const *)b)->score;
  58. return sj < si ? -1 : sj > si;
  59. }
  60. gb_internal void check_expr (CheckerContext *c, Operand *operand, Ast *expression);
  61. gb_internal void check_multi_expr (CheckerContext *c, Operand *operand, Ast *expression);
  62. gb_internal void check_multi_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression);
  63. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint);
  64. gb_internal void check_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  65. gb_internal ExprKind check_expr_base (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
  66. gb_internal void check_expr_with_type_hint (CheckerContext *c, Operand *o, Ast *e, Type *t);
  67. gb_internal Type * check_type (CheckerContext *c, Ast *expression);
  68. gb_internal Type * check_type_expr (CheckerContext *c, Ast *expression, Type *named_type);
  69. gb_internal Type * make_optional_ok_type (Type *value, bool typed=true);
  70. gb_internal Entity * check_selector (CheckerContext *c, Operand *operand, Ast *node, Type *type_hint);
  71. gb_internal Entity * check_ident (CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name);
  72. gb_internal void check_not_tuple (CheckerContext *c, Operand *operand);
  73. gb_internal void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
  74. gb_internal gbString expr_to_string (Ast *expression);
  75. gb_internal gbString expr_to_string (Ast *expression, gbAllocator allocator);
  76. gb_internal void update_untyped_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
  77. gb_internal bool check_is_terminating (Ast *node, String const &label);
  78. gb_internal bool check_has_break (Ast *stmt, String const &label, bool implicit);
  79. gb_internal void check_stmt (CheckerContext *c, Ast *node, u32 flags);
  80. gb_internal void check_stmt_list (CheckerContext *c, Slice<Ast *> const &stmts, u32 flags);
  81. gb_internal void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
  82. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
  83. gb_internal bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> const *operands = nullptr);
  84. gb_internal void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
  85. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  86. gb_internal void check_union_type (CheckerContext *c, Type *union_type, Ast *node, Array<Operand> *poly_operands,
  87. Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
  88. gb_internal Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
  89. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0);
  90. gb_internal void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
  91. gb_internal Type *make_soa_struct_fixed(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem, i64 count, Type *generic_type);
  92. gb_internal Type *make_soa_struct_slice(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  93. gb_internal Type *make_soa_struct_dynamic_array(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
  94. gb_internal bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint);
  95. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand=true);
  96. gb_internal void check_or_else_right_type(CheckerContext *c, Ast *expr, String const &name, Type *right_type);
  97. gb_internal void check_or_else_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  98. gb_internal void check_or_else_expr_no_value_error(CheckerContext *c, String const &name, Operand const &x, Type *type_hint);
  99. gb_internal void check_or_return_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
  100. gb_internal bool is_diverging_expr(Ast *expr);
  101. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_);
  102. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr);
  103. gb_internal Entity *find_polymorphic_record_entity(GenTypesData *found_gen_types, isize param_count, Array<Operand> const &ordered_operands);
  104. gb_internal bool complete_soa_type(Checker *checker, Type *t, bool wait_to_finish);
  105. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y);
  106. gb_internal bool is_exact_value_zero(ExactValue const &v);
  107. enum LoadDirectiveResult {
  108. LoadDirective_Success = 0,
  109. LoadDirective_Error = 1,
  110. LoadDirective_NotFound = 2,
  111. };
  112. gb_internal bool is_load_directive_call(Ast *call) {
  113. call = unparen_expr(call);
  114. if (call->kind != Ast_CallExpr) {
  115. return false;
  116. }
  117. ast_node(ce, CallExpr, call);
  118. if (ce->proc->kind != Ast_BasicDirective) {
  119. return false;
  120. }
  121. ast_node(bd, BasicDirective, ce->proc);
  122. String name = bd->name.string;
  123. return name == "load";
  124. }
  125. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  126. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  127. auto results = did_you_mean_results(d);
  128. if (results.count != 0) {
  129. error_line("\tSuggestion: Did you mean?\n");
  130. for (auto const &result : results) {
  131. String const &target = result.target;
  132. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  133. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  134. }
  135. }
  136. }
  137. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  138. if (e->kind != Entity_TypeName) {
  139. return;
  140. }
  141. if (e->TypeName.objc_metadata == nullptr) {
  142. return;
  143. }
  144. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  145. Type *t = base_type(e->type);
  146. GB_ASSERT(t->kind == Type_Struct);
  147. if (is_type) {
  148. for (auto const &entry : objc_metadata->type_entries) {
  149. string_set_add(set, entry.name);
  150. }
  151. } else {
  152. for (auto const &entry : objc_metadata->value_entries) {
  153. string_set_add(set, entry.name);
  154. }
  155. }
  156. for (Entity *f : t->Struct.fields) {
  157. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  158. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  159. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  160. }
  161. }
  162. }
  163. }
  164. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  165. if (build_context.terse_errors) { return; }
  166. ERROR_BLOCK();
  167. GB_ASSERT(e->kind == Entity_TypeName);
  168. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  169. auto *objc_metadata = e->TypeName.objc_metadata;
  170. MUTEX_GUARD(objc_metadata->mutex);
  171. StringSet set = {};
  172. defer (string_set_destroy(&set));
  173. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  174. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  175. defer (did_you_mean_destroy(&d));
  176. for (String const &target : set) {
  177. did_you_mean_append(&d, target);
  178. }
  179. check_did_you_mean_print(&d, prefix);
  180. }
  181. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  182. if (build_context.terse_errors) { return; }
  183. ERROR_BLOCK();
  184. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  185. defer (did_you_mean_destroy(&d));
  186. for (Entity *e : fields) {
  187. did_you_mean_append(&d, e->token.string);
  188. }
  189. check_did_you_mean_print(&d, prefix);
  190. }
  191. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  192. if (build_context.terse_errors) { return; }
  193. ERROR_BLOCK();
  194. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  195. defer (did_you_mean_destroy(&d));
  196. for (Entity *e : fields) {
  197. did_you_mean_append(&d, e->token.string);
  198. }
  199. check_did_you_mean_print(&d, prefix);
  200. }
  201. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  202. if (build_context.terse_errors) { return; }
  203. ERROR_BLOCK();
  204. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  205. defer (did_you_mean_destroy(&d));
  206. rw_mutex_shared_lock(&scope->mutex);
  207. for (auto const &entry : scope->elements) {
  208. Entity *e = entry.value;
  209. did_you_mean_append(&d, e->token.string);
  210. }
  211. rw_mutex_shared_unlock(&scope->mutex);
  212. check_did_you_mean_print(&d, prefix);
  213. }
  214. gb_internal Entity *entity_from_expr(Ast *expr) {
  215. expr = unparen_expr(expr);
  216. switch (expr->kind) {
  217. case Ast_Ident:
  218. return expr->Ident.entity;
  219. case Ast_SelectorExpr:
  220. return entity_from_expr(expr->SelectorExpr.selector);
  221. }
  222. return nullptr;
  223. }
  224. gb_internal void error_operand_not_expression(Operand *o) {
  225. if (o->mode == Addressing_Type) {
  226. gbString err = expr_to_string(o->expr);
  227. error(o->expr, "'%s' is not an expression but a type", err);
  228. gb_string_free(err);
  229. o->mode = Addressing_Invalid;
  230. }
  231. }
  232. gb_internal void error_operand_no_value(Operand *o) {
  233. if (o->mode == Addressing_NoValue) {
  234. Ast *x = unparen_expr(o->expr);
  235. if (x->kind == Ast_CallExpr) {
  236. Ast *p = unparen_expr(x->CallExpr.proc);
  237. if (p->kind == Ast_BasicDirective) {
  238. String tag = p->BasicDirective.name.string;
  239. if (tag == "panic" ||
  240. tag == "assert") {
  241. return;
  242. }
  243. }
  244. }
  245. gbString err = expr_to_string(o->expr);
  246. if (x->kind == Ast_CallExpr) {
  247. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  248. } else {
  249. error(o->expr, "'%s' used as a value", err);
  250. }
  251. gb_string_free(err);
  252. o->mode = Addressing_Invalid;
  253. }
  254. }
  255. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  256. if (build_context.dynamic_map_calls) {
  257. add_package_dependency(c, "runtime", "__dynamic_map_get");
  258. } else {
  259. add_package_dependency(c, "runtime", "map_desired_position");
  260. add_package_dependency(c, "runtime", "map_probe_distance");
  261. }
  262. }
  263. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  264. init_core_source_code_location(c->checker);
  265. if (t_map_set_proc == nullptr) {
  266. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  267. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  268. }
  269. if (build_context.dynamic_map_calls) {
  270. add_package_dependency(c, "runtime", "__dynamic_map_set");
  271. } else {
  272. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  273. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  274. }
  275. }
  276. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  277. init_core_source_code_location(c->checker);
  278. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  279. }
  280. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  281. Scope *s = c->scope;
  282. check_collect_entities(c, nodes);
  283. for (auto const &entry : s->elements) {
  284. Entity *e = entry.value;
  285. switch (e->kind) {
  286. case Entity_Constant:
  287. case Entity_TypeName:
  288. case Entity_Procedure:
  289. break;
  290. default:
  291. continue;
  292. }
  293. DeclInfo *d = decl_info_of_entity(e);
  294. if (d != nullptr) {
  295. check_entity_decl(c, e, d, nullptr);
  296. }
  297. }
  298. }
  299. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  300. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  301. ///////////////////////////////////////////////////////////////////////////////
  302. // //
  303. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  304. // //
  305. ///////////////////////////////////////////////////////////////////////////////
  306. CheckerInfo *info = old_c->info;
  307. if (base_entity == nullptr) {
  308. return false;
  309. }
  310. if (!is_type_proc(base_entity->type)) {
  311. return false;
  312. }
  313. if (base_entity->flags & EntityFlag_Disabled) {
  314. return false;
  315. }
  316. String name = base_entity->token.string;
  317. Type *src = base_type(base_entity->type);
  318. Type *dst = nullptr;
  319. if (type != nullptr) {
  320. dst = base_type(type);
  321. }
  322. if (param_operands == nullptr) {
  323. GB_ASSERT(dst != nullptr);
  324. }
  325. if (param_operands != nullptr) {
  326. GB_ASSERT(dst == nullptr);
  327. }
  328. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  329. return false;
  330. }
  331. if (dst != nullptr) {
  332. if (dst->Proc.is_polymorphic) {
  333. return false;
  334. }
  335. if (dst->Proc.param_count != src->Proc.param_count ||
  336. dst->Proc.result_count != src->Proc.result_count) {
  337. return false;
  338. }
  339. }
  340. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  341. if (old_decl == nullptr) {
  342. return false;
  343. }
  344. gbAllocator a = heap_allocator();
  345. Array<Operand> operands = {};
  346. if (param_operands) {
  347. operands = *param_operands;
  348. } else {
  349. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  350. for (isize i = 0; i < dst->Proc.param_count; i++) {
  351. Entity *param = dst->Proc.params->Tuple.variables[i];
  352. Operand o = {Addressing_Value};
  353. o.type = param->type;
  354. array_add(&operands, o);
  355. }
  356. }
  357. defer (if (param_operands == nullptr) {
  358. array_free(&operands);
  359. });
  360. CheckerContext nctx = *old_c;
  361. Scope *scope = create_scope(info, base_entity->scope);
  362. scope->flags |= ScopeFlag_Proc;
  363. nctx.scope = scope;
  364. nctx.allow_polymorphic_types = true;
  365. if (nctx.polymorphic_scope == nullptr) {
  366. nctx.polymorphic_scope = scope;
  367. }
  368. auto *pt = &src->Proc;
  369. // NOTE(bill): This is slightly memory leaking if the type already exists
  370. // Maybe it's better to check with the previous types first?
  371. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  372. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  373. if (!success) {
  374. return false;
  375. }
  376. GenProcsData *gen_procs = nullptr;
  377. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  378. GB_ASSERT(base_entity->kind == Entity_Procedure);
  379. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  380. gen_procs = base_entity->Procedure.gen_procs;
  381. if (gen_procs) {
  382. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  383. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  384. for (Entity *other : gen_procs->procs) {
  385. Type *pt = base_type(other->type);
  386. if (are_types_identical(pt, final_proc_type)) {
  387. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  388. if (poly_proc_data) {
  389. poly_proc_data->gen_entity = other;
  390. }
  391. return true;
  392. }
  393. }
  394. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  395. } else {
  396. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  397. gen_procs->procs.allocator = heap_allocator();
  398. base_entity->Procedure.gen_procs = gen_procs;
  399. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  400. }
  401. {
  402. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  403. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  404. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  405. nctx.no_polymorphic_errors = false;
  406. // NOTE(bill): Reset scope from the failed procedure type
  407. scope->head_child.store(nullptr, std::memory_order_relaxed);
  408. string_map_clear(&scope->elements);
  409. ptr_set_clear(&scope->imported);
  410. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  411. Ast *cloned_proc_type_node = clone_ast(pt->node);
  412. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  413. if (!success) {
  414. return false;
  415. }
  416. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  417. for (Entity *other : gen_procs->procs) {
  418. Type *pt = base_type(other->type);
  419. if (are_types_identical(pt, final_proc_type)) {
  420. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  421. if (poly_proc_data) {
  422. poly_proc_data->gen_entity = other;
  423. }
  424. DeclInfo *decl = other->decl_info;
  425. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  426. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  427. proc_info->file = other->file;
  428. proc_info->token = other->token;
  429. proc_info->decl = decl;
  430. proc_info->type = other->type;
  431. proc_info->body = decl->proc_lit->ProcLit.body;
  432. proc_info->tags = other->Procedure.tags;;
  433. proc_info->generated_from_polymorphic = true;
  434. proc_info->poly_def_node = poly_def_node;
  435. check_procedure_later(nctx.checker, proc_info);
  436. }
  437. return true;
  438. }
  439. }
  440. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  441. }
  442. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  443. ast_node(pl, ProcLit, proc_lit);
  444. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  445. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  446. final_proc_type->Proc.is_poly_specialized = true;
  447. final_proc_type->Proc.is_polymorphic = true;
  448. final_proc_type->Proc.variadic = src->Proc.variadic;
  449. final_proc_type->Proc.require_results = src->Proc.require_results;
  450. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  451. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  452. final_proc_type->Proc.diverging = src->Proc.diverging;
  453. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  454. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  455. final_proc_type->Proc.enable_target_feature = src->Proc.enable_target_feature;
  456. final_proc_type->Proc.require_target_feature = src->Proc.require_target_feature;
  457. for (isize i = 0; i < operands.count; i++) {
  458. Operand o = operands[i];
  459. if (final_proc_type == o.type ||
  460. base_entity->type == o.type) {
  461. // NOTE(bill): Cycle
  462. final_proc_type->Proc.is_poly_specialized = false;
  463. break;
  464. }
  465. }
  466. u64 tags = base_entity->Procedure.tags;
  467. Ast *ident = clone_ast(base_entity->identifier);
  468. Token token = ident->Ident.token;
  469. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  470. d->gen_proc_type = final_proc_type;
  471. d->type_expr = pl->type;
  472. d->proc_lit = proc_lit;
  473. d->proc_checked_state = ProcCheckedState_Unchecked;
  474. d->defer_use_checked = false;
  475. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  476. entity->state.store(EntityState_Resolved);
  477. entity->identifier = ident;
  478. add_entity_and_decl_info(&nctx, ident, entity, d);
  479. // NOTE(bill): Set the scope afterwards as this is not real overloading
  480. entity->scope = scope->parent;
  481. entity->file = base_entity->file;
  482. entity->pkg = base_entity->pkg;
  483. entity->flags = 0;
  484. entity->Procedure.optimization_mode = base_entity->Procedure.optimization_mode;
  485. if (base_entity->flags & EntityFlag_Cold) {
  486. entity->flags |= EntityFlag_Cold;
  487. }
  488. if (base_entity->flags & EntityFlag_Disabled) {
  489. entity->flags |= EntityFlag_Disabled;
  490. }
  491. d->entity = entity;
  492. AstFile *file = nullptr;
  493. {
  494. Scope *s = entity->scope;
  495. while (s != nullptr && s->file == nullptr) {
  496. file = s->file;
  497. s = s->parent;
  498. }
  499. }
  500. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  501. array_add(&gen_procs->procs, entity);
  502. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  503. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  504. proc_info->file = file;
  505. proc_info->token = token;
  506. proc_info->decl = d;
  507. proc_info->type = final_proc_type;
  508. proc_info->body = pl->body;
  509. proc_info->tags = tags;
  510. proc_info->generated_from_polymorphic = true;
  511. proc_info->poly_def_node = poly_def_node;
  512. if (poly_proc_data) {
  513. poly_proc_data->gen_entity = entity;
  514. poly_proc_data->proc_info = proc_info;
  515. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  516. }
  517. // NOTE(bill): Check the newly generated procedure body
  518. check_procedure_later(nctx.checker, proc_info);
  519. return true;
  520. }
  521. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  522. if (operand->expr == nullptr) return false;
  523. Entity *base_entity = entity_of_node(operand->expr);
  524. if (base_entity == nullptr) return false;
  525. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  526. }
  527. gb_internal bool find_or_generate_polymorphic_procedure_from_parameters(CheckerContext *c, Entity *base_entity, Array<Operand> const *operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  528. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  529. }
  530. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  531. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  532. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  533. #define MAXIMUM_TYPE_DISTANCE 10
  534. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming) {
  535. if (c == nullptr) {
  536. GB_ASSERT(operand->mode == Addressing_Value);
  537. GB_ASSERT(is_type_typed(operand->type));
  538. }
  539. if (operand->mode == Addressing_Invalid ||
  540. type == t_invalid) {
  541. return -1;
  542. }
  543. if (operand->mode == Addressing_Builtin) {
  544. return -1;
  545. }
  546. if (operand->mode == Addressing_Type) {
  547. if (is_type_typeid(type)) {
  548. if (is_type_polymorphic(operand->type)) {
  549. return -1;
  550. }
  551. add_type_info_type(c, operand->type);
  552. return 4;
  553. }
  554. return -1;
  555. }
  556. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  557. return -1;
  558. }
  559. Type *s = operand->type;
  560. if (are_types_identical(s, type)) {
  561. return 0;
  562. }
  563. Type *src = base_type(s);
  564. Type *dst = base_type(type);
  565. if (is_type_untyped_uninit(src)) {
  566. return 1;
  567. }
  568. if (is_type_untyped_nil(src)) {
  569. if (type_has_nil(dst)) {
  570. return 1;
  571. }
  572. return -1;
  573. }
  574. if (is_type_untyped(src)) {
  575. if (is_type_any(dst)) {
  576. // NOTE(bill): Anything can cast to 'Any'
  577. add_type_info_type(c, s);
  578. return MAXIMUM_TYPE_DISTANCE;
  579. }
  580. if (dst->kind == Type_Basic) {
  581. if (operand->mode == Addressing_Constant) {
  582. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  583. if (is_type_typed(dst) && src->kind == Type_Basic) {
  584. switch (src->Basic.kind) {
  585. case Basic_UntypedBool:
  586. if (is_type_boolean(dst)) {
  587. return 1;
  588. }
  589. break;
  590. case Basic_UntypedRune:
  591. if (is_type_integer(dst) || is_type_rune(dst)) {
  592. return 1;
  593. }
  594. break;
  595. case Basic_UntypedInteger:
  596. if (is_type_integer(dst) || is_type_rune(dst)) {
  597. return 1;
  598. }
  599. break;
  600. case Basic_UntypedString:
  601. if (is_type_string(dst)) {
  602. return 1;
  603. }
  604. break;
  605. case Basic_UntypedFloat:
  606. if (is_type_float(dst)) {
  607. return 1;
  608. }
  609. break;
  610. case Basic_UntypedComplex:
  611. if (is_type_complex(dst)) {
  612. return 1;
  613. }
  614. if (is_type_quaternion(dst)) {
  615. return 2;
  616. }
  617. break;
  618. case Basic_UntypedQuaternion:
  619. if (is_type_quaternion(dst)) {
  620. return 1;
  621. }
  622. break;
  623. }
  624. }
  625. return 2;
  626. }
  627. return -1;
  628. }
  629. if (src->kind == Type_Basic) {
  630. Type *d = base_array_type(dst);
  631. i64 score = -1;
  632. switch (src->Basic.kind) {
  633. case Basic_UntypedBool:
  634. if (is_type_boolean(d)) {
  635. score = 1;
  636. }
  637. break;
  638. case Basic_UntypedRune:
  639. if (is_type_integer(d) || is_type_rune(d)) {
  640. score = 1;
  641. }
  642. break;
  643. case Basic_UntypedInteger:
  644. if (is_type_integer(d) || is_type_rune(d)) {
  645. score = 1;
  646. }
  647. break;
  648. case Basic_UntypedString:
  649. if (is_type_string(d)) {
  650. score = 1;
  651. }
  652. break;
  653. case Basic_UntypedFloat:
  654. if (is_type_float(d)) {
  655. score = 1;
  656. }
  657. break;
  658. case Basic_UntypedComplex:
  659. if (is_type_complex(d)) {
  660. score = 1;
  661. }
  662. if (is_type_quaternion(d)) {
  663. score = 2;
  664. }
  665. break;
  666. case Basic_UntypedQuaternion:
  667. if (is_type_quaternion(d)) {
  668. score = 1;
  669. }
  670. break;
  671. }
  672. if (score > 0) {
  673. if (is_type_typed(d)) {
  674. score += 1;
  675. }
  676. if (d != dst) {
  677. score += 6;
  678. }
  679. }
  680. return score;
  681. }
  682. }
  683. }
  684. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  685. if (c->in_enum_type) {
  686. return 3;
  687. }
  688. }
  689. {
  690. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  691. if (subtype_level > 0) {
  692. return 4 + subtype_level;
  693. }
  694. }
  695. // rawptr <- ^T
  696. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  697. return 5;
  698. }
  699. // rawptr <- [^]T
  700. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  701. return 5;
  702. }
  703. // ^T <- [^]T
  704. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  705. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  706. return 4;
  707. }
  708. }
  709. // [^]T <- ^T
  710. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  711. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  712. return 4;
  713. }
  714. }
  715. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  716. bool modify_type = !c->no_polymorphic_errors;
  717. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  718. return 2;
  719. }
  720. }
  721. if (is_type_union(dst)) {
  722. for (Type *vt : dst->Union.variants) {
  723. if (are_types_identical(vt, s)) {
  724. return 1;
  725. }
  726. }
  727. if (dst->Union.variants.count == 1) {
  728. Type *vt = dst->Union.variants[0];
  729. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  730. if (score >= 0) {
  731. return score+2;
  732. }
  733. } else if (is_type_untyped(src)) {
  734. i64 prev_lowest_score = -1;
  735. i64 lowest_score = -1;
  736. for (Type *vt : dst->Union.variants) {
  737. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  738. if (score >= 0) {
  739. if (lowest_score < 0) {
  740. lowest_score = score;
  741. } else {
  742. if (prev_lowest_score < 0) {
  743. prev_lowest_score = lowest_score;
  744. } else {
  745. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  746. }
  747. lowest_score = gb_min(lowest_score, score);
  748. }
  749. }
  750. }
  751. if (lowest_score >= 0) {
  752. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  753. return lowest_score+2;
  754. }
  755. }
  756. }
  757. }
  758. if (is_type_relative_pointer(dst)) {
  759. i64 score = check_distance_between_types(c, operand, dst->RelativePointer.pointer_type, allow_array_programming);
  760. if (score >= 0) {
  761. return score+2;
  762. }
  763. }
  764. if (is_type_relative_multi_pointer(dst)) {
  765. i64 score = check_distance_between_types(c, operand, dst->RelativeMultiPointer.pointer_type, allow_array_programming);
  766. if (score >= 0) {
  767. return score+2;
  768. }
  769. }
  770. if (is_type_proc(dst)) {
  771. if (are_types_identical(src, dst)) {
  772. return 3;
  773. }
  774. PolyProcData poly_proc_data = {};
  775. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  776. Entity *e = poly_proc_data.gen_entity;
  777. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  778. add_entity_use(c, operand->expr, e);
  779. return 4;
  780. }
  781. }
  782. if (is_type_complex_or_quaternion(dst)) {
  783. Type *elem = base_complex_elem_type(dst);
  784. if (are_types_identical(elem, base_type(src))) {
  785. return 5;
  786. }
  787. }
  788. if (allow_array_programming) {
  789. if (is_type_array(dst)) {
  790. Type *elem = base_array_type(dst);
  791. i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
  792. if (distance >= 0) {
  793. return distance + 6;
  794. }
  795. }
  796. if (is_type_simd_vector(dst)) {
  797. Type *dst_elem = base_array_type(dst);
  798. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  799. if (distance >= 0) {
  800. return distance + 6;
  801. }
  802. }
  803. }
  804. if (is_type_matrix(dst)) {
  805. if (are_types_identical(src, dst)) {
  806. return 5;
  807. }
  808. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  809. Type *dst_elem = base_array_type(dst);
  810. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  811. if (distance >= 0) {
  812. return distance + 7;
  813. }
  814. }
  815. }
  816. if (is_type_any(dst)) {
  817. if (!is_type_polymorphic(src)) {
  818. if (operand->mode == Addressing_Context && operand->type == t_context) {
  819. return -1;
  820. } else {
  821. // NOTE(bill): Anything can cast to 'Any'
  822. add_type_info_type(c, s);
  823. return MAXIMUM_TYPE_DISTANCE;
  824. }
  825. }
  826. }
  827. Ast *expr = unparen_expr(operand->expr);
  828. if (expr != nullptr) {
  829. if (expr->kind == Ast_AutoCast) {
  830. Operand x = *operand;
  831. x.expr = expr->AutoCast.expr;
  832. if (check_cast_internal(c, &x, type)) {
  833. return MAXIMUM_TYPE_DISTANCE;
  834. }
  835. }
  836. }
  837. return -1;
  838. }
  839. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  840. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  841. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  842. // TODO(bill): A decent score function
  843. i64 d = distance*distance; // x^2
  844. if (is_variadic && d >= 0) {
  845. d += distance + 1; // x^2 + x + 1
  846. }
  847. return gb_max(c - d, 0);
  848. }
  849. gb_internal bool check_is_assignable_to_with_score(CheckerContext *c, Operand *operand, Type *type, i64 *score_, bool is_variadic=false, bool allow_array_programming=true) {
  850. i64 score = 0;
  851. i64 distance = check_distance_between_types(c, operand, type, allow_array_programming);
  852. bool ok = distance >= 0;
  853. if (ok) {
  854. score = assign_score_function(distance, is_variadic);
  855. }
  856. if (score_) *score_ = score;
  857. return ok;
  858. }
  859. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming=true) {
  860. i64 score = 0;
  861. return check_is_assignable_to_with_score(c, operand, type, &score, /*is_variadic*/false, allow_array_programming);
  862. }
  863. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  864. Operand x = {};
  865. x.type = src;
  866. x.mode = Addressing_Value;
  867. return check_is_assignable_to(nullptr, &x, dst);
  868. }
  869. gb_internal AstPackage *get_package_of_type(Type *type) {
  870. for (;;) {
  871. if (type == nullptr) {
  872. return nullptr;
  873. }
  874. switch (type->kind) {
  875. case Type_Basic:
  876. return builtin_pkg;
  877. case Type_Named:
  878. if (type->Named.type_name != nullptr) {
  879. return type->Named.type_name->pkg;
  880. }
  881. return nullptr;
  882. case Type_Pointer:
  883. type = type->Pointer.elem;
  884. continue;
  885. case Type_Array:
  886. type = type->Array.elem;
  887. continue;
  888. case Type_Slice:
  889. type = type->Slice.elem;
  890. continue;
  891. case Type_DynamicArray:
  892. type = type->DynamicArray.elem;
  893. continue;
  894. case Type_RelativePointer:
  895. type = type->RelativePointer.pointer_type;
  896. continue;
  897. case Type_RelativeMultiPointer:
  898. type = type->RelativeMultiPointer.pointer_type;
  899. continue;
  900. }
  901. return nullptr;
  902. }
  903. }
  904. // NOTE(bill): 'content_name' is for debugging and error messages
  905. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  906. check_not_tuple(c, operand);
  907. if (operand->mode == Addressing_Invalid) {
  908. return;
  909. }
  910. // Grab definite or indefinite article matching `context_name`, or "" if not found.
  911. String article = error_article(context_name);
  912. if (is_type_untyped(operand->type)) {
  913. Type *target_type = type;
  914. if (type == nullptr || is_type_any(type)) {
  915. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  916. error(operand->expr, "Use of --- in %.*s%.*s", LIT(article), LIT(context_name));
  917. operand->mode = Addressing_Invalid;
  918. return;
  919. }
  920. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  921. error(operand->expr, "Use of untyped nil in %.*s%.*s", LIT(article), LIT(context_name));
  922. operand->mode = Addressing_Invalid;
  923. return;
  924. }
  925. target_type = default_type(operand->type);
  926. if (type != nullptr && !is_type_any(type)) {
  927. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  928. }
  929. add_type_info_type(c, type);
  930. add_type_info_type(c, target_type);
  931. }
  932. convert_to_typed(c, operand, target_type);
  933. if (operand->mode == Addressing_Invalid) {
  934. return;
  935. }
  936. }
  937. if (type == nullptr) {
  938. return;
  939. }
  940. if (operand->mode == Addressing_ProcGroup) {
  941. bool good = false;
  942. if (type != nullptr && is_type_proc(type)) {
  943. Array<Entity *> procs = proc_group_entities(c, *operand);
  944. // NOTE(bill): These should be done
  945. for (Entity *e : procs) {
  946. Type *t = base_type(e->type);
  947. if (t == t_invalid) {
  948. continue;
  949. }
  950. Operand x = {};
  951. x.mode = Addressing_Value;
  952. x.type = t;
  953. if (check_is_assignable_to(c, &x, type)) {
  954. add_entity_use(c, operand->expr, e);
  955. good = true;
  956. break;
  957. }
  958. }
  959. }
  960. if (!good) {
  961. gbString expr_str = expr_to_string(operand->expr);
  962. gbString op_type_str = type_to_string(operand->type);
  963. gbString type_str = type_to_string(type);
  964. defer (gb_string_free(type_str));
  965. defer (gb_string_free(op_type_str));
  966. defer (gb_string_free(expr_str));
  967. // TODO(bill): is this a good enough error message?
  968. error(operand->expr,
  969. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s%.*s",
  970. expr_str,
  971. op_type_str,
  972. LIT(article),
  973. LIT(context_name));
  974. operand->mode = Addressing_Invalid;
  975. }
  976. convert_to_typed(c, operand, type);
  977. return;
  978. }
  979. if (check_is_assignable_to(c, operand, type)) {
  980. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  981. add_type_info_type(c, operand->type);
  982. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  983. }
  984. } else {
  985. gbString expr_str = expr_to_string(operand->expr);
  986. gbString op_type_str = type_to_string(operand->type);
  987. gbString type_str = type_to_string(type);
  988. defer (gb_string_free(type_str));
  989. defer (gb_string_free(op_type_str));
  990. defer (gb_string_free(expr_str));
  991. switch (operand->mode) {
  992. case Addressing_Builtin:
  993. error(operand->expr,
  994. "Cannot assign built-in procedure '%s' to %.*s%.*s",
  995. expr_str,
  996. LIT(article),
  997. LIT(context_name));
  998. break;
  999. case Addressing_Type:
  1000. if (is_type_polymorphic(operand->type)) {
  1001. error(operand->expr,
  1002. "Cannot assign '%s', a polymorphic type, to %.*s%.*s",
  1003. op_type_str,
  1004. LIT(article),
  1005. LIT(context_name));
  1006. } else {
  1007. ERROR_BLOCK();
  1008. error(operand->expr,
  1009. "Cannot assign '%s', a type, to %.*s%.*s",
  1010. op_type_str,
  1011. LIT(article),
  1012. LIT(context_name));
  1013. if (type && are_types_identical(type, t_any)) {
  1014. error_line("\tSuggestion: 'typeid_of(%s)'", expr_str);
  1015. }
  1016. }
  1017. break;
  1018. default:
  1019. // TODO(bill): is this a good enough error message?
  1020. {
  1021. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  1022. gbString type_extra = gb_string_make(heap_allocator(), "");
  1023. defer (gb_string_free(op_type_extra));
  1024. defer (gb_string_free(type_extra));
  1025. isize on = gb_string_length(op_type_str);
  1026. isize tn = gb_string_length(type_str);
  1027. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  1028. AstPackage *op_pkg = get_package_of_type(operand->type);
  1029. AstPackage *type_pkg = get_package_of_type(type);
  1030. if (op_pkg != nullptr) {
  1031. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  1032. }
  1033. if (type_pkg != nullptr) {
  1034. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  1035. }
  1036. }
  1037. ERROR_BLOCK();
  1038. error(operand->expr,
  1039. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s%.*s",
  1040. expr_str,
  1041. op_type_str, op_type_extra,
  1042. type_str, type_extra,
  1043. LIT(article),
  1044. LIT(context_name));
  1045. check_assignment_error_suggestion(c, operand, type);
  1046. Type *src = base_type(operand->type);
  1047. Type *dst = base_type(type);
  1048. if (context_name == "procedure argument") {
  1049. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  1050. gbString a = expr_to_string(operand->expr);
  1051. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  1052. gb_string_free(a);
  1053. }
  1054. }
  1055. if (src->kind == dst->kind && src->kind == Type_Proc) {
  1056. Type *x = src;
  1057. Type *y = dst;
  1058. bool same_inputs = are_types_identical_internal(x->Proc.params, y->Proc.params, false);
  1059. bool same_outputs = are_types_identical_internal(x->Proc.results, y->Proc.results, false);
  1060. if (same_inputs && same_outputs &&
  1061. x->Proc.calling_convention != y->Proc.calling_convention) {
  1062. gbString s_expected = type_to_string(y);
  1063. gbString s_got = type_to_string(x);
  1064. error_line("\tNote: The calling conventions differ between the procedure signature types\n");
  1065. error_line("\t Expected \"%s\", got \"%s\"\n",
  1066. proc_calling_convention_strings[y->Proc.calling_convention],
  1067. proc_calling_convention_strings[x->Proc.calling_convention]);
  1068. error_line("\t Expected: %s\n", s_expected);
  1069. error_line("\t Got: %s\n", s_got);
  1070. gb_string_free(s_got);
  1071. gb_string_free(s_expected);
  1072. } else if (same_inputs && same_outputs &&
  1073. x->Proc.diverging != y->Proc.diverging) {
  1074. gbString s_expected = type_to_string(y);
  1075. if (y->Proc.diverging) {
  1076. s_expected = gb_string_appendc(s_expected, " -> !");
  1077. }
  1078. gbString s_got = type_to_string(x);
  1079. if (x->Proc.diverging) {
  1080. s_got = gb_string_appendc(s_got, " -> !");
  1081. }
  1082. error_line("\tNote: One of the procedures is diverging while the other isn't\n");
  1083. error_line("\t Expected: %s\n", s_expected);
  1084. error_line("\t Got: %s\n", s_got);
  1085. gb_string_free(s_got);
  1086. gb_string_free(s_expected);
  1087. } else if (same_inputs && !same_outputs) {
  1088. gbString s_expected = type_to_string(y->Proc.results);
  1089. gbString s_got = type_to_string(x->Proc.results);
  1090. error_line("\tNote: The return types differ between the procedure signature types\n");
  1091. error_line("\t Expected: %s\n", s_expected);
  1092. error_line("\t Got: %s\n", s_got);
  1093. gb_string_free(s_got);
  1094. gb_string_free(s_expected);
  1095. } else if (!same_inputs && same_outputs) {
  1096. gbString s_expected = type_to_string(y->Proc.params);
  1097. gbString s_got = type_to_string(x->Proc.params);
  1098. error_line("\tNote: The input parameter types differ between the procedure signature types\n");
  1099. error_line("\t Expected: %s\n", s_expected);
  1100. error_line("\t Got: %s\n", s_got);
  1101. gb_string_free(s_got);
  1102. gb_string_free(s_expected);
  1103. } else {
  1104. gbString s_expected = type_to_string(y);
  1105. gbString s_got = type_to_string(x);
  1106. error_line("\tNote: The signature type do not match whatsoever\n");
  1107. error_line("\t Expected: %s\n", s_expected);
  1108. error_line("\t Got: %s\n", s_got);
  1109. gb_string_free(s_got);
  1110. gb_string_free(s_expected);
  1111. }
  1112. }
  1113. }
  1114. break;
  1115. }
  1116. operand->mode = Addressing_Invalid;
  1117. return;
  1118. }
  1119. }
  1120. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1121. Type *gt = *gt_;
  1122. GB_ASSERT(gt->kind == Type_Generic);
  1123. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1124. GB_ASSERT(e != nullptr);
  1125. if (e->kind == Entity_TypeName) {
  1126. *gt_ = nullptr;
  1127. *dst_count = source_count;
  1128. e->kind = Entity_Constant;
  1129. e->Constant.value = exact_value_i64(source_count);
  1130. e->type = t_untyped_integer;
  1131. return true;
  1132. } else if (e->kind == Entity_Constant) {
  1133. *gt_ = nullptr;
  1134. if (e->Constant.value.kind != ExactValue_Integer) {
  1135. return false;
  1136. }
  1137. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1138. if (count != source_count) {
  1139. return false;
  1140. }
  1141. *dst_count = source_count;
  1142. return true;
  1143. }
  1144. return false;
  1145. }
  1146. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1147. Operand o = {Addressing_Value};
  1148. o.type = source;
  1149. switch (poly->kind) {
  1150. case Type_Basic:
  1151. if (compound) return are_types_identical(poly, source);
  1152. return check_is_assignable_to(c, &o, poly);
  1153. case Type_Named: {
  1154. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1155. return true;
  1156. }
  1157. if (compound || !is_type_generic(poly)) {
  1158. return are_types_identical(poly, source);
  1159. }
  1160. return check_is_assignable_to(c, &o, poly);
  1161. }
  1162. case Type_Generic: {
  1163. if (poly->Generic.specialized != nullptr) {
  1164. Type *s = poly->Generic.specialized;
  1165. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1166. return false;
  1167. }
  1168. }
  1169. if (modify_type) {
  1170. Type *ds = default_type(source);
  1171. gb_memmove(poly, ds, gb_size_of(Type));
  1172. }
  1173. return true;
  1174. }
  1175. case Type_Pointer:
  1176. if (source->kind == Type_Pointer) {
  1177. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1178. if (level > 0) {
  1179. return true;
  1180. }
  1181. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1182. } else if (source->kind == Type_MultiPointer) {
  1183. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1184. if (level > 0) {
  1185. return true;
  1186. }
  1187. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1188. }
  1189. return false;
  1190. case Type_MultiPointer:
  1191. if (source->kind == Type_MultiPointer) {
  1192. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1193. if (level > 0) {
  1194. return true;
  1195. }
  1196. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1197. } else if (source->kind == Type_Pointer) {
  1198. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1199. if (level > 0) {
  1200. return true;
  1201. }
  1202. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1203. }
  1204. return false;
  1205. case Type_Array:
  1206. if (source->kind == Type_Array) {
  1207. if (poly->Array.generic_count != nullptr) {
  1208. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1209. return false;
  1210. }
  1211. }
  1212. if (poly->Array.count == source->Array.count) {
  1213. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1214. }
  1215. } else if (source->kind == Type_EnumeratedArray) {
  1216. if (poly->Array.generic_count != nullptr) {
  1217. Type *gt = poly->Array.generic_count;
  1218. GB_ASSERT(gt->kind == Type_Generic);
  1219. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1220. GB_ASSERT(e != nullptr);
  1221. if (e->kind == Entity_TypeName) {
  1222. Type *index = source->EnumeratedArray.index;
  1223. Type *it = base_type(index);
  1224. if (it->kind != Type_Enum) {
  1225. return false;
  1226. }
  1227. poly->kind = Type_EnumeratedArray;
  1228. poly->cached_size = -1;
  1229. poly->cached_align = -1;
  1230. poly->flags.exchange(source->flags);
  1231. poly->failure = false;
  1232. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1233. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1234. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1235. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1236. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1237. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1238. e->kind = Entity_TypeName;
  1239. e->TypeName.is_type_alias = true;
  1240. e->type = index;
  1241. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1242. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1243. }
  1244. }
  1245. }
  1246. }
  1247. return false;
  1248. case Type_EnumeratedArray:
  1249. if (source->kind == Type_EnumeratedArray) {
  1250. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1251. return false;
  1252. }
  1253. if (poly->EnumeratedArray.op) {
  1254. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1255. return false;
  1256. }
  1257. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1258. return false;
  1259. }
  1260. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1261. return false;
  1262. }
  1263. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1264. }
  1265. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1266. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1267. return index || elem;
  1268. }
  1269. return false;
  1270. case Type_DynamicArray:
  1271. if (source->kind == Type_DynamicArray) {
  1272. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1273. }
  1274. return false;
  1275. case Type_Slice:
  1276. if (source->kind == Type_Slice) {
  1277. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1278. }
  1279. return false;
  1280. case Type_Enum:
  1281. return false;
  1282. case Type_BitSet:
  1283. if (source->kind == Type_BitSet) {
  1284. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1285. return false;
  1286. }
  1287. // For generic types like bit_set[$T] the upper and lower of the poly type will be zeroes since
  1288. // it could not figure that stuff out when the poly type was created.
  1289. if (poly->BitSet.upper == 0 && modify_type) {
  1290. poly->BitSet.upper = source->BitSet.upper;
  1291. }
  1292. if (poly->BitSet.lower == 0 && modify_type) {
  1293. poly->BitSet.lower = source->BitSet.lower;
  1294. }
  1295. if (poly->BitSet.underlying == nullptr) {
  1296. if (modify_type) {
  1297. poly->BitSet.underlying = source->BitSet.underlying;
  1298. }
  1299. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1300. return false;
  1301. }
  1302. return true;
  1303. }
  1304. return false;
  1305. case Type_Union:
  1306. if (source->kind == Type_Union) {
  1307. TypeUnion *x = &poly->Union;
  1308. TypeUnion *y = &source->Union;
  1309. if (x->variants.count != y->variants.count) {
  1310. return false;
  1311. }
  1312. for_array(i, x->variants) {
  1313. Type *a = x->variants[i];
  1314. Type *b = y->variants[i];
  1315. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1316. if (!ok) return false;
  1317. }
  1318. return true;
  1319. }
  1320. return false;
  1321. case Type_Struct:
  1322. if (source->kind == Type_Struct) {
  1323. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1324. poly->Struct.soa_kind != StructSoa_None) {
  1325. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1326. if (ok) switch (source->Struct.soa_kind) {
  1327. case StructSoa_None:
  1328. default:
  1329. GB_PANIC("Unhandled SOA Kind");
  1330. break;
  1331. case StructSoa_Fixed:
  1332. if (modify_type) {
  1333. Type *type = make_soa_struct_fixed(c, nullptr, poly->Struct.node, poly->Struct.soa_elem, poly->Struct.soa_count, nullptr);
  1334. gb_memmove(poly, type, gb_size_of(*type));
  1335. }
  1336. break;
  1337. case StructSoa_Slice:
  1338. if (modify_type) {
  1339. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1340. gb_memmove(poly, type, gb_size_of(*type));
  1341. }
  1342. break;
  1343. case StructSoa_Dynamic:
  1344. if (modify_type) {
  1345. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1346. gb_memmove(poly, type, gb_size_of(*type));
  1347. }
  1348. break;
  1349. }
  1350. return ok;
  1351. }
  1352. // NOTE(bill): Check for subtypes of
  1353. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1354. }
  1355. return false;
  1356. case Type_BitField:
  1357. if (source->kind == Type_BitField) {
  1358. return is_polymorphic_type_assignable(c, poly->BitField.backing_type, source->BitField.backing_type, true, modify_type);
  1359. }
  1360. return false;
  1361. case Type_Tuple:
  1362. GB_PANIC("This should never happen");
  1363. return false;
  1364. case Type_Proc:
  1365. if (source->kind == Type_Proc) {
  1366. TypeProc *x = &poly->Proc;
  1367. TypeProc *y = &source->Proc;
  1368. if (x->calling_convention != y->calling_convention) {
  1369. return false;
  1370. }
  1371. if (x->c_vararg != y->c_vararg) {
  1372. return false;
  1373. }
  1374. if (x->variadic != y->variadic) {
  1375. return false;
  1376. }
  1377. if (x->param_count != y->param_count) {
  1378. return false;
  1379. }
  1380. if (x->result_count != y->result_count) {
  1381. return false;
  1382. }
  1383. for (isize i = 0; i < x->param_count; i++) {
  1384. Entity *a = x->params->Tuple.variables[i];
  1385. Entity *b = y->params->Tuple.variables[i];
  1386. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1387. if (!ok) return false;
  1388. }
  1389. for (isize i = 0; i < x->result_count; i++) {
  1390. Entity *a = x->results->Tuple.variables[i];
  1391. Entity *b = y->results->Tuple.variables[i];
  1392. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1393. if (!ok) return false;
  1394. }
  1395. return true;
  1396. }
  1397. return false;
  1398. case Type_Map:
  1399. if (source->kind == Type_Map) {
  1400. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1401. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1402. if (key || value) {
  1403. poly->Map.lookup_result_type = nullptr;
  1404. init_map_internal_types(poly);
  1405. return true;
  1406. }
  1407. }
  1408. return false;
  1409. case Type_Matrix:
  1410. if (source->kind == Type_Matrix) {
  1411. if (poly->Matrix.generic_row_count != nullptr) {
  1412. poly->Matrix.stride_in_bytes = 0;
  1413. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1414. return false;
  1415. }
  1416. }
  1417. if (poly->Matrix.generic_column_count != nullptr) {
  1418. poly->Matrix.stride_in_bytes = 0;
  1419. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1420. return false;
  1421. }
  1422. }
  1423. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1424. poly->Matrix.column_count == source->Matrix.column_count) {
  1425. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1426. }
  1427. }
  1428. return false;
  1429. case Type_SimdVector:
  1430. if (source->kind == Type_SimdVector) {
  1431. if (poly->SimdVector.generic_count != nullptr) {
  1432. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1433. return false;
  1434. }
  1435. }
  1436. if (poly->SimdVector.count == source->SimdVector.count) {
  1437. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1438. }
  1439. }
  1440. return false;
  1441. }
  1442. return false;
  1443. }
  1444. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1445. if (curr->state != EntityState_InProgress) {
  1446. return false;
  1447. }
  1448. for_array(i, *c->type_path) {
  1449. Entity *prev = c->type_path->data[i];
  1450. if (prev == curr) {
  1451. if (report) {
  1452. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1453. for (isize j = i; j < c->type_path->count; j++) {
  1454. Entity *curr = (*c->type_path)[j];
  1455. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1456. }
  1457. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1458. curr->type = t_invalid;
  1459. }
  1460. return true;
  1461. }
  1462. }
  1463. return false;
  1464. }
  1465. struct CIdentSuggestion {
  1466. String name;
  1467. String msg;
  1468. };
  1469. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1470. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1471. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1472. {str_lit("sizeof"), str_lit("'size_of'?")},
  1473. {str_lit("alignof"), str_lit("'align_of'?")},
  1474. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1475. {str_lit("_Bool"), str_lit("'bool'?")},
  1476. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1477. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1478. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1479. {str_lit("float"), str_lit("'f32'?")},
  1480. {str_lit("double"), str_lit("'f64'?")},
  1481. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1482. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1483. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1484. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1485. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1486. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1487. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1488. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1489. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1490. {str_lit("uint8_t"), str_lit("'u8'?")},
  1491. {str_lit("int8_t"), str_lit("'i8'?")},
  1492. {str_lit("uint16_t"), str_lit("'u16'?")},
  1493. {str_lit("int16_t"), str_lit("'i16'?")},
  1494. {str_lit("uint32_t"), str_lit("'u32'?")},
  1495. {str_lit("int32_t"), str_lit("'i32'?")},
  1496. {str_lit("uint64_t"), str_lit("'u64'?")},
  1497. {str_lit("int64_t"), str_lit("'i64'?")},
  1498. {str_lit("uint128_t"), str_lit("'u128'?")},
  1499. {str_lit("int128_t"), str_lit("'i128'?")},
  1500. {str_lit("float32"), str_lit("'f32'?")},
  1501. {str_lit("float64"), str_lit("'f64'?")},
  1502. {str_lit("float32_t"), str_lit("'f32'?")},
  1503. {str_lit("float64_t"), str_lit("'f64'?")},
  1504. };
  1505. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1506. GB_ASSERT(n->kind == Ast_Ident);
  1507. o->mode = Addressing_Invalid;
  1508. o->expr = n;
  1509. String name = n->Ident.token.string;
  1510. Entity *e = scope_lookup(c->scope, name);
  1511. if (e == nullptr) {
  1512. if (is_blank_ident(name)) {
  1513. error(n, "'_' cannot be used as a value");
  1514. } else {
  1515. ERROR_BLOCK();
  1516. error(n, "Undeclared name: %.*s", LIT(name));
  1517. // NOTE(bill): Loads of checks for C programmers
  1518. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1519. if (name == suggestion.name) {
  1520. error_line("\tSuggestion: Did you mean %.*s\n", LIT(suggestion.msg));
  1521. }
  1522. }
  1523. }
  1524. o->type = t_invalid;
  1525. o->mode = Addressing_Invalid;
  1526. if (named_type != nullptr) {
  1527. set_base_type(named_type, t_invalid);
  1528. }
  1529. return nullptr;
  1530. }
  1531. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1532. if (e->parent_proc_decl != nullptr &&
  1533. e->parent_proc_decl != c->curr_proc_decl) {
  1534. if (e->kind == Entity_Variable) {
  1535. if ((e->flags & EntityFlag_Static) == 0) {
  1536. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1537. return nullptr;
  1538. }
  1539. } else if (e->kind == Entity_Label) {
  1540. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1541. return nullptr;
  1542. }
  1543. }
  1544. if (e->kind == Entity_ProcGroup) {
  1545. auto *pge = &e->ProcGroup;
  1546. DeclInfo *d = decl_info_of_entity(e);
  1547. check_entity_decl(c, e, d, nullptr);
  1548. Array<Entity *> procs = pge->entities;
  1549. bool skip = false;
  1550. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1551. // NOTE(bill): These should be done
  1552. for (Entity *proc : procs) {
  1553. Type *t = base_type(proc->type);
  1554. if (t == t_invalid) {
  1555. continue;
  1556. }
  1557. Operand x = {};
  1558. x.mode = Addressing_Value;
  1559. x.type = t;
  1560. if (check_is_assignable_to(c, &x, type_hint)) {
  1561. e = proc;
  1562. add_entity_use(c, n, e);
  1563. skip = true;
  1564. break;
  1565. }
  1566. }
  1567. }
  1568. if (!skip) {
  1569. o->mode = Addressing_ProcGroup;
  1570. o->type = t_invalid;
  1571. o->proc_group = e;
  1572. return nullptr;
  1573. }
  1574. }
  1575. add_entity_use(c, n, e);
  1576. if (e->state == EntityState_Unresolved) {
  1577. check_entity_decl(c, e, nullptr, named_type);
  1578. }
  1579. if (e->type == nullptr) {
  1580. // TODO(bill): Which is correct? return or compiler_error?
  1581. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1582. return nullptr;
  1583. }
  1584. e->flags |= EntityFlag_Used;
  1585. Type *type = e->type;
  1586. o->type = type;
  1587. switch (e->kind) {
  1588. case Entity_Constant:
  1589. if (type == t_invalid) {
  1590. o->type = t_invalid;
  1591. return e;
  1592. }
  1593. o->value = e->Constant.value;
  1594. if (o->value.kind == ExactValue_Invalid) {
  1595. return e;
  1596. }
  1597. if (o->value.kind == ExactValue_Procedure) {
  1598. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1599. if (proc != nullptr) {
  1600. o->mode = Addressing_Value;
  1601. o->type = proc->type;
  1602. return proc;
  1603. }
  1604. }
  1605. o->mode = Addressing_Constant;
  1606. break;
  1607. case Entity_Variable:
  1608. e->flags |= EntityFlag_Used;
  1609. if (type == t_invalid) {
  1610. o->type = t_invalid;
  1611. return e;
  1612. }
  1613. o->mode = Addressing_Variable;
  1614. if (e->flags & EntityFlag_Value) {
  1615. o->mode = Addressing_Value;
  1616. }
  1617. break;
  1618. case Entity_Procedure:
  1619. o->mode = Addressing_Value;
  1620. o->value = exact_value_procedure(n);
  1621. break;
  1622. case Entity_Builtin:
  1623. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1624. o->mode = Addressing_Builtin;
  1625. break;
  1626. case Entity_TypeName:
  1627. o->mode = Addressing_Type;
  1628. if (check_cycle(c, e, true)) {
  1629. o->type = t_invalid;
  1630. }
  1631. if (o->type != nullptr && o->type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1632. o->type = base_type(o->type);
  1633. }
  1634. break;
  1635. case Entity_ImportName:
  1636. if (!allow_import_name) {
  1637. error(n, "Use of import name '%.*s' not in the form of 'x.y'", LIT(name));
  1638. }
  1639. return e;
  1640. case Entity_LibraryName:
  1641. if (!allow_import_name) {
  1642. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1643. }
  1644. return e;
  1645. case Entity_Label:
  1646. o->mode = Addressing_NoValue;
  1647. break;
  1648. case Entity_Nil:
  1649. o->mode = Addressing_Value;
  1650. break;
  1651. default:
  1652. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1653. break;
  1654. }
  1655. return e;
  1656. }
  1657. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1658. if (o->type == nullptr) {
  1659. gbString str = expr_to_string(o->expr);
  1660. error(o->expr, "Expression has no value '%s'", str);
  1661. gb_string_free(str);
  1662. return false;
  1663. }
  1664. if (o->mode == Addressing_Type) {
  1665. gbString str = type_to_string(o->type);
  1666. error(o->expr, "Expected an expression for operator '%.*s', got type '%s'", LIT(op.string), str);
  1667. gb_string_free(str);
  1668. return false;
  1669. }
  1670. Type *type = base_type(core_array_type(o->type));
  1671. gbString str = nullptr;
  1672. switch (op.kind) {
  1673. case Token_Add:
  1674. case Token_Sub:
  1675. if (!is_type_numeric(type)) {
  1676. str = expr_to_string(o->expr);
  1677. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1678. gb_string_free(str);
  1679. }
  1680. break;
  1681. case Token_Xor:
  1682. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1683. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1684. }
  1685. break;
  1686. case Token_Not:
  1687. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1688. ERROR_BLOCK();
  1689. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1690. if (is_type_integer(type)) {
  1691. str = expr_to_string(o->expr);
  1692. error_line("\tSuggestion: Did you mean to do one of the following?\n");
  1693. error_line("\t\t'%s == 0'?\n", str);
  1694. error_line("\t\tUse of the bitwise not operator '~'?\n");
  1695. gb_string_free(str);
  1696. }
  1697. } else {
  1698. o->type = t_untyped_bool;
  1699. }
  1700. break;
  1701. case Token_Mul:
  1702. {
  1703. ERROR_BLOCK();
  1704. error(op, "Operator '%.*s' is not a valid unary operator in Odin", LIT(op.string));
  1705. if (is_type_pointer(o->type)) {
  1706. str = expr_to_string(o->expr);
  1707. error_line("\tSuggestion: Did you mean '%s^'?\n", str);
  1708. o->type = type_deref(o->type);
  1709. } else if (is_type_multi_pointer(o->type)) {
  1710. str = expr_to_string(o->expr);
  1711. error_line("\tSuggestion: The value is a multi-pointer, did you mean '%s[0]'?\n", str);
  1712. o->type = type_deref(o->type, true);
  1713. }
  1714. }
  1715. break;
  1716. default:
  1717. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1718. return false;
  1719. }
  1720. return true;
  1721. }
  1722. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1723. Type *main_type = o->type;
  1724. Type *type = base_type(core_array_type(main_type));
  1725. Type *ct = core_type(type);
  1726. switch (op.kind) {
  1727. case Token_Sub:
  1728. case Token_SubEq:
  1729. if (is_type_bit_set(type)) {
  1730. return true;
  1731. } else if (!is_type_numeric(type)) {
  1732. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1733. return false;
  1734. }
  1735. break;
  1736. case Token_Quo:
  1737. case Token_QuoEq:
  1738. if (is_type_matrix(main_type)) {
  1739. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1740. return false;
  1741. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1742. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1743. return false;
  1744. }
  1745. /*fallthrough*/
  1746. case Token_Mul:
  1747. case Token_MulEq:
  1748. case Token_AddEq:
  1749. if (is_type_bit_set(type)) {
  1750. return true;
  1751. } else if (!is_type_numeric(type)) {
  1752. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1753. return false;
  1754. }
  1755. break;
  1756. case Token_Add:
  1757. if (is_type_string(type)) {
  1758. if (o->mode == Addressing_Constant) {
  1759. return true;
  1760. }
  1761. error(op, "String concatenation is only allowed with constant strings");
  1762. return false;
  1763. } else if (is_type_bit_set(type)) {
  1764. return true;
  1765. } else if (!is_type_numeric(type)) {
  1766. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1767. return false;
  1768. }
  1769. break;
  1770. case Token_And:
  1771. case Token_Or:
  1772. case Token_AndEq:
  1773. case Token_OrEq:
  1774. case Token_Xor:
  1775. case Token_XorEq:
  1776. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1777. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1778. return false;
  1779. }
  1780. break;
  1781. case Token_Mod:
  1782. case Token_ModMod:
  1783. case Token_ModEq:
  1784. case Token_ModModEq:
  1785. if (is_type_matrix(main_type)) {
  1786. error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string));
  1787. return false;
  1788. }
  1789. if (!is_type_integer(type)) {
  1790. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1791. return false;
  1792. } else if (is_type_simd_vector(main_type)) {
  1793. error(op, "Operator '%.*s' is only allowed with #simd types with integer elements", LIT(op.string));
  1794. return false;
  1795. }
  1796. break;
  1797. case Token_AndNot:
  1798. case Token_AndNotEq:
  1799. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1800. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1801. return false;
  1802. }
  1803. break;
  1804. case Token_CmpAnd:
  1805. case Token_CmpOr:
  1806. case Token_CmpAndEq:
  1807. case Token_CmpOrEq:
  1808. if (!is_type_boolean(type)) {
  1809. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1810. return false;
  1811. }
  1812. break;
  1813. default:
  1814. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1815. return false;
  1816. }
  1817. return true;
  1818. }
  1819. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1820. if (in_value.kind == ExactValue_Invalid) {
  1821. // NOTE(bill): There's already been an error
  1822. return true;
  1823. }
  1824. type = core_type(type);
  1825. if (type == t_invalid) {
  1826. return false;
  1827. } else if (is_type_boolean(type)) {
  1828. return in_value.kind == ExactValue_Bool;
  1829. } else if (is_type_string(type)) {
  1830. return in_value.kind == ExactValue_String;
  1831. } else if (is_type_integer(type) || is_type_rune(type)) {
  1832. if (in_value.kind == ExactValue_Bool) {
  1833. return false;
  1834. }
  1835. ExactValue v = exact_value_to_integer(in_value);
  1836. if (v.kind != ExactValue_Integer) {
  1837. return false;
  1838. }
  1839. if (out_value) *out_value = v;
  1840. if (is_type_untyped(type)) {
  1841. return true;
  1842. }
  1843. BigInt i = v.value_integer;
  1844. i64 byte_size = type_size_of(type);
  1845. BigInt umax = {};
  1846. BigInt imin = {};
  1847. BigInt imax = {};
  1848. if (c->bit_field_bit_size > 0) {
  1849. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1850. big_int_from_u64(&umax, 1);
  1851. big_int_from_i64(&imin, 1);
  1852. big_int_from_i64(&imax, 1);
  1853. BigInt bu = {};
  1854. BigInt bi = {};
  1855. big_int_from_i64(&bu, bit_size);
  1856. big_int_from_i64(&bi, bit_size-1);
  1857. big_int_shl_eq(&umax, &bu);
  1858. mp_decr(&umax);
  1859. big_int_shl_eq(&imin, &bi);
  1860. big_int_neg(&imin, &imin);
  1861. big_int_shl_eq(&imax, &bi);
  1862. mp_decr(&imax);
  1863. } else {
  1864. if (byte_size < 16) {
  1865. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1866. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1867. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1868. } else {
  1869. big_int_from_u64(&umax, 1);
  1870. big_int_from_i64(&imin, 1);
  1871. big_int_from_i64(&imax, 1);
  1872. BigInt bi128 = {};
  1873. BigInt bi127 = {};
  1874. big_int_from_i64(&bi128, 128);
  1875. big_int_from_i64(&bi127, 127);
  1876. big_int_shl_eq(&umax, &bi128);
  1877. mp_decr(&umax);
  1878. big_int_shl_eq(&imin, &bi127);
  1879. big_int_neg(&imin, &imin);
  1880. big_int_shl_eq(&imax, &bi127);
  1881. mp_decr(&imax);
  1882. }
  1883. }
  1884. switch (type->Basic.kind) {
  1885. case Basic_rune:
  1886. case Basic_i8:
  1887. case Basic_i16:
  1888. case Basic_i32:
  1889. case Basic_i64:
  1890. case Basic_i128:
  1891. case Basic_int:
  1892. case Basic_i16le:
  1893. case Basic_i32le:
  1894. case Basic_i64le:
  1895. case Basic_i128le:
  1896. case Basic_i16be:
  1897. case Basic_i32be:
  1898. case Basic_i64be:
  1899. case Basic_i128be:
  1900. {
  1901. // return imin <= i && i <= imax;
  1902. int a = big_int_cmp(&imin, &i);
  1903. int b = big_int_cmp(&i, &imax);
  1904. return (a <= 0) && (b <= 0);
  1905. }
  1906. case Basic_u8:
  1907. case Basic_u16:
  1908. case Basic_u32:
  1909. case Basic_u64:
  1910. case Basic_u128:
  1911. case Basic_uint:
  1912. case Basic_uintptr:
  1913. case Basic_u16le:
  1914. case Basic_u32le:
  1915. case Basic_u64le:
  1916. case Basic_u128le:
  1917. case Basic_u16be:
  1918. case Basic_u32be:
  1919. case Basic_u64be:
  1920. case Basic_u128be:
  1921. {
  1922. // return 0ull <= i && i <= umax;
  1923. int b = big_int_cmp(&i, &umax);
  1924. return !i.sign && (b <= 0);
  1925. }
  1926. case Basic_UntypedInteger:
  1927. return true;
  1928. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1929. }
  1930. } else if (is_type_float(type)) {
  1931. ExactValue v = exact_value_to_float(in_value);
  1932. if (v.kind != ExactValue_Float) {
  1933. return false;
  1934. }
  1935. if (out_value) *out_value = v;
  1936. switch (type->Basic.kind) {
  1937. case Basic_f16:
  1938. case Basic_f32:
  1939. case Basic_f64:
  1940. return true;
  1941. case Basic_f16le:
  1942. case Basic_f16be:
  1943. case Basic_f32le:
  1944. case Basic_f32be:
  1945. case Basic_f64le:
  1946. case Basic_f64be:
  1947. return true;
  1948. case Basic_UntypedFloat:
  1949. return true;
  1950. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1951. }
  1952. } else if (is_type_complex(type)) {
  1953. ExactValue v = exact_value_to_complex(in_value);
  1954. if (v.kind != ExactValue_Complex) {
  1955. return false;
  1956. }
  1957. switch (type->Basic.kind) {
  1958. case Basic_complex32:
  1959. case Basic_complex64:
  1960. case Basic_complex128: {
  1961. ExactValue real = exact_value_real(v);
  1962. ExactValue imag = exact_value_imag(v);
  1963. if (real.kind != ExactValue_Invalid &&
  1964. imag.kind != ExactValue_Invalid) {
  1965. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1966. return true;
  1967. }
  1968. break;
  1969. }
  1970. case Basic_UntypedComplex:
  1971. return true;
  1972. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1973. }
  1974. return false;
  1975. } else if (is_type_quaternion(type)) {
  1976. ExactValue v = exact_value_to_quaternion(in_value);
  1977. if (v.kind != ExactValue_Quaternion) {
  1978. return false;
  1979. }
  1980. switch (type->Basic.kind) {
  1981. case Basic_quaternion64:
  1982. case Basic_quaternion128:
  1983. case Basic_quaternion256: {
  1984. ExactValue real = exact_value_real(v);
  1985. ExactValue imag = exact_value_imag(v);
  1986. ExactValue jmag = exact_value_jmag(v);
  1987. ExactValue kmag = exact_value_kmag(v);
  1988. if (real.kind != ExactValue_Invalid &&
  1989. imag.kind != ExactValue_Invalid) {
  1990. 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));
  1991. return true;
  1992. }
  1993. break;
  1994. }
  1995. case Basic_UntypedComplex:
  1996. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  1997. return true;
  1998. case Basic_UntypedQuaternion:
  1999. return true;
  2000. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  2001. }
  2002. return false;
  2003. } else if (is_type_pointer(type)) {
  2004. if (in_value.kind == ExactValue_Pointer) {
  2005. return true;
  2006. }
  2007. if (in_value.kind == ExactValue_Integer) {
  2008. return false;
  2009. // return true;
  2010. }
  2011. if (in_value.kind == ExactValue_String) {
  2012. return false;
  2013. }
  2014. if (out_value) *out_value = in_value;
  2015. } else if (is_type_bit_set(type)) {
  2016. if (in_value.kind == ExactValue_Integer) {
  2017. return true;
  2018. }
  2019. }
  2020. return false;
  2021. }
  2022. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  2023. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  2024. gbString b = type_to_string(type);
  2025. defer (gb_string_free(b));
  2026. if (is_type_enum(o->type)) {
  2027. if (check_is_castable_to(c, o, type)) {
  2028. gbString ot = type_to_string(o->type);
  2029. error_line("\tSuggestion: Try casting the '%s' expression to '%s'", ot, b);
  2030. gb_string_free(ot);
  2031. }
  2032. return true;
  2033. }
  2034. i64 sz = type_size_of(type);
  2035. i64 bit_size = 8*sz;
  2036. bool size_changed = false;
  2037. if (max_bit_size > 0) {
  2038. size_changed = (bit_size != max_bit_size);
  2039. bit_size = gb_min(bit_size, max_bit_size);
  2040. }
  2041. BigInt *bi = &o->value.value_integer;
  2042. if (is_type_unsigned(type)) {
  2043. BigInt one = big_int_make_u64(1);
  2044. BigInt max_size = big_int_make_u64(1);
  2045. BigInt bits = big_int_make_i64(bit_size);
  2046. big_int_shl_eq(&max_size, &bits);
  2047. big_int_sub_eq(&max_size, &one);
  2048. if (big_int_is_neg(bi)) {
  2049. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  2050. BigInt dst = {};
  2051. big_int_neg(&dst, bi);
  2052. if (big_int_cmp(&dst, &max_size) < 0) {
  2053. big_int_sub_eq(&dst, &one);
  2054. String dst_str = big_int_to_string(temporary_allocator(), &dst);
  2055. gbString t = type_to_string(type);
  2056. error_line("\tSuggestion: ~%s(%.*s)\n", t, LIT(dst_str));
  2057. gb_string_free(t);
  2058. }
  2059. } else {
  2060. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2061. if (size_changed) {
  2062. error_line("\tThe maximum value that can be represented with that bit_field's field of '%s | %u' is '%.*s'\n", b, bit_size, LIT(max_size_str));
  2063. } else {
  2064. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2065. }
  2066. }
  2067. } else {
  2068. BigInt zero = big_int_make_u64(0);
  2069. BigInt one = big_int_make_u64(1);
  2070. BigInt max_size = big_int_make_u64(1);
  2071. BigInt bits = big_int_make_i64(bit_size - 1);
  2072. big_int_shl_eq(&max_size, &bits);
  2073. String max_size_str = {};
  2074. if (big_int_is_neg(bi)) {
  2075. big_int_neg(&max_size, &max_size);
  2076. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2077. } else {
  2078. big_int_sub_eq(&max_size, &one);
  2079. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2080. }
  2081. if (size_changed) {
  2082. error_line("\tThe maximum value that can be represented with that bit_field's field of '%s | %u' is '%.*s'\n", b, bit_size, LIT(max_size_str));
  2083. } else {
  2084. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2085. }
  2086. }
  2087. return true;
  2088. }
  2089. return false;
  2090. }
  2091. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  2092. gbString a = expr_to_string(o->expr);
  2093. gbString b = type_to_string(type);
  2094. defer(
  2095. gb_string_free(b);
  2096. gb_string_free(a);
  2097. );
  2098. Type *src = base_type(o->type);
  2099. Type *dst = base_type(type);
  2100. if (is_type_array(src) && is_type_slice(dst)) {
  2101. Type *s = src->Array.elem;
  2102. Type *d = dst->Slice.elem;
  2103. if (are_types_identical(s, d)) {
  2104. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2105. }
  2106. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  2107. Type *s = src->DynamicArray.elem;
  2108. Type *d = dst->Slice.elem;
  2109. if (are_types_identical(s, d)) {
  2110. error_line("\tSuggestion: the dynamic array expression may be sliced with %s[:]\n", a);
  2111. }
  2112. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  2113. error_line("\tSuggestion: the expression may be directly casted to type %s\n", b);
  2114. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2115. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2116. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable, \n");
  2117. error_line("\t whereas slices in general are assumed to be mutable.\n");
  2118. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  2119. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  2120. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  2121. return;
  2122. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  2123. gbString s = expr_to_string(c->type_hint_expr);
  2124. error_line("\tSuggestion: make sure that `%s` is attached to the compound literal directly\n", s);
  2125. gb_string_free(s);
  2126. } else if (is_type_pointer(type) &&
  2127. o->mode == Addressing_Variable &&
  2128. are_types_identical(type_deref(type), o->type)) {
  2129. gbString s = expr_to_string(o->expr);
  2130. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  2131. gb_string_free(s);
  2132. } else if (is_type_pointer(o->type) &&
  2133. are_types_identical(type_deref(o->type), type)) {
  2134. gbString s = expr_to_string(o->expr);
  2135. error_line("\tSuggestion: Did you mean `%s^`\n", s);
  2136. gb_string_free(s);
  2137. }
  2138. }
  2139. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  2140. gbString a = expr_to_string(o->expr);
  2141. gbString b = type_to_string(type);
  2142. defer(
  2143. gb_string_free(b);
  2144. gb_string_free(a);
  2145. );
  2146. Type *src = base_type(o->type);
  2147. Type *dst = base_type(type);
  2148. if (is_type_array(src) && is_type_slice(dst)) {
  2149. Type *s = src->Array.elem;
  2150. Type *d = dst->Slice.elem;
  2151. if (are_types_identical(s, d)) {
  2152. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2153. }
  2154. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  2155. if (is_type_uintptr(type)) {
  2156. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  2157. } else {
  2158. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  2159. i64 x = type_size_of(o->type);
  2160. i64 y = type_size_of(type);
  2161. if (x != y) {
  2162. 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);
  2163. }
  2164. }
  2165. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2166. if (is_type_uintptr(o->type)) {
  2167. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2168. } else {
  2169. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2170. }
  2171. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2172. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2173. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2174. return;
  2175. }
  2176. }
  2177. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2178. GB_ASSERT(o->mode == Addressing_Constant);
  2179. ExactValue out_value = o->value;
  2180. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2181. o->value = out_value;
  2182. return true;
  2183. } else {
  2184. o->value = out_value;
  2185. gbString a = expr_to_string(o->expr);
  2186. gbString b = type_to_string(type);
  2187. gbString c = type_to_string(o->type);
  2188. gbString s = exact_value_to_string(o->value);
  2189. defer(
  2190. gb_string_free(s);
  2191. gb_string_free(c);
  2192. gb_string_free(b);
  2193. gb_string_free(a);
  2194. o->mode = Addressing_Invalid;
  2195. );
  2196. ERROR_BLOCK();
  2197. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2198. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2199. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2200. } else {
  2201. i64 max_bit_size = 0;
  2202. if (ctx->bit_field_bit_size) {
  2203. max_bit_size = ctx->bit_field_bit_size;
  2204. }
  2205. if (are_types_identical(o->type, type)) {
  2206. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2207. } else {
  2208. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2209. }
  2210. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2211. }
  2212. } else {
  2213. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2214. check_assignment_error_suggestion(ctx, o, type);
  2215. }
  2216. return false;
  2217. }
  2218. }
  2219. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2220. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2221. if (o->expr->SelectorExpr.is_bit_field) {
  2222. return true;
  2223. }
  2224. }
  2225. if (o->mode == Addressing_OptionalOk) {
  2226. Ast *expr = unselector_expr(o->expr);
  2227. if (expr->kind != Ast_TypeAssertion) {
  2228. return true;
  2229. }
  2230. ast_node(ta, TypeAssertion, expr);
  2231. TypeAndValue tv = ta->expr->tav;
  2232. if (is_type_pointer(tv.type)) {
  2233. return false;
  2234. }
  2235. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2236. return false;
  2237. }
  2238. if (is_type_any(tv.type)) {
  2239. return false;
  2240. }
  2241. return true;
  2242. }
  2243. if (o->mode == Addressing_MapIndex) {
  2244. return false;
  2245. }
  2246. Ast *expr = unparen_expr(o->expr);
  2247. if (expr->kind == Ast_CompoundLit) {
  2248. return false;
  2249. }
  2250. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2251. }
  2252. gb_internal ExactValue exact_bit_set_all_set_mask(Type *type) {
  2253. type = base_type(type);
  2254. GB_ASSERT(type->kind == Type_BitSet);
  2255. i64 lower = type->BitSet.lower;
  2256. i64 upper = type->BitSet.upper;
  2257. Type *elem = type->BitSet.elem;
  2258. Type *underlying = type->BitSet.underlying;
  2259. bool is_backed = underlying != nullptr;
  2260. gb_unused(is_backed);
  2261. BigInt b_lower = {};
  2262. BigInt b_upper = {};
  2263. big_int_from_i64(&b_lower, lower);
  2264. big_int_from_i64(&b_upper, upper);
  2265. BigInt one = {};
  2266. big_int_from_u64(&one, 1);
  2267. BigInt mask = {};
  2268. if (elem == nullptr) {
  2269. big_int_from_i64(&mask, -1);
  2270. } else if (is_type_enum(elem)) {
  2271. Type *e = base_type(elem);
  2272. GB_ASSERT(e->kind == Type_Enum);
  2273. gb_unused(e);
  2274. if ((big_int_cmp(&e->Enum.min_value->value_integer, &b_lower) == 0 || is_backed) &&
  2275. big_int_cmp(&e->Enum.max_value->value_integer, &b_upper) == 0) {
  2276. i64 lower_base = is_backed ? gb_min(0, lower) : lower;
  2277. BigInt b_lower_base = {};
  2278. big_int_from_i64(&b_lower_base, lower_base);
  2279. for (Entity *f : e->Enum.fields) {
  2280. if (f->kind != Entity_Constant) {
  2281. continue;
  2282. }
  2283. if (f->Constant.value.kind != ExactValue_Integer) {
  2284. continue;
  2285. }
  2286. BigInt shift_amount = f->Constant.value.value_integer;
  2287. big_int_sub_eq(&shift_amount, &b_lower_base);
  2288. BigInt value = {};
  2289. big_int_shl(&value, &one, &shift_amount);
  2290. big_int_or(&mask, &mask, &value);
  2291. }
  2292. } else {
  2293. // TODO(bill): enum range based");
  2294. big_int_from_i64(&mask, -1);
  2295. }
  2296. } else {
  2297. i64 lower_base = lower;
  2298. for (i64 x = lower; x <= upper; x++) {
  2299. BigInt shift_amount = {};
  2300. big_int_from_i64(&shift_amount, x - lower_base);
  2301. BigInt value = {};
  2302. big_int_shl(&value, &one, &shift_amount);
  2303. big_int_or(&mask, &mask, &value);
  2304. }
  2305. }
  2306. ExactValue res = {};
  2307. res.kind = ExactValue_Integer;
  2308. res.value_integer = mask;
  2309. return res;
  2310. }
  2311. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2312. switch (op.kind) {
  2313. case Token_And: { // Pointer address
  2314. if (check_is_not_addressable(c, o)) {
  2315. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2316. ast_node(ue, UnaryExpr, node);
  2317. gbString str = expr_to_string(ue->expr);
  2318. defer (gb_string_free(str));
  2319. Entity *e = entity_of_node(ue->expr);
  2320. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2321. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2322. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2323. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2324. } else {
  2325. switch (o->mode) {
  2326. case Addressing_Constant:
  2327. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2328. break;
  2329. case Addressing_SwizzleValue:
  2330. case Addressing_SwizzleVariable:
  2331. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2332. break;
  2333. default:
  2334. {
  2335. ERROR_BLOCK();
  2336. error(op, "Cannot take the pointer address of '%s'", str);
  2337. if (e == nullptr) {
  2338. break;
  2339. }
  2340. if ((e->flags & EntityFlag_ForValue) != 0) {
  2341. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2342. if (parent_type != nullptr && is_type_string(parent_type)) {
  2343. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2344. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2345. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2346. } else {
  2347. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2348. }
  2349. if (parent_type != nullptr && is_type_map(parent_type)) {
  2350. error_line("\t Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2351. } else {
  2352. error_line("\t Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2353. }
  2354. }
  2355. if ((e->flags & EntityFlag_SwitchValue) != 0) {
  2356. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2357. error_line("\t Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2358. }
  2359. }
  2360. break;
  2361. }
  2362. }
  2363. }
  2364. o->mode = Addressing_Invalid;
  2365. return;
  2366. }
  2367. if (o->mode == Addressing_SoaVariable) {
  2368. ast_node(ue, UnaryExpr, node);
  2369. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2370. ast_node(ie, IndexExpr, ue->expr);
  2371. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2372. GB_ASSERT(is_type_soa_struct(soa_type));
  2373. o->type = alloc_type_soa_pointer(soa_type);
  2374. } else {
  2375. o->type = alloc_type_pointer(o->type);
  2376. }
  2377. } else {
  2378. o->type = alloc_type_pointer(o->type);
  2379. }
  2380. switch (o->mode) {
  2381. case Addressing_OptionalOk:
  2382. case Addressing_MapIndex:
  2383. o->mode = Addressing_OptionalOkPtr;
  2384. break;
  2385. default:
  2386. o->mode = Addressing_Value;
  2387. break;
  2388. }
  2389. return;
  2390. }
  2391. }
  2392. if (!check_unary_op(c, o, op)) {
  2393. o->mode = Addressing_Invalid;
  2394. return;
  2395. }
  2396. if (o->mode == Addressing_Constant) {
  2397. Type *type = base_type(o->type);
  2398. if (!is_type_constant_type(o->type)) {
  2399. if (is_type_array_like(o->type)) {
  2400. o->mode = Addressing_Value;
  2401. return;
  2402. }
  2403. gbString xt = type_to_string(o->type);
  2404. gbString err_str = expr_to_string(node);
  2405. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2406. gb_string_free(err_str);
  2407. gb_string_free(xt);
  2408. o->mode = Addressing_Invalid;
  2409. return;
  2410. }
  2411. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2412. gbString err_str = expr_to_string(node);
  2413. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2414. gb_string_free(err_str);
  2415. o->mode = Addressing_Invalid;
  2416. return;
  2417. }
  2418. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2419. gbString err_str = expr_to_string(node);
  2420. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2421. gb_string_free(err_str);
  2422. o->mode = Addressing_Invalid;
  2423. return;
  2424. }
  2425. i32 precision = 0;
  2426. if (is_type_typed(type)) {
  2427. precision = cast(i32)(8 * type_size_of(type));
  2428. }
  2429. bool is_unsigned = is_type_unsigned(type);
  2430. if (is_type_rune(type)) {
  2431. GB_ASSERT(!is_unsigned);
  2432. }
  2433. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2434. if (op.kind == Token_Xor && is_type_bit_set(type)) {
  2435. ExactValue mask = exact_bit_set_all_set_mask(type);
  2436. o->value = exact_binary_operator_value(Token_And, o->value, mask);
  2437. }
  2438. if (is_type_typed(type)) {
  2439. if (node != nullptr) {
  2440. o->expr = node;
  2441. }
  2442. check_is_expressible(c, o, type);
  2443. }
  2444. return;
  2445. }
  2446. o->mode = Addressing_Value;
  2447. }
  2448. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2449. if (t == nullptr) {
  2450. return;
  2451. }
  2452. t = base_type(t);
  2453. if (!is_type_comparable(t)) {
  2454. return;
  2455. }
  2456. switch (t->kind) {
  2457. case Type_Basic:
  2458. switch (t->Basic.kind) {
  2459. case Basic_complex32:
  2460. add_package_dependency(c, "runtime", "complex32_eq");
  2461. add_package_dependency(c, "runtime", "complex32_ne");
  2462. break;
  2463. case Basic_complex64:
  2464. add_package_dependency(c, "runtime", "complex64_eq");
  2465. add_package_dependency(c, "runtime", "complex64_ne");
  2466. break;
  2467. case Basic_complex128:
  2468. add_package_dependency(c, "runtime", "complex128_eq");
  2469. add_package_dependency(c, "runtime", "complex128_ne");
  2470. break;
  2471. case Basic_quaternion64:
  2472. add_package_dependency(c, "runtime", "quaternion64_eq");
  2473. add_package_dependency(c, "runtime", "quaternion64_ne");
  2474. break;
  2475. case Basic_quaternion128:
  2476. add_package_dependency(c, "runtime", "quaternion128_eq");
  2477. add_package_dependency(c, "runtime", "quaternion128_ne");
  2478. break;
  2479. case Basic_quaternion256:
  2480. add_package_dependency(c, "runtime", "quaternion256_eq");
  2481. add_package_dependency(c, "runtime", "quaternion256_ne");
  2482. break;
  2483. case Basic_cstring:
  2484. add_package_dependency(c, "runtime", "cstring_eq");
  2485. add_package_dependency(c, "runtime", "cstring_ne");
  2486. break;
  2487. case Basic_string:
  2488. add_package_dependency(c, "runtime", "string_eq");
  2489. add_package_dependency(c, "runtime", "string_ne");
  2490. break;
  2491. }
  2492. break;
  2493. case Type_Struct:
  2494. for (Entity *field : t->Struct.fields) {
  2495. add_comparison_procedures_for_fields(c, field->type);
  2496. }
  2497. break;
  2498. }
  2499. }
  2500. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2501. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2502. bool comp = are_types_identical(x->type, y->type);
  2503. switch (op) {
  2504. case Token_CmpEq: /* comp = comp; */ break;
  2505. case Token_NotEq: comp = !comp; break;
  2506. }
  2507. x->mode = Addressing_Constant;
  2508. x->type = t_untyped_bool;
  2509. x->value = exact_value_bool(comp);
  2510. return;
  2511. }
  2512. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2513. add_type_info_type(c, x->type);
  2514. add_type_info_type(c, y->type);
  2515. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2516. x->mode = Addressing_Value;
  2517. x->type = t_untyped_bool;
  2518. return;
  2519. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2520. add_type_info_type(c, x->type);
  2521. add_type_info_type(c, y->type);
  2522. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2523. x->mode = Addressing_Value;
  2524. x->type = t_untyped_bool;
  2525. return;
  2526. }
  2527. TEMPORARY_ALLOCATOR_GUARD();
  2528. gbString err_str = nullptr;
  2529. if (check_is_assignable_to(c, x, y->type) ||
  2530. check_is_assignable_to(c, y, x->type)) {
  2531. Type *err_type = x->type;
  2532. bool defined = false;
  2533. switch (op) {
  2534. case Token_CmpEq:
  2535. case Token_NotEq:
  2536. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2537. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2538. (is_operand_nil(*y) && type_has_nil(x->type));
  2539. break;
  2540. case Token_Lt:
  2541. case Token_Gt:
  2542. case Token_LtEq:
  2543. case Token_GtEq:
  2544. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2545. defined = true;
  2546. } else {
  2547. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2548. }
  2549. break;
  2550. }
  2551. if (!defined) {
  2552. gbString xs = type_to_string(x->type, temporary_allocator());
  2553. gbString ys = type_to_string(y->type, temporary_allocator());
  2554. err_str = gb_string_make(temporary_allocator(),
  2555. gb_bprintf("operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2556. );
  2557. } else {
  2558. Type *comparison_type = x->type;
  2559. if (x->type == err_type && is_operand_nil(*x)) {
  2560. comparison_type = y->type;
  2561. }
  2562. add_comparison_procedures_for_fields(c, comparison_type);
  2563. }
  2564. } else {
  2565. gbString xt, yt;
  2566. if (x->mode == Addressing_ProcGroup) {
  2567. xt = gb_string_make(temporary_allocator(), "procedure group");
  2568. } else {
  2569. xt = type_to_string(x->type);
  2570. }
  2571. if (y->mode == Addressing_ProcGroup) {
  2572. yt = gb_string_make(temporary_allocator(), "procedure group");
  2573. } else {
  2574. yt = type_to_string(y->type);
  2575. }
  2576. err_str = gb_string_make(temporary_allocator(), gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  2577. }
  2578. if (err_str != nullptr) {
  2579. error(node, "Cannot compare expression, %s", err_str);
  2580. x->type = t_untyped_bool;
  2581. } else {
  2582. if (x->mode == Addressing_Constant &&
  2583. y->mode == Addressing_Constant) {
  2584. if (is_type_constant_type(x->type)) {
  2585. if (is_type_bit_set(x->type)) {
  2586. switch (op) {
  2587. case Token_CmpEq:
  2588. case Token_NotEq:
  2589. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2590. break;
  2591. case Token_Lt:
  2592. case Token_LtEq:
  2593. {
  2594. ExactValue lhs = x->value;
  2595. ExactValue rhs = y->value;
  2596. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2597. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2598. if (op == Token_Lt) {
  2599. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2600. }
  2601. x->value = res;
  2602. break;
  2603. }
  2604. case Token_Gt:
  2605. case Token_GtEq:
  2606. {
  2607. ExactValue lhs = x->value;
  2608. ExactValue rhs = y->value;
  2609. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2610. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2611. if (op == Token_Gt) {
  2612. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2613. }
  2614. x->value = res;
  2615. break;
  2616. }
  2617. }
  2618. } else {
  2619. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2620. }
  2621. } else {
  2622. x->mode = Addressing_Value;
  2623. }
  2624. } else {
  2625. x->mode = Addressing_Value;
  2626. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2627. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2628. i64 size = 0;
  2629. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2630. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2631. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2632. switch (op) {
  2633. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2634. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2635. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2636. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2637. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2638. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2639. }
  2640. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2641. switch (op) {
  2642. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2643. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2644. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2645. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2646. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2647. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2648. }
  2649. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2650. switch (op) {
  2651. case Token_CmpEq:
  2652. switch (8*size) {
  2653. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2654. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2655. }
  2656. break;
  2657. case Token_NotEq:
  2658. switch (8*size) {
  2659. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2660. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2661. }
  2662. break;
  2663. }
  2664. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2665. switch (op) {
  2666. case Token_CmpEq:
  2667. switch (8*size) {
  2668. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2669. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2670. }
  2671. break;
  2672. case Token_NotEq:
  2673. switch (8*size) {
  2674. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2675. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2676. }
  2677. break;
  2678. }
  2679. }
  2680. }
  2681. x->type = t_untyped_bool;
  2682. }
  2683. }
  2684. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2685. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2686. ast_node(be, BinaryExpr, node);
  2687. ExactValue x_val = {};
  2688. if (x->mode == Addressing_Constant) {
  2689. x_val = exact_value_to_integer(x->value);
  2690. }
  2691. bool x_is_untyped = is_type_untyped(x->type);
  2692. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  2693. gbString err_str = expr_to_string(x->expr);
  2694. error(node, "Shifted operand '%s' must be an integer", err_str);
  2695. gb_string_free(err_str);
  2696. x->mode = Addressing_Invalid;
  2697. return;
  2698. }
  2699. if (is_type_unsigned(y->type)) {
  2700. } else if (is_type_untyped(y->type)) {
  2701. convert_to_typed(c, y, t_untyped_integer);
  2702. if (y->mode == Addressing_Invalid) {
  2703. x->mode = Addressing_Invalid;
  2704. return;
  2705. }
  2706. } else {
  2707. gbString err_str = expr_to_string(y->expr);
  2708. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2709. gb_string_free(err_str);
  2710. x->mode = Addressing_Invalid;
  2711. return;
  2712. }
  2713. if (x->mode == Addressing_Constant) {
  2714. if (y->mode == Addressing_Constant) {
  2715. ExactValue y_val = exact_value_to_integer(y->value);
  2716. if (y_val.kind != ExactValue_Integer) {
  2717. gbString err_str = expr_to_string(y->expr);
  2718. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2719. gb_string_free(err_str);
  2720. x->mode = Addressing_Invalid;
  2721. return;
  2722. }
  2723. BigInt max_shift = {};
  2724. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2725. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  2726. gbString err_str = expr_to_string(y->expr);
  2727. error(node, "Shift amount too large: '%s'", err_str);
  2728. gb_string_free(err_str);
  2729. x->mode = Addressing_Invalid;
  2730. return;
  2731. }
  2732. if (!is_type_integer(x->type)) {
  2733. // NOTE(bill): It could be an untyped float but still representable
  2734. // as an integer
  2735. x->type = t_untyped_integer;
  2736. }
  2737. x->expr = node;
  2738. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  2739. if (is_type_typed(x->type)) {
  2740. check_is_expressible(c, x, x->type);
  2741. }
  2742. return;
  2743. }
  2744. TokenPos pos = ast_token(x->expr).pos;
  2745. if (x_is_untyped) {
  2746. if (x->expr != nullptr) {
  2747. x->expr->tav.is_lhs = true;
  2748. }
  2749. x->mode = Addressing_Value;
  2750. if (type_hint) {
  2751. if (is_type_integer(type_hint)) {
  2752. convert_to_typed(c, x, type_hint);
  2753. } else {
  2754. gbString x_str = expr_to_string(x->expr);
  2755. gbString to_type = type_to_string(type_hint);
  2756. error(node, "Conversion of shifted operand '%s' to '%s' is not allowed", x_str, to_type);
  2757. gb_string_free(x_str);
  2758. gb_string_free(to_type);
  2759. x->mode = Addressing_Invalid;
  2760. }
  2761. } else if (!is_type_integer(x->type)) {
  2762. gbString x_str = expr_to_string(x->expr);
  2763. error(node, "Non-integer shifted operand '%s' is not allowed", x_str);
  2764. gb_string_free(x_str);
  2765. x->mode = Addressing_Invalid;
  2766. }
  2767. // x->value = x_val;
  2768. return;
  2769. }
  2770. }
  2771. if (y->mode == Addressing_Constant && big_int_is_neg(&y->value.value_integer)) {
  2772. gbString err_str = expr_to_string(y->expr);
  2773. error(node, "Shift amount cannot be negative: '%s'", err_str);
  2774. gb_string_free(err_str);
  2775. }
  2776. if (!is_type_integer(x->type)) {
  2777. gbString err_str = expr_to_string(x->expr);
  2778. error(node, "Shift operand '%s' must be an integer", err_str);
  2779. gb_string_free(err_str);
  2780. x->mode = Addressing_Invalid;
  2781. return;
  2782. }
  2783. if (is_type_untyped(y->type)) {
  2784. convert_to_typed(c, y, t_uint);
  2785. }
  2786. x->mode = Addressing_Value;
  2787. }
  2788. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2789. if (check_is_assignable_to(c, operand, y)) {
  2790. return true;
  2791. }
  2792. bool is_constant = operand->mode == Addressing_Constant;
  2793. Type *x = operand->type;
  2794. Type *src = core_type(x);
  2795. Type *dst = core_type(y);
  2796. if (are_types_identical(src, dst)) {
  2797. return true;
  2798. }
  2799. // if (is_type_tuple(src)) {
  2800. // Ast *expr = unparen_expr(operand->expr);
  2801. // if (expr && expr->kind == Ast_CallExpr) {
  2802. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2803. // ast_node(ce, CallExpr, expr);
  2804. // Type *pt = base_type(type_of_expr(ce->proc));
  2805. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2806. // if (pt->Proc.result_count > 0) {
  2807. // Operand op = *operand;
  2808. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2809. // bool ok = check_is_castable_to(c, &op, y);
  2810. // if (ok) {
  2811. // ce->optional_ok_one = true;
  2812. // }
  2813. // return ok;
  2814. // }
  2815. // }
  2816. // }
  2817. // }
  2818. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2819. if (is_type_u8_array(dst)) {
  2820. String s = operand->value.value_string;
  2821. return s.len == dst->Array.count;
  2822. }
  2823. if (is_type_rune_array(dst)) {
  2824. String s = operand->value.value_string;
  2825. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2826. }
  2827. }
  2828. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2829. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2830. return dst->Array.count == src->Array.count;
  2831. }
  2832. }
  2833. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2834. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2835. }
  2836. // Cast between booleans and integers
  2837. if (is_type_boolean(src) || is_type_integer(src)) {
  2838. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2839. return true;
  2840. }
  2841. }
  2842. // Cast between numbers
  2843. if (is_type_integer(src) || is_type_float(src)) {
  2844. if (is_type_integer(dst) || is_type_float(dst)) {
  2845. return true;
  2846. }
  2847. }
  2848. if (is_type_bit_field(src)) {
  2849. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2850. }
  2851. if (is_type_bit_field(dst)) {
  2852. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2853. }
  2854. if (is_type_integer(src) && is_type_rune(dst)) {
  2855. return true;
  2856. }
  2857. if (is_type_rune(src) && is_type_integer(dst)) {
  2858. return true;
  2859. }
  2860. if (is_type_complex(src) && is_type_complex(dst)) {
  2861. return true;
  2862. }
  2863. if (is_type_float(src) && is_type_complex(dst)) {
  2864. return true;
  2865. }
  2866. if (is_type_float(src) && is_type_quaternion(dst)) {
  2867. return true;
  2868. }
  2869. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2870. return true;
  2871. }
  2872. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2873. return true;
  2874. }
  2875. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2876. GB_ASSERT(src->kind == Type_Matrix);
  2877. GB_ASSERT(dst->kind == Type_Matrix);
  2878. Operand op = *operand;
  2879. op.type = src->Matrix.elem;
  2880. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2881. return false;
  2882. }
  2883. if (src->Matrix.row_count != src->Matrix.column_count) {
  2884. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2885. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2886. return src_count == dst_count;
  2887. }
  2888. return is_matrix_square(dst) && is_matrix_square(src);
  2889. }
  2890. // Cast between pointers
  2891. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2892. return true;
  2893. }
  2894. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2895. return true;
  2896. }
  2897. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2898. return true;
  2899. }
  2900. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2901. return true;
  2902. }
  2903. // uintptr <-> pointer
  2904. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2905. return true;
  2906. }
  2907. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2908. return true;
  2909. }
  2910. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2911. return true;
  2912. }
  2913. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2914. return true;
  2915. }
  2916. // []byte/[]u8 <-> string (not cstring)
  2917. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2918. return true;
  2919. }
  2920. // cstring -> string
  2921. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2922. if (operand->mode != Addressing_Constant) {
  2923. add_package_dependency(c, "runtime", "cstring_to_string");
  2924. }
  2925. return true;
  2926. }
  2927. // cstring -> ^u8
  2928. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2929. return !is_constant;
  2930. }
  2931. // cstring -> [^]u8
  2932. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2933. return !is_constant;
  2934. }
  2935. // cstring -> rawptr
  2936. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2937. return !is_constant;
  2938. }
  2939. // ^u8 -> cstring
  2940. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2941. return !is_constant;
  2942. }
  2943. // [^]u8 -> cstring
  2944. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2945. return !is_constant;
  2946. }
  2947. // rawptr -> cstring
  2948. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2949. return !is_constant;
  2950. }
  2951. // proc <-> proc
  2952. if (is_type_proc(src) && is_type_proc(dst)) {
  2953. if (is_type_polymorphic(dst)) {
  2954. if (is_type_polymorphic(src) &&
  2955. operand->mode == Addressing_Variable) {
  2956. return true;
  2957. }
  2958. return false;
  2959. }
  2960. return true;
  2961. }
  2962. // proc -> rawptr
  2963. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2964. return true;
  2965. }
  2966. // rawptr -> proc
  2967. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2968. return true;
  2969. }
  2970. if (is_type_array(dst)) {
  2971. Type *elem = base_array_type(dst);
  2972. if (check_is_castable_to(c, operand, elem)) {
  2973. return true;
  2974. }
  2975. }
  2976. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2977. if (src->SimdVector.count != dst->SimdVector.count) {
  2978. return false;
  2979. }
  2980. Type *elem_src = base_array_type(src);
  2981. Type *elem_dst = base_array_type(dst);
  2982. Operand x = {};
  2983. x.type = elem_src;
  2984. x.mode = Addressing_Value;
  2985. return check_is_castable_to(c, &x, elem_dst);
  2986. }
  2987. if (is_type_simd_vector(dst)) {
  2988. Type *elem = base_array_type(dst);
  2989. if (check_is_castable_to(c, operand, elem)) {
  2990. return true;
  2991. }
  2992. }
  2993. return false;
  2994. }
  2995. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2996. bool is_const_expr = x->mode == Addressing_Constant;
  2997. Type *bt = base_type(type);
  2998. if (is_const_expr && is_type_constant_type(bt)) {
  2999. if (core_type(bt)->kind == Type_Basic) {
  3000. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  3001. return true;
  3002. } else if (check_is_castable_to(c, x, type)) {
  3003. if (is_type_pointer(type)) {
  3004. return true;
  3005. }
  3006. }
  3007. } else if (check_is_castable_to(c, x, type)) {
  3008. x->value = {};
  3009. x->mode = Addressing_Value;
  3010. return true;
  3011. }
  3012. } else if (check_is_castable_to(c, x, type)) {
  3013. if (x->mode != Addressing_Constant) {
  3014. x->mode = Addressing_Value;
  3015. } else if (is_type_slice(type) && is_type_string(x->type)) {
  3016. x->mode = Addressing_Value;
  3017. } else if (is_type_union(type)) {
  3018. x->mode = Addressing_Value;
  3019. }
  3020. if (x->mode == Addressing_Value) {
  3021. x->value = {};
  3022. }
  3023. return true;
  3024. }
  3025. return false;
  3026. }
  3027. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type, bool forbid_identical = false) {
  3028. if (!is_operand_value(*x)) {
  3029. error(x->expr, "Only values can be casted");
  3030. x->mode = Addressing_Invalid;
  3031. return;
  3032. }
  3033. bool is_const_expr = x->mode == Addressing_Constant;
  3034. bool can_convert = check_cast_internal(c, x, type);
  3035. if (!can_convert) {
  3036. TEMPORARY_ALLOCATOR_GUARD();
  3037. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  3038. gbString to_type = type_to_string(type, temporary_allocator());
  3039. gbString from_type = type_to_string(x->type, temporary_allocator());
  3040. x->mode = Addressing_Invalid;
  3041. ERROR_BLOCK();
  3042. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  3043. if (is_const_expr) {
  3044. gbString val_str = exact_value_to_string(x->value);
  3045. if (is_type_float(x->type) && is_type_integer(type)) {
  3046. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  3047. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3048. x->mode = Addressing_Constant;
  3049. x->type = type;
  3050. } else {
  3051. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  3052. if (is_type_numeric(type)) {
  3053. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3054. x->mode = Addressing_Constant;
  3055. x->type = type;
  3056. }
  3057. }
  3058. gb_string_free(val_str);
  3059. }
  3060. check_cast_error_suggestion(c, x, type);
  3061. return;
  3062. }
  3063. if (is_type_untyped(x->type)) {
  3064. Type *final_type = type;
  3065. if (is_const_expr && !is_type_constant_type(type)) {
  3066. if (is_type_union(type)) {
  3067. convert_to_typed(c, x, type);
  3068. }
  3069. final_type = default_type(x->type);
  3070. }
  3071. update_untyped_expr_type(c, x->expr, final_type, true);
  3072. } else {
  3073. Type *src = core_type(x->type);
  3074. Type *dst = core_type(type);
  3075. if (src != dst) {
  3076. bool const REQUIRE = true;
  3077. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  3078. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  3079. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  3080. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  3081. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  3082. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  3083. } else if (src == t_f16 && is_type_float(dst)) {
  3084. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  3085. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  3086. } else if (is_type_float(dst) && dst == t_f16) {
  3087. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  3088. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  3089. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  3090. }
  3091. }
  3092. // If we check polymorphic procedures, we risk erring on
  3093. // identical casts that cannot be foreseen or otherwise
  3094. // forbidden, so just skip them.
  3095. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3096. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig))) {
  3097. Type *src_exact = x->type;
  3098. Type *dst_exact = type;
  3099. if (src_exact != nullptr &&
  3100. dst_exact != nullptr &&
  3101. are_types_identical(src_exact, dst_exact)
  3102. ) {
  3103. gbString oper_str = expr_to_string(x->expr);
  3104. gbString to_type = type_to_string(dst_exact);
  3105. error(x->expr, "Unneeded cast of '%s' to identical type '%s'", oper_str, to_type);
  3106. gb_string_free(oper_str);
  3107. gb_string_free(to_type);
  3108. }
  3109. }
  3110. }
  3111. x->type = type;
  3112. }
  3113. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t, bool forbid_identical = false) {
  3114. if (!is_operand_value(*o)) {
  3115. error(o->expr, "'transmute' can only be applied to values");
  3116. o->mode = Addressing_Invalid;
  3117. return false;
  3118. }
  3119. Type *src_t = o->type;
  3120. Type *dst_t = t;
  3121. Type *src_bt = base_type(src_t);
  3122. Type *dst_bt = base_type(dst_t);
  3123. if (is_type_untyped(src_t)) {
  3124. gbString expr_str = expr_to_string(o->expr);
  3125. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  3126. gb_string_free(expr_str);
  3127. o->mode = Addressing_Invalid;
  3128. o->expr = node;
  3129. return false;
  3130. }
  3131. if (dst_bt == nullptr || dst_bt == t_invalid) {
  3132. GB_ASSERT(global_error_collector.count != 0);
  3133. o->mode = Addressing_Invalid;
  3134. o->expr = node;
  3135. return false;
  3136. }
  3137. if (src_bt == nullptr || src_bt == t_invalid) {
  3138. // NOTE(bill): this should be an error
  3139. GB_ASSERT(global_error_collector.count != 0);
  3140. o->mode = Addressing_Value;
  3141. o->expr = node;
  3142. o->type = dst_t;
  3143. return true;
  3144. }
  3145. i64 srcz = type_size_of(src_t);
  3146. i64 dstz = type_size_of(dst_t);
  3147. if (srcz != dstz) {
  3148. gbString expr_str = expr_to_string(o->expr);
  3149. gbString type_str = type_to_string(dst_t);
  3150. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  3151. gb_string_free(type_str);
  3152. gb_string_free(expr_str);
  3153. o->mode = Addressing_Invalid;
  3154. o->expr = node;
  3155. return false;
  3156. }
  3157. o->expr = node;
  3158. o->type = dst_t;
  3159. if (o->mode == Addressing_Constant) {
  3160. if (are_types_identical(src_bt, dst_bt)) {
  3161. return true;
  3162. }
  3163. if (is_type_integer(src_t) && is_type_integer(dst_t)) {
  3164. if (types_have_same_internal_endian(src_t, dst_t)) {
  3165. ExactValue src_v = exact_value_to_integer(o->value);
  3166. GB_ASSERT(src_v.kind == ExactValue_Integer || src_v.kind == ExactValue_Invalid);
  3167. BigInt v = src_v.value_integer;
  3168. BigInt smax = {};
  3169. BigInt umax = {};
  3170. big_int_from_u64(&smax, 0);
  3171. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  3172. big_int_from_u64(&umax, 1);
  3173. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  3174. big_int_shl_eq(&umax, &sz_in_bits);
  3175. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  3176. if (big_int_cmp(&v, &smax) >= 0) {
  3177. big_int_sub_eq(&v, &umax);
  3178. }
  3179. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  3180. if (big_int_is_neg(&v)) {
  3181. big_int_add_eq(&v, &umax);
  3182. }
  3183. }
  3184. o->value.kind = ExactValue_Integer;
  3185. o->value.value_integer = v;
  3186. return true;
  3187. }
  3188. }
  3189. } else {
  3190. // If we check polymorphic procedures, we risk erring on
  3191. // identical casts that cannot be foreseen or otherwise
  3192. // forbidden, so just skip them.
  3193. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3194. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig))) {
  3195. if (are_types_identical(src_t, dst_t)) {
  3196. gbString oper_str = expr_to_string(o->expr);
  3197. gbString to_type = type_to_string(dst_t);
  3198. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3199. gb_string_free(oper_str);
  3200. gb_string_free(to_type);
  3201. } else if (is_type_internally_pointer_like(src_t) &&
  3202. is_type_internally_pointer_like(dst_t)) {
  3203. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since the types are pointer-like");
  3204. } else if (are_types_identical(src_bt, dst_bt)) {
  3205. gbString oper_str = expr_to_string(o->expr);
  3206. gbString to_type = type_to_string(dst_t);
  3207. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3208. gb_string_free(oper_str);
  3209. gb_string_free(to_type);
  3210. } else if (is_type_integer(src_t) && is_type_integer(dst_t) &&
  3211. types_have_same_internal_endian(src_t, dst_t)) {
  3212. gbString oper_type = type_to_string(src_t);
  3213. gbString to_type = type_to_string(dst_t);
  3214. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since both are integers of the same endianness, from '%s' to '%s'", oper_type, to_type);
  3215. gb_string_free(to_type);
  3216. gb_string_free(oper_type);
  3217. }
  3218. }
  3219. }
  3220. o->mode = Addressing_Value;
  3221. o->value = {};
  3222. return true;
  3223. }
  3224. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  3225. if (is_type_array(x->type) && !is_type_array(y->type)) {
  3226. if (check_is_assignable_to(c, y, x->type)) {
  3227. if (check_binary_op(c, x, op)) {
  3228. return true;
  3229. }
  3230. }
  3231. }
  3232. return false;
  3233. }
  3234. gb_internal bool is_ise_expr(Ast *node) {
  3235. node = unparen_expr(node);
  3236. return node->kind == Ast_ImplicitSelectorExpr;
  3237. }
  3238. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  3239. if (use_lhs_as_type_hint) { // RHS in this case
  3240. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  3241. }
  3242. return false;
  3243. }
  3244. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  3245. Type *xt = base_type(matrix);
  3246. if (type_hint != nullptr) {
  3247. Type *th = base_type(type_hint);
  3248. if (are_types_identical(th, xt)) {
  3249. return type_hint;
  3250. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  3251. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  3252. // ignore
  3253. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  3254. xt->Matrix.column_count == th->Matrix.column_count) {
  3255. return type_hint;
  3256. }
  3257. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  3258. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  3259. // ignore
  3260. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  3261. return type_hint;
  3262. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3263. return type_hint;
  3264. }
  3265. }
  3266. }
  3267. return matrix;
  3268. }
  3269. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3270. if (!check_binary_op(c, x, op)) {
  3271. x->mode = Addressing_Invalid;
  3272. return;
  3273. }
  3274. Type *xt = base_type(x->type);
  3275. Type *yt = base_type(y->type);
  3276. if (is_type_matrix(x->type)) {
  3277. GB_ASSERT(xt->kind == Type_Matrix);
  3278. if (op.kind == Token_Mul) {
  3279. if (yt->kind == Type_Matrix) {
  3280. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3281. goto matrix_error;
  3282. }
  3283. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3284. goto matrix_error;
  3285. }
  3286. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3287. goto matrix_error;
  3288. }
  3289. x->mode = Addressing_Value;
  3290. if (are_types_identical(xt, yt)) {
  3291. if (are_types_identical(x->type, y->type)) {
  3292. return;
  3293. }
  3294. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3295. // prefer the named type
  3296. x->type = y->type;
  3297. }
  3298. } else {
  3299. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3300. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3301. }
  3302. goto matrix_success;
  3303. } else if (yt->kind == Type_Array) {
  3304. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3305. goto matrix_error;
  3306. }
  3307. if (xt->Matrix.column_count != yt->Array.count) {
  3308. goto matrix_error;
  3309. }
  3310. // Treat arrays as column vectors
  3311. x->mode = Addressing_Value;
  3312. if (xt->Matrix.row_count == yt->Array.count) {
  3313. x->type = y->type;
  3314. } else {
  3315. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3316. }
  3317. goto matrix_success;
  3318. }
  3319. }
  3320. if (!are_types_identical(xt, yt)) {
  3321. goto matrix_error;
  3322. }
  3323. x->mode = Addressing_Value;
  3324. x->type = xt;
  3325. goto matrix_success;
  3326. } else {
  3327. GB_ASSERT(!is_type_matrix(xt));
  3328. GB_ASSERT(is_type_matrix(yt));
  3329. if (op.kind == Token_Mul) {
  3330. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3331. if (xt->kind == Type_Array) {
  3332. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3333. goto matrix_error;
  3334. }
  3335. if (xt->Array.count != yt->Matrix.row_count) {
  3336. goto matrix_error;
  3337. }
  3338. // Treat arrays as row vectors
  3339. x->mode = Addressing_Value;
  3340. if (yt->Matrix.column_count == xt->Array.count) {
  3341. x->type = x->type;
  3342. } else {
  3343. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3344. }
  3345. goto matrix_success;
  3346. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3347. x->type = check_matrix_type_hint(y->type, type_hint);
  3348. return;
  3349. }
  3350. }
  3351. if (!are_types_identical(xt, yt)) {
  3352. goto matrix_error;
  3353. }
  3354. x->mode = Addressing_Value;
  3355. x->type = xt;
  3356. goto matrix_success;
  3357. }
  3358. matrix_success:
  3359. x->type = check_matrix_type_hint(x->type, type_hint);
  3360. return;
  3361. matrix_error:
  3362. gbString xts = type_to_string(x->type);
  3363. gbString yts = type_to_string(y->type);
  3364. gbString expr_str = expr_to_string(x->expr);
  3365. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3366. gb_string_free(expr_str);
  3367. gb_string_free(yts);
  3368. gb_string_free(xts);
  3369. x->type = t_invalid;
  3370. x->mode = Addressing_Invalid;
  3371. return;
  3372. }
  3373. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3374. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3375. Operand y_ = {}, *y = &y_;
  3376. ast_node(be, BinaryExpr, node);
  3377. defer({
  3378. node->viral_state_flags |= be->left->viral_state_flags;
  3379. node->viral_state_flags |= be->right->viral_state_flags;
  3380. });
  3381. Token op = be->op;
  3382. switch (op.kind) {
  3383. case Token_CmpEq:
  3384. case Token_NotEq: {
  3385. // NOTE(bill): Allow comparisons between types
  3386. if (is_ise_expr(be->left)) {
  3387. // Evalute the right before the left for an '.X' expression
  3388. check_expr_or_type(c, y, be->right, nullptr /* ignore type hint */);
  3389. check_expr_or_type(c, x, be->left, y->type);
  3390. } else {
  3391. check_expr_or_type(c, x, be->left, nullptr /* ignore type hint */);
  3392. check_expr_or_type(c, y, be->right, x->type);
  3393. }
  3394. bool xt = x->mode == Addressing_Type;
  3395. bool yt = y->mode == Addressing_Type;
  3396. // If only one is a type, this is an error
  3397. if (xt ^ yt) {
  3398. GB_ASSERT(xt != yt);
  3399. if (xt) {
  3400. if (!is_type_typeid(y->type)) {
  3401. error_operand_not_expression(x);
  3402. }
  3403. }
  3404. if (yt) {
  3405. if (!is_type_typeid(x->type)) {
  3406. error_operand_not_expression(y);
  3407. }
  3408. }
  3409. }
  3410. break;
  3411. }
  3412. case Token_in:
  3413. case Token_not_in:
  3414. {
  3415. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3416. check_expr(c, y, be->right);
  3417. Type *rhs_type = type_deref(y->type);
  3418. if (is_type_bit_set(rhs_type)) {
  3419. Type *elem = base_type(rhs_type)->BitSet.elem;
  3420. check_expr_with_type_hint(c, x, be->left, elem);
  3421. } else if (is_type_map(rhs_type)) {
  3422. Type *key = base_type(rhs_type)->Map.key;
  3423. check_expr_with_type_hint(c, x, be->left, key);
  3424. } else {
  3425. check_expr(c, x, be->left);
  3426. }
  3427. if (x->mode == Addressing_Invalid) {
  3428. return;
  3429. }
  3430. if (y->mode == Addressing_Invalid) {
  3431. x->mode = Addressing_Invalid;
  3432. x->expr = y->expr;
  3433. return;
  3434. }
  3435. if (is_type_map(rhs_type)) {
  3436. Type *yt = base_type(rhs_type);
  3437. if (op.kind == Token_in) {
  3438. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3439. } else {
  3440. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3441. }
  3442. add_map_get_dependencies(c);
  3443. } else if (is_type_bit_set(rhs_type)) {
  3444. Type *yt = base_type(rhs_type);
  3445. if (op.kind == Token_in) {
  3446. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3447. } else {
  3448. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3449. }
  3450. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3451. ExactValue k = exact_value_to_integer(x->value);
  3452. ExactValue v = exact_value_to_integer(y->value);
  3453. GB_ASSERT(k.kind == ExactValue_Integer);
  3454. GB_ASSERT(v.kind == ExactValue_Integer);
  3455. i64 key = big_int_to_i64(&k.value_integer);
  3456. i64 lower = yt->BitSet.lower;
  3457. i64 upper = yt->BitSet.upper;
  3458. if (lower <= key && key <= upper) {
  3459. i64 bit = 1ll<<key;
  3460. i64 bits = big_int_to_i64(&v.value_integer);
  3461. x->mode = Addressing_Constant;
  3462. x->type = t_untyped_bool;
  3463. if (op.kind == Token_in) {
  3464. x->value = exact_value_bool((bit & bits) != 0);
  3465. } else {
  3466. x->value = exact_value_bool((bit & bits) == 0);
  3467. }
  3468. x->expr = node;
  3469. return;
  3470. } else {
  3471. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3472. x->mode = Addressing_Invalid;
  3473. }
  3474. }
  3475. } else {
  3476. gbString t = type_to_string(y->type);
  3477. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3478. gb_string_free(t);
  3479. x->expr = node;
  3480. x->mode = Addressing_Invalid;
  3481. return;
  3482. }
  3483. if (x->mode != Addressing_Invalid) {
  3484. x->mode = Addressing_Value;
  3485. x->type = t_untyped_bool;
  3486. }
  3487. x->expr = node;
  3488. return;
  3489. }
  3490. default:
  3491. if (is_ise_expr(be->left)) {
  3492. // Evalute the right before the left for an '.X' expression
  3493. check_expr_or_type(c, y, be->right, type_hint);
  3494. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3495. check_expr_or_type(c, x, be->left, y->type);
  3496. } else {
  3497. check_expr_with_type_hint(c, x, be->left, type_hint);
  3498. }
  3499. } else {
  3500. check_expr_with_type_hint(c, x, be->left, type_hint);
  3501. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3502. check_expr_with_type_hint(c, y, be->right, x->type);
  3503. } else {
  3504. check_expr_with_type_hint(c, y, be->right, type_hint);
  3505. }
  3506. }
  3507. break;
  3508. }
  3509. if (x->mode == Addressing_Invalid) {
  3510. return;
  3511. }
  3512. if (y->mode == Addressing_Invalid) {
  3513. x->mode = Addressing_Invalid;
  3514. x->expr = y->expr;
  3515. return;
  3516. }
  3517. if (x->mode == Addressing_Builtin) {
  3518. x->mode = Addressing_Invalid;
  3519. error(x->expr, "built-in expression in binary expression");
  3520. return;
  3521. }
  3522. if (y->mode == Addressing_Builtin) {
  3523. x->mode = Addressing_Invalid;
  3524. error(y->expr, "built-in expression in binary expression");
  3525. return;
  3526. }
  3527. if (x->mode == Addressing_ProcGroup) {
  3528. x->mode = Addressing_Invalid;
  3529. if (x->proc_group != nullptr) {
  3530. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3531. } else {
  3532. error(x->expr, "procedure group used in binary expression");
  3533. }
  3534. return;
  3535. }
  3536. if (y->mode == Addressing_ProcGroup) {
  3537. x->mode = Addressing_Invalid;
  3538. if (x->proc_group != nullptr) {
  3539. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3540. } else {
  3541. error(y->expr, "procedure group used in binary expression");
  3542. }
  3543. return;
  3544. }
  3545. bool REQUIRE = true;
  3546. Type *bt = base_type(x->type);
  3547. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3548. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3549. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3550. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3551. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3552. }
  3553. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3554. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3555. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3556. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3557. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3558. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3559. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3560. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3561. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3562. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3563. }
  3564. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3565. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3566. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3567. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3568. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3569. case Basic_u128:
  3570. case Basic_i128:
  3571. if (is_arch_wasm()) {
  3572. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3573. }
  3574. break;
  3575. }
  3576. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3577. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3578. case Basic_u128:
  3579. case Basic_i128:
  3580. if (is_arch_wasm()) {
  3581. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3582. }
  3583. break;
  3584. }
  3585. } else if (op.kind == Token_Shr || op.kind == Token_ShrEq) {
  3586. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3587. case Basic_u128:
  3588. case Basic_i128:
  3589. if (is_arch_wasm()) {
  3590. add_package_dependency(c, "runtime", "__lshrti3", REQUIRE);
  3591. }
  3592. break;
  3593. }
  3594. }
  3595. if (token_is_shift(op.kind)) {
  3596. check_shift(c, x, y, node, type_hint);
  3597. return;
  3598. }
  3599. switch (op.kind) {
  3600. case Token_Quo:
  3601. case Token_Mod:
  3602. case Token_ModMod:
  3603. case Token_QuoEq:
  3604. case Token_ModEq:
  3605. case Token_ModModEq:
  3606. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3607. is_type_float(x->type) && is_type_untyped(x->type)) {
  3608. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3609. gbString t = type_to_string(y->type);
  3610. if (x->value.kind != ExactValue_Invalid) {
  3611. gbString s = exact_value_to_string(x->value);
  3612. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3613. gb_string_free(s);
  3614. } else {
  3615. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3616. }
  3617. gb_string_free(t);
  3618. }
  3619. break;
  3620. }
  3621. convert_to_typed(c, x, y->type);
  3622. if (x->mode == Addressing_Invalid) {
  3623. return;
  3624. }
  3625. convert_to_typed(c, y, x->type);
  3626. if (y->mode == Addressing_Invalid) {
  3627. x->mode = Addressing_Invalid;
  3628. return;
  3629. }
  3630. if (token_is_comparison(op.kind)) {
  3631. check_comparison(c, node, x, y, op.kind);
  3632. return;
  3633. }
  3634. if (check_binary_array_expr(c, op, x, y)) {
  3635. x->mode = Addressing_Value;
  3636. x->type = x->type;
  3637. return;
  3638. }
  3639. if (check_binary_array_expr(c, op, y, x)) {
  3640. x->mode = Addressing_Value;
  3641. x->type = y->type;
  3642. return;
  3643. }
  3644. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3645. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3646. x->expr = node;
  3647. return;
  3648. }
  3649. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3650. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3651. // NOTE(bill, 2022-06-26)
  3652. // Allow any boolean types within `&&` and `||`
  3653. // This is an exception to all other binary expressions since the result
  3654. // of a comparison will always be an untyped boolean, and allowing
  3655. // any boolean between these two simplifies a lot of expressions
  3656. } else if (!are_types_identical(x->type, y->type)) {
  3657. if (x->type != t_invalid &&
  3658. y->type != t_invalid) {
  3659. gbString xt = type_to_string(x->type);
  3660. gbString yt = type_to_string(y->type);
  3661. gbString expr_str = expr_to_string(node);
  3662. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3663. gb_string_free(expr_str);
  3664. gb_string_free(yt);
  3665. gb_string_free(xt);
  3666. }
  3667. x->mode = Addressing_Invalid;
  3668. return;
  3669. }
  3670. if (!check_binary_op(c, x, op)) {
  3671. x->mode = Addressing_Invalid;
  3672. return;
  3673. }
  3674. switch (op.kind) {
  3675. case Token_Quo:
  3676. case Token_Mod:
  3677. case Token_ModMod:
  3678. case Token_QuoEq:
  3679. case Token_ModEq:
  3680. case Token_ModModEq:
  3681. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3682. y->mode == Addressing_Constant) {
  3683. bool fail = false;
  3684. switch (y->value.kind) {
  3685. case ExactValue_Integer:
  3686. if (big_int_is_zero(&y->value.value_integer)) {
  3687. fail = true;
  3688. }
  3689. break;
  3690. case ExactValue_Float:
  3691. if (y->value.value_float == 0.0) {
  3692. fail = true;
  3693. }
  3694. break;
  3695. }
  3696. if (fail) {
  3697. error(y->expr, "Division by zero not allowed");
  3698. x->mode = Addressing_Invalid;
  3699. return;
  3700. }
  3701. }
  3702. break;
  3703. case Token_CmpAnd:
  3704. case Token_CmpOr:
  3705. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3706. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3707. }
  3708. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3709. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3710. }
  3711. break;
  3712. }
  3713. if (x->mode == Addressing_Constant &&
  3714. y->mode == Addressing_Constant) {
  3715. ExactValue a = x->value;
  3716. ExactValue b = y->value;
  3717. if (!is_type_constant_type(x->type)) {
  3718. x->mode = Addressing_Value;
  3719. return;
  3720. }
  3721. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3722. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3723. }
  3724. if (is_type_bit_set(x->type)) {
  3725. switch (op.kind) {
  3726. case Token_Add: op.kind = Token_Or; break;
  3727. case Token_Sub: op.kind = Token_AndNot; break;
  3728. }
  3729. }
  3730. x->value = exact_binary_operator_value(op.kind, a, b);
  3731. if (is_type_typed(x->type)) {
  3732. if (node != nullptr) {
  3733. x->expr = node;
  3734. }
  3735. check_is_expressible(c, x, x->type);
  3736. }
  3737. return;
  3738. } else if (is_type_string(x->type)) {
  3739. error(node, "String concatenation is only allowed with constant strings");
  3740. x->mode = Addressing_Invalid;
  3741. return;
  3742. }
  3743. x->mode = Addressing_Value;
  3744. }
  3745. gb_internal Operand make_operand_from_node(Ast *node) {
  3746. GB_ASSERT(node != nullptr);
  3747. Operand x = {};
  3748. x.expr = node;
  3749. x.mode = node->tav.mode;
  3750. x.type = node->tav.type;
  3751. x.value = node->tav.value;
  3752. return x;
  3753. }
  3754. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3755. GB_ASSERT(e != nullptr);
  3756. ExprInfo *old = check_get_expr_info(c, e);
  3757. if (old == nullptr) {
  3758. if (type != nullptr && type != t_invalid) {
  3759. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3760. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3761. if (e->kind == Ast_TernaryIfExpr) {
  3762. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3763. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3764. }
  3765. }
  3766. }
  3767. return;
  3768. }
  3769. switch (e->kind) {
  3770. case_ast_node(ue, UnaryExpr, e);
  3771. if (old->value.kind != ExactValue_Invalid) {
  3772. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3773. // They don't need to be updated as they will be updated later and
  3774. // checked at the end of general checking stage.
  3775. break;
  3776. }
  3777. update_untyped_expr_type(c, ue->expr, type, final);
  3778. case_end;
  3779. case_ast_node(be, BinaryExpr, e);
  3780. if (old->value.kind != ExactValue_Invalid) {
  3781. // See above note in UnaryExpr case
  3782. break;
  3783. }
  3784. if (token_is_comparison(be->op.kind)) {
  3785. // NOTE(bill): Do nothing as the types are fine
  3786. } else if (token_is_shift(be->op.kind)) {
  3787. update_untyped_expr_type(c, be->left, type, final);
  3788. } else {
  3789. update_untyped_expr_type(c, be->left, type, final);
  3790. update_untyped_expr_type(c, be->right, type, final);
  3791. }
  3792. case_end;
  3793. case_ast_node(te, TernaryIfExpr, e);
  3794. if (old->value.kind != ExactValue_Invalid) {
  3795. // See above note in UnaryExpr case
  3796. break;
  3797. }
  3798. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3799. // having an untyped value
  3800. Operand x = make_operand_from_node(te->x);
  3801. Operand y = make_operand_from_node(te->y);
  3802. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3803. update_untyped_expr_type(c, te->x, type, final);
  3804. }
  3805. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3806. update_untyped_expr_type(c, te->y, type, final);
  3807. }
  3808. case_end;
  3809. case_ast_node(te, TernaryWhenExpr, e);
  3810. if (old->value.kind != ExactValue_Invalid) {
  3811. // See above note in UnaryExpr case
  3812. break;
  3813. }
  3814. update_untyped_expr_type(c, te->x, type, final);
  3815. update_untyped_expr_type(c, te->y, type, final);
  3816. case_end;
  3817. case_ast_node(ore, OrReturnExpr, e);
  3818. if (old->value.kind != ExactValue_Invalid) {
  3819. // See above note in UnaryExpr case
  3820. break;
  3821. }
  3822. update_untyped_expr_type(c, ore->expr, type, final);
  3823. case_end;
  3824. case_ast_node(obe, OrBranchExpr, e);
  3825. if (old->value.kind != ExactValue_Invalid) {
  3826. // See above note in UnaryExpr case
  3827. break;
  3828. }
  3829. update_untyped_expr_type(c, obe->expr, type, final);
  3830. case_end;
  3831. case_ast_node(oee, OrElseExpr, e);
  3832. if (old->value.kind != ExactValue_Invalid) {
  3833. // See above note in UnaryExpr case
  3834. break;
  3835. }
  3836. update_untyped_expr_type(c, oee->x, type, final);
  3837. update_untyped_expr_type(c, oee->y, type, final);
  3838. case_end;
  3839. case_ast_node(pe, ParenExpr, e);
  3840. update_untyped_expr_type(c, pe->expr, type, final);
  3841. case_end;
  3842. }
  3843. if (!final && is_type_untyped(type)) {
  3844. old->type = base_type(type);
  3845. return;
  3846. }
  3847. // We need to remove it and then give it a new one
  3848. check_remove_expr_info(c, e);
  3849. if (old->is_lhs && !is_type_integer(type)) {
  3850. gbString expr_str = expr_to_string(e);
  3851. gbString type_str = type_to_string(type);
  3852. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3853. gb_string_free(type_str);
  3854. gb_string_free(expr_str);
  3855. return;
  3856. }
  3857. add_type_and_value(c, e, old->mode, type, old->value);
  3858. }
  3859. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3860. GB_ASSERT(e != nullptr);
  3861. ExprInfo *found = check_get_expr_info(c, e);
  3862. if (found) {
  3863. found->value = value;
  3864. }
  3865. }
  3866. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type, bool ignore_error_block=false) {
  3867. gbString expr_str = expr_to_string(operand->expr);
  3868. gbString type_str = type_to_string(target_type);
  3869. gbString from_type_str = type_to_string(operand->type);
  3870. char const *extra_text = "";
  3871. if (operand->mode == Addressing_Constant) {
  3872. if (big_int_is_zero(&operand->value.value_integer)) {
  3873. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3874. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3875. extra_text = " - Did you want 'nil'?";
  3876. }
  3877. }
  3878. }
  3879. if (!ignore_error_block) {
  3880. begin_error_block();
  3881. }
  3882. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3883. if (operand->value.kind == ExactValue_String) {
  3884. String key = operand->value.value_string;
  3885. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3886. Type *et = base_type(target_type);
  3887. check_did_you_mean_type(key, et->Enum.fields, ".");
  3888. }
  3889. }
  3890. gb_string_free(from_type_str);
  3891. gb_string_free(type_str);
  3892. gb_string_free(expr_str);
  3893. operand->mode = Addressing_Invalid;
  3894. if (!ignore_error_block) {
  3895. end_error_block();
  3896. }
  3897. }
  3898. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3899. Type *t = core_type(type);
  3900. if (is_type_boolean(t)) {
  3901. // v = exact_value_to_boolean(v);
  3902. } else if (is_type_float(t)) {
  3903. v = exact_value_to_float(v);
  3904. } else if (is_type_integer(t)) {
  3905. v = exact_value_to_integer(v);
  3906. } else if (is_type_pointer(t)) {
  3907. v = exact_value_to_integer(v);
  3908. } else if (is_type_complex(t)) {
  3909. v = exact_value_to_complex(v);
  3910. } else if (is_type_quaternion(t)) {
  3911. v = exact_value_to_quaternion(v);
  3912. }
  3913. return v;
  3914. }
  3915. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3916. GB_ASSERT_NOT_NULL(target_type);
  3917. if (operand->mode == Addressing_Invalid ||
  3918. operand->mode == Addressing_Type ||
  3919. is_type_typed(operand->type) ||
  3920. target_type == t_invalid) {
  3921. return;
  3922. }
  3923. if (is_type_untyped(target_type)) {
  3924. GB_ASSERT(operand->type->kind == Type_Basic);
  3925. GB_ASSERT(target_type->kind == Type_Basic);
  3926. BasicKind x_kind = operand->type->Basic.kind;
  3927. BasicKind y_kind = target_type->Basic.kind;
  3928. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3929. if (x_kind < y_kind) {
  3930. operand->type = target_type;
  3931. update_untyped_expr_type(c, operand->expr, target_type, false);
  3932. }
  3933. } else if (x_kind != y_kind) {
  3934. operand->mode = Addressing_Invalid;
  3935. convert_untyped_error(c, operand, target_type);
  3936. return;
  3937. }
  3938. return;
  3939. }
  3940. Type *t = base_type(target_type);
  3941. if (c->in_enum_type) {
  3942. t = core_type(target_type);
  3943. }
  3944. switch (t->kind) {
  3945. case Type_Basic:
  3946. if (operand->mode == Addressing_Constant) {
  3947. check_is_expressible(c, operand, t);
  3948. if (operand->mode == Addressing_Invalid) {
  3949. return;
  3950. }
  3951. update_untyped_expr_value(c, operand->expr, operand->value);
  3952. } else {
  3953. switch (operand->type->Basic.kind) {
  3954. case Basic_UntypedBool:
  3955. if (!is_type_boolean(target_type) &&
  3956. !is_type_integer(target_type)) {
  3957. operand->mode = Addressing_Invalid;
  3958. convert_untyped_error(c, operand, target_type);
  3959. return;
  3960. }
  3961. break;
  3962. case Basic_UntypedInteger:
  3963. case Basic_UntypedFloat:
  3964. case Basic_UntypedComplex:
  3965. case Basic_UntypedQuaternion:
  3966. case Basic_UntypedRune:
  3967. if (!is_type_numeric(target_type)) {
  3968. operand->mode = Addressing_Invalid;
  3969. convert_untyped_error(c, operand, target_type);
  3970. return;
  3971. }
  3972. break;
  3973. case Basic_UntypedNil:
  3974. if (is_type_any(target_type)) {
  3975. // target_type = t_untyped_nil;
  3976. } else if (is_type_cstring(target_type)) {
  3977. // target_type = t_untyped_nil;
  3978. } else if (!type_has_nil(target_type)) {
  3979. operand->mode = Addressing_Invalid;
  3980. convert_untyped_error(c, operand, target_type);
  3981. return;
  3982. }
  3983. break;
  3984. }
  3985. }
  3986. break;
  3987. case Type_Array: {
  3988. Type *elem = base_array_type(t);
  3989. if (check_is_assignable_to(c, operand, elem)) {
  3990. operand->mode = Addressing_Value;
  3991. } else {
  3992. if (operand->value.kind == ExactValue_String) {
  3993. String s = operand->value.value_string;
  3994. if (is_type_u8_array(t)) {
  3995. if (s.len == t->Array.count) {
  3996. break;
  3997. }
  3998. } else if (is_type_rune_array(t)) {
  3999. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  4000. if (rune_count == t->Array.count) {
  4001. break;
  4002. }
  4003. }
  4004. }
  4005. operand->mode = Addressing_Invalid;
  4006. convert_untyped_error(c, operand, target_type);
  4007. return;
  4008. }
  4009. break;
  4010. }
  4011. case Type_Matrix: {
  4012. Type *elem = base_array_type(t);
  4013. if (check_is_assignable_to(c, operand, elem)) {
  4014. if (t->Matrix.row_count != t->Matrix.column_count) {
  4015. operand->mode = Addressing_Invalid;
  4016. ERROR_BLOCK();
  4017. convert_untyped_error(c, operand, target_type, true);
  4018. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  4019. return;
  4020. } else {
  4021. operand->mode = Addressing_Value;
  4022. }
  4023. } else {
  4024. operand->mode = Addressing_Invalid;
  4025. convert_untyped_error(c, operand, target_type);
  4026. return;
  4027. }
  4028. break;
  4029. }
  4030. case Type_Union:
  4031. // IMPORTANT NOTE HACK(bill): This is just to allow for comparisons against `0` with the `os.Error` type
  4032. // as a kind of transition period
  4033. if (!build_context.strict_style &&
  4034. operand->mode == Addressing_Constant &&
  4035. target_type->kind == Type_Named &&
  4036. (c->pkg == nullptr || c->pkg->name != "os") &&
  4037. target_type->Named.name == "Error") {
  4038. Entity *e = target_type->Named.type_name;
  4039. if (e->pkg && e->pkg->name == "os") {
  4040. if (is_exact_value_zero(operand->value) &&
  4041. (operand->value.kind == ExactValue_Integer ||
  4042. operand->value.kind == ExactValue_Float)) {
  4043. operand->mode = Addressing_Value;
  4044. target_type = t_untyped_nil;
  4045. operand->value = empty_exact_value;
  4046. update_untyped_expr_value(c, operand->expr, operand->value);
  4047. break;
  4048. }
  4049. }
  4050. }
  4051. // "fallthrough"
  4052. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  4053. TEMPORARY_ALLOCATOR_GUARD();
  4054. isize count = t->Union.variants.count;
  4055. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  4056. isize valid_count = 0;
  4057. isize first_success_index = -1;
  4058. for_array(i, t->Union.variants) {
  4059. Type *vt = t->Union.variants[i];
  4060. i64 score = 0;
  4061. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  4062. valids[valid_count].index = i;
  4063. valids[valid_count].score = score;
  4064. valid_count += 1;
  4065. if (first_success_index < 0) {
  4066. first_success_index = i;
  4067. }
  4068. }
  4069. }
  4070. if (valid_count > 1) {
  4071. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  4072. i64 best_score = valids[0].score;
  4073. for (isize i = 1; i < valid_count; i++) {
  4074. auto v = valids[i];
  4075. if (best_score > v.score) {
  4076. valid_count = i;
  4077. break;
  4078. }
  4079. best_score = v.score;
  4080. }
  4081. first_success_index = valids[0].index;
  4082. }
  4083. gbString type_str = type_to_string(target_type);
  4084. defer (gb_string_free(type_str));
  4085. if (valid_count == 1) {
  4086. Type *new_type = t->Union.variants[first_success_index];
  4087. target_type = new_type;
  4088. if (is_type_union(new_type)) {
  4089. convert_to_typed(c, operand, new_type);
  4090. break;
  4091. }
  4092. operand->type = new_type;
  4093. operand->mode = Addressing_Value;
  4094. break;
  4095. } else if (valid_count > 1) {
  4096. ERROR_BLOCK();
  4097. GB_ASSERT(first_success_index >= 0);
  4098. operand->mode = Addressing_Invalid;
  4099. convert_untyped_error(c, operand, target_type, true);
  4100. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  4101. i32 j = 0;
  4102. for (i32 i = 0; i < valid_count; i++) {
  4103. ValidIndexAndScore valid = valids[i];
  4104. if (j > 0 && valid_count > 2) error_line(", ");
  4105. if (j == valid_count-1) {
  4106. if (valid_count == 2) error_line(" ");
  4107. error_line("or ");
  4108. }
  4109. gbString str = type_to_string(t->Union.variants[valid.index]);
  4110. error_line("'%s'", str);
  4111. gb_string_free(str);
  4112. j++;
  4113. }
  4114. error_line("\n\n");
  4115. return;
  4116. } else if (is_type_untyped_uninit(operand->type)) {
  4117. target_type = t_untyped_uninit;
  4118. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  4119. ERROR_BLOCK();
  4120. operand->mode = Addressing_Invalid;
  4121. convert_untyped_error(c, operand, target_type, true);
  4122. if (count > 0) {
  4123. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  4124. error_line("\t");
  4125. for (i32 i = 0; i < count; i++) {
  4126. Type *v = t->Union.variants[i];
  4127. if (i > 0 && count > 2) error_line(", ");
  4128. if (i == count-1) {
  4129. if (count == 2) error_line(" ");
  4130. if (count > 1) {
  4131. error_line("or ");
  4132. }
  4133. }
  4134. gbString str = type_to_string(v);
  4135. error_line("'%s'", str);
  4136. gb_string_free(str);
  4137. }
  4138. error_line("\n\n");
  4139. }
  4140. return;
  4141. }
  4142. }
  4143. /* fallthrough */
  4144. default:
  4145. if (is_type_untyped_uninit(operand->type)) {
  4146. target_type = t_untyped_uninit;
  4147. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  4148. target_type = t_untyped_nil;
  4149. } else {
  4150. operand->mode = Addressing_Invalid;
  4151. convert_untyped_error(c, operand, target_type);
  4152. return;
  4153. }
  4154. break;
  4155. }
  4156. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  4157. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  4158. } else {
  4159. target_type = default_type(operand->type);
  4160. }
  4161. }
  4162. update_untyped_expr_type(c, operand->expr, target_type, true);
  4163. operand->type = target_type;
  4164. }
  4165. gb_internal bool check_index_value(CheckerContext *c, Type *main_type, bool open_range, Ast *index_value, i64 max_count, i64 *value, Type *type_hint=nullptr) {
  4166. Operand operand = {Addressing_Invalid};
  4167. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  4168. if (operand.mode == Addressing_Invalid) {
  4169. if (value) *value = 0;
  4170. // NOTE(bill): return true here to propagate the errors better
  4171. return true;
  4172. }
  4173. Type *index_type = t_int;
  4174. if (type_hint != nullptr) {
  4175. index_type = type_hint;
  4176. }
  4177. convert_to_typed(c, &operand, index_type);
  4178. if (operand.mode == Addressing_Invalid) {
  4179. if (value) *value = 0;
  4180. return false;
  4181. }
  4182. if (type_hint != nullptr) {
  4183. if (!check_is_assignable_to(c, &operand, type_hint)) {
  4184. gbString expr_str = expr_to_string(operand.expr);
  4185. gbString index_type_str = type_to_string(type_hint);
  4186. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  4187. gb_string_free(index_type_str);
  4188. gb_string_free(expr_str);
  4189. if (value) *value = 0;
  4190. return false;
  4191. }
  4192. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  4193. gbString expr_str = expr_to_string(operand.expr);
  4194. gbString type_str = type_to_string(operand.type);
  4195. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  4196. gb_string_free(type_str);
  4197. gb_string_free(expr_str);
  4198. if (value) *value = 0;
  4199. return false;
  4200. }
  4201. if (operand.mode == Addressing_Constant &&
  4202. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  4203. BigInt i = exact_value_to_integer(operand.value).value_integer;
  4204. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  4205. TEMPORARY_ALLOCATOR_GUARD();
  4206. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4207. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4208. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  4209. if (value) *value = 0;
  4210. return false;
  4211. }
  4212. if (max_count >= 0) {
  4213. if (is_type_enum(index_type)) {
  4214. Type *bt = base_type(index_type);
  4215. GB_ASSERT(bt->kind == Type_Enum);
  4216. ExactValue const &lo = *bt->Enum.min_value;
  4217. ExactValue const &hi = *bt->Enum.max_value;
  4218. String lo_str = {};
  4219. String hi_str = {};
  4220. if (bt->Enum.fields.count > 0) {
  4221. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  4222. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  4223. lo_str = bt->Enum.fields[lo_idx]->token.string;
  4224. hi_str = bt->Enum.fields[hi_idx]->token.string;
  4225. }
  4226. bool out_of_bounds = false;
  4227. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  4228. out_of_bounds = true;
  4229. }
  4230. if (out_of_bounds) {
  4231. gbString expr_str = expr_to_string(operand.expr);
  4232. if (lo_str.len > 0) {
  4233. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  4234. } else {
  4235. gbString index_type_str = type_to_string(index_type);
  4236. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  4237. gb_string_free(index_type_str);
  4238. }
  4239. gb_string_free(expr_str);
  4240. return false;
  4241. }
  4242. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  4243. return true;
  4244. } else { // NOTE(bill): Do array bound checking
  4245. i64 v = -1;
  4246. if (i.used <= 1) {
  4247. v = big_int_to_i64(&i);
  4248. }
  4249. if (value) *value = v;
  4250. bool out_of_bounds = false;
  4251. if (v < 0) {
  4252. out_of_bounds = true;
  4253. } else if (open_range) {
  4254. out_of_bounds = v > max_count;
  4255. } else {
  4256. out_of_bounds = v >= max_count;
  4257. }
  4258. if (out_of_bounds) {
  4259. TEMPORARY_ALLOCATOR_GUARD();
  4260. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4261. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4262. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  4263. return false;
  4264. }
  4265. return true;
  4266. }
  4267. } else {
  4268. if (value) *value = exact_value_to_i64(operand.value);
  4269. return true;
  4270. }
  4271. }
  4272. // NOTE(bill): It's alright :D
  4273. if (value) *value = -1;
  4274. return true;
  4275. }
  4276. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  4277. if (value.kind == ExactValue_String) {
  4278. GB_ASSERT(0 <= index && index < value.value_string.len);
  4279. u8 val = value.value_string[index];
  4280. if (success_) *success_ = true;
  4281. if (finish_) *finish_ = true;
  4282. return exact_value_u64(val);
  4283. }
  4284. if (value.kind != ExactValue_Compound) {
  4285. if (success_) *success_ = true;
  4286. if (finish_) *finish_ = true;
  4287. return value;
  4288. }
  4289. Ast *node = value.value_compound;
  4290. switch (node->kind) {
  4291. case_ast_node(cl, CompoundLit, node);
  4292. if (cl->elems.count == 0) {
  4293. if (success_) *success_ = true;
  4294. if (finish_) *finish_ = true;
  4295. return empty_exact_value;
  4296. }
  4297. if (cl->elems[0]->kind == Ast_FieldValue) {
  4298. if (is_type_struct(node->tav.type)) {
  4299. bool found = false;
  4300. for (Ast *elem : cl->elems) {
  4301. if (elem->kind != Ast_FieldValue) {
  4302. continue;
  4303. }
  4304. ast_node(fv, FieldValue, elem);
  4305. String name = fv->field->Ident.token.string;
  4306. Selection sub_sel = lookup_field(node->tav.type, name, false);
  4307. defer (array_free(&sub_sel.index));
  4308. if (sub_sel.index.count > 0 &&
  4309. sub_sel.index[0] == index) {
  4310. value = fv->value->tav.value;
  4311. found = true;
  4312. break;
  4313. }
  4314. }
  4315. if (!found) {
  4316. // Use the zero value if it is not found
  4317. value = {};
  4318. }
  4319. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4320. for (Ast *elem : cl->elems) {
  4321. if (elem->kind != Ast_FieldValue) {
  4322. continue;
  4323. }
  4324. ast_node(fv, FieldValue, elem);
  4325. if (is_ast_range(fv->field)) {
  4326. ast_node(ie, BinaryExpr, fv->field);
  4327. TypeAndValue lo_tav = ie->left->tav;
  4328. TypeAndValue hi_tav = ie->right->tav;
  4329. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4330. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4331. TokenKind op = ie->op.kind;
  4332. i64 lo = exact_value_to_i64(lo_tav.value);
  4333. i64 hi = exact_value_to_i64(hi_tav.value);
  4334. i64 corrected_index = index;
  4335. if (is_type_enumerated_array(node->tav.type)) {
  4336. Type *bt = base_type(node->tav.type);
  4337. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4338. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4339. }
  4340. if (op != Token_RangeHalf) {
  4341. if (lo <= corrected_index && corrected_index <= hi) {
  4342. TypeAndValue tav = fv->value->tav;
  4343. if (success_) *success_ = true;
  4344. if (finish_) *finish_ = false;
  4345. return tav.value;
  4346. }
  4347. } else {
  4348. if (lo <= corrected_index && corrected_index < hi) {
  4349. TypeAndValue tav = fv->value->tav;
  4350. if (success_) *success_ = true;
  4351. if (finish_) *finish_ = false;
  4352. return tav.value;
  4353. }
  4354. }
  4355. } else {
  4356. TypeAndValue index_tav = fv->field->tav;
  4357. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4358. ExactValue index_value = index_tav.value;
  4359. if (is_type_enumerated_array(node->tav.type)) {
  4360. Type *bt = base_type(node->tav.type);
  4361. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4362. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4363. }
  4364. i64 field_index = exact_value_to_i64(index_value);
  4365. if (index == field_index) {
  4366. TypeAndValue tav = fv->value->tav;
  4367. if (success_) *success_ = true;
  4368. if (finish_) *finish_ = false;
  4369. return tav.value;
  4370. }
  4371. }
  4372. }
  4373. }
  4374. } else {
  4375. i32 count = (i32)cl->elems.count;
  4376. if (count < index) {
  4377. if (success_) *success_ = false;
  4378. if (finish_) *finish_ = true;
  4379. return empty_exact_value;
  4380. }
  4381. if (cl->elems.count <= index) {
  4382. if (success_) *success_ = false;
  4383. if (finish_) *finish_ = false;
  4384. return value;
  4385. }
  4386. TypeAndValue tav = cl->elems[index]->tav;
  4387. if (tav.mode == Addressing_Constant) {
  4388. if (success_) *success_ = true;
  4389. if (finish_) *finish_ = false;
  4390. return tav.value;
  4391. } else {
  4392. GB_ASSERT(is_type_untyped_nil(tav.type));
  4393. if (success_) *success_ = true;
  4394. if (finish_) *finish_ = false;
  4395. return tav.value;
  4396. }
  4397. }
  4398. case_end;
  4399. default:
  4400. if (success_) *success_ = true;
  4401. if (finish_) *finish_ = true;
  4402. return empty_exact_value;
  4403. }
  4404. if (finish_) *finish_ = false;
  4405. return value;
  4406. }
  4407. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4408. if (operand->mode != Addressing_Constant) {
  4409. if (success_) *success_ = false;
  4410. return empty_exact_value;
  4411. }
  4412. if (sel.indirect) {
  4413. if (success_) *success_ = false;
  4414. return empty_exact_value;
  4415. }
  4416. if (sel.index.count == 0) {
  4417. if (success_) *success_ = false;
  4418. return empty_exact_value;
  4419. }
  4420. ExactValue value = operand->value;
  4421. if (value.kind == ExactValue_Compound) {
  4422. while (sel.index.count > 0) {
  4423. i32 index = sel.index[0];
  4424. sel = sub_selection(sel, 1);
  4425. bool finish = false;
  4426. value = get_constant_field_single(c, value, index, success_, &finish);
  4427. if (finish) {
  4428. return value;
  4429. }
  4430. }
  4431. if (success_) *success_ = true;
  4432. return value;
  4433. } else if (value.kind == ExactValue_Quaternion) {
  4434. // @QuaternionLayout
  4435. Quaternion256 q = *value.value_quaternion;
  4436. GB_ASSERT(sel.index.count == 1);
  4437. switch (sel.index[0]) {
  4438. case 3: // w
  4439. if (success_) *success_ = true;
  4440. return exact_value_float(q.real);
  4441. case 0: // x
  4442. if (success_) *success_ = true;
  4443. return exact_value_float(q.imag);
  4444. case 1: // y
  4445. if (success_) *success_ = true;
  4446. return exact_value_float(q.jmag);
  4447. case 2: // z
  4448. if (success_) *success_ = true;
  4449. return exact_value_float(q.kmag);
  4450. }
  4451. if (success_) *success_ = false;
  4452. return empty_exact_value;
  4453. } else if (value.kind == ExactValue_Complex) {
  4454. // @QuaternionLayout
  4455. Complex128 c = *value.value_complex;
  4456. GB_ASSERT(sel.index.count == 1);
  4457. switch (sel.index[0]) {
  4458. case 0: // real
  4459. if (success_) *success_ = true;
  4460. return exact_value_float(c.real);
  4461. case 1: // imag
  4462. if (success_) *success_ = true;
  4463. return exact_value_float(c.imag);
  4464. }
  4465. if (success_) *success_ = false;
  4466. return empty_exact_value;
  4467. }
  4468. if (success_) *success_ = true;
  4469. return empty_exact_value;
  4470. }
  4471. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4472. Type *array_type = base_type(type_deref(original_type));
  4473. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4474. if (array_type->kind == Type_SimdVector) {
  4475. Type *elem_type = array_type->SimdVector.elem;
  4476. return alloc_type_simd_vector(new_count, elem_type);
  4477. }
  4478. Type *elem_type = array_type->Array.elem;
  4479. Type *swizzle_array_type = nullptr;
  4480. Type *bth = base_type(type_deref(type_hint));
  4481. if (bth != nullptr && bth->kind == Type_Array &&
  4482. bth->Array.count == new_count &&
  4483. are_types_identical(bth->Array.elem, elem_type)) {
  4484. swizzle_array_type = type_hint;
  4485. } else {
  4486. i64 max_count = array_type->Array.count;
  4487. if (new_count == max_count) {
  4488. swizzle_array_type = original_type;
  4489. } else {
  4490. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4491. }
  4492. }
  4493. return swizzle_array_type;
  4494. }
  4495. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4496. bool is_declared = entity != nullptr;
  4497. if (is_declared) {
  4498. if (entity->kind == Entity_Builtin) {
  4499. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4500. // This means that we should just ignore the found result through it
  4501. *allow_builtin = entity->scope == import_scope ||
  4502. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4503. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4504. is_declared = false;
  4505. }
  4506. }
  4507. return is_declared;
  4508. }
  4509. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4510. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4511. if (node == nullptr) {
  4512. return nullptr;
  4513. }
  4514. /*if (node->kind == Ast_TernaryWhenExpr) {
  4515. ast_node(we, TernaryWhenExpr, node);
  4516. if (we->cond == nullptr) {
  4517. return nullptr;
  4518. }
  4519. if (we->cond->tav.mode != Addressing_Constant) {
  4520. return nullptr;
  4521. }
  4522. if (we->cond->tav.value.kind != ExactValue_Bool) {
  4523. return nullptr;
  4524. }
  4525. if (we->cond->tav.value.value_bool) {
  4526. return check_entity_from_ident_or_selector(c, we->x, ident_only);
  4527. } else {
  4528. Entity *e = check_entity_from_ident_or_selector(c, we->y, ident_only);
  4529. return e;
  4530. }
  4531. } else */if (node->kind == Ast_Ident) {
  4532. String name = node->Ident.token.string;
  4533. return scope_lookup(c->scope, name);
  4534. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4535. ast_node(se, SelectorExpr, node);
  4536. if (se->token.kind == Token_ArrowRight) {
  4537. return nullptr;
  4538. }
  4539. Ast *op_expr = se->expr;
  4540. Ast *selector = unparen_expr(se->selector);
  4541. if (selector == nullptr) {
  4542. return nullptr;
  4543. }
  4544. if (selector->kind != Ast_Ident) {
  4545. return nullptr;
  4546. }
  4547. Entity *entity = nullptr;
  4548. Entity *expr_entity = nullptr;
  4549. bool check_op_expr = true;
  4550. if (op_expr->kind == Ast_Ident) {
  4551. String op_name = op_expr->Ident.token.string;
  4552. Entity *e = scope_lookup(c->scope, op_name);
  4553. if (e == nullptr) {
  4554. return nullptr;
  4555. }
  4556. add_entity_use(c, op_expr, e);
  4557. expr_entity = e;
  4558. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4559. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4560. // It pretty much needs to be in this order and this way
  4561. // If you can clean this up, please do but be really careful
  4562. String import_name = op_name;
  4563. Scope *import_scope = e->ImportName.scope;
  4564. String entity_name = selector->Ident.token.string;
  4565. check_op_expr = false;
  4566. entity = scope_lookup_current(import_scope, entity_name);
  4567. bool allow_builtin = false;
  4568. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4569. return nullptr;
  4570. }
  4571. check_entity_decl(c, entity, nullptr, nullptr);
  4572. if (entity->kind == Entity_ProcGroup) {
  4573. return entity;
  4574. }
  4575. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4576. }
  4577. }
  4578. Operand operand = {};
  4579. if (check_op_expr) {
  4580. check_expr_base(c, &operand, op_expr, nullptr);
  4581. if (operand.mode == Addressing_Invalid) {
  4582. return nullptr;
  4583. }
  4584. }
  4585. if (entity == nullptr && selector->kind == Ast_Ident) {
  4586. String field_name = selector->Ident.token.string;
  4587. if (is_type_dynamic_array(type_deref(operand.type))) {
  4588. init_mem_allocator(c->checker);
  4589. }
  4590. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4591. entity = sel.entity;
  4592. }
  4593. if (entity != nullptr) {
  4594. return entity;
  4595. }
  4596. }
  4597. return nullptr;
  4598. }
  4599. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4600. ast_node(se, SelectorExpr, node);
  4601. bool check_op_expr = true;
  4602. Entity *expr_entity = nullptr;
  4603. Entity *entity = nullptr;
  4604. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4605. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4606. ERROR_BLOCK();
  4607. error(node, "Illegal use of -> selector shorthand outside of a call");
  4608. gbString x = expr_to_string(se->expr);
  4609. gbString y = expr_to_string(se->selector);
  4610. error_line("\tSuggestion: Did you mean '%s.%s'?\n", x, y);
  4611. gb_string_free(y);
  4612. gb_string_free(x);
  4613. // TODO(bill): Should this terminate here or propagate onwards?
  4614. // operand->mode = Addressing_Invalid;
  4615. // operand->expr = node;
  4616. // return nullptr;
  4617. }
  4618. operand->expr = node;
  4619. Ast *op_expr = se->expr;
  4620. Ast *selector = unparen_expr(se->selector);
  4621. if (selector == nullptr) {
  4622. operand->mode = Addressing_Invalid;
  4623. operand->expr = node;
  4624. return nullptr;
  4625. }
  4626. if (selector->kind != Ast_Ident) {
  4627. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4628. operand->mode = Addressing_Invalid;
  4629. operand->expr = node;
  4630. return nullptr;
  4631. }
  4632. if (op_expr->kind == Ast_Ident) {
  4633. String op_name = op_expr->Ident.token.string;
  4634. Entity *e = scope_lookup(c->scope, op_name);
  4635. add_entity_use(c, op_expr, e);
  4636. expr_entity = e;
  4637. if (e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup) && selector->kind == Ast_Ident) {
  4638. gbString sel_str = expr_to_string(selector);
  4639. error(node, "'%s' is not declared by by '%.*s'", sel_str, LIT(e->token.string));
  4640. gb_string_free(sel_str);
  4641. operand->mode = Addressing_Invalid;
  4642. operand->expr = node;
  4643. return nullptr;
  4644. } else if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4645. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4646. // It pretty much needs to be in this order and this way
  4647. // If you can clean this up, please do but be really careful
  4648. String import_name = op_name;
  4649. Scope *import_scope = e->ImportName.scope;
  4650. String entity_name = selector->Ident.token.string;
  4651. if (import_scope == nullptr) {
  4652. ERROR_BLOCK();
  4653. error(node, "'%.*s' is not imported in this file, '%.*s' is unavailable", LIT(import_name), LIT(entity_name));
  4654. operand->mode = Addressing_Invalid;
  4655. operand->expr = node;
  4656. return nullptr;
  4657. }
  4658. check_op_expr = false;
  4659. entity = scope_lookup_current(import_scope, entity_name);
  4660. bool allow_builtin = false;
  4661. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4662. ERROR_BLOCK();
  4663. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4664. operand->mode = Addressing_Invalid;
  4665. operand->expr = node;
  4666. check_did_you_mean_scope(entity_name, import_scope);
  4667. return nullptr;
  4668. }
  4669. check_entity_decl(c, entity, nullptr, nullptr);
  4670. if (entity->kind == Entity_ProcGroup) {
  4671. operand->mode = Addressing_ProcGroup;
  4672. operand->proc_group = entity;
  4673. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4674. return entity;
  4675. }
  4676. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4677. if (!is_entity_exported(entity, allow_builtin)) {
  4678. gbString sel_str = expr_to_string(selector);
  4679. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4680. gb_string_free(sel_str);
  4681. // NOTE(bill): make the state valid still, even if it's "invalid"
  4682. // operand->mode = Addressing_Invalid;
  4683. // operand->expr = node;
  4684. // return nullptr;
  4685. }
  4686. if (entity->kind == Entity_ProcGroup) {
  4687. Array<Entity *> procs = entity->ProcGroup.entities;
  4688. bool skip = false;
  4689. for (Entity *p : procs) {
  4690. Type *t = base_type(p->type);
  4691. if (t == t_invalid) {
  4692. continue;
  4693. }
  4694. Operand x = {};
  4695. x.mode = Addressing_Value;
  4696. x.type = t;
  4697. if (type_hint != nullptr) {
  4698. if (check_is_assignable_to(c, &x, type_hint)) {
  4699. entity = p;
  4700. skip = true;
  4701. break;
  4702. }
  4703. }
  4704. }
  4705. if (!skip) {
  4706. GB_ASSERT(entity != nullptr);
  4707. operand->mode = Addressing_ProcGroup;
  4708. operand->type = t_invalid;
  4709. operand->expr = node;
  4710. operand->proc_group = entity;
  4711. return entity;
  4712. }
  4713. }
  4714. }
  4715. }
  4716. if (check_op_expr) {
  4717. check_expr_base(c, operand, op_expr, nullptr);
  4718. if (operand->mode == Addressing_Invalid) {
  4719. operand->mode = Addressing_Invalid;
  4720. operand->expr = node;
  4721. return nullptr;
  4722. }
  4723. }
  4724. if (operand->type && is_type_soa_struct(type_deref(operand->type))) {
  4725. complete_soa_type(c->checker, type_deref(operand->type), false);
  4726. }
  4727. if (entity == nullptr && selector->kind == Ast_Ident) {
  4728. String field_name = selector->Ident.token.string;
  4729. Type *t = type_deref(operand->type);
  4730. if (t == nullptr) {
  4731. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4732. } else if (is_type_dynamic_array(t)) {
  4733. init_mem_allocator(c->checker);
  4734. }
  4735. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4736. entity = sel.entity;
  4737. // NOTE(bill): Add type info needed for fields like 'names'
  4738. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4739. add_type_info_type(c, operand->type);
  4740. }
  4741. if (is_type_enum(operand->type)) {
  4742. add_type_info_type(c, operand->type);
  4743. }
  4744. }
  4745. if (entity == nullptr && selector->kind == Ast_Ident && (is_type_array(type_deref(operand->type)) || is_type_simd_vector(type_deref(operand->type)))) {
  4746. String field_name = selector->Ident.token.string;
  4747. if (1 < field_name.len && field_name.len <= 4) {
  4748. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4749. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4750. bool found_xyzw = false;
  4751. bool found_rgba = false;
  4752. for (isize i = 0; i < field_name.len; i++) {
  4753. bool valid = false;
  4754. for (isize j = 0; j < 4; j++) {
  4755. if (field_name.text[i] == swizzles_xyzw[j]) {
  4756. found_xyzw = true;
  4757. valid = true;
  4758. break;
  4759. }
  4760. if (field_name.text[i] == swizzles_rgba[j]) {
  4761. found_rgba = true;
  4762. valid = true;
  4763. break;
  4764. }
  4765. }
  4766. if (!valid) {
  4767. goto end_of_array_selector_swizzle;
  4768. }
  4769. }
  4770. u8 *swizzles = nullptr;
  4771. u8 index_count = cast(u8)field_name.len;
  4772. if (found_xyzw && found_rgba) {
  4773. gbString op_str = expr_to_string(op_expr);
  4774. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4775. gb_string_free(op_str);
  4776. operand->mode = Addressing_Invalid;
  4777. operand->expr = node;
  4778. return nullptr;
  4779. }
  4780. u8 indices = 0;
  4781. if (found_xyzw) {
  4782. swizzles = swizzles_xyzw;
  4783. } else if (found_rgba) {
  4784. swizzles = swizzles_rgba;
  4785. }
  4786. for (isize i = 0; i < field_name.len; i++) {
  4787. for (isize j = 0; j < 4; j++) {
  4788. if (field_name.text[i] == swizzles[j]) {
  4789. indices |= cast(u8)(j)<<(i*2);
  4790. break;
  4791. }
  4792. }
  4793. }
  4794. Type *original_type = operand->type;
  4795. Type *array_type = base_type(type_deref(original_type));
  4796. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4797. i64 array_count = get_array_type_count(array_type);
  4798. for (u8 i = 0; i < index_count; i++) {
  4799. u8 idx = indices>>(i*2) & 3;
  4800. if (idx >= array_count) {
  4801. char c = 0;
  4802. if (found_xyzw) {
  4803. c = swizzles_xyzw[idx];
  4804. } else if (found_rgba) {
  4805. c = swizzles_rgba[idx];
  4806. } else {
  4807. GB_PANIC("unknown swizzle kind");
  4808. }
  4809. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4810. break;
  4811. }
  4812. }
  4813. se->swizzle_count = index_count;
  4814. se->swizzle_indices = indices;
  4815. AddressingMode prev_mode = operand->mode;
  4816. operand->mode = Addressing_SwizzleValue;
  4817. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4818. operand->expr = node;
  4819. switch (prev_mode) {
  4820. case Addressing_Variable:
  4821. case Addressing_SoaVariable:
  4822. case Addressing_SwizzleVariable:
  4823. operand->mode = Addressing_SwizzleVariable;
  4824. break;
  4825. }
  4826. if (array_type->kind == Type_SimdVector) {
  4827. operand->mode = Addressing_Value;
  4828. }
  4829. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4830. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4831. return swizzle_entity;
  4832. }
  4833. end_of_array_selector_swizzle:;
  4834. }
  4835. if (entity == nullptr) {
  4836. gbString op_str = expr_to_string(op_expr);
  4837. gbString type_str = type_to_string_shorthand(operand->type);
  4838. gbString sel_str = expr_to_string(selector);
  4839. if (operand->mode == Addressing_Type) {
  4840. if (is_type_polymorphic(operand->type, true)) {
  4841. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4842. } else {
  4843. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4844. }
  4845. } else {
  4846. ERROR_BLOCK();
  4847. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4848. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4849. String const &name = selector->Ident.token.string;
  4850. Type *bt = base_type(operand->type);
  4851. if (operand->type->kind == Type_Named &&
  4852. operand->type->Named.type_name &&
  4853. operand->type->Named.type_name->kind == Entity_TypeName &&
  4854. operand->type->Named.type_name->TypeName.objc_metadata) {
  4855. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4856. } else if (bt->kind == Type_Struct) {
  4857. check_did_you_mean_type(name, bt->Struct.fields);
  4858. } else if (bt->kind == Type_Enum) {
  4859. check_did_you_mean_type(name, bt->Enum.fields);
  4860. }
  4861. }
  4862. }
  4863. gb_string_free(sel_str);
  4864. gb_string_free(type_str);
  4865. gb_string_free(op_str);
  4866. operand->mode = Addressing_Invalid;
  4867. operand->expr = node;
  4868. return nullptr;
  4869. }
  4870. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4871. bool success = false;
  4872. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4873. if (success) {
  4874. operand->mode = Addressing_Constant;
  4875. operand->expr = node;
  4876. operand->value = field_value;
  4877. operand->type = entity->type;
  4878. add_entity_use(c, selector, entity);
  4879. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4880. return entity;
  4881. }
  4882. gbString op_str = expr_to_string(op_expr);
  4883. gbString type_str = type_to_string_shorthand(operand->type);
  4884. gbString sel_str = expr_to_string(selector);
  4885. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4886. gb_string_free(sel_str);
  4887. gb_string_free(type_str);
  4888. gb_string_free(op_str);
  4889. operand->mode = Addressing_Invalid;
  4890. operand->expr = node;
  4891. return nullptr;
  4892. }
  4893. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4894. bool success = false;
  4895. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4896. if (success) {
  4897. operand->mode = Addressing_Constant;
  4898. operand->expr = node;
  4899. operand->value = field_value;
  4900. operand->type = entity->type;
  4901. add_entity_use(c, selector, entity);
  4902. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4903. return entity;
  4904. }
  4905. gbString op_str = expr_to_string(op_expr);
  4906. gbString type_str = type_to_string_shorthand(operand->type);
  4907. gbString sel_str = expr_to_string(selector);
  4908. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4909. gb_string_free(sel_str);
  4910. gb_string_free(type_str);
  4911. gb_string_free(op_str);
  4912. operand->mode = Addressing_Invalid;
  4913. operand->expr = node;
  4914. return nullptr;
  4915. }
  4916. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4917. gbString op_str = expr_to_string(op_expr);
  4918. gbString type_str = type_to_string_shorthand(operand->type);
  4919. gbString sel_str = expr_to_string(selector);
  4920. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4921. gb_string_free(sel_str);
  4922. gb_string_free(type_str);
  4923. gb_string_free(op_str);
  4924. operand->mode = Addressing_Invalid;
  4925. operand->expr = node;
  4926. return nullptr;
  4927. }
  4928. add_entity_use(c, selector, entity);
  4929. operand->type = entity->type;
  4930. operand->expr = node;
  4931. if (entity->flags & EntityFlag_BitFieldField) {
  4932. add_package_dependency(c, "runtime", "__write_bits");
  4933. add_package_dependency(c, "runtime", "__read_bits");
  4934. }
  4935. switch (entity->kind) {
  4936. case Entity_Constant:
  4937. operand->value = entity->Constant.value;
  4938. operand->mode = Addressing_Constant;
  4939. if (operand->value.kind == ExactValue_Procedure) {
  4940. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4941. if (proc != nullptr) {
  4942. operand->mode = Addressing_Value;
  4943. operand->type = proc->type;
  4944. }
  4945. }
  4946. break;
  4947. case Entity_Variable:
  4948. if (sel.is_bit_field) {
  4949. se->is_bit_field = true;
  4950. }
  4951. if (sel.indirect) {
  4952. operand->mode = Addressing_Variable;
  4953. } else if (operand->mode == Addressing_Context) {
  4954. // Do nothing
  4955. } else if (operand->mode == Addressing_MapIndex) {
  4956. operand->mode = Addressing_Value;
  4957. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4958. operand->mode = Addressing_SoaVariable;
  4959. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4960. operand->mode = Addressing_Value;
  4961. } else if (operand->mode == Addressing_SoaVariable) {
  4962. operand->mode = Addressing_Variable;
  4963. } else if (operand->mode != Addressing_Value) {
  4964. operand->mode = Addressing_Variable;
  4965. } else {
  4966. operand->mode = Addressing_Value;
  4967. }
  4968. break;
  4969. case Entity_TypeName:
  4970. operand->mode = Addressing_Type;
  4971. break;
  4972. case Entity_Procedure:
  4973. operand->mode = Addressing_Value;
  4974. operand->value = exact_value_procedure(node);
  4975. break;
  4976. case Entity_Builtin:
  4977. operand->mode = Addressing_Builtin;
  4978. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  4979. break;
  4980. case Entity_ProcGroup:
  4981. operand->mode = Addressing_ProcGroup;
  4982. operand->proc_group = entity;
  4983. break;
  4984. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  4985. case Entity_Nil:
  4986. operand->mode = Addressing_Value;
  4987. break;
  4988. }
  4989. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4990. return entity;
  4991. }
  4992. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  4993. ptr = base_type(ptr);
  4994. if (is_type_pointer(ptr)) {
  4995. if (is_type_rawptr(ptr)) {
  4996. return false;
  4997. }
  4998. if (elem) *elem = ptr->Pointer.elem;
  4999. return true;
  5000. }
  5001. return false;
  5002. }
  5003. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  5004. elem = core_type(elem);
  5005. if (is_type_internally_pointer_like(elem)) {
  5006. return true;
  5007. }
  5008. if (elem->kind == Type_BitSet) {
  5009. elem = bit_set_to_int(elem);
  5010. }
  5011. if (elem->kind != Type_Basic) {
  5012. return false;
  5013. }
  5014. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  5015. }
  5016. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  5017. switch (node->kind) {
  5018. case_ast_node(i, Ident, node);
  5019. String name = i->token.string;
  5020. if (nested) {
  5021. Entity *e = scope_lookup_current(s, name);
  5022. if (e != nullptr) {
  5023. if (out_scope) *out_scope = e->scope;
  5024. return true;
  5025. }
  5026. } else {
  5027. Entity *e = scope_lookup(s, name);
  5028. if (e != nullptr) {
  5029. if (out_scope) *out_scope = e->scope;
  5030. return true;
  5031. }
  5032. }
  5033. case_end;
  5034. case_ast_node(se, SelectorExpr, node);
  5035. Ast *lhs = se->expr;
  5036. Ast *rhs = se->selector;
  5037. Scope *lhs_scope = nullptr;
  5038. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  5039. return check_identifier_exists(lhs_scope, rhs, true);
  5040. }
  5041. case_end;
  5042. }
  5043. return false;
  5044. }
  5045. gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) {
  5046. if (o.type && is_type_no_copy(o.type)) {
  5047. Ast *expr = unparen_expr(o.expr);
  5048. if (expr && o.mode != Addressing_Constant && o.mode != Addressing_Type) {
  5049. if (expr->kind == Ast_CallExpr) {
  5050. // Okay
  5051. } else {
  5052. error(o.expr, "Invalid use of #no_copy value in %.*s", LIT(context));
  5053. return true;
  5054. }
  5055. }
  5056. }
  5057. return false;
  5058. }
  5059. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  5060. bool optional_ok = false;
  5061. isize tuple_index = 0;
  5062. for (Ast *rhs_expr : rhs) {
  5063. CheckerContext c_ = *ctx;
  5064. CheckerContext *c = &c_;
  5065. Operand o = {};
  5066. Type *type_hint = nullptr;
  5067. if (tuple_index < lhs.count) {
  5068. type_hint = lhs[tuple_index].type;
  5069. }
  5070. check_expr_base(c, &o, rhs_expr, type_hint);
  5071. if (o.mode == Addressing_NoValue) {
  5072. error_operand_no_value(&o);
  5073. o.mode = Addressing_Invalid;
  5074. }
  5075. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5076. if (lhs.count == 2 && rhs.count == 1 &&
  5077. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5078. Ast *expr = unparen_expr(o.expr);
  5079. Operand val0 = o;
  5080. Operand val1 = o;
  5081. val0.mode = Addressing_Value;
  5082. val1.mode = Addressing_Value;
  5083. val1.type = t_untyped_bool;
  5084. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5085. if (expr->kind == Ast_TypeAssertion &&
  5086. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5087. // NOTE(bill): Used only for optimizations in the backend
  5088. if (is_blank_ident(lhs[0].expr)) {
  5089. expr->TypeAssertion.ignores[0] = true;
  5090. }
  5091. if (is_blank_ident(lhs[1].expr)) {
  5092. expr->TypeAssertion.ignores[1] = true;
  5093. }
  5094. }
  5095. array_add(operands, val0);
  5096. array_add(operands, val1);
  5097. optional_ok = true;
  5098. tuple_index += 2;
  5099. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  5100. Type *tuple = o.type;
  5101. GB_ASSERT(tuple->Tuple.variables.count == 2);
  5102. Ast *expr = unparen_expr(o.expr);
  5103. if (expr->kind == Ast_CallExpr) {
  5104. expr->CallExpr.optional_ok_one = true;
  5105. }
  5106. Operand val = o;
  5107. val.type = tuple->Tuple.variables[0]->type;
  5108. val.mode = Addressing_Value;
  5109. array_add(operands, val);
  5110. tuple_index += tuple->Tuple.variables.count;
  5111. } else {
  5112. array_add(operands, o);
  5113. tuple_index += 1;
  5114. }
  5115. } else {
  5116. TypeTuple *tuple = &o.type->Tuple;
  5117. for (Entity *e : tuple->variables) {
  5118. o.type = e->type;
  5119. array_add(operands, o);
  5120. check_no_copy_assignment(o, str_lit("assignment"));
  5121. }
  5122. tuple_index += tuple->variables.count;
  5123. }
  5124. }
  5125. return optional_ok;
  5126. }
  5127. typedef u32 UnpackFlags;
  5128. enum UnpackFlag : u32 {
  5129. UnpackFlag_None = 0,
  5130. UnpackFlag_AllowOk = 1<<0,
  5131. UnpackFlag_IsVariadic = 1<<1,
  5132. UnpackFlag_AllowUndef = 1<<2,
  5133. };
  5134. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags) {
  5135. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  5136. if (lhs == nullptr || c->decl == nullptr) {
  5137. return tuple_count;
  5138. }
  5139. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  5140. Entity *e = lhs[tuple_index + j];
  5141. if (e == nullptr) {
  5142. continue;
  5143. }
  5144. DeclInfo *decl = decl_info_of_entity(e);
  5145. if (decl == nullptr) {
  5146. continue;
  5147. }
  5148. rw_mutex_shared_lock(&decl->deps_mutex);
  5149. rw_mutex_lock(&c->decl->deps_mutex);
  5150. for (Entity *dep : decl->deps) {
  5151. ptr_set_add(&c->decl->deps, dep);
  5152. }
  5153. rw_mutex_unlock(&c->decl->deps_mutex);
  5154. rw_mutex_shared_unlock(&decl->deps_mutex);
  5155. }
  5156. return tuple_count;
  5157. };
  5158. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  5159. bool is_variadic = (flags & UnpackFlag_IsVariadic) != 0;
  5160. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  5161. bool optional_ok = false;
  5162. isize tuple_index = 0;
  5163. for (Ast *rhs : rhs_arguments) {
  5164. if (rhs->kind == Ast_FieldValue) {
  5165. error(rhs, "Invalid use of 'field = value'");
  5166. rhs = rhs->FieldValue.value;
  5167. }
  5168. CheckerContext c_ = *ctx;
  5169. CheckerContext *c = &c_;
  5170. Operand o = {};
  5171. Type *type_hint = nullptr;
  5172. if (lhs != nullptr && tuple_index < lhs_count) {
  5173. // NOTE(bill): override DeclInfo for dependency
  5174. Entity *e = lhs[tuple_index];
  5175. if (e != nullptr) {
  5176. type_hint = e->type;
  5177. if (e->flags & EntityFlag_Ellipsis) {
  5178. GB_ASSERT(is_type_slice(e->type));
  5179. GB_ASSERT(e->type->kind == Type_Slice);
  5180. type_hint = e->type->Slice.elem;
  5181. }
  5182. }
  5183. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  5184. // NOTE(bill): override DeclInfo for dependency
  5185. Entity *e = lhs[lhs_count-1];
  5186. if (e != nullptr) {
  5187. type_hint = e->type;
  5188. if (e->flags & EntityFlag_Ellipsis) {
  5189. GB_ASSERT(is_type_slice(e->type));
  5190. GB_ASSERT(e->type->kind == Type_Slice);
  5191. type_hint = e->type->Slice.elem;
  5192. }
  5193. }
  5194. }
  5195. Ast *rhs_expr = unparen_expr(rhs);
  5196. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  5197. // NOTE(bill): Just handle this very specific logic here
  5198. o.type = t_untyped_uninit;
  5199. o.mode = Addressing_Value;
  5200. o.expr = rhs;
  5201. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  5202. } else {
  5203. check_expr_base(c, &o, rhs, type_hint);
  5204. }
  5205. if (o.mode == Addressing_NoValue) {
  5206. error_operand_no_value(&o);
  5207. o.mode = Addressing_Invalid;
  5208. }
  5209. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5210. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  5211. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5212. Ast *expr = unparen_expr(o.expr);
  5213. Operand val0 = o;
  5214. Operand val1 = o;
  5215. val0.mode = Addressing_Value;
  5216. val1.mode = Addressing_Value;
  5217. val1.type = t_untyped_bool;
  5218. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5219. if (expr->kind == Ast_TypeAssertion &&
  5220. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5221. // NOTE(bill): Used only for optimizations in the backend
  5222. if (is_blank_ident(lhs[0]->token)) {
  5223. expr->TypeAssertion.ignores[0] = true;
  5224. }
  5225. if (is_blank_ident(lhs[1]->token)) {
  5226. expr->TypeAssertion.ignores[1] = true;
  5227. }
  5228. }
  5229. array_add(operands, val0);
  5230. array_add(operands, val1);
  5231. optional_ok = true;
  5232. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  5233. } else {
  5234. array_add(operands, o);
  5235. tuple_index += 1;
  5236. }
  5237. } else {
  5238. TypeTuple *tuple = &o.type->Tuple;
  5239. for (Entity *e : tuple->variables) {
  5240. o.type = e->type;
  5241. array_add(operands, o);
  5242. }
  5243. isize count = tuple->variables.count;
  5244. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  5245. }
  5246. }
  5247. return optional_ok;
  5248. }
  5249. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  5250. GB_ASSERT(pt != nullptr);
  5251. GB_ASSERT(pt->kind == Type_Proc);
  5252. isize param_count = 0;
  5253. isize param_count_excluding_defaults = 0;
  5254. bool variadic = pt->Proc.variadic;
  5255. TypeTuple *param_tuple = nullptr;
  5256. if (pt->Proc.params != nullptr) {
  5257. param_tuple = &pt->Proc.params->Tuple;
  5258. param_count = param_tuple->variables.count;
  5259. if (variadic) {
  5260. for (isize i = param_count-1; i >= 0; i--) {
  5261. Entity *e = param_tuple->variables[i];
  5262. if (e->kind == Entity_TypeName) {
  5263. break;
  5264. }
  5265. if (e->kind == Entity_Variable) {
  5266. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5267. param_count--;
  5268. continue;
  5269. }
  5270. }
  5271. break;
  5272. }
  5273. param_count--;
  5274. }
  5275. }
  5276. param_count_excluding_defaults = param_count;
  5277. if (param_tuple != nullptr) {
  5278. for (isize i = param_count-1; i >= 0; i--) {
  5279. Entity *e = param_tuple->variables[i];
  5280. if (e->kind == Entity_TypeName) {
  5281. break;
  5282. }
  5283. if (e->kind == Entity_Variable) {
  5284. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5285. param_count_excluding_defaults--;
  5286. continue;
  5287. }
  5288. }
  5289. break;
  5290. }
  5291. }
  5292. if (param_count_) *param_count_ = param_count;
  5293. return param_count_excluding_defaults;
  5294. }
  5295. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  5296. isize param_count = pt->param_count;
  5297. for (isize i = 0; i < param_count; i++) {
  5298. Entity *e = pt->params->Tuple.variables[i];
  5299. String name = e->token.string;
  5300. if (is_blank_ident(name)) {
  5301. continue;
  5302. }
  5303. if (name == parameter_name) {
  5304. return i;
  5305. }
  5306. }
  5307. return -1;
  5308. }
  5309. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  5310. type = base_type(type);
  5311. GB_ASSERT(type->kind == Type_Proc);
  5312. return lookup_procedure_parameter(&type->Proc, parameter_name);
  5313. }
  5314. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  5315. Entity *entity, Type *proc_type,
  5316. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  5317. CallArgumentErrorMode show_error_mode,
  5318. CallArgumentData *data) {
  5319. TEMPORARY_ALLOCATOR_GUARD();
  5320. CallArgumentError err = CallArgumentError_None;
  5321. ast_node(ce, CallExpr, call);
  5322. GB_ASSERT(is_type_proc(proc_type));
  5323. proc_type = base_type(proc_type);
  5324. TypeProc *pt = &proc_type->Proc;
  5325. isize param_count = 0;
  5326. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  5327. bool variadic = pt->variadic;
  5328. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5329. i64 score = 0;
  5330. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  5331. Type *final_proc_type = proc_type;
  5332. Entity *gen_entity = nullptr;
  5333. if (vari_expand && !variadic) {
  5334. if (show_error) {
  5335. error(ce->ellipsis,
  5336. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  5337. LIT(ce->proc->Ident.token.string));
  5338. }
  5339. err = CallArgumentError_NonVariadicExpand;
  5340. } else if (vari_expand && pt->c_vararg) {
  5341. if (show_error) {
  5342. error(ce->ellipsis,
  5343. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  5344. LIT(ce->proc->Ident.token.string));
  5345. }
  5346. err = CallArgumentError_NonVariadicExpand;
  5347. }
  5348. GB_ASSERT(ce->split_args);
  5349. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  5350. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  5351. defer ({
  5352. for (Operand const &o : ordered_operands) {
  5353. if (o.expr != nullptr) {
  5354. call->viral_state_flags |= o.expr->viral_state_flags;
  5355. }
  5356. }
  5357. });
  5358. isize positional_operand_count = positional_operands.count;
  5359. if (variadic) {
  5360. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5361. } else if (positional_operand_count > pt->param_count) {
  5362. err = CallArgumentError_TooManyArguments;
  5363. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5364. if (show_error) {
  5365. gbString proc_str = expr_to_string(ce->proc);
  5366. defer (gb_string_free(proc_str));
  5367. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5368. }
  5369. return err;
  5370. }
  5371. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5372. for (isize i = 0; i < positional_operand_count; i++) {
  5373. ordered_operands[i] = positional_operands[i];
  5374. visited[i] = true;
  5375. }
  5376. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5377. bool named_variadic_param = false;
  5378. if (named_operands.count != 0) {
  5379. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5380. for_array(i, ce->split_args->named) {
  5381. Ast *arg = ce->split_args->named[i];
  5382. Operand operand = named_operands[i];
  5383. ast_node(fv, FieldValue, arg);
  5384. if (fv->field->kind != Ast_Ident) {
  5385. if (show_error) {
  5386. gbString expr_str = expr_to_string(fv->field);
  5387. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5388. gb_string_free(expr_str);
  5389. }
  5390. err = CallArgumentError_InvalidFieldValue;
  5391. continue;
  5392. }
  5393. String name = fv->field->Ident.token.string;
  5394. isize param_index = lookup_procedure_parameter(pt, name);
  5395. if (param_index < 0) {
  5396. if (show_error) {
  5397. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5398. }
  5399. err = CallArgumentError_ParameterNotFound;
  5400. continue;
  5401. }
  5402. if (pt->variadic && param_index == pt->variadic_index) {
  5403. named_variadic_param = true;
  5404. }
  5405. if (visited[param_index]) {
  5406. if (show_error) {
  5407. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5408. }
  5409. err = CallArgumentError_DuplicateParameter;
  5410. continue;
  5411. }
  5412. visited[param_index] = true;
  5413. ordered_operands[param_index] = operand;
  5414. }
  5415. }
  5416. isize dummy_argument_count = 0;
  5417. bool actually_variadic = false;
  5418. if (variadic) {
  5419. if (visited[pt->variadic_index] &&
  5420. positional_operand_count < positional_operands.count) {
  5421. if (show_error) {
  5422. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5423. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5424. }
  5425. err = CallArgumentError_DuplicateParameter;
  5426. } else if (!visited[pt->variadic_index]) {
  5427. visited[pt->variadic_index] = true;
  5428. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5429. if (vari_expand) {
  5430. if (variadic_operands.count == 0) {
  5431. error(call, "'..' in the wrong position");
  5432. } else {
  5433. GB_ASSERT(variadic_operands.count != 0);
  5434. *variadic_operand = variadic_operands[0];
  5435. variadic_operand->type = default_type(variadic_operand->type);
  5436. actually_variadic = true;
  5437. }
  5438. } else {
  5439. AstFile *f = call->file();
  5440. // HACK(bill): this is an awful hack
  5441. Operand o = {};
  5442. o.mode = Addressing_Value;
  5443. o.expr = ast_ident(f, make_token_ident("nil"));
  5444. o.expr->Ident.token.pos = ast_token(call).pos;
  5445. if (variadic_operands.count != 0) {
  5446. actually_variadic = true;
  5447. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5448. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5449. o.type = vt->type;
  5450. // NOTE(bill, 2024-07-14): minimize the stack usage for variadic parameters with the backing array
  5451. if (c->decl) {
  5452. bool found = false;
  5453. for (auto &vr : c->decl->variadic_reuses) {
  5454. if (are_types_identical(vt->type, vr.slice_type)) {
  5455. vr.max_count = gb_max(vr.max_count, variadic_operands.count);
  5456. found = true;
  5457. break;
  5458. }
  5459. }
  5460. if (!found) {
  5461. array_add(&c->decl->variadic_reuses, VariadicReuseData{vt->type, variadic_operands.count});
  5462. }
  5463. }
  5464. } else {
  5465. dummy_argument_count += 1;
  5466. o.type = t_untyped_nil;
  5467. }
  5468. *variadic_operand = o;
  5469. }
  5470. }
  5471. }
  5472. for (Operand const &o : ordered_operands) {
  5473. if (o.mode != Addressing_Invalid) {
  5474. check_no_copy_assignment(o, str_lit("procedure call expression"));
  5475. }
  5476. }
  5477. for (isize i = 0; i < pt->param_count; i++) {
  5478. if (!visited[i]) {
  5479. Entity *e = pt->params->Tuple.variables[i];
  5480. if (e->kind == Entity_Variable) {
  5481. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5482. ordered_operands[i].mode = Addressing_Value;
  5483. ordered_operands[i].type = e->type;
  5484. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5485. dummy_argument_count += 1;
  5486. score += assign_score_function(1);
  5487. continue;
  5488. }
  5489. }
  5490. if (show_error) {
  5491. if (e->kind == Entity_TypeName) {
  5492. error(call, "Type parameter '%.*s' is missing in procedure call",
  5493. LIT(e->token.string));
  5494. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5495. // Ignore
  5496. } else {
  5497. gbString str = type_to_string(e->type);
  5498. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5499. LIT(e->token.string), str);
  5500. gb_string_free(str);
  5501. }
  5502. }
  5503. err = CallArgumentError_ParameterMissing;
  5504. }
  5505. }
  5506. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5507. bool allow_array_programming = !(e && (e->flags & EntityFlag_NoBroadcast));
  5508. i64 s = 0;
  5509. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic, allow_array_programming)) {
  5510. bool ok = false;
  5511. if (e && (e->flags & EntityFlag_AnyInt)) {
  5512. if (is_type_integer(param_type)) {
  5513. ok = check_is_castable_to(c, o, param_type);
  5514. }
  5515. }
  5516. if (!allow_array_programming && check_is_assignable_to_with_score(c, o, param_type, nullptr, param_is_variadic, !allow_array_programming)) {
  5517. if (show_error) {
  5518. error(o->expr, "'#no_broadcast' disallows automatic broadcasting a value across all elements of an array-like type in a procedure argument");
  5519. }
  5520. }
  5521. if (ok) {
  5522. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5523. } else {
  5524. if (show_error) {
  5525. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5526. }
  5527. err = CallArgumentError_WrongTypes;
  5528. }
  5529. } else if (show_error) {
  5530. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5531. }
  5532. if (e && e->flags & EntityFlag_ConstInput) {
  5533. if (o->mode != Addressing_Constant) {
  5534. if (show_error) {
  5535. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5536. }
  5537. err = CallArgumentError_NoneConstantParameter;
  5538. }
  5539. }
  5540. if (!err && is_type_any(param_type)) {
  5541. add_type_info_type(c, o->type);
  5542. }
  5543. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5544. add_type_info_type(c, o->type);
  5545. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5546. } else if (show_error && is_type_untyped(o->type)) {
  5547. update_untyped_expr_type(c, o->expr, param_type, true);
  5548. }
  5549. return s;
  5550. };
  5551. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5552. err = CallArgumentError_None;
  5553. if (variadic) {
  5554. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5555. Type *t = pt->params->Tuple.variables[0]->type;
  5556. if (is_type_polymorphic(t)) {
  5557. if (show_error) {
  5558. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5559. }
  5560. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5561. }
  5562. }
  5563. } else {
  5564. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5565. PolyProcData poly_proc_data = {};
  5566. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5567. gen_entity = poly_proc_data.gen_entity;
  5568. Type *gept = base_type(gen_entity->type);
  5569. GB_ASSERT(is_type_proc(gept));
  5570. final_proc_type = gen_entity->type;
  5571. pt = &gept->Proc;
  5572. } else {
  5573. err = CallArgumentError_WrongTypes;
  5574. }
  5575. }
  5576. for (isize i = 0; i < pt->param_count; i++) {
  5577. Operand *o = &ordered_operands[i];
  5578. if (o->mode == Addressing_Invalid) {
  5579. continue;
  5580. }
  5581. Entity *e = pt->params->Tuple.variables[i];
  5582. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5583. if (e->kind == Entity_TypeName) {
  5584. GB_ASSERT(pt->is_polymorphic);
  5585. if (o->mode != Addressing_Type) {
  5586. if (show_error) {
  5587. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5588. }
  5589. err = CallArgumentError_WrongTypes;
  5590. }
  5591. if (are_types_identical(e->type, o->type)) {
  5592. score += assign_score_function(1);
  5593. } else {
  5594. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5595. }
  5596. continue;
  5597. }
  5598. if (param_is_variadic) {
  5599. if (!named_variadic_param) {
  5600. continue;
  5601. }
  5602. }
  5603. score += eval_param_and_score(c, o, e->type, err, false, e, show_error);
  5604. }
  5605. }
  5606. if (variadic) {
  5607. Entity *var_entity = pt->params->Tuple.variables[pt->variadic_index];
  5608. Type *slice = var_entity->type;
  5609. GB_ASSERT(is_type_slice(slice));
  5610. Type *elem = base_type(slice)->Slice.elem;
  5611. Type *t = elem;
  5612. if (is_type_polymorphic(t)) {
  5613. if (show_error) {
  5614. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5615. }
  5616. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5617. }
  5618. for_array(operand_index, variadic_operands) {
  5619. Operand *o = &variadic_operands[operand_index];
  5620. if (vari_expand) {
  5621. t = slice;
  5622. if (operand_index > 0) {
  5623. if (show_error) {
  5624. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5625. }
  5626. if (data) {
  5627. data->score = score;
  5628. data->result_type = final_proc_type->Proc.results;
  5629. data->gen_entity = gen_entity;
  5630. }
  5631. return CallArgumentError_MultipleVariadicExpand;
  5632. }
  5633. }
  5634. score += eval_param_and_score(c, o, t, err, true, var_entity, show_error);
  5635. }
  5636. }
  5637. if (data) {
  5638. data->score = score;
  5639. data->result_type = final_proc_type->Proc.results;
  5640. data->gen_entity = gen_entity;
  5641. Ast *proc_lit = nullptr;
  5642. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5643. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5644. if (vp && vp->kind == Ast_ProcLit) {
  5645. proc_lit = vp;
  5646. }
  5647. }
  5648. if (proc_lit == nullptr) {
  5649. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5650. }
  5651. }
  5652. return err;
  5653. }
  5654. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5655. GB_ASSERT(ce != nullptr);
  5656. if (ce->args.count == 0) {
  5657. return false;
  5658. }
  5659. return ce->args[0]->kind == Ast_FieldValue;
  5660. }
  5661. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  5662. Entity **lhs = nullptr;
  5663. isize lhs_count = -1;
  5664. if (proc_type == nullptr) {
  5665. return nullptr;
  5666. }
  5667. GB_ASSERT(is_type_proc(proc_type));
  5668. TypeProc *pt = &base_type(proc_type)->Proc;
  5669. *is_variadic = pt->variadic;
  5670. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5671. if (pt->params != nullptr) {
  5672. lhs = pt->params->Tuple.variables.data;
  5673. lhs_count = pt->params->Tuple.variables.count;
  5674. }
  5675. } else {
  5676. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5677. if (pt->params == nullptr) {
  5678. lhs_count = 0;
  5679. } else {
  5680. lhs_count = pt->params->Tuple.variables.count;
  5681. }
  5682. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5683. for (isize i = 0; i < lhs_count; i++) {
  5684. Entity *e = pt->params->Tuple.variables[i];
  5685. if (!is_type_polymorphic(e->type)) {
  5686. lhs[i] = e;
  5687. }
  5688. }
  5689. }
  5690. if (lhs_count_) *lhs_count_ = lhs_count;
  5691. return lhs;
  5692. }
  5693. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5694. if (clauses != nullptr) {
  5695. for (Ast *clause : *clauses) {
  5696. Operand o = {};
  5697. check_expr(ctx, &o, clause);
  5698. if (o.mode != Addressing_Constant) {
  5699. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5700. if (print_err && call_expr) error(call_expr, "at caller location");
  5701. return false;
  5702. } else if (o.value.kind != ExactValue_Bool) {
  5703. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5704. if (print_err && call_expr) error(call_expr, "at caller location");
  5705. return false;
  5706. } else if (!o.value.value_bool) {
  5707. if (print_err) {
  5708. ERROR_BLOCK();
  5709. gbString str = expr_to_string(clause);
  5710. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5711. gb_string_free(str);
  5712. if (scope != nullptr) {
  5713. isize print_count = 0;
  5714. for (auto const &entry : scope->elements) {
  5715. Entity *e = entry.value;
  5716. switch (e->kind) {
  5717. case Entity_TypeName: {
  5718. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5719. gbString str = type_to_string(e->type);
  5720. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5721. gb_string_free(str);
  5722. print_count += 1;
  5723. break;
  5724. }
  5725. case Entity_Constant: {
  5726. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5727. gbString str = exact_value_to_string(e->Constant.value);
  5728. if (is_type_untyped(e->type)) {
  5729. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5730. } else {
  5731. gbString t = type_to_string(e->type);
  5732. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5733. gb_string_free(t);
  5734. }
  5735. gb_string_free(str);
  5736. print_count += 1;
  5737. break;
  5738. }
  5739. }
  5740. }
  5741. }
  5742. if (call_expr) {
  5743. TokenPos pos = ast_token(call_expr).pos;
  5744. error_line("%s at caller location\n", token_pos_to_string(pos));
  5745. }
  5746. }
  5747. return false;
  5748. }
  5749. if (ast_file_vet_style(ctx->file)) {
  5750. Ast *c = unparen_expr(clause);
  5751. if (c->kind == Ast_BinaryExpr && c->BinaryExpr.op.kind == Token_CmpAnd) {
  5752. ERROR_BLOCK();
  5753. error(c, "Prefer to separate 'where' clauses with a comma rather than '&&'");
  5754. gbString x = expr_to_string(c->BinaryExpr.left);
  5755. gbString y = expr_to_string(c->BinaryExpr.right);
  5756. error_line("\tSuggestion: '%s, %s'\n", x, y);
  5757. gb_string_free(y);
  5758. gb_string_free(x);
  5759. }
  5760. }
  5761. }
  5762. }
  5763. return true;
  5764. }
  5765. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5766. bool success = true;
  5767. type = base_type(type);
  5768. if (named_args.count > 0) {
  5769. TypeProc *pt = nullptr;
  5770. if (is_type_proc(type)) {
  5771. pt = &type->Proc;
  5772. }
  5773. for_array(i, named_args) {
  5774. Ast *arg = named_args[i];
  5775. if (arg->kind != Ast_FieldValue) {
  5776. if (show_error) {
  5777. error(arg, "Expected a 'field = value'");
  5778. }
  5779. return false;
  5780. }
  5781. ast_node(fv, FieldValue, arg);
  5782. if (fv->field->kind != Ast_Ident) {
  5783. if (show_error) {
  5784. gbString expr_str = expr_to_string(fv->field);
  5785. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5786. gb_string_free(expr_str);
  5787. }
  5788. success = false;
  5789. continue;
  5790. }
  5791. String key = fv->field->Ident.token.string;
  5792. Ast *value = fv->value;
  5793. Type *type_hint = nullptr;
  5794. if (pt) {
  5795. isize param_index = lookup_procedure_parameter(pt, key);
  5796. if (param_index < 0) {
  5797. if (show_error) {
  5798. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5799. }
  5800. success = false;
  5801. continue;
  5802. }
  5803. Entity *e = pt->params->Tuple.variables[param_index];
  5804. if (!is_type_polymorphic(e->type)) {
  5805. type_hint = e->type;
  5806. }
  5807. }
  5808. Operand o = {};
  5809. check_expr_with_type_hint(c, &o, value, type_hint);
  5810. if (o.mode == Addressing_Invalid) {
  5811. success = false;
  5812. }
  5813. array_add(named_operands, o);
  5814. }
  5815. }
  5816. return success;
  5817. }
  5818. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5819. Entity *e, Type *proc_type,
  5820. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5821. CallArgumentErrorMode show_error_mode,
  5822. CallArgumentData *data) {
  5823. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5824. Ast *ident = operand->expr;
  5825. while (ident->kind == Ast_SelectorExpr) {
  5826. Ast *s = ident->SelectorExpr.selector;
  5827. ident = s;
  5828. }
  5829. if (e == nullptr) {
  5830. e = entity_of_node(ident);
  5831. if (e != nullptr) {
  5832. proc_type = e->type;
  5833. }
  5834. }
  5835. GB_ASSERT(proc_type != nullptr);
  5836. proc_type = base_type(proc_type);
  5837. GB_ASSERT(proc_type->kind == Type_Proc);
  5838. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5839. if (return_on_failure && err != CallArgumentError_None) {
  5840. return false;
  5841. }
  5842. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5843. if (!return_on_failure && entity_to_use != nullptr) {
  5844. add_entity_use(c, ident, entity_to_use);
  5845. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5846. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5847. }
  5848. if (data->gen_entity != nullptr) {
  5849. Entity *e = data->gen_entity;
  5850. DeclInfo *decl = data->gen_entity->decl_info;
  5851. CheckerContext ctx = *c;
  5852. ctx.scope = decl->scope;
  5853. ctx.decl = decl;
  5854. ctx.proc_name = e->token.string;
  5855. ctx.curr_proc_decl = decl;
  5856. ctx.curr_proc_sig = e->type;
  5857. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5858. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5859. if (return_on_failure) {
  5860. if (!ok) {
  5861. return false;
  5862. }
  5863. } else {
  5864. decl->where_clauses_evaluated = true;
  5865. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5866. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5867. }
  5868. if (is_type_proc(data->gen_entity->type)) {
  5869. Type *t = base_type(entity_to_use->type);
  5870. data->result_type = t->Proc.results;
  5871. }
  5872. }
  5873. }
  5874. return true;
  5875. }
  5876. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5877. ast_node(ce, CallExpr, call);
  5878. GB_ASSERT(ce->split_args != nullptr);
  5879. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5880. Slice<Ast *> const &named_args = ce->split_args->named;
  5881. CallArgumentData data = {};
  5882. data.result_type = t_invalid;
  5883. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5884. auto procs = proc_group_entities_cloned(c, *operand);
  5885. if (procs.count > 1) {
  5886. isize max_arg_count = positional_args.count + named_args.count;
  5887. for (Ast *arg : positional_args) {
  5888. // NOTE(bill): The only thing that may have multiple values
  5889. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5890. arg = strip_or_return_expr(arg);
  5891. if (arg && arg->kind == Ast_CallExpr) {
  5892. max_arg_count = ISIZE_MAX;
  5893. break;
  5894. }
  5895. }
  5896. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5897. // NOTE(bill): The only thing that may have multiple values
  5898. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5899. if (arg->kind == Ast_FieldValue) {
  5900. arg = strip_or_return_expr(arg->FieldValue.value);
  5901. if (arg && arg->kind == Ast_CallExpr) {
  5902. max_arg_count = ISIZE_MAX;
  5903. break;
  5904. }
  5905. }
  5906. }
  5907. // ignore named arguments first
  5908. for (Ast *arg : named_args) {
  5909. if (arg->kind != Ast_FieldValue) {
  5910. continue;
  5911. }
  5912. ast_node(fv, FieldValue, arg);
  5913. if (fv->field->kind != Ast_Ident) {
  5914. continue;
  5915. }
  5916. String key = fv->field->Ident.token.string;
  5917. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5918. Type *t = procs[proc_index]->type;
  5919. if (is_type_proc(t)) {
  5920. isize param_index = lookup_procedure_parameter(t, key);
  5921. if (param_index < 0) {
  5922. array_unordered_remove(&procs, proc_index);
  5923. }
  5924. }
  5925. }
  5926. }
  5927. if (procs.count == 0) {
  5928. // if any of the named arguments are wrong, the `procs` will be empty
  5929. // just start from scratch
  5930. array_free(&procs);
  5931. procs = proc_group_entities_cloned(c, *operand);
  5932. }
  5933. // filter by positional argument length
  5934. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5935. Entity *proc = procs[proc_index];
  5936. Type *pt = base_type(proc->type);
  5937. if (!(pt != nullptr && is_type_proc(pt))) {
  5938. proc_index++;
  5939. continue;
  5940. }
  5941. isize param_count = 0;
  5942. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5943. if (param_count_excluding_defaults > max_arg_count) {
  5944. array_unordered_remove(&procs, proc_index);
  5945. continue;
  5946. }
  5947. proc_index++;
  5948. }
  5949. }
  5950. Entity **lhs = nullptr;
  5951. isize lhs_count = -1;
  5952. bool is_variadic = false;
  5953. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5954. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5955. defer (array_free(&positional_operands));
  5956. defer (array_free(&named_operands));
  5957. if (procs.count == 1) {
  5958. Entity *e = procs[0];
  5959. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  5960. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5961. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5962. check_call_arguments_single(c, call, operand,
  5963. e, e->type,
  5964. positional_operands, named_operands,
  5965. CallArgumentErrorMode::ShowErrors,
  5966. &data);
  5967. }
  5968. return data;
  5969. }
  5970. {
  5971. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  5972. // where the same positional parameter has the same type value (and ellipsis)
  5973. isize proc_arg_count = -1;
  5974. for (Entity *p : procs) {
  5975. Type *pt = base_type(p->type);
  5976. if (pt != nullptr && is_type_proc(pt)) {
  5977. if (proc_arg_count < 0) {
  5978. proc_arg_count = pt->Proc.param_count;
  5979. } else {
  5980. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  5981. }
  5982. }
  5983. }
  5984. if (proc_arg_count >= 0) {
  5985. lhs_count = proc_arg_count;
  5986. if (lhs_count > 0) {
  5987. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  5988. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  5989. Entity *e = nullptr;
  5990. for (Entity *p : procs) {
  5991. Type *pt = base_type(p->type);
  5992. if (!(pt != nullptr && is_type_proc(pt))) {
  5993. continue;
  5994. }
  5995. if (e == nullptr) {
  5996. e = pt->Proc.params->Tuple.variables[param_index];
  5997. } else {
  5998. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  5999. if (e == f) {
  6000. continue;
  6001. }
  6002. if (are_types_identical(e->type, f->type)) {
  6003. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  6004. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  6005. if (ee == fe) {
  6006. continue;
  6007. }
  6008. }
  6009. // NOTE(bill): Entities are not close enough to be used
  6010. e = nullptr;
  6011. break;
  6012. }
  6013. }
  6014. lhs[param_index] = e;
  6015. }
  6016. }
  6017. }
  6018. }
  6019. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  6020. for_array(i, named_args) {
  6021. Ast *arg = named_args[i];
  6022. if (arg->kind != Ast_FieldValue) {
  6023. error(arg, "Expected a 'field = value'");
  6024. return data;
  6025. }
  6026. ast_node(fv, FieldValue, arg);
  6027. if (fv->field->kind != Ast_Ident) {
  6028. gbString expr_str = expr_to_string(fv->field);
  6029. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6030. gb_string_free(expr_str);
  6031. return data;
  6032. }
  6033. String key = fv->field->Ident.token.string;
  6034. Ast *value = fv->value;
  6035. Type *type_hint = nullptr;
  6036. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  6037. Entity *e = lhs[lhs_idx];
  6038. if (e != nullptr && e->token.string == key &&
  6039. !is_type_polymorphic(e->type)) {
  6040. type_hint = e->type;
  6041. break;
  6042. }
  6043. }
  6044. Operand o = {};
  6045. check_expr_with_type_hint(c, &o, value, type_hint);
  6046. array_add(&named_operands, o);
  6047. }
  6048. gb_free(heap_allocator(), lhs);
  6049. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  6050. defer (array_free(&valids));
  6051. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  6052. defer (array_free(&proc_entities));
  6053. for (Entity *proc : procs) {
  6054. array_add(&proc_entities, proc);
  6055. }
  6056. int max_matched_features = 0;
  6057. gbString expr_name = expr_to_string(operand->expr);
  6058. defer (gb_string_free(expr_name));
  6059. for_array(i, procs) {
  6060. Entity *p = procs[i];
  6061. if (p->flags & EntityFlag_Disabled) {
  6062. continue;
  6063. }
  6064. Type *pt = base_type(p->type);
  6065. if (pt != nullptr && is_type_proc(pt)) {
  6066. CallArgumentData data = {};
  6067. CheckerContext ctx = *c;
  6068. ctx.no_polymorphic_errors = true;
  6069. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  6070. ctx.hide_polymorphic_errors = true;
  6071. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  6072. p, pt,
  6073. positional_operands, named_operands,
  6074. CallArgumentErrorMode::NoErrors,
  6075. &data);
  6076. if (!is_a_candidate) {
  6077. continue;
  6078. }
  6079. isize index = i;
  6080. ValidIndexAndScore item = {};
  6081. item.score = data.score;
  6082. if (data.gen_entity != nullptr) {
  6083. array_add(&proc_entities, data.gen_entity);
  6084. index = proc_entities.count-1;
  6085. // prefer non-polymorphic procedures over polymorphic
  6086. item.score += assign_score_function(1);
  6087. }
  6088. max_matched_features = gb_max(max_matched_features, matched_target_features(&pt->Proc));
  6089. item.index = index;
  6090. array_add(&valids, item);
  6091. }
  6092. }
  6093. if (max_matched_features > 0) {
  6094. for_array(i, valids) {
  6095. Entity *p = procs[valids[i].index];
  6096. Type *t = base_type(p->type);
  6097. GB_ASSERT(t->kind == Type_Proc);
  6098. int matched = matched_target_features(&t->Proc);
  6099. valids[i].score += assign_score_function(max_matched_features-matched);
  6100. }
  6101. }
  6102. if (valids.count > 1) {
  6103. array_sort(valids, valid_index_and_score_cmp);
  6104. i64 best_score = valids[0].score;
  6105. Entity *best_entity = proc_entities[valids[0].index];
  6106. GB_ASSERT(best_entity != nullptr);
  6107. for (isize i = 1; i < valids.count; i++) {
  6108. if (best_score > valids[i].score) {
  6109. valids.count = i;
  6110. break;
  6111. }
  6112. if (best_entity == proc_entities[valids[i].index]) {
  6113. valids.count = i;
  6114. break;
  6115. }
  6116. }
  6117. }
  6118. auto print_argument_types = [&]() {
  6119. error_line("\tGiven argument types: (");
  6120. isize i = 0;
  6121. for (Operand const &o : positional_operands) {
  6122. if (i++ > 0) error_line(", ");
  6123. gbString type = type_to_string(o.type);
  6124. defer (gb_string_free(type));
  6125. error_line("%s", type);
  6126. }
  6127. for (Operand const &o : named_operands) {
  6128. if (i++ > 0) error_line(", ");
  6129. gbString type = type_to_string(o.type);
  6130. defer (gb_string_free(type));
  6131. if (i < ce->split_args->named.count) {
  6132. Ast *named_field = ce->split_args->named[i];
  6133. ast_node(fv, FieldValue, named_field);
  6134. gbString field = expr_to_string(fv->field);
  6135. defer (gb_string_free(field));
  6136. error_line("%s = %s", field, type);
  6137. } else {
  6138. error_line("%s", type);
  6139. }
  6140. }
  6141. error_line(")\n");
  6142. };
  6143. if (valids.count == 0) {
  6144. ERROR_BLOCK();
  6145. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  6146. if (positional_operands.count == 0 && named_operands.count == 0) {
  6147. error_line("\tNo given arguments\n");
  6148. } else {
  6149. print_argument_types();
  6150. }
  6151. if (procs.count == 0) {
  6152. procs = proc_group_entities_cloned(c, *operand);
  6153. }
  6154. if (procs.count > 0) {
  6155. error_line("Did you mean to use one of the following:\n");
  6156. }
  6157. // Try to reduce the list further for `$T: typeid` like parameters
  6158. bool *possibly_ignore = gb_alloc_array(temporary_allocator(), bool, procs.count);
  6159. isize possibly_ignore_set = 0;
  6160. if (true) {
  6161. // NOTE(bill): This currently only checks for #soa types
  6162. for_array(i, procs) {
  6163. Entity *proc = procs[i];
  6164. Type *t = base_type(proc->type);
  6165. if (t == nullptr || t->kind != Type_Proc) {
  6166. continue;
  6167. }
  6168. TypeProc *pt = &t->Proc;
  6169. if (pt->param_count == 0) {
  6170. continue;
  6171. }
  6172. for_array(j, pt->params->Tuple.variables) {
  6173. Entity *v = pt->params->Tuple.variables[j];
  6174. if (v->kind != Entity_TypeName) {
  6175. continue;
  6176. }
  6177. Type *dst_t = base_type(v->type);
  6178. while (dst_t->kind == Type_Generic && dst_t->Generic.specialized) {
  6179. dst_t = dst_t->Generic.specialized;
  6180. }
  6181. if (j >= positional_operands.count) {
  6182. continue;
  6183. }
  6184. Operand const &o = positional_operands[j];
  6185. if (o.mode != Addressing_Type) {
  6186. continue;
  6187. }
  6188. Type *t = base_type(o.type);
  6189. if (t->kind == dst_t->kind) {
  6190. continue;
  6191. }
  6192. Type *st = base_type(type_deref(o.type));
  6193. Type *dt = base_type(type_deref(dst_t));
  6194. if (st->kind == dt->kind) {
  6195. continue;
  6196. }
  6197. if (is_type_soa_struct(st)) {
  6198. possibly_ignore[i] = true;
  6199. possibly_ignore_set += 1;
  6200. continue;
  6201. }
  6202. }
  6203. }
  6204. }
  6205. if (possibly_ignore_set == procs.count) {
  6206. possibly_ignore_set = 0;
  6207. }
  6208. isize max_name_length = 0;
  6209. isize max_type_length = 0;
  6210. for_array(i, procs) {
  6211. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6212. continue;
  6213. }
  6214. Entity *proc = procs[i];
  6215. Type *t = base_type(proc->type);
  6216. if (t == t_invalid) continue;
  6217. String prefix = {};
  6218. String prefix_sep = {};
  6219. if (proc->pkg) {
  6220. prefix = proc->pkg->name;
  6221. prefix_sep = str_lit(".");
  6222. }
  6223. String name = proc->token.string;
  6224. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  6225. gbString pt;
  6226. if (t->Proc.node != nullptr) {
  6227. pt = expr_to_string(t->Proc.node);
  6228. } else {
  6229. pt = type_to_string(t);
  6230. }
  6231. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  6232. gb_string_free(pt);
  6233. }
  6234. isize max_spaces = gb_max(max_name_length, max_type_length);
  6235. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  6236. for (isize i = 0; i < max_spaces; i++) {
  6237. spaces[i] = ' ';
  6238. }
  6239. spaces[max_spaces] = 0;
  6240. for_array(i, procs) {
  6241. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6242. continue;
  6243. }
  6244. Entity *proc = procs[i];
  6245. TokenPos pos = proc->token.pos;
  6246. Type *t = base_type(proc->type);
  6247. if (t == t_invalid) continue;
  6248. GB_ASSERT(t->kind == Type_Proc);
  6249. gbString pt;
  6250. defer (gb_string_free(pt));
  6251. if (t->Proc.node != nullptr) {
  6252. pt = expr_to_string(t->Proc.node);
  6253. } else {
  6254. pt = type_to_string(t);
  6255. }
  6256. String prefix = {};
  6257. String prefix_sep = {};
  6258. if (proc->pkg) {
  6259. prefix = proc->pkg->name;
  6260. prefix_sep = str_lit(".");
  6261. }
  6262. String name = proc->token.string;
  6263. isize len = prefix.len + prefix_sep.len + name.len;
  6264. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  6265. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  6266. char const *sep = "::";
  6267. if (proc->kind == Entity_Variable) {
  6268. sep = ":=";
  6269. }
  6270. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  6271. LIT(prefix), LIT(prefix_sep), LIT(name),
  6272. name_padding, spaces,
  6273. sep,
  6274. pt,
  6275. type_padding, spaces,
  6276. token_pos_to_string(pos)
  6277. );
  6278. }
  6279. if (procs.count > 0) {
  6280. error_line("\n");
  6281. }
  6282. data.result_type = t_invalid;
  6283. } else if (valids.count > 1) {
  6284. ERROR_BLOCK();
  6285. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  6286. if (positional_operands.count == 0 && named_operands.count == 0) {
  6287. error_line("\tNo given arguments\n");
  6288. } else {
  6289. print_argument_types();
  6290. }
  6291. for (auto const &valid : valids) {
  6292. Entity *proc = proc_entities[valid.index];
  6293. GB_ASSERT(proc != nullptr);
  6294. TokenPos pos = proc->token.pos;
  6295. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  6296. gbString pt = nullptr;
  6297. defer (gb_string_free(pt));
  6298. if (t->Proc.node != nullptr) {
  6299. pt = expr_to_string(t->Proc.node);
  6300. } else {
  6301. pt = type_to_string(t);
  6302. }
  6303. String name = proc->token.string;
  6304. char const *sep = "::";
  6305. if (proc->kind == Entity_Variable) {
  6306. sep = ":=";
  6307. }
  6308. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  6309. if (proc->decl_info->proc_lit != nullptr) {
  6310. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  6311. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  6312. if (pl->where_token.kind != Token_Invalid) {
  6313. error_line("\n\t\twhere ");
  6314. for_array(j, pl->where_clauses) {
  6315. Ast *clause = pl->where_clauses[j];
  6316. if (j != 0) {
  6317. error_line("\t\t ");
  6318. }
  6319. gbString str = expr_to_string(clause);
  6320. error_line("%s", str);
  6321. gb_string_free(str);
  6322. if (j != pl->where_clauses.count-1) {
  6323. error_line(",");
  6324. }
  6325. }
  6326. error_line("\n\t");
  6327. }
  6328. }
  6329. error_line("at %s\n", token_pos_to_string(pos));
  6330. }
  6331. data.result_type = t_invalid;
  6332. } else {
  6333. GB_ASSERT(valids.count == 1);
  6334. Ast *ident = operand->expr;
  6335. while (ident->kind == Ast_SelectorExpr) {
  6336. Ast *s = ident->SelectorExpr.selector;
  6337. ident = s;
  6338. }
  6339. Entity *e = proc_entities[valids[0].index];
  6340. GB_ASSERT(e != nullptr);
  6341. Array<Operand> named_operands = {};
  6342. check_call_arguments_single(c, call, operand,
  6343. e, e->type,
  6344. positional_operands, named_operands,
  6345. CallArgumentErrorMode::ShowErrors,
  6346. &data);
  6347. return data;
  6348. }
  6349. return data;
  6350. }
  6351. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  6352. Type *proc_type = nullptr;
  6353. CallArgumentData data = {};
  6354. data.result_type = t_invalid;
  6355. proc_type = base_type(operand->type);
  6356. TypeProc *pt = nullptr;
  6357. if (proc_type) {
  6358. pt = &proc_type->Proc;
  6359. }
  6360. TEMPORARY_ALLOCATOR_GUARD();
  6361. ast_node(ce, CallExpr, call);
  6362. bool any_failure = false;
  6363. // Split positional and named args into separate arrays/slices
  6364. Slice<Ast *> positional_args = {};
  6365. Slice<Ast *> named_args = {};
  6366. if (ce->split_args == nullptr) {
  6367. positional_args = ce->args;
  6368. for (isize i = 0; i < ce->args.count; i++) {
  6369. Ast *arg = ce->args.data[i];
  6370. if (arg->kind == Ast_FieldValue) {
  6371. positional_args.count = i;
  6372. break;
  6373. }
  6374. }
  6375. named_args = slice(ce->args, positional_args.count, ce->args.count);
  6376. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  6377. split_args->positional = positional_args;
  6378. split_args->named = named_args;
  6379. ce->split_args = split_args;
  6380. } else {
  6381. positional_args = ce->split_args->positional;
  6382. named_args = ce->split_args->named;
  6383. }
  6384. if (operand->mode == Addressing_ProcGroup) {
  6385. return check_call_arguments_proc_group(c, operand, call);
  6386. }
  6387. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  6388. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6389. defer (array_free(&positional_operands));
  6390. defer (array_free(&named_operands));
  6391. if (positional_args.count > 0) {
  6392. isize lhs_count = -1;
  6393. bool is_variadic = false;
  6394. Entity **lhs = nullptr;
  6395. if (pt != nullptr) {
  6396. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  6397. }
  6398. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  6399. }
  6400. if (named_args.count > 0) {
  6401. for_array(i, named_args) {
  6402. Ast *arg = named_args[i];
  6403. if (arg->kind != Ast_FieldValue) {
  6404. error(arg, "Expected a 'field = value'");
  6405. return data;
  6406. }
  6407. ast_node(fv, FieldValue, arg);
  6408. if (fv->field->kind != Ast_Ident) {
  6409. gbString expr_str = expr_to_string(fv->field);
  6410. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6411. any_failure = true;
  6412. gb_string_free(expr_str);
  6413. continue;
  6414. }
  6415. String key = fv->field->Ident.token.string;
  6416. Ast *value = fv->value;
  6417. isize param_index = lookup_procedure_parameter(pt, key);
  6418. Type *type_hint = nullptr;
  6419. if (param_index >= 0) {
  6420. Entity *e = pt->params->Tuple.variables[param_index];
  6421. type_hint = e->type;
  6422. }
  6423. Operand o = {};
  6424. check_expr_with_type_hint(c, &o, value, type_hint);
  6425. if (o.mode == Addressing_Invalid) {
  6426. any_failure = true;
  6427. }
  6428. array_add(&named_operands, o);
  6429. }
  6430. }
  6431. if (!any_failure) {
  6432. check_call_arguments_single(c, call, operand,
  6433. nullptr, proc_type,
  6434. positional_operands, named_operands,
  6435. CallArgumentErrorMode::ShowErrors,
  6436. &data);
  6437. } else if (pt) {
  6438. data.result_type = pt->results;
  6439. }
  6440. return data;
  6441. }
  6442. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6443. if (!is_type_polymorphic_record(t)) {
  6444. return -1;
  6445. }
  6446. TypeTuple *params = get_record_polymorphic_params(t);
  6447. if (params == nullptr) {
  6448. return -1;
  6449. }
  6450. for_array(i, params->variables) {
  6451. Entity *e = params->variables[i];
  6452. String name = e->token.string;
  6453. if (is_blank_ident(name)) {
  6454. continue;
  6455. }
  6456. if (name == parameter_name) {
  6457. return i;
  6458. }
  6459. }
  6460. return -1;
  6461. }
  6462. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6463. ast_node(ce, CallExpr, call);
  6464. Type *original_type = operand->type;
  6465. GB_ASSERT(is_type_polymorphic_record(original_type));
  6466. bool show_error = true;
  6467. Array<Operand> operands = {};
  6468. defer (array_free(&operands));
  6469. CallArgumentError err = CallArgumentError_None;
  6470. bool named_fields = false;
  6471. {
  6472. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6473. auto prev_type_path = c->type_path;
  6474. c->type_path = new_checker_type_path();
  6475. defer ({
  6476. destroy_checker_type_path(c->type_path);
  6477. c->type_path = prev_type_path;
  6478. });
  6479. if (is_call_expr_field_value(ce)) {
  6480. named_fields = true;
  6481. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6482. for_array(i, ce->args) {
  6483. Ast *arg = ce->args[i];
  6484. ast_node(fv, FieldValue, arg);
  6485. if (fv->value == nullptr) {
  6486. error(fv->eq, "Expected a value");
  6487. err = CallArgumentError_InvalidFieldValue;
  6488. continue;
  6489. }
  6490. if (fv->field->kind == Ast_Ident) {
  6491. String name = fv->field->Ident.token.string;
  6492. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6493. if (index >= 0) {
  6494. TypeTuple *params = get_record_polymorphic_params(original_type);
  6495. Entity *e = params->variables[index];
  6496. if (e->kind == Entity_Constant) {
  6497. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6498. continue;
  6499. }
  6500. }
  6501. }
  6502. check_expr_or_type(c, &operands[i], fv->value);
  6503. }
  6504. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6505. if (vari_expand) {
  6506. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6507. }
  6508. } else {
  6509. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6510. Entity **lhs = nullptr;
  6511. isize lhs_count = -1;
  6512. TypeTuple *params = get_record_polymorphic_params(original_type);
  6513. if (params != nullptr) {
  6514. lhs = params->variables.data;
  6515. lhs_count = params->variables.count;
  6516. }
  6517. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6518. }
  6519. }
  6520. if (err != 0) {
  6521. operand->mode = Addressing_Invalid;
  6522. return err;
  6523. }
  6524. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6525. isize param_count = tuple->variables.count;
  6526. isize minimum_param_count = param_count;
  6527. for (; minimum_param_count > 0; minimum_param_count--) {
  6528. Entity *e = tuple->variables[minimum_param_count-1];
  6529. if (e->kind != Entity_Constant) {
  6530. break;
  6531. }
  6532. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6533. break;
  6534. }
  6535. }
  6536. Array<Operand> ordered_operands = operands;
  6537. if (!named_fields) {
  6538. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6539. array_copy(&ordered_operands, operands, 0);
  6540. } else {
  6541. TEMPORARY_ALLOCATOR_GUARD();
  6542. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6543. // LEAK(bill)
  6544. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6545. for_array(i, ce->args) {
  6546. Ast *arg = ce->args[i];
  6547. ast_node(fv, FieldValue, arg);
  6548. if (fv->field->kind != Ast_Ident) {
  6549. if (show_error) {
  6550. gbString expr_str = expr_to_string(fv->field);
  6551. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6552. gb_string_free(expr_str);
  6553. }
  6554. err = CallArgumentError_InvalidFieldValue;
  6555. continue;
  6556. }
  6557. String name = fv->field->Ident.token.string;
  6558. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6559. if (index < 0) {
  6560. if (show_error) {
  6561. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6562. }
  6563. err = CallArgumentError_ParameterNotFound;
  6564. continue;
  6565. }
  6566. if (visited[index]) {
  6567. if (show_error) {
  6568. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6569. }
  6570. err = CallArgumentError_DuplicateParameter;
  6571. continue;
  6572. }
  6573. visited[index] = true;
  6574. ordered_operands[index] = operands[i];
  6575. }
  6576. for (isize i = 0; i < param_count; i++) {
  6577. if (!visited[i]) {
  6578. Entity *e = tuple->variables[i];
  6579. if (is_blank_ident(e->token)) {
  6580. continue;
  6581. }
  6582. if (show_error) {
  6583. if (e->kind == Entity_TypeName) {
  6584. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6585. LIT(e->token.string));
  6586. } else {
  6587. gbString str = type_to_string(e->type);
  6588. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6589. LIT(e->token.string), str);
  6590. gb_string_free(str);
  6591. }
  6592. }
  6593. err = CallArgumentError_ParameterMissing;
  6594. }
  6595. }
  6596. }
  6597. if (err != 0) {
  6598. operand->mode = Addressing_Invalid;
  6599. return err;
  6600. }
  6601. while (ordered_operands.count > 0) {
  6602. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6603. break;
  6604. }
  6605. array_pop(&ordered_operands);
  6606. }
  6607. if (minimum_param_count != param_count) {
  6608. if (param_count < ordered_operands.count) {
  6609. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6610. err = CallArgumentError_TooManyArguments;
  6611. } else if (minimum_param_count > ordered_operands.count) {
  6612. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6613. err = CallArgumentError_TooFewArguments;
  6614. }
  6615. } else {
  6616. if (param_count < ordered_operands.count) {
  6617. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6618. err = CallArgumentError_TooManyArguments;
  6619. } else if (param_count > ordered_operands.count) {
  6620. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6621. err = CallArgumentError_TooFewArguments;
  6622. }
  6623. }
  6624. if (err != 0) {
  6625. return err;
  6626. }
  6627. if (minimum_param_count != param_count) {
  6628. array_resize(&ordered_operands, param_count);
  6629. isize missing_count = 0;
  6630. // NOTE(bill): Replace missing operands with the default values (if possible)
  6631. for_array(i, ordered_operands) {
  6632. Operand *o = &ordered_operands[i];
  6633. if (o->expr == nullptr) {
  6634. Entity *e = tuple->variables[i];
  6635. if (e->kind == Entity_Constant) {
  6636. missing_count += 1;
  6637. o->mode = Addressing_Constant;
  6638. o->type = default_type(e->type);
  6639. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6640. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6641. o->value = e->Constant.param_value.value;
  6642. }
  6643. } else if (e->kind == Entity_TypeName) {
  6644. missing_count += 1;
  6645. o->mode = Addressing_Type;
  6646. o->type = e->type;
  6647. o->expr = e->identifier;
  6648. }
  6649. }
  6650. }
  6651. }
  6652. isize oo_count = gb_min(param_count, ordered_operands.count);
  6653. i64 score = 0;
  6654. for (isize i = 0; i < oo_count; i++) {
  6655. Entity *e = tuple->variables[i];
  6656. Operand *o = &ordered_operands[i];
  6657. if (o->mode == Addressing_Invalid) {
  6658. continue;
  6659. }
  6660. if (e->kind == Entity_TypeName) {
  6661. if (o->mode != Addressing_Type) {
  6662. if (show_error) {
  6663. gbString expr = expr_to_string(o->expr);
  6664. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6665. gb_string_free(expr);
  6666. }
  6667. err = CallArgumentError_WrongTypes;
  6668. }
  6669. if (are_types_identical(e->type, o->type)) {
  6670. score += assign_score_function(1);
  6671. } else {
  6672. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6673. }
  6674. } else {
  6675. i64 s = 0;
  6676. if (o->type->kind == Type_Generic) {
  6677. // Polymorphic name!
  6678. score += assign_score_function(1);
  6679. continue;
  6680. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6681. if (show_error) {
  6682. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6683. }
  6684. err = CallArgumentError_WrongTypes;
  6685. }
  6686. o->type = e->type;
  6687. if (o->mode != Addressing_Constant) {
  6688. bool valid = false;
  6689. if (is_type_proc(o->type)) {
  6690. Entity *proc_entity = entity_from_expr(o->expr);
  6691. valid = proc_entity != nullptr;
  6692. }
  6693. if (!valid) {
  6694. if (show_error) {
  6695. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6696. }
  6697. err = CallArgumentError_NoneConstantParameter;
  6698. }
  6699. }
  6700. score += s;
  6701. }
  6702. // NOTE(bill): Add type info the parameters
  6703. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6704. // add_type_info_type(c, o->type);
  6705. }
  6706. if (show_error && err) {
  6707. return err;
  6708. }
  6709. {
  6710. GenTypesData *found_gen_types = ensure_polymorphic_record_entity_has_gen_types(c, original_type);
  6711. mutex_lock(&found_gen_types->mutex);
  6712. defer (mutex_unlock(&found_gen_types->mutex));
  6713. Entity *found_entity = find_polymorphic_record_entity(found_gen_types, param_count, ordered_operands);
  6714. if (found_entity) {
  6715. operand->mode = Addressing_Type;
  6716. operand->type = found_entity->type;
  6717. return err;
  6718. }
  6719. CheckerContext ctx = *c;
  6720. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6721. ctx.scope = polymorphic_record_parent_scope(original_type);
  6722. GB_ASSERT(ctx.scope != nullptr);
  6723. Type *bt = base_type(original_type);
  6724. String generated_name = make_string_c(expr_to_string(call));
  6725. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6726. if (bt->kind == Type_Struct) {
  6727. Ast *node = clone_ast(bt->Struct.node);
  6728. Type *struct_type = alloc_type_struct();
  6729. struct_type->Struct.node = node;
  6730. struct_type->Struct.polymorphic_parent = original_type;
  6731. set_base_type(named_type, struct_type);
  6732. check_open_scope(&ctx, node);
  6733. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6734. check_close_scope(&ctx);
  6735. } else if (bt->kind == Type_Union) {
  6736. Ast *node = clone_ast(bt->Union.node);
  6737. Type *union_type = alloc_type_union();
  6738. union_type->Union.node = node;
  6739. union_type->Union.polymorphic_parent = original_type;
  6740. set_base_type(named_type, union_type);
  6741. check_open_scope(&ctx, node);
  6742. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6743. check_close_scope(&ctx);
  6744. } else {
  6745. GB_PANIC("Unsupported parametric polymorphic record type");
  6746. }
  6747. bt = base_type(named_type);
  6748. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6749. GB_ASSERT(original_type->kind == Type_Named);
  6750. Entity *e = original_type->Named.type_name;
  6751. GB_ASSERT(e->kind == Entity_TypeName);
  6752. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6753. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6754. TypeTuple *tuple = get_record_polymorphic_params(bt);
  6755. if (tuple != nullptr) for_array(i, tuple->variables) {
  6756. Entity *v = tuple->variables[i];
  6757. String name = v->token.string;
  6758. if (i > 0) {
  6759. s = gb_string_append_fmt(s, ", ");
  6760. }
  6761. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6762. if (v->kind == Entity_TypeName) {
  6763. if (v->type->kind != Type_Generic) {
  6764. s = gb_string_append_fmt(s, "=");
  6765. s = write_type_to_string(s, v->type, false);
  6766. }
  6767. } else if (v->kind == Entity_Constant) {
  6768. if (v->Constant.value.kind != ExactValue_Invalid) {
  6769. s = gb_string_append_fmt(s, "=");
  6770. s = write_exact_value_to_string(s, v->Constant.value);
  6771. }
  6772. }
  6773. }
  6774. s = gb_string_append_fmt(s, ")");
  6775. String new_name = make_string_c(s);
  6776. named_type->Named.name = new_name;
  6777. if (named_type->Named.type_name) {
  6778. named_type->Named.type_name->token.string = new_name;
  6779. }
  6780. }
  6781. operand->mode = Addressing_Type;
  6782. operand->type = named_type;
  6783. }
  6784. return err;
  6785. }
  6786. // returns true on success
  6787. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6788. bool success = true;
  6789. if (args.count > 0) {
  6790. if (allow_mixed) {
  6791. bool was_named = false;
  6792. for (Ast *arg : args) {
  6793. if (was_named && arg->kind != Ast_FieldValue) {
  6794. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6795. success = false;
  6796. break;
  6797. }
  6798. was_named = was_named || arg->kind == Ast_FieldValue;
  6799. }
  6800. } else {
  6801. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6802. for (Ast *arg : args) {
  6803. bool mix = false;
  6804. if (first_is_field_value) {
  6805. mix = arg->kind != Ast_FieldValue;
  6806. } else {
  6807. mix = arg->kind == Ast_FieldValue;
  6808. }
  6809. if (mix) {
  6810. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6811. success = false;
  6812. }
  6813. }
  6814. }
  6815. }
  6816. return success;
  6817. }
  6818. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6819. operand->mode = Addressing_Invalid; \
  6820. operand->expr = call; \
  6821. return Expr_Stmt; \
  6822. }
  6823. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6824. if (proc != nullptr &&
  6825. proc->kind == Ast_BasicDirective) {
  6826. ast_node(bd, BasicDirective, proc);
  6827. String name = bd->name.string;
  6828. if (
  6829. name == "location" ||
  6830. name == "exists" ||
  6831. name == "assert" ||
  6832. name == "panic" ||
  6833. name == "defined" ||
  6834. name == "config" ||
  6835. name == "load" ||
  6836. name == "load_directory" ||
  6837. name == "load_hash" ||
  6838. name == "hash"
  6839. ) {
  6840. operand->mode = Addressing_Builtin;
  6841. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6842. operand->expr = proc;
  6843. operand->type = t_invalid;
  6844. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6845. } else {
  6846. error(proc, "Unknown directive: #%.*s", LIT(name));
  6847. operand->expr = proc;
  6848. operand->type = t_invalid;
  6849. operand->mode = Addressing_Invalid;
  6850. return Expr_Expr;
  6851. }
  6852. if (inlining != ProcInlining_none) {
  6853. error(call, "Inlining operators are not allowed on built-in procedures");
  6854. }
  6855. } else {
  6856. if (proc != nullptr) {
  6857. check_expr_or_type(c, operand, proc);
  6858. } else {
  6859. GB_ASSERT(operand->expr != nullptr);
  6860. }
  6861. }
  6862. if (operand->mode == Addressing_Invalid) {
  6863. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6864. for (Ast *arg : args) {
  6865. if (arg->kind == Ast_FieldValue) {
  6866. arg = arg->FieldValue.value;
  6867. }
  6868. check_expr_base(c, operand, arg, nullptr);
  6869. }
  6870. operand->mode = Addressing_Invalid;
  6871. operand->expr = call;
  6872. return Expr_Stmt;
  6873. }
  6874. if (operand->mode == Addressing_Type) {
  6875. Type *t = operand->type;
  6876. if (is_type_polymorphic_record(t)) {
  6877. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6878. if (!is_type_named(t)) {
  6879. gbString s = expr_to_string(operand->expr);
  6880. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6881. gb_string_free(s);
  6882. operand->mode = Addressing_Invalid;
  6883. operand->type = t_invalid;;
  6884. return Expr_Expr;
  6885. }
  6886. auto err = check_polymorphic_record_type(c, operand, call);
  6887. if (err == 0) {
  6888. Ast *ident = operand->expr;
  6889. while (ident->kind == Ast_SelectorExpr) {
  6890. Ast *s = ident->SelectorExpr.selector;
  6891. ident = s;
  6892. }
  6893. Type *ot = operand->type;
  6894. GB_ASSERT(ot->kind == Type_Named);
  6895. Entity *e = ot->Named.type_name;
  6896. add_entity_use(c, ident, e);
  6897. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6898. } else {
  6899. operand->mode = Addressing_Invalid;
  6900. operand->type = t_invalid;
  6901. }
  6902. } else {
  6903. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6904. operand->mode = Addressing_Invalid;
  6905. isize arg_count = args.count;
  6906. switch (arg_count) {
  6907. case 0:
  6908. {
  6909. gbString str = type_to_string(t);
  6910. error(call, "Missing argument in conversion to '%s'", str);
  6911. gb_string_free(str);
  6912. } break;
  6913. default:
  6914. {
  6915. gbString str = type_to_string(t);
  6916. error(call, "Too many arguments in conversion to '%s'", str);
  6917. gb_string_free(str);
  6918. } break;
  6919. case 1: {
  6920. Ast *arg = args[0];
  6921. if (arg->kind == Ast_FieldValue) {
  6922. error(call, "'field = value' cannot be used in a type conversion");
  6923. arg = arg->FieldValue.value;
  6924. // NOTE(bill): Carry on the cast regardless
  6925. }
  6926. check_expr_with_type_hint(c, operand, arg, t);
  6927. if (operand->mode != Addressing_Invalid) {
  6928. if (is_type_polymorphic(t)) {
  6929. error(call, "A polymorphic type cannot be used in a type conversion");
  6930. } else {
  6931. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  6932. // as it assumes it is determining the type
  6933. check_cast(c, operand, t);
  6934. }
  6935. }
  6936. operand->type = t;
  6937. operand->expr = call;
  6938. if (operand->mode != Addressing_Invalid) {
  6939. update_untyped_expr_type(c, arg, t, false);
  6940. }
  6941. break;
  6942. }
  6943. }
  6944. }
  6945. return Expr_Expr;
  6946. }
  6947. if (operand->mode == Addressing_Builtin) {
  6948. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  6949. i32 id = operand->builtin_id;
  6950. Entity *e = entity_of_node(operand->expr);
  6951. if (e != nullptr && e->token.string == "expand_to_tuple") {
  6952. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  6953. }
  6954. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  6955. operand->mode = Addressing_Invalid;
  6956. operand->type = t_invalid;
  6957. }
  6958. operand->expr = call;
  6959. return builtin_procs[id].kind;
  6960. }
  6961. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  6962. Entity *initial_entity = entity_of_node(operand->expr);
  6963. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  6964. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  6965. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  6966. if (c->decl) {
  6967. c->decl->defer_used += 1;
  6968. }
  6969. }
  6970. add_entity_use(c, operand->expr, initial_entity);
  6971. if (initial_entity->Procedure.entry_point_only) {
  6972. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  6973. // Okay
  6974. } else {
  6975. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  6976. }
  6977. }
  6978. }
  6979. if (operand->mode != Addressing_ProcGroup) {
  6980. Type *proc_type = base_type(operand->type);
  6981. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  6982. bool valid_mode = is_operand_value(*operand);
  6983. if (!valid_type || !valid_mode) {
  6984. Ast *e = operand->expr;
  6985. gbString str = expr_to_string(e);
  6986. gbString type_str = type_to_string(operand->type);
  6987. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  6988. gb_string_free(type_str);
  6989. gb_string_free(str);
  6990. operand->mode = Addressing_Invalid;
  6991. operand->expr = call;
  6992. return Expr_Stmt;
  6993. }
  6994. }
  6995. CallArgumentData data = check_call_arguments(c, operand, call);
  6996. Type *result_type = data.result_type;
  6997. gb_zero_item(operand);
  6998. operand->expr = call;
  6999. if (result_type == t_invalid) {
  7000. operand->mode = Addressing_Invalid;
  7001. operand->type = t_invalid;
  7002. return Expr_Stmt;
  7003. }
  7004. Type *pt = base_type(operand->type);
  7005. if (pt == nullptr) {
  7006. pt = t_invalid;
  7007. }
  7008. if (pt == t_invalid) {
  7009. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7010. pt = type_of_expr(operand->expr->CallExpr.proc);
  7011. }
  7012. if (pt == t_invalid && data.gen_entity) {
  7013. pt = data.gen_entity->type;
  7014. }
  7015. }
  7016. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  7017. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  7018. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  7019. }
  7020. }
  7021. if (result_type == nullptr) {
  7022. operand->mode = Addressing_NoValue;
  7023. } else {
  7024. GB_ASSERT(is_type_tuple(result_type));
  7025. isize count = result_type->Tuple.variables.count;
  7026. switch (count) {
  7027. case 0:
  7028. operand->mode = Addressing_NoValue;
  7029. break;
  7030. case 1:
  7031. operand->mode = Addressing_Value;
  7032. operand->type = result_type->Tuple.variables[0]->type;
  7033. break;
  7034. default:
  7035. operand->mode = Addressing_Value;
  7036. operand->type = result_type;
  7037. break;
  7038. }
  7039. }
  7040. bool is_call_inlined = false;
  7041. switch (inlining) {
  7042. case ProcInlining_inline:
  7043. is_call_inlined = true;
  7044. if (proc != nullptr) {
  7045. Entity *e = entity_from_expr(proc);
  7046. if (e != nullptr && e->kind == Entity_Procedure) {
  7047. DeclInfo *decl = e->decl_info;
  7048. if (decl->proc_lit) {
  7049. ast_node(pl, ProcLit, decl->proc_lit);
  7050. if (pl->inlining == ProcInlining_no_inline) {
  7051. error(call, "'#force_inline' cannot be applied to a procedure that has been marked as '#force_no_inline'");
  7052. }
  7053. }
  7054. }
  7055. }
  7056. break;
  7057. case ProcInlining_no_inline:
  7058. break;
  7059. case ProcInlining_none:
  7060. if (proc != nullptr) {
  7061. Entity *e = entity_from_expr(proc);
  7062. if (e != nullptr && e->kind == Entity_Procedure) {
  7063. DeclInfo *decl = e->decl_info;
  7064. if (decl->proc_lit) {
  7065. ast_node(pl, ProcLit, decl->proc_lit);
  7066. if (pl->inlining == ProcInlining_inline) {
  7067. is_call_inlined = true;
  7068. }
  7069. }
  7070. }
  7071. }
  7072. }
  7073. {
  7074. String invalid;
  7075. if (pt->kind == Type_Proc && pt->Proc.require_target_feature.len != 0) {
  7076. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.require_target_feature, &invalid)) {
  7077. error(call, "Called procedure requires target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7078. } else if (!check_target_feature_is_enabled(pt->Proc.require_target_feature, &invalid)) {
  7079. error(call, "Calling this procedure requires target feature '%.*s' to be enabled", LIT(invalid));
  7080. }
  7081. }
  7082. if (pt->kind == Type_Proc && pt->Proc.enable_target_feature.len != 0) {
  7083. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.enable_target_feature, &invalid)) {
  7084. error(call, "Called procedure enables target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7085. }
  7086. // NOTE: Due to restrictions in LLVM you can not inline calls with a superset of features.
  7087. if (is_call_inlined) {
  7088. if (c->curr_proc_decl == nullptr) {
  7089. error(call, "Calling a '#force_inline' procedure that enables target features is not allowed at file scope");
  7090. } else {
  7091. GB_ASSERT(c->curr_proc_decl->entity);
  7092. GB_ASSERT(c->curr_proc_decl->entity->type->kind == Type_Proc);
  7093. String scope_features = c->curr_proc_decl->entity->type->Proc.enable_target_feature;
  7094. if (!check_target_feature_is_superset_of(scope_features, pt->Proc.enable_target_feature, &invalid)) {
  7095. error(call, "Inlined procedure enables target feature '%.*s', this requires the calling procedure to at least enable the same feature", LIT(invalid));
  7096. }
  7097. }
  7098. }
  7099. }
  7100. }
  7101. operand->expr = call;
  7102. {
  7103. Type *type = nullptr;
  7104. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7105. type = type_of_expr(operand->expr->CallExpr.proc);
  7106. }
  7107. if (type == nullptr) {
  7108. type = pt;
  7109. }
  7110. type = base_type(type);
  7111. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  7112. operand->mode = Addressing_OptionalOk;
  7113. operand->type = type->Proc.results->Tuple.variables[0]->type;
  7114. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7115. operand->expr->CallExpr.optional_ok_one = true;
  7116. }
  7117. }
  7118. }
  7119. return Expr_Expr;
  7120. }
  7121. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  7122. check_expr_base(c, o, e, t);
  7123. check_not_tuple(c, o);
  7124. char const *err_str = nullptr;
  7125. switch (o->mode) {
  7126. case Addressing_NoValue:
  7127. err_str = "used as a value";
  7128. break;
  7129. case Addressing_Type:
  7130. if (t == nullptr || !is_type_typeid(t)) {
  7131. err_str = "is not an expression but a type, in this context it is ambiguous";
  7132. }
  7133. break;
  7134. case Addressing_Builtin:
  7135. err_str = "must be called";
  7136. break;
  7137. }
  7138. if (err_str != nullptr) {
  7139. gbString str = expr_to_string(e);
  7140. error(e, "'%s' %s", str, err_str);
  7141. gb_string_free(str);
  7142. o->mode = Addressing_Invalid;
  7143. }
  7144. }
  7145. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  7146. switch (t->kind) {
  7147. case Type_Basic:
  7148. if (t->Basic.kind == Basic_string) {
  7149. if (o->mode == Addressing_Constant) {
  7150. *max_count = o->value.value_string.len;
  7151. }
  7152. if (o->mode != Addressing_Constant) {
  7153. o->mode = Addressing_Value;
  7154. }
  7155. o->type = t_u8;
  7156. return true;
  7157. } else if (t->Basic.kind == Basic_UntypedString) {
  7158. if (o->mode == Addressing_Constant) {
  7159. *max_count = o->value.value_string.len;
  7160. o->type = t_u8;
  7161. return true;
  7162. }
  7163. return false;
  7164. }
  7165. break;
  7166. case Type_MultiPointer:
  7167. o->type = t->MultiPointer.elem;
  7168. if (o->mode != Addressing_Constant) {
  7169. o->mode = Addressing_Variable;
  7170. }
  7171. return true;
  7172. case Type_Array:
  7173. *max_count = t->Array.count;
  7174. if (indirection) {
  7175. o->mode = Addressing_Variable;
  7176. } else if (o->mode != Addressing_Variable &&
  7177. o->mode != Addressing_Constant) {
  7178. o->mode = Addressing_Value;
  7179. }
  7180. o->type = t->Array.elem;
  7181. return true;
  7182. case Type_EnumeratedArray:
  7183. *max_count = t->EnumeratedArray.count;
  7184. if (indirection) {
  7185. o->mode = Addressing_Variable;
  7186. } else if (o->mode != Addressing_Variable &&
  7187. o->mode != Addressing_Constant) {
  7188. o->mode = Addressing_Value;
  7189. }
  7190. o->type = t->EnumeratedArray.elem;
  7191. return true;
  7192. case Type_Matrix:
  7193. if (indirection) {
  7194. o->mode = Addressing_Variable;
  7195. } else if (o->mode != Addressing_Variable) {
  7196. o->mode = Addressing_Value;
  7197. }
  7198. if (t->Matrix.is_row_major) {
  7199. *max_count = t->Matrix.row_count;
  7200. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.column_count);
  7201. } else {
  7202. *max_count = t->Matrix.column_count;
  7203. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  7204. }
  7205. return true;
  7206. case Type_Slice:
  7207. o->type = t->Slice.elem;
  7208. if (o->mode != Addressing_Constant) {
  7209. o->mode = Addressing_Variable;
  7210. }
  7211. return true;
  7212. case Type_RelativeMultiPointer:
  7213. {
  7214. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  7215. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  7216. o->type = pointer_type->MultiPointer.elem;
  7217. if (o->mode != Addressing_Constant) {
  7218. o->mode = Addressing_Variable;
  7219. }
  7220. }
  7221. return true;
  7222. case Type_DynamicArray:
  7223. o->type = t->DynamicArray.elem;
  7224. if (o->mode != Addressing_Constant) {
  7225. o->mode = Addressing_Variable;
  7226. }
  7227. return true;
  7228. case Type_Struct:
  7229. if (t->Struct.soa_kind != StructSoa_None) {
  7230. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7231. *max_count = t->Struct.soa_count;
  7232. }
  7233. o->type = t->Struct.soa_elem;
  7234. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  7235. o->mode = Addressing_SoaVariable;
  7236. } else {
  7237. o->mode = Addressing_Value;
  7238. }
  7239. return true;
  7240. }
  7241. return false;
  7242. }
  7243. if (is_type_pointer(original_type) && indirection) {
  7244. Type *ptr = base_type(original_type);
  7245. if (ptr->kind == Type_MultiPointer && o->mode == Addressing_SoaVariable) {
  7246. o->type = ptr->MultiPointer.elem;
  7247. o->mode = Addressing_Value;
  7248. return true;
  7249. }
  7250. }
  7251. return false;
  7252. }
  7253. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  7254. if (is_type_untyped_uninit(x)) {
  7255. return true;
  7256. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  7257. return true;
  7258. } else if (is_type_untyped_uninit(y)) {
  7259. return true;
  7260. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  7261. return true;
  7262. }
  7263. return are_types_identical(x, y);
  7264. }
  7265. gb_internal bool check_range(CheckerContext *c, Ast *node, bool is_for_loop, Operand *x, Operand *y, ExactValue *inline_for_depth_, Type *type_hint=nullptr) {
  7266. if (!is_ast_range(node)) {
  7267. return false;
  7268. }
  7269. ast_node(ie, BinaryExpr, node);
  7270. check_expr_with_type_hint(c, x, ie->left, type_hint);
  7271. if (x->mode == Addressing_Invalid) {
  7272. return false;
  7273. }
  7274. check_expr_with_type_hint(c, y, ie->right, type_hint);
  7275. if (y->mode == Addressing_Invalid) {
  7276. return false;
  7277. }
  7278. convert_to_typed(c, x, y->type);
  7279. if (x->mode == Addressing_Invalid) {
  7280. return false;
  7281. }
  7282. convert_to_typed(c, y, x->type);
  7283. if (y->mode == Addressing_Invalid) {
  7284. return false;
  7285. }
  7286. convert_to_typed(c, x, default_type(y->type));
  7287. if (x->mode == Addressing_Invalid) {
  7288. return false;
  7289. }
  7290. convert_to_typed(c, y, default_type(x->type));
  7291. if (y->mode == Addressing_Invalid) {
  7292. return false;
  7293. }
  7294. if (!are_types_identical(x->type, y->type)) {
  7295. if (x->type != t_invalid &&
  7296. y->type != t_invalid) {
  7297. gbString xt = type_to_string(x->type);
  7298. gbString yt = type_to_string(y->type);
  7299. gbString expr_str = expr_to_string(x->expr);
  7300. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  7301. gb_string_free(expr_str);
  7302. gb_string_free(yt);
  7303. gb_string_free(xt);
  7304. }
  7305. return false;
  7306. }
  7307. Type *type = x->type;
  7308. if (is_for_loop) {
  7309. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  7310. error(ie->op, "Only numerical types are allowed within interval expressions");
  7311. return false;
  7312. }
  7313. } else {
  7314. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  7315. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  7316. return false;
  7317. }
  7318. }
  7319. if (x->mode == Addressing_Constant &&
  7320. y->mode == Addressing_Constant) {
  7321. ExactValue a = x->value;
  7322. ExactValue b = y->value;
  7323. GB_ASSERT(are_types_identical(x->type, y->type));
  7324. TokenKind op = Token_Lt;
  7325. switch (ie->op.kind) {
  7326. case Token_Ellipsis: op = Token_LtEq; break; // ..
  7327. case Token_RangeFull: op = Token_LtEq; break; // ..=
  7328. case Token_RangeHalf: op = Token_Lt; break; // ..<
  7329. default: error(ie->op, "Invalid range operator"); break;
  7330. }
  7331. bool ok = compare_exact_values(op, a, b);
  7332. if (!ok) {
  7333. // TODO(bill): Better error message
  7334. error(ie->op, "Invalid interval range");
  7335. return false;
  7336. }
  7337. ExactValue inline_for_depth = exact_value_sub(b, a);
  7338. if (ie->op.kind != Token_RangeHalf) {
  7339. inline_for_depth = exact_value_increment_one(inline_for_depth);
  7340. }
  7341. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  7342. } else if (inline_for_depth_ != nullptr) {
  7343. error(ie->op, "Interval expressions must be constant");
  7344. return false;
  7345. }
  7346. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  7347. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  7348. return true;
  7349. }
  7350. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  7351. if (is_operand_nil(*o)) {
  7352. return true;
  7353. }
  7354. Ast *expr = unparen_expr(o->expr);
  7355. if (expr != nullptr) {
  7356. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  7357. if (e != nullptr && e->kind == Entity_Procedure) {
  7358. return true;
  7359. }
  7360. if (expr->kind == Ast_ProcLit) {
  7361. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  7362. return true;
  7363. }
  7364. }
  7365. return o->mode == Addressing_Constant;
  7366. }
  7367. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  7368. if (is_type_enum(th)) {
  7369. Type *enum_type = base_type(th);
  7370. GB_ASSERT(enum_type->kind == Type_Enum);
  7371. String name = ise->selector->Ident.token.string;
  7372. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  7373. if (e == nullptr) {
  7374. return false;
  7375. }
  7376. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  7377. GB_ASSERT(e->kind == Entity_Constant);
  7378. o->value = e->Constant.value;
  7379. o->mode = Addressing_Constant;
  7380. o->type = e->type;
  7381. return true;
  7382. }
  7383. if (is_type_union(th)) {
  7384. TEMPORARY_ALLOCATOR_GUARD();
  7385. Type *union_type = base_type(th);
  7386. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  7387. for (Type *vt : union_type->Union.variants) {
  7388. Operand x = {};
  7389. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  7390. array_add(&operands, x);
  7391. }
  7392. }
  7393. if (operands.count == 1) {
  7394. *o = operands[0];
  7395. return true;
  7396. }
  7397. }
  7398. return false;
  7399. }
  7400. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7401. ast_node(ise, ImplicitSelectorExpr, node);
  7402. o->type = t_invalid;
  7403. o->expr = node;
  7404. o->mode = Addressing_Invalid;
  7405. Type *th = type_hint;
  7406. if (th == nullptr) {
  7407. gbString str = expr_to_string(node);
  7408. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  7409. gb_string_free(str);
  7410. return Expr_Expr;
  7411. }
  7412. o->type = th;
  7413. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  7414. if (!ok) {
  7415. String name = ise->selector->Ident.token.string;
  7416. if (is_type_enum(th)) {
  7417. ERROR_BLOCK();
  7418. Type *bt = base_type(th);
  7419. GB_ASSERT(bt->kind == Type_Enum);
  7420. gbString typ = type_to_string(th);
  7421. defer (gb_string_free(typ));
  7422. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  7423. check_did_you_mean_type(name, bt->Enum.fields);
  7424. } else {
  7425. gbString typ = type_to_string(th);
  7426. gbString str = expr_to_string(node);
  7427. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  7428. gb_string_free(str);
  7429. gb_string_free(typ);
  7430. }
  7431. }
  7432. o->expr = node;
  7433. return Expr_Expr;
  7434. }
  7435. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  7436. switch (x->mode) {
  7437. case Addressing_MapIndex:
  7438. case Addressing_OptionalOk:
  7439. case Addressing_OptionalOkPtr:
  7440. if (val_type_) *val_type_ = x->type;
  7441. break;
  7442. default:
  7443. if (ok_type_) *ok_type_ = x->type;
  7444. return;
  7445. }
  7446. Ast *expr = unparen_expr(x->expr);
  7447. if (expr->kind == Ast_CallExpr) {
  7448. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  7449. if (is_type_proc(pt)) {
  7450. Type *tuple = pt->Proc.results;
  7451. if (pt->Proc.result_count >= 2) {
  7452. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7453. }
  7454. if (change_operand) {
  7455. expr->CallExpr.optional_ok_one = false;
  7456. x->type = tuple;
  7457. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7458. }
  7459. return;
  7460. }
  7461. }
  7462. Type *tuple = make_optional_ok_type(x->type);
  7463. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7464. if (change_operand) {
  7465. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7466. x->type = tuple;
  7467. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  7468. }
  7469. }
  7470. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7471. ast_node(ie, MatrixIndexExpr, node);
  7472. check_expr(c, o, ie->expr);
  7473. node->viral_state_flags |= ie->expr->viral_state_flags;
  7474. if (o->mode == Addressing_Invalid) {
  7475. o->expr = node;
  7476. return;
  7477. }
  7478. Type *t = base_type(type_deref(o->type));
  7479. bool is_ptr = is_type_pointer(o->type);
  7480. bool is_const = o->mode == Addressing_Constant;
  7481. if (t->kind != Type_Matrix) {
  7482. gbString str = expr_to_string(o->expr);
  7483. gbString type_str = type_to_string(o->type);
  7484. defer (gb_string_free(str));
  7485. defer (gb_string_free(type_str));
  7486. if (is_const) {
  7487. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  7488. } else {
  7489. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  7490. }
  7491. o->mode = Addressing_Invalid;
  7492. o->expr = node;
  7493. return;
  7494. }
  7495. o->type = t->Matrix.elem;
  7496. if (is_ptr) {
  7497. o->mode = Addressing_Variable;
  7498. } else if (o->mode != Addressing_Variable) {
  7499. o->mode = Addressing_Value;
  7500. }
  7501. if (ie->row_index == nullptr) {
  7502. gbString str = expr_to_string(o->expr);
  7503. error(o->expr, "Missing row index for '%s'", str);
  7504. gb_string_free(str);
  7505. o->mode = Addressing_Invalid;
  7506. o->expr = node;
  7507. return;
  7508. }
  7509. if (ie->column_index == nullptr) {
  7510. gbString str = expr_to_string(o->expr);
  7511. error(o->expr, "Missing column index for '%s'", str);
  7512. gb_string_free(str);
  7513. o->mode = Addressing_Invalid;
  7514. o->expr = node;
  7515. return;
  7516. }
  7517. i64 row_count = t->Matrix.row_count;
  7518. i64 column_count = t->Matrix.column_count;
  7519. i64 row_index = 0;
  7520. i64 column_index = 0;
  7521. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7522. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7523. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7524. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7525. }
  7526. gb_unused(row_ok);
  7527. gb_unused(column_ok);
  7528. }
  7529. struct TypeAndToken {
  7530. Type *type;
  7531. Token token;
  7532. };
  7533. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7534. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7535. if (operand.mode != Addressing_Constant) {
  7536. return;
  7537. }
  7538. if (operand.value.kind == ExactValue_Invalid) {
  7539. return;
  7540. }
  7541. uintptr key = hash_exact_value(operand.value);
  7542. GB_ASSERT(key != 0);
  7543. isize count = multi_map_count(seen, key);
  7544. if (count) {
  7545. TEMPORARY_ALLOCATOR_GUARD();
  7546. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  7547. multi_map_get_all(seen, key, taps);
  7548. for (isize i = 0; i < count; i++) {
  7549. TypeAndToken tap = taps[i];
  7550. Operand to = {};
  7551. to.mode = Addressing_Value;
  7552. to.type = tap.type;
  7553. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7554. continue;
  7555. }
  7556. TokenPos pos = tap.token.pos;
  7557. if (use_expr) {
  7558. gbString expr_str = expr_to_string(operand.expr);
  7559. error(operand.expr,
  7560. "Duplicate case '%s'\n"
  7561. "\tprevious case at %s",
  7562. expr_str,
  7563. token_pos_to_string(pos));
  7564. gb_string_free(expr_str);
  7565. } else {
  7566. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7567. }
  7568. return;
  7569. }
  7570. }
  7571. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7572. multi_map_insert(seen, key, tap);
  7573. }
  7574. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7575. if (is_type_enum(x.type)) {
  7576. // TODO(bill): Fix this logic so it's fast!!!
  7577. i64 v0 = exact_value_to_i64(lhs.value);
  7578. i64 v1 = exact_value_to_i64(rhs.value);
  7579. Operand v = {};
  7580. v.mode = Addressing_Constant;
  7581. v.type = x.type;
  7582. v.expr = x.expr;
  7583. Type *bt = base_type(x.type);
  7584. GB_ASSERT(bt->kind == Type_Enum);
  7585. for (i64 vi = v0; vi <= v1; vi++) {
  7586. if (upper_op != Token_LtEq && vi == v1) {
  7587. break;
  7588. }
  7589. v.value = exact_value_i64(vi);
  7590. add_constant_switch_case(ctx, seen, v);
  7591. }
  7592. } else {
  7593. add_constant_switch_case(ctx, seen, lhs);
  7594. if (upper_op == Token_LtEq) {
  7595. add_constant_switch_case(ctx, seen, rhs);
  7596. }
  7597. }
  7598. }
  7599. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7600. add_constant_switch_case(ctx, seen, x);
  7601. }
  7602. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7603. ast_node(bd, BasicDirective, node);
  7604. ExprKind kind = Expr_Expr;
  7605. o->mode = Addressing_Constant;
  7606. String name = bd->name.string;
  7607. if (name == "file") {
  7608. String file = get_file_path_string(bd->token.pos.file_id);
  7609. if (build_context.obfuscate_source_code_locations) {
  7610. file = obfuscate_string(file, "F");
  7611. }
  7612. o->type = t_untyped_string;
  7613. o->value = exact_value_string(file);
  7614. } else if (name == "directory") {
  7615. String file = get_file_path_string(bd->token.pos.file_id);
  7616. String path = dir_from_path(file);
  7617. if (build_context.obfuscate_source_code_locations) {
  7618. path = obfuscate_string(path, "D");
  7619. }
  7620. o->type = t_untyped_string;
  7621. o->value = exact_value_string(path);
  7622. } else if (name == "line") {
  7623. i32 line = bd->token.pos.line;
  7624. if (build_context.obfuscate_source_code_locations) {
  7625. line = obfuscate_i32(line);
  7626. }
  7627. o->type = t_untyped_integer;
  7628. o->value = exact_value_i64(line);
  7629. } else if (name == "procedure") {
  7630. if (c->curr_proc_decl == nullptr) {
  7631. error(node, "#procedure may only be used within procedures");
  7632. o->type = t_untyped_string;
  7633. o->value = exact_value_string(str_lit(""));
  7634. } else {
  7635. String p = c->proc_name;
  7636. if (build_context.obfuscate_source_code_locations) {
  7637. p = obfuscate_string(p, "P");
  7638. }
  7639. o->type = t_untyped_string;
  7640. o->value = exact_value_string(p);
  7641. }
  7642. } else if (name == "caller_location") {
  7643. init_core_source_code_location(c->checker);
  7644. error(node, "#caller_location may only be used as a default argument parameter");
  7645. o->type = t_source_code_location;
  7646. o->mode = Addressing_Value;
  7647. } else {
  7648. if (name == "location") {
  7649. init_core_source_code_location(c->checker);
  7650. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  7651. o->type = t_source_code_location;
  7652. o->mode = Addressing_Value;
  7653. } else if (
  7654. name == "assert" ||
  7655. name == "defined" ||
  7656. name == "config" ||
  7657. name == "exists" ||
  7658. name == "load" ||
  7659. name == "load_hash" ||
  7660. name == "load_directory" ||
  7661. name == "load_or"
  7662. ) {
  7663. error(node, "'#%.*s' must be used as a call", LIT(name));
  7664. o->type = t_invalid;
  7665. o->mode = Addressing_Invalid;
  7666. } else {
  7667. error(node, "Unknown directive: #%.*s", LIT(name));
  7668. o->type = t_invalid;
  7669. o->mode = Addressing_Invalid;
  7670. }
  7671. }
  7672. return kind;
  7673. }
  7674. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7675. ExprKind kind = Expr_Expr;
  7676. Operand cond = {Addressing_Invalid};
  7677. ast_node(te, TernaryIfExpr, node);
  7678. check_expr(c, &cond, te->cond);
  7679. node->viral_state_flags |= te->cond->viral_state_flags;
  7680. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7681. error(te->cond, "Non-boolean condition in ternary if expression");
  7682. }
  7683. Operand x = {Addressing_Invalid};
  7684. Operand y = {Addressing_Invalid};
  7685. check_expr_or_type(c, &x, te->x, type_hint);
  7686. node->viral_state_flags |= te->x->viral_state_flags;
  7687. if (te->y != nullptr) {
  7688. Type *th = type_hint;
  7689. if (type_hint == nullptr && is_type_typed(x.type)) {
  7690. th = x.type;
  7691. }
  7692. check_expr_or_type(c, &y, te->y, th);
  7693. node->viral_state_flags |= te->y->viral_state_flags;
  7694. } else {
  7695. error(node, "A ternary expression must have an else clause");
  7696. return kind;
  7697. }
  7698. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7699. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7700. gbString type_string = expr_to_string(type_expr);
  7701. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7702. gb_string_free(type_string);
  7703. return kind;
  7704. }
  7705. if (x.type == nullptr || x.type == t_invalid ||
  7706. y.type == nullptr || y.type == t_invalid) {
  7707. return kind;
  7708. }
  7709. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7710. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7711. if (x.mode == Addressing_Invalid) {
  7712. return kind;
  7713. }
  7714. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7715. if (y.mode == Addressing_Invalid) {
  7716. x.mode = Addressing_Invalid;
  7717. return kind;
  7718. }
  7719. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7720. // x: union{f32} = f32(123) if cond else nil
  7721. if (type_hint && !is_type_any(type_hint)) {
  7722. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7723. check_cast(c, &x, type_hint);
  7724. check_cast(c, &y, type_hint);
  7725. }
  7726. }
  7727. if (!ternary_compare_types(x.type, y.type)) {
  7728. gbString its = type_to_string(x.type);
  7729. gbString ets = type_to_string(y.type);
  7730. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7731. gb_string_free(ets);
  7732. gb_string_free(its);
  7733. return kind;
  7734. }
  7735. o->type = x.type;
  7736. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  7737. o->type = y.type;
  7738. }
  7739. o->mode = Addressing_Value;
  7740. o->expr = node;
  7741. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7742. if (check_cast_internal(c, &x, type_hint) &&
  7743. check_cast_internal(c, &y, type_hint)) {
  7744. convert_to_typed(c, o, type_hint);
  7745. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7746. o->type = type_hint;
  7747. }
  7748. }
  7749. return kind;
  7750. }
  7751. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7752. ExprKind kind = Expr_Expr;
  7753. Operand cond = {};
  7754. ast_node(te, TernaryWhenExpr, node);
  7755. check_expr(c, &cond, te->cond);
  7756. node->viral_state_flags |= te->cond->viral_state_flags;
  7757. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7758. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7759. return kind;
  7760. }
  7761. if (cond.value.value_bool) {
  7762. check_expr_or_type(c, o, te->x, type_hint);
  7763. node->viral_state_flags |= te->x->viral_state_flags;
  7764. } else {
  7765. if (te->y != nullptr) {
  7766. check_expr_or_type(c, o, te->y, type_hint);
  7767. node->viral_state_flags |= te->y->viral_state_flags;
  7768. } else {
  7769. error(node, "A ternary when expression must have an else clause");
  7770. return kind;
  7771. }
  7772. }
  7773. return kind;
  7774. }
  7775. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7776. ast_node(oe, OrElseExpr, node);
  7777. String name = oe->token.string;
  7778. Ast *arg = oe->x;
  7779. Ast *default_value = oe->y;
  7780. Operand x = {};
  7781. Operand y = {};
  7782. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7783. if (is_load_directive_call(arg)) {
  7784. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7785. // Allow for chaining of '#load(path) or_else #load(path)'
  7786. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  7787. bool y_is_diverging = false;
  7788. check_expr_base(c, &y, default_value, x.type);
  7789. switch (y.mode) {
  7790. case Addressing_NoValue:
  7791. if (is_diverging_expr(y.expr)) {
  7792. // Allow
  7793. y.mode = Addressing_Value;
  7794. y_is_diverging = true;
  7795. } else {
  7796. error_operand_no_value(&y);
  7797. y.mode = Addressing_Invalid;
  7798. }
  7799. break;
  7800. case Addressing_Type:
  7801. error_operand_not_expression(&y);
  7802. y.mode = Addressing_Invalid;
  7803. break;
  7804. }
  7805. if (y.mode == Addressing_Invalid) {
  7806. o->mode = Addressing_Value;
  7807. o->type = t_invalid;
  7808. o->expr = node;
  7809. return Expr_Expr;
  7810. }
  7811. if (!y_is_diverging) {
  7812. check_assignment(c, &y, x.type, name);
  7813. if (y.mode != Addressing_Constant) {
  7814. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7815. }
  7816. }
  7817. }
  7818. if (res == LoadDirective_Success) {
  7819. *o = x;
  7820. } else {
  7821. *o = y;
  7822. }
  7823. o->expr = node;
  7824. return Expr_Expr;
  7825. }
  7826. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7827. if (x.mode == Addressing_Invalid) {
  7828. o->mode = Addressing_Value;
  7829. o->type = t_invalid;
  7830. o->expr = node;
  7831. return Expr_Expr;
  7832. }
  7833. bool y_is_diverging = false;
  7834. check_expr_base(c, &y, default_value, x.type);
  7835. switch (y.mode) {
  7836. case Addressing_NoValue:
  7837. if (is_diverging_expr(y.expr)) {
  7838. // Allow
  7839. y.mode = Addressing_Value;
  7840. y_is_diverging = true;
  7841. } else {
  7842. error_operand_no_value(&y);
  7843. y.mode = Addressing_Invalid;
  7844. }
  7845. break;
  7846. case Addressing_Type:
  7847. error_operand_not_expression(&y);
  7848. y.mode = Addressing_Invalid;
  7849. break;
  7850. }
  7851. if (y.mode == Addressing_Invalid) {
  7852. o->mode = Addressing_Value;
  7853. o->type = t_invalid;
  7854. o->expr = node;
  7855. return Expr_Expr;
  7856. }
  7857. Type *left_type = nullptr;
  7858. Type *right_type = nullptr;
  7859. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7860. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7861. if (left_type != nullptr) {
  7862. if (!y_is_diverging) {
  7863. check_assignment(c, &y, left_type, name);
  7864. }
  7865. } else {
  7866. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7867. }
  7868. if (left_type == nullptr) {
  7869. left_type = t_invalid;
  7870. }
  7871. o->mode = Addressing_Value;
  7872. o->type = left_type;
  7873. o->expr = node;
  7874. return Expr_Expr;
  7875. }
  7876. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7877. ast_node(re, OrReturnExpr, node);
  7878. String name = re->token.string;
  7879. Operand x = {};
  7880. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  7881. if (x.mode == Addressing_Invalid) {
  7882. o->mode = Addressing_Value;
  7883. o->type = t_invalid;
  7884. o->expr = node;
  7885. return Expr_Expr;
  7886. }
  7887. Type *left_type = nullptr;
  7888. Type *right_type = nullptr;
  7889. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7890. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  7891. if (right_type == nullptr) {
  7892. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7893. } else {
  7894. Type *proc_type = base_type(c->curr_proc_sig);
  7895. GB_ASSERT(proc_type->kind == Type_Proc);
  7896. Type *result_type = proc_type->Proc.results;
  7897. if (result_type == nullptr) {
  7898. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  7899. } else {
  7900. GB_ASSERT(result_type->kind == Type_Tuple);
  7901. auto const &vars = result_type->Tuple.variables;
  7902. Type *end_type = vars[vars.count-1]->type;
  7903. if (vars.count > 1) {
  7904. if (!proc_type->Proc.has_named_results) {
  7905. 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));
  7906. }
  7907. }
  7908. Operand rhs = {};
  7909. rhs.type = right_type;
  7910. rhs.mode = Addressing_Value;
  7911. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  7912. // NOTE(bill): allow implicit conversion between boolean types
  7913. // within 'or_return' to improve the experience using third-party code
  7914. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  7915. ERROR_BLOCK();
  7916. // TODO(bill): better error message
  7917. gbString a = type_to_string(right_type);
  7918. gbString b = type_to_string(end_type);
  7919. gbString ret_type = type_to_string(result_type);
  7920. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  7921. if (vars.count == 1) {
  7922. error_line("\tProcedure return value type: %s\n", ret_type);
  7923. } else {
  7924. error_line("\tProcedure return value types: (%s)\n", ret_type);
  7925. }
  7926. gb_string_free(ret_type);
  7927. gb_string_free(b);
  7928. gb_string_free(a);
  7929. }
  7930. }
  7931. }
  7932. o->expr = node;
  7933. o->type = left_type;
  7934. if (left_type != nullptr) {
  7935. o->mode = Addressing_Value;
  7936. } else {
  7937. o->mode = Addressing_NoValue;
  7938. }
  7939. if (c->curr_proc_sig == nullptr) {
  7940. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7941. }
  7942. if (c->in_defer) {
  7943. error(node, "'or_return' cannot be used within a defer statement");
  7944. }
  7945. return Expr_Expr;
  7946. }
  7947. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7948. ast_node(be, OrBranchExpr, node);
  7949. String name = be->token.string;
  7950. Operand x = {};
  7951. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  7952. if (x.mode == Addressing_Invalid) {
  7953. o->mode = Addressing_Value;
  7954. o->type = t_invalid;
  7955. o->expr = node;
  7956. return Expr_Expr;
  7957. }
  7958. Type *left_type = nullptr;
  7959. Type *right_type = nullptr;
  7960. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7961. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  7962. if (right_type == nullptr) {
  7963. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7964. } else {
  7965. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  7966. // okay
  7967. } else {
  7968. gbString s = type_to_string(right_type);
  7969. error(node, "'%.*s' requires a boolean or nil-able type, got %s", LIT(name), s);
  7970. gb_string_free(s);
  7971. }
  7972. }
  7973. o->expr = node;
  7974. o->type = left_type;
  7975. if (left_type != nullptr) {
  7976. o->mode = Addressing_Value;
  7977. } else {
  7978. o->mode = Addressing_NoValue;
  7979. }
  7980. if (c->curr_proc_sig == nullptr) {
  7981. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7982. }
  7983. Ast *label = be->label;
  7984. switch (be->token.kind) {
  7985. case Token_or_break:
  7986. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  7987. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  7988. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  7989. }
  7990. break;
  7991. case Token_or_continue:
  7992. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  7993. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  7994. }
  7995. break;
  7996. }
  7997. if (label != nullptr) {
  7998. if (label->kind != Ast_Ident) {
  7999. error(label, "A branch statement's label name must be an identifier");
  8000. return Expr_Expr;
  8001. }
  8002. Ast *ident = label;
  8003. String name = ident->Ident.token.string;
  8004. Operand o = {};
  8005. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  8006. if (e == nullptr) {
  8007. error(ident, "Undeclared label name: %.*s", LIT(name));
  8008. return Expr_Expr;
  8009. }
  8010. add_entity_use(c, ident, e);
  8011. if (e->kind != Entity_Label) {
  8012. error(ident, "'%.*s' is not a label", LIT(name));
  8013. return Expr_Expr;
  8014. }
  8015. Ast *parent = e->Label.parent;
  8016. GB_ASSERT(parent != nullptr);
  8017. switch (parent->kind) {
  8018. case Ast_BlockStmt:
  8019. case Ast_IfStmt:
  8020. case Ast_SwitchStmt:
  8021. if (be->token.kind != Token_or_break) {
  8022. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  8023. }
  8024. break;
  8025. case Ast_RangeStmt:
  8026. case Ast_ForStmt:
  8027. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  8028. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  8029. }
  8030. break;
  8031. }
  8032. }
  8033. return Expr_Expr;
  8034. }
  8035. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  8036. Type *bt = base_type(type);
  8037. StringSet fields_visited = {};
  8038. defer (string_set_destroy(&fields_visited));
  8039. StringMap<String> fields_visited_through_raw_union = {};
  8040. defer (string_map_destroy(&fields_visited_through_raw_union));
  8041. String assignment_str = str_lit("structure literal");
  8042. if (bt->kind == Type_BitField) {
  8043. assignment_str = str_lit("bit_field literal");
  8044. }
  8045. for (Ast *elem : elems) {
  8046. if (elem->kind != Ast_FieldValue) {
  8047. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8048. continue;
  8049. }
  8050. ast_node(fv, FieldValue, elem);
  8051. Ast *ident = fv->field;
  8052. if (ident->kind == Ast_ImplicitSelectorExpr) {
  8053. gbString expr_str = expr_to_string(ident);
  8054. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  8055. gb_string_free(expr_str);
  8056. ident = ident->ImplicitSelectorExpr.selector;
  8057. }
  8058. if (ident->kind != Ast_Ident) {
  8059. gbString expr_str = expr_to_string(ident);
  8060. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  8061. gb_string_free(expr_str);
  8062. continue;
  8063. }
  8064. String name = ident->Ident.token.string;
  8065. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8066. bool is_unknown = sel.entity == nullptr;
  8067. if (is_unknown) {
  8068. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  8069. continue;
  8070. }
  8071. Entity *field = nullptr;
  8072. if (bt->kind == Type_Struct) {
  8073. field = bt->Struct.fields[sel.index[0]];
  8074. } else if (bt->kind == Type_BitField) {
  8075. field = bt->BitField.fields[sel.index[0]];
  8076. } else {
  8077. GB_PANIC("Unknown type");
  8078. }
  8079. add_entity_use(c, ident, field);
  8080. if (string_set_update(&fields_visited, name)) {
  8081. if (sel.index.count > 1) {
  8082. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8083. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8084. } else {
  8085. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  8086. }
  8087. } else {
  8088. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  8089. }
  8090. continue;
  8091. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8092. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8093. continue;
  8094. }
  8095. if (sel.indirect) {
  8096. error(ident, "Cannot assign to the %d-nested anonymous indirect field '%.*s' in a %.*s", cast(int)sel.index.count-1, LIT(name), LIT(assignment_str));
  8097. continue;
  8098. }
  8099. if (sel.index.count > 1) {
  8100. GB_ASSERT(bt->kind == Type_Struct);
  8101. if (is_constant) {
  8102. Type *ft = type;
  8103. for (i32 index : sel.index) {
  8104. Type *bt = base_type(ft);
  8105. switch (bt->kind) {
  8106. case Type_Struct:
  8107. if (bt->Struct.is_raw_union) {
  8108. is_constant = false;
  8109. break;
  8110. }
  8111. ft = bt->Struct.fields[index]->type;
  8112. break;
  8113. case Type_Array:
  8114. ft = bt->Array.elem;
  8115. break;
  8116. case Type_BitField:
  8117. is_constant = false;
  8118. ft = bt->BitField.fields[index]->type;
  8119. break;
  8120. default:
  8121. GB_PANIC("invalid type: %s", type_to_string(ft));
  8122. break;
  8123. }
  8124. }
  8125. if (is_constant &&
  8126. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  8127. is_constant = false;
  8128. }
  8129. }
  8130. Type *nested_ft = bt;
  8131. for (i32 index : sel.index) {
  8132. Type *bt = base_type(nested_ft);
  8133. switch (bt->kind) {
  8134. case Type_Struct:
  8135. if (bt->Struct.is_raw_union) {
  8136. for (Entity *re : bt->Struct.fields) {
  8137. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  8138. }
  8139. }
  8140. nested_ft = bt->Struct.fields[index]->type;
  8141. break;
  8142. case Type_Array:
  8143. nested_ft = bt->Array.elem;
  8144. break;
  8145. case Type_BitField:
  8146. nested_ft = bt->BitField.fields[index]->type;
  8147. break;
  8148. default:
  8149. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  8150. break;
  8151. }
  8152. }
  8153. field = sel.entity;
  8154. }
  8155. Operand o = {};
  8156. check_expr_or_type(c, &o, fv->value, field->type);
  8157. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8158. is_constant = false;
  8159. }
  8160. if (is_constant) {
  8161. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8162. }
  8163. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  8164. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  8165. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  8166. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  8167. }
  8168. check_assignment(c, &o, field->type, assignment_str);
  8169. c->bit_field_bit_size = prev_bit_field_bit_size;
  8170. }
  8171. }
  8172. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  8173. type_expr = unparen_expr(type_expr);
  8174. if (type_expr == nullptr) {
  8175. return false;
  8176. }
  8177. // [?]Type
  8178. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  8179. Ast *count = type_expr->ArrayType.count;
  8180. if (count->kind == Ast_UnaryExpr &&
  8181. count->UnaryExpr.op.kind == Token_Question) {
  8182. return true;
  8183. }
  8184. }
  8185. return false;
  8186. }
  8187. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8188. ExprKind kind = Expr_Expr;
  8189. ast_node(cl, CompoundLit, node);
  8190. Type *type = type_hint;
  8191. if (type != nullptr && is_type_untyped(type)) {
  8192. type = nullptr;
  8193. }
  8194. bool is_to_be_determined_array_count = false;
  8195. bool is_constant = true;
  8196. Ast *type_expr = cl->type;
  8197. bool used_type_hint_expr = false;
  8198. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  8199. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  8200. type_expr = clone_ast(c->type_hint_expr);
  8201. used_type_hint_expr = true;
  8202. }
  8203. }
  8204. if (type_expr != nullptr) {
  8205. type = nullptr;
  8206. // [?]Type
  8207. if (type_expr->kind == Ast_ArrayType) {
  8208. Ast *count = type_expr->ArrayType.count;
  8209. if (count != nullptr) {
  8210. if (count->kind == Ast_UnaryExpr &&
  8211. count->UnaryExpr.op.kind == Token_Question) {
  8212. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  8213. is_to_be_determined_array_count = true;
  8214. }
  8215. } else {
  8216. type = alloc_type_slice(check_type(c, type_expr->ArrayType.elem));
  8217. }
  8218. if (cl->elems.count > 0) {
  8219. if (type_expr->ArrayType.tag != nullptr) {
  8220. Ast *tag = type_expr->ArrayType.tag;
  8221. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8222. String name = tag->BasicDirective.name.string;
  8223. if (name == "soa") {
  8224. error(node, "#soa arrays are not supported for compound literals");
  8225. return kind;
  8226. }
  8227. }
  8228. }
  8229. } else if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  8230. if (cl->elems.count > 0) {
  8231. Ast *tag = type_expr->DynamicArrayType.tag;
  8232. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8233. String name = tag->BasicDirective.name.string;
  8234. if (name == "soa") {
  8235. error(node, "#soa arrays are not supported for compound literals");
  8236. return kind;
  8237. }
  8238. }
  8239. }
  8240. if (type == nullptr) {
  8241. type = check_type(c, type_expr);
  8242. }
  8243. }
  8244. if (type == nullptr) {
  8245. error(node, "Missing type in compound literal");
  8246. return kind;
  8247. }
  8248. Type *t = base_type(type);
  8249. if (is_type_polymorphic(t)) {
  8250. gbString str = type_to_string(type);
  8251. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  8252. o->expr = node;
  8253. o->type = type;
  8254. gb_string_free(str);
  8255. return kind;
  8256. }
  8257. switch (t->kind) {
  8258. case Type_Struct: {
  8259. if (cl->elems.count == 0) {
  8260. break; // NOTE(bill): No need to init
  8261. }
  8262. if (t->Struct.soa_kind != StructSoa_None) {
  8263. error(node, "#soa arrays are not supported for compound literals");
  8264. break;
  8265. }
  8266. if (t->Struct.is_raw_union) {
  8267. if (cl->elems.count > 0) {
  8268. // NOTE: unions cannot be constant
  8269. is_constant = false;
  8270. if (cl->elems[0]->kind != Ast_FieldValue) {
  8271. gbString type_str = type_to_string(type);
  8272. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  8273. gb_string_free(type_str);
  8274. } else {
  8275. if (cl->elems.count != 1) {
  8276. gbString type_str = type_to_string(type);
  8277. 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);
  8278. gb_string_free(type_str);
  8279. } else {
  8280. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8281. }
  8282. }
  8283. }
  8284. break;
  8285. }
  8286. wait_signal_until_available(&t->Struct.fields_wait_signal);
  8287. isize field_count = t->Struct.fields.count;
  8288. isize min_field_count = t->Struct.fields.count;
  8289. for (isize i = min_field_count-1; i >= 0; i--) {
  8290. Entity *e = t->Struct.fields[i];
  8291. GB_ASSERT(e->kind == Entity_Variable);
  8292. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  8293. min_field_count--;
  8294. } else {
  8295. break;
  8296. }
  8297. }
  8298. if (cl->elems[0]->kind == Ast_FieldValue) {
  8299. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8300. } else {
  8301. bool seen_field_value = false;
  8302. for_array(index, cl->elems) {
  8303. Entity *field = nullptr;
  8304. Ast *elem = cl->elems[index];
  8305. if (elem->kind == Ast_FieldValue) {
  8306. seen_field_value = true;
  8307. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8308. continue;
  8309. } else if (seen_field_value) {
  8310. error(elem, "Value elements cannot be used after a 'field = value'");
  8311. continue;
  8312. }
  8313. if (index >= field_count) {
  8314. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8315. break;
  8316. }
  8317. if (field == nullptr) {
  8318. field = t->Struct.fields[index];
  8319. }
  8320. Operand o = {};
  8321. check_expr_or_type(c, &o, elem, field->type);
  8322. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8323. is_constant = false;
  8324. }
  8325. if (is_constant) {
  8326. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8327. }
  8328. check_assignment(c, &o, field->type, str_lit("structure literal"));
  8329. }
  8330. if (cl->elems.count < field_count) {
  8331. if (min_field_count < field_count) {
  8332. if (cl->elems.count < min_field_count) {
  8333. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  8334. }
  8335. } else {
  8336. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8337. }
  8338. }
  8339. }
  8340. break;
  8341. }
  8342. case Type_Slice:
  8343. case Type_Array:
  8344. case Type_DynamicArray:
  8345. case Type_SimdVector:
  8346. case Type_Matrix:
  8347. {
  8348. Type *elem_type = nullptr;
  8349. String context_name = {};
  8350. i64 max_type_count = -1;
  8351. if (t->kind == Type_Slice) {
  8352. elem_type = t->Slice.elem;
  8353. context_name = str_lit("slice literal");
  8354. } else if (t->kind == Type_Array) {
  8355. elem_type = t->Array.elem;
  8356. context_name = str_lit("array literal");
  8357. if (!is_to_be_determined_array_count) {
  8358. max_type_count = t->Array.count;
  8359. }
  8360. } else if (t->kind == Type_DynamicArray) {
  8361. elem_type = t->DynamicArray.elem;
  8362. context_name = str_lit("dynamic array literal");
  8363. is_constant = false;
  8364. if (!build_context.no_dynamic_literals) {
  8365. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  8366. add_package_dependency(c, "runtime", "__dynamic_array_append");
  8367. }
  8368. } else if (t->kind == Type_SimdVector) {
  8369. elem_type = t->SimdVector.elem;
  8370. context_name = str_lit("simd vector literal");
  8371. max_type_count = t->SimdVector.count;
  8372. } else if (t->kind == Type_Matrix) {
  8373. elem_type = t->Matrix.elem;
  8374. context_name = str_lit("matrix literal");
  8375. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  8376. } else {
  8377. GB_PANIC("unreachable");
  8378. }
  8379. i64 max = 0;
  8380. Type *bet = base_type(elem_type);
  8381. if (!elem_type_can_be_constant(bet)) {
  8382. is_constant = false;
  8383. }
  8384. if (bet == t_invalid) {
  8385. break;
  8386. }
  8387. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8388. RangeCache rc = range_cache_make(heap_allocator());
  8389. defer (range_cache_destroy(&rc));
  8390. for (Ast *elem : cl->elems) {
  8391. if (elem->kind != Ast_FieldValue) {
  8392. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8393. continue;
  8394. }
  8395. ast_node(fv, FieldValue, elem);
  8396. if (is_ast_range(fv->field)) {
  8397. Token op = fv->field->BinaryExpr.op;
  8398. Operand x = {};
  8399. Operand y = {};
  8400. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  8401. if (!ok) {
  8402. continue;
  8403. }
  8404. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  8405. error(x.expr, "Expected a constant integer as an array field");
  8406. continue;
  8407. }
  8408. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  8409. error(y.expr, "Expected a constant integer as an array field");
  8410. continue;
  8411. }
  8412. i64 lo = exact_value_to_i64(x.value);
  8413. i64 hi = exact_value_to_i64(y.value);
  8414. i64 max_index = hi;
  8415. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  8416. hi -= 1;
  8417. } else { // .. (inclusive)
  8418. max_index += 1;
  8419. }
  8420. bool new_range = range_cache_add_range(&rc, lo, hi);
  8421. if (!new_range) {
  8422. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  8423. continue;
  8424. }
  8425. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  8426. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  8427. continue;
  8428. }
  8429. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  8430. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  8431. continue;
  8432. }
  8433. if (max < hi) {
  8434. max = max_index;
  8435. }
  8436. Operand operand = {};
  8437. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8438. check_assignment(c, &operand, elem_type, context_name);
  8439. is_constant = is_constant && operand.mode == Addressing_Constant;
  8440. } else {
  8441. Operand op_index = {};
  8442. check_expr(c, &op_index, fv->field);
  8443. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  8444. error(elem, "Expected a constant integer as an array field");
  8445. continue;
  8446. }
  8447. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  8448. i64 index = exact_value_to_i64(op_index.value);
  8449. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  8450. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  8451. continue;
  8452. }
  8453. bool new_index = range_cache_add_index(&rc, index);
  8454. if (!new_index) {
  8455. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  8456. continue;
  8457. }
  8458. if (max < index+1) {
  8459. max = index+1;
  8460. }
  8461. Operand operand = {};
  8462. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8463. check_assignment(c, &operand, elem_type, context_name);
  8464. is_constant = is_constant && operand.mode == Addressing_Constant;
  8465. }
  8466. }
  8467. cl->max_count = max;
  8468. } else {
  8469. isize index = 0;
  8470. for (; index < cl->elems.count; index++) {
  8471. Ast *e = cl->elems[index];
  8472. if (e == nullptr) {
  8473. error(node, "Invalid literal element");
  8474. continue;
  8475. }
  8476. if (e->kind == Ast_FieldValue) {
  8477. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8478. continue;
  8479. }
  8480. if (0 <= max_type_count && max_type_count <= index) {
  8481. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8482. }
  8483. Operand operand = {};
  8484. check_expr_with_type_hint(c, &operand, e, elem_type);
  8485. check_assignment(c, &operand, elem_type, context_name);
  8486. is_constant = is_constant && operand.mode == Addressing_Constant;
  8487. }
  8488. if (max < index) {
  8489. max = index;
  8490. }
  8491. }
  8492. if (t->kind == Type_Array) {
  8493. if (is_to_be_determined_array_count) {
  8494. t->Array.count = max;
  8495. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8496. if (0 < max && max < t->Array.count) {
  8497. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8498. }
  8499. }
  8500. }
  8501. if (t->kind == Type_SimdVector) {
  8502. if (!is_constant) {
  8503. // error(node, "Expected all constant elements for a simd vector");
  8504. }
  8505. }
  8506. if (t->kind == Type_DynamicArray) {
  8507. if (build_context.no_dynamic_literals && cl->elems.count) {
  8508. error(node, "Compound literals of dynamic types have been disabled");
  8509. }
  8510. }
  8511. if (t->kind == Type_Matrix) {
  8512. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8513. if (0 < max && max < max_type_count) {
  8514. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  8515. }
  8516. }
  8517. }
  8518. break;
  8519. }
  8520. case Type_EnumeratedArray:
  8521. {
  8522. Type *elem_type = t->EnumeratedArray.elem;
  8523. Type *index_type = t->EnumeratedArray.index;
  8524. String context_name = str_lit("enumerated array literal");
  8525. i64 max_type_count = t->EnumeratedArray.count;
  8526. gbString index_type_str = type_to_string(index_type);
  8527. defer (gb_string_free(index_type_str));
  8528. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  8529. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  8530. String total_lo_string = {};
  8531. String total_hi_string = {};
  8532. GB_ASSERT(is_type_enum(index_type));
  8533. {
  8534. Type *bt = base_type(index_type);
  8535. GB_ASSERT(bt->kind == Type_Enum);
  8536. for (Entity *f : bt->Enum.fields) {
  8537. if (f->kind != Entity_Constant) {
  8538. continue;
  8539. }
  8540. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  8541. total_lo_string = f->token.string;
  8542. }
  8543. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  8544. total_hi_string = f->token.string;
  8545. }
  8546. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8547. break;
  8548. }
  8549. }
  8550. }
  8551. i64 max = 0;
  8552. Type *bet = base_type(elem_type);
  8553. if (!elem_type_can_be_constant(bet)) {
  8554. is_constant = false;
  8555. }
  8556. if (bet == t_invalid) {
  8557. break;
  8558. }
  8559. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8560. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8561. defer (map_destroy(&seen));
  8562. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8563. RangeCache rc = range_cache_make(heap_allocator());
  8564. defer (range_cache_destroy(&rc));
  8565. for (Ast *elem : cl->elems) {
  8566. if (elem->kind != Ast_FieldValue) {
  8567. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8568. continue;
  8569. }
  8570. ast_node(fv, FieldValue, elem);
  8571. if (is_ast_range(fv->field)) {
  8572. Token op = fv->field->BinaryExpr.op;
  8573. Operand x = {};
  8574. Operand y = {};
  8575. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8576. if (!ok) {
  8577. continue;
  8578. }
  8579. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8580. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8581. continue;
  8582. }
  8583. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8584. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8585. continue;
  8586. }
  8587. i64 lo = exact_value_to_i64(x.value);
  8588. i64 hi = exact_value_to_i64(y.value);
  8589. i64 max_index = hi;
  8590. if (op.kind == Token_RangeHalf) {
  8591. hi -= 1;
  8592. }
  8593. bool new_range = range_cache_add_range(&rc, lo, hi);
  8594. if (!new_range) {
  8595. gbString lo_str = expr_to_string(x.expr);
  8596. gbString hi_str = expr_to_string(y.expr);
  8597. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8598. gb_string_free(hi_str);
  8599. gb_string_free(lo_str);
  8600. continue;
  8601. }
  8602. // NOTE(bill): These are sanity checks for invalid enum values
  8603. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8604. gbString lo_str = expr_to_string(x.expr);
  8605. 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));
  8606. gb_string_free(lo_str);
  8607. continue;
  8608. }
  8609. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8610. gbString hi_str = expr_to_string(y.expr);
  8611. 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));
  8612. gb_string_free(hi_str);
  8613. continue;
  8614. }
  8615. if (max < hi) {
  8616. max = max_index;
  8617. }
  8618. Operand operand = {};
  8619. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8620. check_assignment(c, &operand, elem_type, context_name);
  8621. is_constant = is_constant && operand.mode == Addressing_Constant;
  8622. TokenKind upper_op = Token_LtEq;
  8623. if (op.kind == Token_RangeHalf) {
  8624. upper_op = Token_Lt;
  8625. }
  8626. add_to_seen_map(c, &seen, upper_op, x, x, y);
  8627. } else {
  8628. Operand op_index = {};
  8629. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8630. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8631. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8632. continue;
  8633. }
  8634. i64 index = exact_value_to_i64(op_index.value);
  8635. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8636. gbString idx_str = expr_to_string(op_index.expr);
  8637. 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));
  8638. gb_string_free(idx_str);
  8639. continue;
  8640. }
  8641. bool new_index = range_cache_add_index(&rc, index);
  8642. if (!new_index) {
  8643. gbString idx_str = expr_to_string(op_index.expr);
  8644. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8645. gb_string_free(idx_str);
  8646. continue;
  8647. }
  8648. if (max < index+1) {
  8649. max = index+1;
  8650. }
  8651. Operand operand = {};
  8652. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8653. check_assignment(c, &operand, elem_type, context_name);
  8654. is_constant = is_constant && operand.mode == Addressing_Constant;
  8655. add_to_seen_map(c, &seen, op_index);
  8656. }
  8657. }
  8658. cl->max_count = max;
  8659. } else {
  8660. isize index = 0;
  8661. for (; index < cl->elems.count; index++) {
  8662. Ast *e = cl->elems[index];
  8663. if (e == nullptr) {
  8664. error(node, "Invalid literal element");
  8665. continue;
  8666. }
  8667. if (e->kind == Ast_FieldValue) {
  8668. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8669. continue;
  8670. }
  8671. if (0 <= max_type_count && max_type_count <= index) {
  8672. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8673. }
  8674. Operand operand = {};
  8675. check_expr_with_type_hint(c, &operand, e, elem_type);
  8676. check_assignment(c, &operand, elem_type, context_name);
  8677. is_constant = is_constant && operand.mode == Addressing_Constant;
  8678. }
  8679. if (max < index) {
  8680. max = index;
  8681. }
  8682. }
  8683. bool was_error = false;
  8684. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8685. if (0 < max && max < t->EnumeratedArray.count) {
  8686. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  8687. was_error = true;
  8688. } else {
  8689. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  8690. was_error = true;
  8691. }
  8692. }
  8693. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  8694. if (cl->elems.count > 0 && !was_error && !is_partial) {
  8695. TEMPORARY_ALLOCATOR_GUARD();
  8696. Type *et = base_type(index_type);
  8697. GB_ASSERT(et->kind == Type_Enum);
  8698. auto fields = et->Enum.fields;
  8699. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  8700. for (Entity *f : fields) {
  8701. if (f->kind != Entity_Constant) {
  8702. continue;
  8703. }
  8704. ExactValue v = f->Constant.value;
  8705. uintptr hash = hash_exact_value(v);
  8706. auto found = map_get(&seen, hash);
  8707. if (!found) {
  8708. array_add(&unhandled, f);
  8709. }
  8710. }
  8711. if (unhandled.count > 0) {
  8712. ERROR_BLOCK();
  8713. if (unhandled.count == 1) {
  8714. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  8715. } else {
  8716. error(node, "Unhandled enumerated array cases:");
  8717. for_array(i, unhandled) {
  8718. Entity *f = unhandled[i];
  8719. error_line("\t%.*s\n", LIT(f->token.string));
  8720. }
  8721. }
  8722. if (!build_context.terse_errors) {
  8723. error_line("\n");
  8724. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  8725. }
  8726. }
  8727. }
  8728. break;
  8729. }
  8730. case Type_Basic: {
  8731. if (!is_type_any(t)) {
  8732. if (cl->elems.count != 0) {
  8733. gbString s = type_to_string(t);
  8734. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  8735. gb_string_free(s);
  8736. is_constant = false;
  8737. }
  8738. break;
  8739. }
  8740. if (cl->elems.count == 0) {
  8741. break; // NOTE(bill): No need to init
  8742. }
  8743. { // Checker values
  8744. Type *field_types[2] = {t_rawptr, t_typeid};
  8745. isize field_count = 2;
  8746. if (cl->elems[0]->kind == Ast_FieldValue) {
  8747. bool fields_visited[2] = {};
  8748. for_array(i, cl->elems) {
  8749. Ast *elem = cl->elems[i];
  8750. if (elem->kind != Ast_FieldValue) {
  8751. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8752. continue;
  8753. }
  8754. ast_node(fv, FieldValue, elem);
  8755. if (fv->field->kind != Ast_Ident) {
  8756. gbString expr_str = expr_to_string(fv->field);
  8757. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  8758. gb_string_free(expr_str);
  8759. continue;
  8760. }
  8761. String name = fv->field->Ident.token.string;
  8762. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8763. if (sel.entity == nullptr) {
  8764. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  8765. continue;
  8766. }
  8767. isize index = sel.index[0];
  8768. if (fields_visited[index]) {
  8769. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  8770. continue;
  8771. }
  8772. fields_visited[index] = true;
  8773. check_expr(c, o, fv->value);
  8774. // NOTE(bill): 'any' literals can never be constant
  8775. is_constant = false;
  8776. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8777. }
  8778. } else {
  8779. for_array(index, cl->elems) {
  8780. Ast *elem = cl->elems[index];
  8781. if (elem->kind == Ast_FieldValue) {
  8782. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8783. continue;
  8784. }
  8785. check_expr(c, o, elem);
  8786. if (index >= field_count) {
  8787. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  8788. break;
  8789. }
  8790. // NOTE(bill): 'any' literals can never be constant
  8791. is_constant = false;
  8792. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8793. }
  8794. if (cl->elems.count < field_count) {
  8795. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  8796. }
  8797. }
  8798. }
  8799. break;
  8800. }
  8801. case Type_Map: {
  8802. if (cl->elems.count == 0) {
  8803. break;
  8804. }
  8805. is_constant = false;
  8806. { // Checker values
  8807. bool key_is_typeid = is_type_typeid(t->Map.key);
  8808. bool value_is_typeid = is_type_typeid(t->Map.value);
  8809. for (Ast *elem : cl->elems) {
  8810. if (elem->kind != Ast_FieldValue) {
  8811. error(elem, "Only 'field = value' elements are allowed in a map literal");
  8812. continue;
  8813. }
  8814. ast_node(fv, FieldValue, elem);
  8815. if (key_is_typeid) {
  8816. check_expr_or_type(c, o, fv->field, t->Map.key);
  8817. } else {
  8818. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  8819. }
  8820. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  8821. if (o->mode == Addressing_Invalid) {
  8822. continue;
  8823. }
  8824. if (value_is_typeid) {
  8825. check_expr_or_type(c, o, fv->value, t->Map.value);
  8826. } else {
  8827. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  8828. }
  8829. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  8830. }
  8831. }
  8832. if (build_context.no_dynamic_literals && cl->elems.count) {
  8833. error(node, "Compound literals of dynamic types have been disabled");
  8834. } else {
  8835. add_map_reserve_dependencies(c);
  8836. add_map_set_dependencies(c);
  8837. }
  8838. break;
  8839. }
  8840. case Type_BitSet: {
  8841. if (cl->elems.count == 0) {
  8842. break; // NOTE(bill): No need to init
  8843. }
  8844. Type *et = base_type(t->BitSet.elem);
  8845. isize field_count = 0;
  8846. if (et != nullptr && et->kind == Type_Enum) {
  8847. field_count = et->Enum.fields.count;
  8848. }
  8849. if (is_type_array(bit_set_to_int(t))) {
  8850. is_constant = false;
  8851. }
  8852. if (cl->elems[0]->kind == Ast_FieldValue) {
  8853. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  8854. is_constant = false;
  8855. } else {
  8856. for (Ast *elem : cl->elems) {
  8857. if (elem->kind == Ast_FieldValue) {
  8858. error(elem, "'field = value' in a bit_set a literal is not allowed");
  8859. continue;
  8860. }
  8861. check_expr_with_type_hint(c, o, elem, et);
  8862. if (is_constant) {
  8863. is_constant = o->mode == Addressing_Constant;
  8864. }
  8865. if (elem->kind == Ast_BinaryExpr) {
  8866. switch (elem->BinaryExpr.op.kind) {
  8867. case Token_Or:
  8868. {
  8869. gbString x = expr_to_string(elem->BinaryExpr.left);
  8870. gbString y = expr_to_string(elem->BinaryExpr.right);
  8871. gbString e = expr_to_string(elem);
  8872. error(elem, "Was the following intended? '%s, %s'; if not, surround the expression with parentheses '(%s)'", x, y, e);
  8873. gb_string_free(e);
  8874. gb_string_free(y);
  8875. gb_string_free(x);
  8876. }
  8877. break;
  8878. }
  8879. }
  8880. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  8881. if (o->mode == Addressing_Constant) {
  8882. i64 lower = t->BitSet.lower;
  8883. i64 upper = t->BitSet.upper;
  8884. i64 v = exact_value_to_i64(o->value);
  8885. if (lower <= v && v <= upper) {
  8886. // okay
  8887. } else {
  8888. gbString s = expr_to_string(o->expr);
  8889. error(elem, "Bit field value out of bounds, %s (%lld) not in the range %lld .. %lld", s, v, lower, upper);
  8890. gb_string_free(s);
  8891. continue;
  8892. }
  8893. }
  8894. }
  8895. }
  8896. break;
  8897. }
  8898. case Type_BitField: {
  8899. if (cl->elems.count == 0) {
  8900. break; // NOTE(bill): No need to init
  8901. }
  8902. is_constant = false;
  8903. if (cl->elems[0]->kind != Ast_FieldValue) {
  8904. gbString type_str = type_to_string(type);
  8905. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  8906. gb_string_free(type_str);
  8907. } else {
  8908. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8909. }
  8910. break;
  8911. }
  8912. default: {
  8913. if (cl->elems.count == 0) {
  8914. break; // NOTE(bill): No need to init
  8915. }
  8916. gbString str = type_to_string(type);
  8917. error(node, "Invalid compound literal type '%s'", str);
  8918. gb_string_free(str);
  8919. return kind;
  8920. }
  8921. }
  8922. if (is_constant) {
  8923. o->mode = Addressing_Constant;
  8924. if (is_type_bit_set(type)) {
  8925. // NOTE(bill): Encode as an integer
  8926. Type *bt = base_type(type);
  8927. BigInt bits = {};
  8928. BigInt one = {};
  8929. big_int_from_u64(&one, 1);
  8930. for (Ast *e : cl->elems) {
  8931. GB_ASSERT(e->kind != Ast_FieldValue);
  8932. TypeAndValue tav = e->tav;
  8933. if (tav.mode != Addressing_Constant) {
  8934. continue;
  8935. }
  8936. if (tav.value.kind != ExactValue_Integer) {
  8937. continue;
  8938. }
  8939. i64 v = big_int_to_i64(&tav.value.value_integer);
  8940. i64 lower = bt->BitSet.lower;
  8941. u64 index = cast(u64)(v-lower);
  8942. BigInt bit = {};
  8943. big_int_from_u64(&bit, index);
  8944. big_int_shl(&bit, &one, &bit);
  8945. big_int_or(&bits, &bits, &bit);
  8946. }
  8947. o->value.kind = ExactValue_Integer;
  8948. o->value.value_integer = bits;
  8949. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  8950. ExactValue value = exact_value_compound(node);
  8951. Type *bt = core_type(type);
  8952. if (bt->kind == Type_Basic) {
  8953. if (bt->Basic.flags & BasicFlag_Boolean) {
  8954. value = exact_value_bool(false);
  8955. } else if (bt->Basic.flags & BasicFlag_Integer) {
  8956. value = exact_value_i64(0);
  8957. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  8958. value = exact_value_i64(0);
  8959. } else if (bt->Basic.flags & BasicFlag_Float) {
  8960. value = exact_value_float(0);
  8961. } else if (bt->Basic.flags & BasicFlag_Complex) {
  8962. value = exact_value_complex(0, 0);
  8963. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  8964. value = exact_value_quaternion(0, 0, 0, 0);
  8965. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  8966. value = exact_value_pointer(0);
  8967. } else if (bt->Basic.flags & BasicFlag_String) {
  8968. String empty_string = {};
  8969. value = exact_value_string(empty_string);
  8970. } else if (bt->Basic.flags & BasicFlag_Rune) {
  8971. value = exact_value_i64(0);
  8972. }
  8973. }
  8974. o->value = value;
  8975. } else {
  8976. o->value = exact_value_compound(node);
  8977. }
  8978. } else {
  8979. o->mode = Addressing_Value;
  8980. }
  8981. o->type = type;
  8982. return kind;
  8983. }
  8984. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8985. ExprKind kind = Expr_Expr;
  8986. ast_node(ta, TypeAssertion, node);
  8987. check_expr(c, o, ta->expr);
  8988. node->viral_state_flags |= ta->expr->viral_state_flags;
  8989. if (o->mode == Addressing_Invalid) {
  8990. o->expr = node;
  8991. return kind;
  8992. }
  8993. if (o->mode == Addressing_Constant) {
  8994. gbString expr_str = expr_to_string(o->expr);
  8995. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  8996. gb_string_free(expr_str);
  8997. o->mode = Addressing_Invalid;
  8998. o->expr = node;
  8999. return kind;
  9000. }
  9001. if (is_type_untyped(o->type)) {
  9002. gbString expr_str = expr_to_string(o->expr);
  9003. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  9004. gb_string_free(expr_str);
  9005. o->mode = Addressing_Invalid;
  9006. o->expr = node;
  9007. return kind;
  9008. }
  9009. Type *src = type_deref(o->type);
  9010. Type *bsrc = base_type(src);
  9011. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  9012. if (!is_type_union(src)) {
  9013. gbString str = type_to_string(o->type);
  9014. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  9015. gb_string_free(str);
  9016. o->mode = Addressing_Invalid;
  9017. o->expr = node;
  9018. return kind;
  9019. }
  9020. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  9021. bool allowed = false;
  9022. for (Type *vt : bsrc->Union.variants) {
  9023. if (are_types_identical(vt, type_hint)) {
  9024. allowed = true;
  9025. add_type_info_type(c, vt);
  9026. break;
  9027. }
  9028. }
  9029. if (allowed) {
  9030. add_type_info_type(c, o->type);
  9031. o->type = type_hint;
  9032. o->mode = Addressing_OptionalOk;
  9033. return kind;
  9034. }
  9035. }
  9036. if (bsrc->Union.variants.count != 1) {
  9037. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  9038. o->mode = Addressing_Invalid;
  9039. o->expr = node;
  9040. return kind;
  9041. }
  9042. add_type_info_type(c, o->type);
  9043. add_type_info_type(c, bsrc->Union.variants[0]);
  9044. o->type = bsrc->Union.variants[0];
  9045. o->mode = Addressing_OptionalOk;
  9046. } else {
  9047. Type *t = check_type(c, ta->type);
  9048. Type *dst = t;
  9049. if (is_type_union(src)) {
  9050. bool ok = false;
  9051. for (Type *vt : bsrc->Union.variants) {
  9052. if (are_types_identical(vt, dst)) {
  9053. ok = true;
  9054. break;
  9055. }
  9056. }
  9057. if (!ok) {
  9058. gbString expr_str = expr_to_string(o->expr);
  9059. gbString dst_type_str = type_to_string(t);
  9060. defer (gb_string_free(expr_str));
  9061. defer (gb_string_free(dst_type_str));
  9062. if (bsrc->Union.variants.count == 0) {
  9063. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  9064. } else {
  9065. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  9066. }
  9067. o->mode = Addressing_Invalid;
  9068. o->expr = node;
  9069. return kind;
  9070. }
  9071. add_type_info_type(c, o->type);
  9072. add_type_info_type(c, t);
  9073. o->type = t;
  9074. o->mode = Addressing_OptionalOk;
  9075. } else if (is_type_any(src)) {
  9076. o->type = t;
  9077. o->mode = Addressing_OptionalOk;
  9078. add_type_info_type(c, o->type);
  9079. add_type_info_type(c, t);
  9080. } else {
  9081. gbString str = type_to_string(o->type);
  9082. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  9083. gb_string_free(str);
  9084. o->mode = Addressing_Invalid;
  9085. o->expr = node;
  9086. return kind;
  9087. }
  9088. }
  9089. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  9090. add_package_dependency(c, "runtime", "type_assertion_check");
  9091. add_package_dependency(c, "runtime", "type_assertion_check2");
  9092. }
  9093. return kind;
  9094. }
  9095. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9096. ast_node(se, SelectorCallExpr, node);
  9097. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  9098. // COM APIs is a great example of where this kind of thing is extremely useful
  9099. // General idea:
  9100. //
  9101. // x->y(123) == x.y(x, 123)
  9102. //
  9103. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  9104. // Just regenerating a new AST aids things
  9105. //
  9106. // TODO(bill): Is this a good hack or not?
  9107. //
  9108. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  9109. if (se->modified_call) {
  9110. // Prevent double evaluation
  9111. o->expr = node;
  9112. o->type = node->tav.type;
  9113. o->value = node->tav.value;
  9114. o->mode = node->tav.mode;
  9115. return Expr_Expr;
  9116. }
  9117. bool allow_arrow_right_selector_expr;
  9118. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9119. c->allow_arrow_right_selector_expr = true;
  9120. Operand x = {};
  9121. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  9122. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9123. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  9124. o->mode = Addressing_Invalid;
  9125. o->type = t_invalid;
  9126. o->expr = node;
  9127. return kind;
  9128. }
  9129. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  9130. gbString type_str = type_to_string(x.type);
  9131. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  9132. gb_string_free(type_str);
  9133. o->mode = Addressing_Invalid;
  9134. o->type = t_invalid;
  9135. o->expr = node;
  9136. return Expr_Stmt;
  9137. }
  9138. ast_node(ce, CallExpr, se->call);
  9139. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  9140. Ast *first_arg = x.expr->SelectorExpr.expr;
  9141. GB_ASSERT(first_arg != nullptr);
  9142. Entity *e = entity_of_node(se->expr);
  9143. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  9144. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  9145. }
  9146. if (e->kind != Entity_ProcGroup) {
  9147. Type *pt = base_type(x.type);
  9148. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  9149. Type *first_type = nullptr;
  9150. String first_arg_name = {};
  9151. if (pt->Proc.param_count > 0) {
  9152. Entity *f = pt->Proc.params->Tuple.variables[0];
  9153. first_type = f->type;
  9154. first_arg_name = f->token.string;
  9155. }
  9156. if (first_arg_name.len == 0) {
  9157. first_arg_name = str_lit("_");
  9158. }
  9159. if (first_type == nullptr) {
  9160. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  9161. o->mode = Addressing_Invalid;
  9162. o->type = t_invalid;
  9163. o->expr = node;
  9164. return Expr_Stmt;
  9165. }
  9166. Operand y = {};
  9167. y.mode = first_arg->tav.mode;
  9168. y.type = first_arg->tav.type;
  9169. y.value = first_arg->tav.value;
  9170. if (check_is_assignable_to(c, &y, first_type)) {
  9171. // Do nothing, it's valid
  9172. } else {
  9173. Operand z = y;
  9174. z.type = type_deref(y.type);
  9175. if (check_is_assignable_to(c, &z, first_type)) {
  9176. // NOTE(bill): AST GENERATION HACK!
  9177. Token op = {Token_Pointer};
  9178. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  9179. } else if (y.mode == Addressing_Variable) {
  9180. Operand w = y;
  9181. w.type = alloc_type_pointer(y.type);
  9182. if (check_is_assignable_to(c, &w, first_type)) {
  9183. // NOTE(bill): AST GENERATION HACK!
  9184. Token op = {Token_And};
  9185. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  9186. }
  9187. }
  9188. }
  9189. if (ce->args.count > 0) {
  9190. bool fail = false;
  9191. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  9192. for (Ast *arg : ce->args) {
  9193. bool mix = false;
  9194. if (first_is_field_value) {
  9195. mix = arg->kind != Ast_FieldValue;
  9196. } else {
  9197. mix = arg->kind == Ast_FieldValue;
  9198. }
  9199. if (mix) {
  9200. fail = true;
  9201. break;
  9202. }
  9203. }
  9204. if (!fail && first_is_field_value) {
  9205. Token op = {Token_Eq};
  9206. AstFile *f = first_arg->file();
  9207. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  9208. }
  9209. }
  9210. }
  9211. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  9212. modified_args[0] = first_arg;
  9213. slice_copy(&modified_args, ce->args, 1);
  9214. ce->args = modified_args;
  9215. se->modified_call = true;
  9216. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9217. c->allow_arrow_right_selector_expr = true;
  9218. check_expr_base(c, o, se->call, type_hint);
  9219. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9220. o->expr = node;
  9221. return Expr_Expr;
  9222. }
  9223. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9224. ExprKind kind = Expr_Expr;
  9225. ast_node(ie, IndexExpr, node);
  9226. check_expr(c, o, ie->expr);
  9227. node->viral_state_flags |= ie->expr->viral_state_flags;
  9228. if (o->mode == Addressing_Invalid) {
  9229. o->expr = node;
  9230. return kind;
  9231. }
  9232. Type *t = base_type(type_deref(o->type));
  9233. bool is_ptr = is_type_pointer(o->type);
  9234. bool is_const = o->mode == Addressing_Constant;
  9235. if (is_type_map(t)) {
  9236. Operand key = {};
  9237. if (is_type_typeid(t->Map.key)) {
  9238. check_expr_or_type(c, &key, ie->index, t->Map.key);
  9239. } else {
  9240. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  9241. }
  9242. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  9243. if (key.mode == Addressing_Invalid) {
  9244. o->mode = Addressing_Invalid;
  9245. o->expr = node;
  9246. return kind;
  9247. }
  9248. o->mode = Addressing_MapIndex;
  9249. o->type = t->Map.value;
  9250. o->expr = node;
  9251. add_map_get_dependencies(c);
  9252. add_map_set_dependencies(c);
  9253. return Expr_Expr;
  9254. }
  9255. i64 max_count = -1;
  9256. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  9257. if (is_const) {
  9258. if (is_type_array(t)) {
  9259. // Okay
  9260. } else if (is_type_slice(t)) {
  9261. // Okay
  9262. } else if (is_type_enumerated_array(t)) {
  9263. // Okay
  9264. } else if (is_type_string(t)) {
  9265. // Okay
  9266. } else if (is_type_relative_multi_pointer(t)) {
  9267. // Okay
  9268. } else if (is_type_matrix(t)) {
  9269. // Okay
  9270. } else {
  9271. valid = false;
  9272. }
  9273. }
  9274. if (!valid) {
  9275. gbString str = expr_to_string(o->expr);
  9276. gbString type_str = type_to_string(o->type);
  9277. defer (gb_string_free(str));
  9278. defer (gb_string_free(type_str));
  9279. if (is_const) {
  9280. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  9281. } else {
  9282. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  9283. }
  9284. o->mode = Addressing_Invalid;
  9285. o->expr = node;
  9286. return kind;
  9287. }
  9288. if (ie->index == nullptr) {
  9289. gbString str = expr_to_string(o->expr);
  9290. error(o->expr, "Missing index for '%s'", str);
  9291. gb_string_free(str);
  9292. o->mode = Addressing_Invalid;
  9293. o->expr = node;
  9294. return kind;
  9295. }
  9296. Type *index_type_hint = nullptr;
  9297. if (is_type_enumerated_array(t)) {
  9298. Type *bt = base_type(t);
  9299. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  9300. index_type_hint = bt->EnumeratedArray.index;
  9301. }
  9302. i64 index = 0;
  9303. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  9304. if (is_const) {
  9305. if (index < 0) {
  9306. ERROR_BLOCK();
  9307. gbString str = expr_to_string(o->expr);
  9308. error(o->expr, "Cannot index a constant '%s'", str);
  9309. if (!build_context.terse_errors) {
  9310. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9311. }
  9312. gb_string_free(str);
  9313. o->mode = Addressing_Invalid;
  9314. o->expr = node;
  9315. return kind;
  9316. } else if (ok && !is_type_matrix(t)) {
  9317. TypeAndValue tav = type_and_value_of_expr(ie->expr);
  9318. ExactValue value = tav.value;
  9319. o->mode = Addressing_Constant;
  9320. bool success = false;
  9321. bool finish = false;
  9322. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  9323. if (!success) {
  9324. ERROR_BLOCK();
  9325. gbString str = expr_to_string(o->expr);
  9326. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  9327. if (!build_context.terse_errors) {
  9328. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9329. }
  9330. gb_string_free(str);
  9331. o->mode = Addressing_Invalid;
  9332. o->expr = node;
  9333. return kind;
  9334. }
  9335. }
  9336. }
  9337. if (type_hint != nullptr && is_type_matrix(t)) {
  9338. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  9339. // if a type hint exists
  9340. }
  9341. return kind;
  9342. }
  9343. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9344. ExprKind kind = Expr_Stmt;
  9345. ast_node(se, SliceExpr, node);
  9346. check_expr(c, o, se->expr);
  9347. node->viral_state_flags |= se->expr->viral_state_flags;
  9348. if (o->mode == Addressing_Invalid) {
  9349. o->mode = Addressing_Invalid;
  9350. o->expr = node;
  9351. return kind;
  9352. }
  9353. bool valid = false;
  9354. i64 max_count = -1;
  9355. Type *t = base_type(type_deref(o->type));
  9356. switch (t->kind) {
  9357. case Type_Basic:
  9358. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  9359. valid = true;
  9360. if (o->mode == Addressing_Constant) {
  9361. max_count = o->value.value_string.len;
  9362. }
  9363. o->type = type_deref(o->type);
  9364. }
  9365. break;
  9366. case Type_Array:
  9367. valid = true;
  9368. max_count = t->Array.count;
  9369. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9370. gbString str = expr_to_string(node);
  9371. error(node, "Cannot slice array '%s', value is not addressable", str);
  9372. gb_string_free(str);
  9373. o->mode = Addressing_Invalid;
  9374. o->expr = node;
  9375. return kind;
  9376. }
  9377. o->type = alloc_type_slice(t->Array.elem);
  9378. break;
  9379. case Type_MultiPointer:
  9380. valid = true;
  9381. o->type = type_deref(o->type);
  9382. break;
  9383. case Type_Slice:
  9384. valid = true;
  9385. o->type = type_deref(o->type);
  9386. break;
  9387. case Type_DynamicArray:
  9388. valid = true;
  9389. o->type = alloc_type_slice(t->DynamicArray.elem);
  9390. break;
  9391. case Type_Struct:
  9392. if (is_type_soa_struct(t)) {
  9393. valid = true;
  9394. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9395. max_count = t->Struct.soa_count;
  9396. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9397. gbString str = expr_to_string(node);
  9398. error(node, "Cannot slice #soa array '%s', value is not addressable", str);
  9399. gb_string_free(str);
  9400. o->mode = Addressing_Invalid;
  9401. o->expr = node;
  9402. return kind;
  9403. }
  9404. }
  9405. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  9406. }
  9407. break;
  9408. case Type_RelativeMultiPointer:
  9409. valid = true;
  9410. o->type = type_deref(o->type);
  9411. break;
  9412. case Type_EnumeratedArray:
  9413. {
  9414. gbString str = expr_to_string(o->expr);
  9415. gbString type_str = type_to_string(o->type);
  9416. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  9417. gb_string_free(type_str);
  9418. gb_string_free(str);
  9419. o->mode = Addressing_Invalid;
  9420. o->expr = node;
  9421. return kind;
  9422. }
  9423. break;
  9424. }
  9425. if (!valid) {
  9426. gbString str = expr_to_string(o->expr);
  9427. gbString type_str = type_to_string(o->type);
  9428. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  9429. gb_string_free(type_str);
  9430. gb_string_free(str);
  9431. o->mode = Addressing_Invalid;
  9432. o->expr = node;
  9433. return kind;
  9434. }
  9435. if (se->low == nullptr && se->high != nullptr) {
  9436. // It is okay to continue as it will assume the 1st index is zero
  9437. }
  9438. i64 indices[2] = {};
  9439. Ast *nodes[2] = {se->low, se->high};
  9440. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9441. i64 index = max_count;
  9442. if (nodes[i] != nullptr) {
  9443. i64 capacity = -1;
  9444. if (max_count >= 0) {
  9445. capacity = max_count;
  9446. }
  9447. i64 j = 0;
  9448. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  9449. index = j;
  9450. }
  9451. node->viral_state_flags |= nodes[i]->viral_state_flags;
  9452. } else if (i == 0) {
  9453. index = 0;
  9454. }
  9455. indices[i] = index;
  9456. }
  9457. for (isize i = 0; i < gb_count_of(indices); i++) {
  9458. i64 a = indices[i];
  9459. for (isize j = i+1; j < gb_count_of(indices); j++) {
  9460. i64 b = indices[j];
  9461. if (a > b && b >= 0) {
  9462. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  9463. }
  9464. }
  9465. }
  9466. if (max_count < 0) {
  9467. if (o->mode == Addressing_Constant) {
  9468. gbString s = expr_to_string(se->expr);
  9469. error(se->expr, "Cannot slice constant value '%s'", s);
  9470. gb_string_free(s);
  9471. }
  9472. }
  9473. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  9474. /*
  9475. x[:] -> [^]T
  9476. x[i:] -> [^]T
  9477. x[:n] -> []T
  9478. x[i:n] -> []T
  9479. */
  9480. o->type = alloc_type_slice(t->MultiPointer.elem);
  9481. } else if (t->kind == Type_RelativeMultiPointer && se->high != nullptr) {
  9482. /*
  9483. x[:] -> [^]T
  9484. x[i:] -> [^]T
  9485. x[:n] -> []T
  9486. x[i:n] -> []T
  9487. */
  9488. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  9489. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  9490. o->type = alloc_type_slice(pointer_type->MultiPointer.elem);
  9491. }
  9492. o->mode = Addressing_Value;
  9493. if (is_type_string(t) && max_count >= 0) {
  9494. bool all_constant = true;
  9495. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9496. if (nodes[i] != nullptr) {
  9497. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  9498. if (tav.mode != Addressing_Constant) {
  9499. all_constant = false;
  9500. break;
  9501. }
  9502. }
  9503. }
  9504. if (!all_constant) {
  9505. ERROR_BLOCK();
  9506. gbString str = expr_to_string(o->expr);
  9507. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  9508. if (!build_context.terse_errors) {
  9509. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9510. }
  9511. gb_string_free(str);
  9512. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  9513. o->expr = node;
  9514. return kind;
  9515. }
  9516. String s = {};
  9517. if (o->value.kind == ExactValue_String) {
  9518. s = o->value.value_string;
  9519. }
  9520. o->mode = Addressing_Constant;
  9521. o->type = t;
  9522. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9523. }
  9524. return kind;
  9525. }
  9526. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9527. u32 prev_state_flags = c->state_flags;
  9528. defer (c->state_flags = prev_state_flags);
  9529. if (node->state_flags != 0) {
  9530. u32 in = node->state_flags;
  9531. u32 out = c->state_flags;
  9532. if (in & StateFlag_no_bounds_check) {
  9533. out |= StateFlag_no_bounds_check;
  9534. out &= ~StateFlag_bounds_check;
  9535. } else if (in & StateFlag_bounds_check) {
  9536. out |= StateFlag_bounds_check;
  9537. out &= ~StateFlag_no_bounds_check;
  9538. }
  9539. if (in & StateFlag_no_type_assert) {
  9540. out |= StateFlag_no_type_assert;
  9541. out &= ~StateFlag_type_assert;
  9542. } else if (in & StateFlag_type_assert) {
  9543. out |= StateFlag_type_assert;
  9544. out &= ~StateFlag_no_type_assert;
  9545. }
  9546. c->state_flags = out;
  9547. }
  9548. ExprKind kind = Expr_Stmt;
  9549. o->mode = Addressing_Invalid;
  9550. o->type = t_invalid;
  9551. o->value = {ExactValue_Invalid};
  9552. switch (node->kind) {
  9553. default:
  9554. return kind;
  9555. case_ast_node(be, BadExpr, node)
  9556. return kind;
  9557. case_end;
  9558. case_ast_node(i, Implicit, node)
  9559. switch (i->kind) {
  9560. case Token_context:
  9561. {
  9562. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  9563. error(node, "'context' is only allowed within procedures");
  9564. return kind;
  9565. }
  9566. if (unparen_expr(c->assignment_lhs_hint) == node) {
  9567. c->scope->flags |= ScopeFlag_ContextDefined;
  9568. }
  9569. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  9570. error(node, "'context' has not been defined within this scope");
  9571. // Continue with value
  9572. }
  9573. init_core_context(c->checker);
  9574. o->mode = Addressing_Context;
  9575. o->type = t_context;
  9576. }
  9577. break;
  9578. default:
  9579. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  9580. return kind;
  9581. }
  9582. case_end;
  9583. case_ast_node(i, Ident, node);
  9584. check_ident(c, o, node, nullptr, type_hint, false);
  9585. case_end;
  9586. case_ast_node(u, Uninit, node);
  9587. o->mode = Addressing_Value;
  9588. o->type = t_untyped_uninit;
  9589. error(node, "Use of --- outside of variable declaration");
  9590. case_end;
  9591. case_ast_node(bl, BasicLit, node);
  9592. Type *t = t_invalid;
  9593. switch (node->tav.value.kind) {
  9594. case ExactValue_String: t = t_untyped_string; break;
  9595. case ExactValue_Float: t = t_untyped_float; break;
  9596. case ExactValue_Complex: t = t_untyped_complex; break;
  9597. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  9598. case ExactValue_Integer:
  9599. t = t_untyped_integer;
  9600. if (bl->token.kind == Token_Rune) {
  9601. t = t_untyped_rune;
  9602. }
  9603. break;
  9604. default:
  9605. GB_PANIC("Unhandled value type for basic literal");
  9606. break;
  9607. }
  9608. o->mode = Addressing_Constant;
  9609. o->type = t;
  9610. o->value = node->tav.value;
  9611. case_end;
  9612. case_ast_node(bd, BasicDirective, node);
  9613. kind = check_basic_directive_expr(c, o, node, type_hint);
  9614. case_end;
  9615. case_ast_node(pg, ProcGroup, node);
  9616. error(node, "Illegal use of a procedure group");
  9617. o->mode = Addressing_Invalid;
  9618. case_end;
  9619. case_ast_node(pl, ProcLit, node);
  9620. CheckerContext ctx = *c;
  9621. DeclInfo *decl = nullptr;
  9622. Type *type = alloc_type(Type_Proc);
  9623. check_open_scope(&ctx, pl->type);
  9624. {
  9625. decl = make_decl_info(ctx.scope, ctx.decl);
  9626. decl->proc_lit = node;
  9627. ctx.decl = decl;
  9628. defer (ctx.decl = ctx.decl->parent);
  9629. if (pl->tags != 0) {
  9630. error(node, "A procedure literal cannot have tags");
  9631. pl->tags = 0; // TODO(bill): Should I zero this?!
  9632. }
  9633. check_procedure_type(&ctx, type, pl->type);
  9634. if (!is_type_proc(type)) {
  9635. gbString str = expr_to_string(node);
  9636. error(node, "Invalid procedure literal '%s'", str);
  9637. gb_string_free(str);
  9638. check_close_scope(&ctx);
  9639. return kind;
  9640. }
  9641. if (pl->body == nullptr) {
  9642. error(node, "A procedure literal must have a body");
  9643. return kind;
  9644. }
  9645. pl->decl = decl;
  9646. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  9647. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  9648. array_add(&ctx.checker->nested_proc_lits, decl);
  9649. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  9650. }
  9651. check_close_scope(&ctx);
  9652. o->mode = Addressing_Value;
  9653. o->type = type;
  9654. case_end;
  9655. case_ast_node(te, TernaryIfExpr, node);
  9656. kind = check_ternary_if_expr(c, o, node, type_hint);
  9657. case_end;
  9658. case_ast_node(te, TernaryWhenExpr, node);
  9659. kind = check_ternary_when_expr(c, o, node, type_hint);
  9660. case_end;
  9661. case_ast_node(oe, OrElseExpr, node);
  9662. return check_or_else_expr(c, o, node, type_hint);
  9663. case_end;
  9664. case_ast_node(re, OrReturnExpr, node);
  9665. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  9666. return check_or_return_expr(c, o, node, type_hint);
  9667. case_end;
  9668. case_ast_node(re, OrBranchExpr, node);
  9669. return check_or_branch_expr(c, o, node, type_hint);
  9670. case_end;
  9671. case_ast_node(cl, CompoundLit, node);
  9672. kind = check_compound_literal(c, o, node, type_hint);
  9673. case_end;
  9674. case_ast_node(pe, ParenExpr, node);
  9675. kind = check_expr_base(c, o, pe->expr, type_hint);
  9676. node->viral_state_flags |= pe->expr->viral_state_flags;
  9677. o->expr = node;
  9678. case_end;
  9679. case_ast_node(te, TagExpr, node);
  9680. String name = te->name.string;
  9681. error(node, "Unknown tag expression, #%.*s", LIT(name));
  9682. if (te->expr) {
  9683. kind = check_expr_base(c, o, te->expr, type_hint);
  9684. node->viral_state_flags |= te->expr->viral_state_flags;
  9685. }
  9686. o->expr = node;
  9687. case_end;
  9688. case_ast_node(ta, TypeAssertion, node);
  9689. kind = check_type_assertion(c, o, node, type_hint);
  9690. case_end;
  9691. case_ast_node(tc, TypeCast, node);
  9692. check_expr_or_type(c, o, tc->type);
  9693. if (o->mode != Addressing_Type) {
  9694. gbString str = expr_to_string(tc->type);
  9695. error(tc->type, "Expected a type, got %s", str);
  9696. gb_string_free(str);
  9697. o->mode = Addressing_Invalid;
  9698. }
  9699. if (o->mode == Addressing_Invalid) {
  9700. o->expr = node;
  9701. return kind;
  9702. }
  9703. Type *type = o->type;
  9704. check_expr_base(c, o, tc->expr, type);
  9705. node->viral_state_flags |= tc->expr->viral_state_flags;
  9706. if (o->mode != Addressing_Invalid) {
  9707. switch (tc->token.kind) {
  9708. case Token_transmute:
  9709. check_transmute(c, node, o, type, true);
  9710. break;
  9711. case Token_cast:
  9712. check_cast(c, o, type, true);
  9713. break;
  9714. default:
  9715. error(node, "Invalid AST: Invalid casting expression");
  9716. o->mode = Addressing_Invalid;
  9717. break;
  9718. }
  9719. }
  9720. return Expr_Expr;
  9721. case_end;
  9722. case_ast_node(ac, AutoCast, node);
  9723. check_expr_base(c, o, ac->expr, type_hint);
  9724. node->viral_state_flags |= ac->expr->viral_state_flags;
  9725. if (o->mode == Addressing_Invalid) {
  9726. o->expr = node;
  9727. return kind;
  9728. }
  9729. if (type_hint) {
  9730. check_cast(c, o, type_hint);
  9731. }
  9732. o->expr = node;
  9733. return Expr_Expr;
  9734. case_end;
  9735. case_ast_node(ue, UnaryExpr, node);
  9736. Type *th = type_hint;
  9737. if (ue->op.kind == Token_And) {
  9738. th = type_deref(th);
  9739. }
  9740. check_expr_base(c, o, ue->expr, th);
  9741. node->viral_state_flags |= ue->expr->viral_state_flags;
  9742. if (o->mode != Addressing_Invalid) {
  9743. check_unary_expr(c, o, ue->op, node);
  9744. }
  9745. o->expr = node;
  9746. return Expr_Expr;
  9747. case_end;
  9748. case_ast_node(be, BinaryExpr, node);
  9749. check_binary_expr(c, o, node, type_hint, true);
  9750. if (o->mode == Addressing_Invalid) {
  9751. o->expr = node;
  9752. return kind;
  9753. }
  9754. case_end;
  9755. case_ast_node(se, SelectorExpr, node);
  9756. check_selector(c, o, node, type_hint);
  9757. node->viral_state_flags |= se->expr->viral_state_flags;
  9758. case_end;
  9759. case_ast_node(se, SelectorCallExpr, node);
  9760. return check_selector_call_expr(c, o, node, type_hint);
  9761. case_end;
  9762. case_ast_node(ise, ImplicitSelectorExpr, node);
  9763. return check_implicit_selector_expr(c, o, node, type_hint);
  9764. case_end;
  9765. case_ast_node(ie, IndexExpr, node);
  9766. kind = check_index_expr(c, o, node, type_hint);
  9767. case_end;
  9768. case_ast_node(se, SliceExpr, node);
  9769. kind = check_slice_expr(c, o, node, type_hint);
  9770. case_end;
  9771. case_ast_node(mie, MatrixIndexExpr, node);
  9772. check_matrix_index_expr(c, o, node, type_hint);
  9773. o->expr = node;
  9774. return Expr_Expr;
  9775. case_end;
  9776. case_ast_node(ce, CallExpr, node);
  9777. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  9778. case_end;
  9779. case_ast_node(de, DerefExpr, node);
  9780. check_expr_or_type(c, o, de->expr);
  9781. node->viral_state_flags |= de->expr->viral_state_flags;
  9782. if (o->mode == Addressing_Invalid) {
  9783. o->mode = Addressing_Invalid;
  9784. o->expr = node;
  9785. return kind;
  9786. } else {
  9787. Type *t = base_type(o->type);
  9788. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  9789. o->mode = Addressing_Variable;
  9790. o->type = t->Pointer.elem;
  9791. } else if (t->kind == Type_SoaPointer) {
  9792. o->mode = Addressing_SoaVariable;
  9793. o->type = type_deref(t);
  9794. } else if (t->kind == Type_RelativePointer) {
  9795. if (o->mode != Addressing_Variable) {
  9796. gbString str = expr_to_string(o->expr);
  9797. gbString typ = type_to_string(o->type);
  9798. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  9799. gb_string_free(typ);
  9800. gb_string_free(str);
  9801. }
  9802. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  9803. add_type_info_type(c, o->type);
  9804. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  9805. GB_ASSERT(ptr_type->kind == Type_Pointer);
  9806. o->mode = Addressing_Variable;
  9807. o->type = ptr_type->Pointer.elem;
  9808. } else {
  9809. gbString str = expr_to_string(o->expr);
  9810. gbString typ = type_to_string(o->type);
  9811. ERROR_BLOCK();
  9812. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  9813. if (o->type && is_type_multi_pointer(o->type)) {
  9814. if (!build_context.terse_errors) {
  9815. error_line("\tDid you mean '%s[0]'?\n", str);
  9816. }
  9817. }
  9818. gb_string_free(typ);
  9819. gb_string_free(str);
  9820. o->mode = Addressing_Invalid;
  9821. o->expr = node;
  9822. return kind;
  9823. }
  9824. }
  9825. case_end;
  9826. case_ast_node(ia, InlineAsmExpr, node);
  9827. if (c->curr_proc_decl == nullptr) {
  9828. error(node, "Inline asm expressions are only allowed within a procedure body");
  9829. }
  9830. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  9831. Type *return_type = nullptr;
  9832. for_array(i, ia->param_types) {
  9833. param_types[i] = check_type(c, ia->param_types[i]);
  9834. }
  9835. if (ia->return_type != nullptr) {
  9836. return_type = check_type(c, ia->return_type);
  9837. }
  9838. Operand x = {};
  9839. check_expr(c, &x, ia->asm_string);
  9840. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9841. error(x.expr, "Expected a constant string for the inline asm main parameter");
  9842. }
  9843. check_expr(c, &x, ia->constraints_string);
  9844. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9845. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  9846. }
  9847. Scope *scope = create_scope(c->info, c->scope);
  9848. scope->flags |= ScopeFlag_Proc;
  9849. Type *params = alloc_type_tuple();
  9850. Type *results = alloc_type_tuple();
  9851. if (param_types.count != 0) {
  9852. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  9853. for_array(i, param_types) {
  9854. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  9855. }
  9856. }
  9857. if (return_type != nullptr) {
  9858. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  9859. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  9860. }
  9861. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  9862. o->type = pt;
  9863. o->mode = Addressing_Value;
  9864. o->expr = node;
  9865. return Expr_Expr;
  9866. case_end;
  9867. case Ast_DistinctType:
  9868. case Ast_TypeidType:
  9869. case Ast_PolyType:
  9870. case Ast_ProcType:
  9871. case Ast_PointerType:
  9872. case Ast_MultiPointerType:
  9873. case Ast_ArrayType:
  9874. case Ast_DynamicArrayType:
  9875. case Ast_StructType:
  9876. case Ast_UnionType:
  9877. case Ast_EnumType:
  9878. case Ast_MapType:
  9879. case Ast_BitSetType:
  9880. case Ast_MatrixType:
  9881. case Ast_RelativeType:
  9882. o->mode = Addressing_Type;
  9883. o->type = check_type(c, node);
  9884. break;
  9885. }
  9886. kind = Expr_Expr;
  9887. o->expr = node;
  9888. return kind;
  9889. }
  9890. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9891. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  9892. if (o->type != nullptr && core_type(o->type) == nullptr) {
  9893. o->type = t_invalid;
  9894. gbString xs = expr_to_string(o->expr);
  9895. if (o->mode == Addressing_Type) {
  9896. error(o->expr, "Invalid type usage '%s'", xs);
  9897. } else {
  9898. error(o->expr, "Invalid expression '%s'", xs);
  9899. }
  9900. gb_string_free(xs);
  9901. }
  9902. if (o->type != nullptr && is_type_untyped(o->type)) {
  9903. add_untyped(c, node, o->mode, o->type, o->value);
  9904. }
  9905. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  9906. add_type_and_value(c, node, o->mode, o->type, o->value);
  9907. return kind;
  9908. }
  9909. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  9910. check_expr_base(c, o, e, nullptr);
  9911. switch (o->mode) {
  9912. default:
  9913. return; // NOTE(bill): Valid
  9914. case Addressing_NoValue:
  9915. error_operand_no_value(o);
  9916. break;
  9917. }
  9918. o->mode = Addressing_Invalid;
  9919. }
  9920. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  9921. check_expr_base(c, o, e, nullptr);
  9922. switch (o->mode) {
  9923. default:
  9924. return; // NOTE(bill): Valid
  9925. case Addressing_NoValue:
  9926. error_operand_no_value(o);
  9927. break;
  9928. case Addressing_Type:
  9929. error_operand_not_expression(o);
  9930. break;
  9931. }
  9932. o->mode = Addressing_Invalid;
  9933. }
  9934. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9935. check_expr_base(c, o, e, type_hint);
  9936. switch (o->mode) {
  9937. default:
  9938. return; // NOTE(bill): Valid
  9939. case Addressing_NoValue:
  9940. error_operand_no_value(o);
  9941. break;
  9942. case Addressing_Type:
  9943. error_operand_not_expression(o);
  9944. break;
  9945. }
  9946. o->mode = Addressing_Invalid;
  9947. }
  9948. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  9949. if (o->mode == Addressing_Value) {
  9950. // NOTE(bill): Tuples are not first class thus never named
  9951. if (o->type->kind == Type_Tuple) {
  9952. isize count = o->type->Tuple.variables.count;
  9953. error(o->expr,
  9954. "%td-valued expression found where single value expected", count);
  9955. o->mode = Addressing_Invalid;
  9956. GB_ASSERT(count != 1);
  9957. }
  9958. }
  9959. }
  9960. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  9961. check_multi_expr(c, o, e);
  9962. check_not_tuple(c, o);
  9963. }
  9964. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9965. check_expr_base(c, o, e, type_hint);
  9966. check_not_tuple(c, o);
  9967. error_operand_no_value(o);
  9968. }
  9969. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  9970. switch (v.kind) {
  9971. case ExactValue_Invalid:
  9972. return true;
  9973. case ExactValue_Bool:
  9974. return !v.value_bool;
  9975. case ExactValue_String:
  9976. return v.value_string.len == 0;
  9977. case ExactValue_Integer:
  9978. return big_int_is_zero(&v.value_integer);
  9979. case ExactValue_Float:
  9980. return v.value_float == 0.0;
  9981. case ExactValue_Complex:
  9982. if (v.value_complex) {
  9983. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  9984. }
  9985. return true;
  9986. case ExactValue_Quaternion:
  9987. if (v.value_quaternion) {
  9988. return v.value_quaternion->real == 0.0 &&
  9989. v.value_quaternion->imag == 0.0 &&
  9990. v.value_quaternion->jmag == 0.0 &&
  9991. v.value_quaternion->kmag == 0.0;
  9992. }
  9993. return true;
  9994. case ExactValue_Pointer:
  9995. return v.value_pointer == 0;
  9996. case ExactValue_Compound:
  9997. if (v.value_compound == nullptr) {
  9998. return true;
  9999. } else {
  10000. ast_node(cl, CompoundLit, v.value_compound);
  10001. if (cl->elems.count == 0) {
  10002. return true;
  10003. } else {
  10004. for (Ast *elem : cl->elems) {
  10005. if (elem->tav.mode != Addressing_Constant) {
  10006. return false;
  10007. }
  10008. if (!is_exact_value_zero(elem->tav.value)) {
  10009. return false;
  10010. }
  10011. }
  10012. return true;
  10013. }
  10014. }
  10015. case ExactValue_Procedure:
  10016. return v.value_procedure == nullptr;
  10017. case ExactValue_Typeid:
  10018. return v.value_typeid == nullptr;
  10019. }
  10020. return true;
  10021. }
  10022. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  10023. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  10024. for_array(i, params) {
  10025. if (i > 0) {
  10026. str = gb_string_appendc(str, ", ");
  10027. }
  10028. str = write_expr_to_string(str, params[i], false);
  10029. }
  10030. return str;
  10031. }
  10032. gb_internal gbString string_append_string(gbString str, String string) {
  10033. if (string.len > 0) {
  10034. return gb_string_append_length(str, &string[0], string.len);
  10035. }
  10036. return str;
  10037. }
  10038. gb_internal gbString string_append_token(gbString str, Token token) {
  10039. str = string_append_string(str, token.string);
  10040. return str;
  10041. }
  10042. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  10043. if (node == nullptr)
  10044. return str;
  10045. if (is_ast_stmt(node)) {
  10046. GB_ASSERT("stmt passed to write_expr_to_string");
  10047. }
  10048. switch (node->kind) {
  10049. default:
  10050. str = gb_string_appendc(str, "(BadExpr)");
  10051. break;
  10052. case_ast_node(i, Ident, node);
  10053. str = string_append_token(str, i->token);
  10054. case_end;
  10055. case_ast_node(i, Implicit, node);
  10056. str = string_append_token(str, *i);
  10057. case_end;
  10058. case_ast_node(bl, BasicLit, node);
  10059. str = string_append_token(str, bl->token);
  10060. case_end;
  10061. case_ast_node(bd, BasicDirective, node);
  10062. str = gb_string_append_rune(str, '#');
  10063. str = string_append_string(str, bd->name.string);
  10064. case_end;
  10065. case_ast_node(ud, Uninit, node);
  10066. str = gb_string_appendc(str, "---");
  10067. case_end;
  10068. case_ast_node(pg, ProcGroup, node);
  10069. str = gb_string_appendc(str, "proc{");
  10070. for_array(i, pg->args) {
  10071. if (i > 0) str = gb_string_appendc(str, ", ");
  10072. str = write_expr_to_string(str, pg->args[i], shorthand);
  10073. }
  10074. str = gb_string_append_rune(str, '}');
  10075. case_end;
  10076. case_ast_node(pl, ProcLit, node);
  10077. str = write_expr_to_string(str, pl->type, shorthand);
  10078. if (pl->body) {
  10079. str = gb_string_appendc(str, " {...}");
  10080. } else {
  10081. str = gb_string_appendc(str, " ---");
  10082. }
  10083. case_end;
  10084. case_ast_node(cl, CompoundLit, node);
  10085. str = write_expr_to_string(str, cl->type, shorthand);
  10086. str = gb_string_append_rune(str, '{');
  10087. if (shorthand) {
  10088. str = gb_string_appendc(str, "...");
  10089. } else {
  10090. for_array(i, cl->elems) {
  10091. if (i > 0) str = gb_string_appendc(str, ", ");
  10092. str = write_expr_to_string(str, cl->elems[i], shorthand);
  10093. }
  10094. }
  10095. str = gb_string_append_rune(str, '}');
  10096. case_end;
  10097. case_ast_node(te, TagExpr, node);
  10098. str = gb_string_append_rune(str, '#');
  10099. str = string_append_token(str, te->name);
  10100. str = write_expr_to_string(str, te->expr, shorthand);
  10101. case_end;
  10102. case_ast_node(ue, UnaryExpr, node);
  10103. str = string_append_token(str, ue->op);
  10104. str = write_expr_to_string(str, ue->expr, shorthand);
  10105. case_end;
  10106. case_ast_node(de, DerefExpr, node);
  10107. str = write_expr_to_string(str, de->expr, shorthand);
  10108. str = gb_string_append_rune(str, '^');
  10109. case_end;
  10110. case_ast_node(be, BinaryExpr, node);
  10111. str = write_expr_to_string(str, be->left, shorthand);
  10112. str = gb_string_append_rune(str, ' ');
  10113. str = string_append_token(str, be->op);
  10114. str = gb_string_append_rune(str, ' ');
  10115. str = write_expr_to_string(str, be->right, shorthand);
  10116. case_end;
  10117. case_ast_node(te, TernaryIfExpr, node);
  10118. TokenPos x = ast_token(te->x).pos;
  10119. TokenPos cond = ast_token(te->cond).pos;
  10120. if (x < cond) {
  10121. str = write_expr_to_string(str, te->x, shorthand);
  10122. str = gb_string_appendc(str, " if ");
  10123. str = write_expr_to_string(str, te->cond, shorthand);
  10124. str = gb_string_appendc(str, " else ");
  10125. str = write_expr_to_string(str, te->y, shorthand);
  10126. } else {
  10127. str = write_expr_to_string(str, te->cond, shorthand);
  10128. str = gb_string_appendc(str, " ? ");
  10129. str = write_expr_to_string(str, te->x, shorthand);
  10130. str = gb_string_appendc(str, " : ");
  10131. str = write_expr_to_string(str, te->y, shorthand);
  10132. }
  10133. case_end;
  10134. case_ast_node(te, TernaryWhenExpr, node);
  10135. str = write_expr_to_string(str, te->x, shorthand);
  10136. str = gb_string_appendc(str, " when ");
  10137. str = write_expr_to_string(str, te->cond, shorthand);
  10138. str = gb_string_appendc(str, " else ");
  10139. str = write_expr_to_string(str, te->y, shorthand);
  10140. case_end;
  10141. case_ast_node(oe, OrElseExpr, node);
  10142. str = write_expr_to_string(str, oe->x, shorthand);
  10143. str = gb_string_appendc(str, " or_else ");
  10144. str = write_expr_to_string(str, oe->y, shorthand);
  10145. case_end;
  10146. case_ast_node(oe, OrReturnExpr, node);
  10147. str = write_expr_to_string(str, oe->expr, shorthand);
  10148. str = gb_string_appendc(str, " or_return");
  10149. case_end;
  10150. case_ast_node(oe, OrBranchExpr, node);
  10151. str = write_expr_to_string(str, oe->expr, shorthand);
  10152. str = gb_string_append_rune(str, ' ');
  10153. str = string_append_token(str, oe->token);
  10154. if (oe->label) {
  10155. str = gb_string_append_rune(str, ' ');
  10156. str = write_expr_to_string(str, oe->label, shorthand);
  10157. }
  10158. case_end;
  10159. case_ast_node(pe, ParenExpr, node);
  10160. str = gb_string_append_rune(str, '(');
  10161. str = write_expr_to_string(str, pe->expr, shorthand);
  10162. str = gb_string_append_rune(str, ')');
  10163. case_end;
  10164. case_ast_node(se, SelectorExpr, node);
  10165. str = write_expr_to_string(str, se->expr, shorthand);
  10166. str = string_append_token(str, se->token);
  10167. str = write_expr_to_string(str, se->selector, shorthand);
  10168. case_end;
  10169. case_ast_node(se, ImplicitSelectorExpr, node);
  10170. str = gb_string_append_rune(str, '.');
  10171. str = write_expr_to_string(str, se->selector, shorthand);
  10172. case_end;
  10173. case_ast_node(se, SelectorCallExpr, node);
  10174. str = write_expr_to_string(str, se->expr, shorthand);
  10175. str = gb_string_appendc(str, "(");
  10176. ast_node(ce, CallExpr, se->call);
  10177. isize start = se->modified_call ? 1 : 0;
  10178. for (isize i = start; i < ce->args.count; i++) {
  10179. Ast *arg = ce->args[i];
  10180. if (i > start) {
  10181. str = gb_string_appendc(str, ", ");
  10182. }
  10183. str = write_expr_to_string(str, arg, shorthand);
  10184. }
  10185. str = gb_string_appendc(str, ")");
  10186. case_end;
  10187. case_ast_node(ta, TypeAssertion, node);
  10188. str = write_expr_to_string(str, ta->expr, shorthand);
  10189. if (ta->type != nullptr &&
  10190. ta->type->kind == Ast_UnaryExpr &&
  10191. ta->type->UnaryExpr.op.kind == Token_Question) {
  10192. str = gb_string_appendc(str, ".?");
  10193. } else {
  10194. str = gb_string_appendc(str, ".(");
  10195. str = write_expr_to_string(str, ta->type, shorthand);
  10196. str = gb_string_append_rune(str, ')');
  10197. }
  10198. case_end;
  10199. case_ast_node(tc, TypeCast, node);
  10200. str = string_append_token(str, tc->token);
  10201. str = gb_string_append_rune(str, '(');
  10202. str = write_expr_to_string(str, tc->type, shorthand);
  10203. str = gb_string_append_rune(str, ')');
  10204. str = write_expr_to_string(str, tc->expr, shorthand);
  10205. case_end;
  10206. case_ast_node(ac, AutoCast, node);
  10207. str = string_append_token(str, ac->token);
  10208. str = gb_string_append_rune(str, ' ');
  10209. str = write_expr_to_string(str, ac->expr, shorthand);
  10210. case_end;
  10211. case_ast_node(ie, IndexExpr, node);
  10212. str = write_expr_to_string(str, ie->expr, shorthand);
  10213. str = gb_string_append_rune(str, '[');
  10214. str = write_expr_to_string(str, ie->index, shorthand);
  10215. str = gb_string_append_rune(str, ']');
  10216. case_end;
  10217. case_ast_node(se, SliceExpr, node);
  10218. str = write_expr_to_string(str, se->expr, shorthand);
  10219. str = gb_string_append_rune(str, '[');
  10220. str = write_expr_to_string(str, se->low, shorthand);
  10221. str = string_append_token(str, se->interval);
  10222. str = write_expr_to_string(str, se->high, shorthand);
  10223. str = gb_string_append_rune(str, ']');
  10224. case_end;
  10225. case_ast_node(mie, MatrixIndexExpr, node);
  10226. str = write_expr_to_string(str, mie->expr, shorthand);
  10227. str = gb_string_append_rune(str, '[');
  10228. str = write_expr_to_string(str, mie->row_index, shorthand);
  10229. str = gb_string_appendc(str, ", ");
  10230. str = write_expr_to_string(str, mie->column_index, shorthand);
  10231. str = gb_string_append_rune(str, ']');
  10232. case_end;
  10233. case_ast_node(e, Ellipsis, node);
  10234. str = gb_string_appendc(str, "..");
  10235. str = write_expr_to_string(str, e->expr, shorthand);
  10236. case_end;
  10237. case_ast_node(fv, FieldValue, node);
  10238. str = write_expr_to_string(str, fv->field, shorthand);
  10239. str = gb_string_appendc(str, " = ");
  10240. str = write_expr_to_string(str, fv->value, shorthand);
  10241. case_end;
  10242. case_ast_node(fv, EnumFieldValue, node);
  10243. str = write_expr_to_string(str, fv->name, shorthand);
  10244. if (fv->value) {
  10245. str = gb_string_appendc(str, " = ");
  10246. str = write_expr_to_string(str, fv->value, shorthand);
  10247. }
  10248. case_end;
  10249. case_ast_node(ht, HelperType, node);
  10250. str = gb_string_appendc(str, "#type ");
  10251. str = write_expr_to_string(str, ht->type, shorthand);
  10252. case_end;
  10253. case_ast_node(ht, DistinctType, node);
  10254. str = gb_string_appendc(str, "distinct ");
  10255. str = write_expr_to_string(str, ht->type, shorthand);
  10256. case_end;
  10257. case_ast_node(pt, PolyType, node);
  10258. str = gb_string_append_rune(str, '$');
  10259. str = write_expr_to_string(str, pt->type, shorthand);
  10260. if (pt->specialization != nullptr) {
  10261. str = gb_string_append_rune(str, '/');
  10262. str = write_expr_to_string(str, pt->specialization, shorthand);
  10263. }
  10264. case_end;
  10265. case_ast_node(pt, PointerType, node);
  10266. if (pt->tag) {
  10267. str = write_expr_to_string(str, pt->tag, false);
  10268. }
  10269. str = gb_string_append_rune(str, '^');
  10270. str = write_expr_to_string(str, pt->type, shorthand);
  10271. case_end;
  10272. case_ast_node(pt, MultiPointerType, node);
  10273. str = gb_string_appendc(str, "[^]");
  10274. str = write_expr_to_string(str, pt->type, shorthand);
  10275. case_end;
  10276. case_ast_node(at, ArrayType, node);
  10277. if (at->tag) {
  10278. str = write_expr_to_string(str, at->tag, false);
  10279. }
  10280. str = gb_string_append_rune(str, '[');
  10281. if (at->count != nullptr &&
  10282. at->count->kind == Ast_UnaryExpr &&
  10283. at->count->UnaryExpr.op.kind == Token_Question) {
  10284. str = gb_string_appendc(str, "?");
  10285. } else {
  10286. str = write_expr_to_string(str, at->count, shorthand);
  10287. }
  10288. str = gb_string_append_rune(str, ']');
  10289. str = write_expr_to_string(str, at->elem, shorthand);
  10290. case_end;
  10291. case_ast_node(at, DynamicArrayType, node);
  10292. if (at->tag) {
  10293. str = write_expr_to_string(str, at->tag, false);
  10294. }
  10295. str = gb_string_appendc(str, "[dynamic]");
  10296. str = write_expr_to_string(str, at->elem, shorthand);
  10297. case_end;
  10298. case_ast_node(bs, BitSetType, node);
  10299. str = gb_string_appendc(str, "bit_set[");
  10300. str = write_expr_to_string(str, bs->elem, shorthand);
  10301. str = gb_string_appendc(str, "]");
  10302. case_end;
  10303. case_ast_node(mt, MapType, node);
  10304. str = gb_string_appendc(str, "map[");
  10305. str = write_expr_to_string(str, mt->key, shorthand);
  10306. str = gb_string_append_rune(str, ']');
  10307. str = write_expr_to_string(str, mt->value, shorthand);
  10308. case_end;
  10309. case_ast_node(mt, MatrixType, node);
  10310. str = gb_string_appendc(str, "matrix[");
  10311. str = write_expr_to_string(str, mt->row_count, shorthand);
  10312. str = gb_string_appendc(str, ", ");
  10313. str = write_expr_to_string(str, mt->column_count, shorthand);
  10314. str = gb_string_append_rune(str, ']');
  10315. str = write_expr_to_string(str, mt->elem, shorthand);
  10316. case_end;
  10317. case_ast_node(f, Field, node);
  10318. if (f->flags&FieldFlag_using) {
  10319. str = gb_string_appendc(str, "using ");
  10320. }
  10321. if (f->flags&FieldFlag_no_alias) {
  10322. str = gb_string_appendc(str, "#no_alias ");
  10323. }
  10324. if (f->flags&FieldFlag_c_vararg) {
  10325. str = gb_string_appendc(str, "#c_vararg ");
  10326. }
  10327. if (f->flags&FieldFlag_any_int) {
  10328. str = gb_string_appendc(str, "#any_int ");
  10329. }
  10330. if (f->flags&FieldFlag_no_broadcast) {
  10331. str = gb_string_appendc(str, "#no_broadcast ");
  10332. }
  10333. if (f->flags&FieldFlag_const) {
  10334. str = gb_string_appendc(str, "#const ");
  10335. }
  10336. if (f->flags&FieldFlag_subtype) {
  10337. str = gb_string_appendc(str, "#subtype ");
  10338. }
  10339. for_array(i, f->names) {
  10340. Ast *name = f->names[i];
  10341. if (i > 0) str = gb_string_appendc(str, ", ");
  10342. str = write_expr_to_string(str, name, shorthand);
  10343. }
  10344. if (f->names.count > 0) {
  10345. if (f->type == nullptr && f->default_value != nullptr) {
  10346. str = gb_string_append_rune(str, ' ');
  10347. }
  10348. str = gb_string_appendc(str, ":");
  10349. }
  10350. if (f->type != nullptr) {
  10351. str = gb_string_append_rune(str, ' ');
  10352. str = write_expr_to_string(str, f->type, shorthand);
  10353. }
  10354. if (f->default_value != nullptr) {
  10355. if (f->type != nullptr) {
  10356. str = gb_string_append_rune(str, ' ');
  10357. }
  10358. str = gb_string_appendc(str, "= ");
  10359. str = write_expr_to_string(str, f->default_value, shorthand);
  10360. }
  10361. case_end;
  10362. case_ast_node(f, FieldList, node);
  10363. bool has_name = false;
  10364. for_array(i, f->list) {
  10365. ast_node(field, Field, f->list[i]);
  10366. if (field->names.count > 1) {
  10367. has_name = true;
  10368. break;
  10369. }
  10370. if (field->names.count == 0) {
  10371. continue;
  10372. }
  10373. if (!is_blank_ident(field->names[0])) {
  10374. has_name = true;
  10375. break;
  10376. }
  10377. }
  10378. for_array(i, f->list) {
  10379. if (i > 0) str = gb_string_appendc(str, ", ");
  10380. if (has_name) {
  10381. str = write_expr_to_string(str, f->list[i], shorthand);
  10382. } else {
  10383. ast_node(field, Field, f->list[i]);
  10384. if (field->flags&FieldFlag_using) {
  10385. str = gb_string_appendc(str, "using ");
  10386. }
  10387. if (field->flags&FieldFlag_no_alias) {
  10388. str = gb_string_appendc(str, "#no_alias ");
  10389. }
  10390. if (field->flags&FieldFlag_c_vararg) {
  10391. str = gb_string_appendc(str, "#c_vararg ");
  10392. }
  10393. if (field->flags&FieldFlag_any_int) {
  10394. str = gb_string_appendc(str, "#any_int ");
  10395. }
  10396. if (field->flags&FieldFlag_no_broadcast) {
  10397. str = gb_string_appendc(str, "#no_broadcast ");
  10398. }
  10399. if (field->flags&FieldFlag_const) {
  10400. str = gb_string_appendc(str, "#const ");
  10401. }
  10402. if (field->flags&FieldFlag_subtype) {
  10403. str = gb_string_appendc(str, "#subtype ");
  10404. }
  10405. str = write_expr_to_string(str, field->type, shorthand);
  10406. }
  10407. }
  10408. case_end;
  10409. case_ast_node(ce, CallExpr, node);
  10410. switch (ce->inlining) {
  10411. case ProcInlining_inline:
  10412. str = gb_string_appendc(str, "#force_inline ");
  10413. break;
  10414. case ProcInlining_no_inline:
  10415. str = gb_string_appendc(str, "#force_no_inline ");
  10416. break;
  10417. }
  10418. str = write_expr_to_string(str, ce->proc, shorthand);
  10419. str = gb_string_appendc(str, "(");
  10420. isize idx0 = cast(isize)ce->was_selector;
  10421. for (isize i = idx0; i < ce->args.count; i++) {
  10422. Ast *arg = ce->args[i];
  10423. if (i > idx0) {
  10424. str = gb_string_appendc(str, ", ");
  10425. }
  10426. str = write_expr_to_string(str, arg, shorthand);
  10427. }
  10428. str = gb_string_appendc(str, ")");
  10429. case_end;
  10430. case_ast_node(tt, TypeidType, node);
  10431. str = gb_string_appendc(str, "typeid");
  10432. if (tt->specialization) {
  10433. str = gb_string_appendc(str, "/");
  10434. str = write_expr_to_string(str, tt->specialization, shorthand);
  10435. }
  10436. case_end;
  10437. case_ast_node(pt, ProcType, node);
  10438. str = gb_string_appendc(str, "proc(");
  10439. str = write_expr_to_string(str, pt->params, shorthand);
  10440. str = gb_string_appendc(str, ")");
  10441. if (pt->results != nullptr) {
  10442. str = gb_string_appendc(str, " -> ");
  10443. bool parens_needed = false;
  10444. if (pt->results && pt->results->kind == Ast_FieldList) {
  10445. for (Ast *field : pt->results->FieldList.list) {
  10446. ast_node(f, Field, field);
  10447. if (f->names.count != 0) {
  10448. parens_needed = true;
  10449. break;
  10450. }
  10451. }
  10452. }
  10453. if (parens_needed) {
  10454. str = gb_string_append_rune(str, '(');
  10455. }
  10456. str = write_expr_to_string(str, pt->results, shorthand);
  10457. if (parens_needed) {
  10458. str = gb_string_append_rune(str, ')');
  10459. }
  10460. }
  10461. case_end;
  10462. case_ast_node(st, StructType, node);
  10463. str = gb_string_appendc(str, "struct ");
  10464. if (st->polymorphic_params) {
  10465. str = gb_string_append_rune(str, '(');
  10466. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10467. str = gb_string_appendc(str, ") ");
  10468. }
  10469. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  10470. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  10471. if (st->align) {
  10472. str = gb_string_appendc(str, "#align ");
  10473. str = write_expr_to_string(str, st->align, shorthand);
  10474. str = gb_string_append_rune(str, ' ');
  10475. }
  10476. str = gb_string_append_rune(str, '{');
  10477. if (shorthand) {
  10478. str = gb_string_appendc(str, "...");
  10479. } else {
  10480. str = write_struct_fields_to_string(str, st->fields);
  10481. }
  10482. str = gb_string_append_rune(str, '}');
  10483. case_end;
  10484. case_ast_node(st, UnionType, node);
  10485. str = gb_string_appendc(str, "union ");
  10486. if (st->polymorphic_params) {
  10487. str = gb_string_append_rune(str, '(');
  10488. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10489. str = gb_string_appendc(str, ") ");
  10490. }
  10491. switch (st->kind) {
  10492. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  10493. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  10494. }
  10495. if (st->align) {
  10496. str = gb_string_appendc(str, "#align ");
  10497. str = write_expr_to_string(str, st->align, shorthand);
  10498. str = gb_string_append_rune(str, ' ');
  10499. }
  10500. str = gb_string_append_rune(str, '{');
  10501. if (shorthand) {
  10502. str = gb_string_appendc(str, "...");
  10503. } else {
  10504. str = write_struct_fields_to_string(str, st->variants);
  10505. }
  10506. str = gb_string_append_rune(str, '}');
  10507. case_end;
  10508. case_ast_node(et, EnumType, node);
  10509. str = gb_string_appendc(str, "enum ");
  10510. if (et->base_type != nullptr) {
  10511. str = write_expr_to_string(str, et->base_type, shorthand);
  10512. str = gb_string_append_rune(str, ' ');
  10513. }
  10514. str = gb_string_append_rune(str, '{');
  10515. if (shorthand) {
  10516. str = gb_string_appendc(str, "...");
  10517. } else {
  10518. for_array(i, et->fields) {
  10519. if (i > 0) {
  10520. str = gb_string_appendc(str, ", ");
  10521. }
  10522. str = write_expr_to_string(str, et->fields[i], shorthand);
  10523. }
  10524. }
  10525. str = gb_string_append_rune(str, '}');
  10526. case_end;
  10527. case_ast_node(rt, RelativeType, node);
  10528. str = write_expr_to_string(str, rt->tag, shorthand);
  10529. str = gb_string_appendc(str, "" );
  10530. str = write_expr_to_string(str, rt->type, shorthand);
  10531. case_end;
  10532. case_ast_node(f, BitFieldField, node);
  10533. str = write_expr_to_string(str, f->name, shorthand);
  10534. str = gb_string_appendc(str, ": ");
  10535. str = write_expr_to_string(str, f->type, shorthand);
  10536. str = gb_string_appendc(str, " | ");
  10537. str = write_expr_to_string(str, f->bit_size, shorthand);
  10538. case_end;
  10539. case_ast_node(bf, BitFieldType, node);
  10540. str = gb_string_appendc(str, "bit_field ");
  10541. if (!shorthand) {
  10542. str = write_expr_to_string(str, bf->backing_type, shorthand);
  10543. }
  10544. str = gb_string_appendc(str, " {");
  10545. if (shorthand) {
  10546. str = gb_string_appendc(str, "...");
  10547. } else {
  10548. for_array(i, bf->fields) {
  10549. if (i > 0) {
  10550. str = gb_string_appendc(str, ", ");
  10551. }
  10552. str = write_expr_to_string(str, bf->fields[i], false);
  10553. }
  10554. }
  10555. str = gb_string_appendc(str, "}");
  10556. case_end;
  10557. case_ast_node(ia, InlineAsmExpr, node);
  10558. str = gb_string_appendc(str, "asm(");
  10559. for_array(i, ia->param_types) {
  10560. if (i > 0) {
  10561. str = gb_string_appendc(str, ", ");
  10562. }
  10563. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  10564. }
  10565. str = gb_string_appendc(str, ")");
  10566. if (ia->return_type != nullptr) {
  10567. str = gb_string_appendc(str, " -> ");
  10568. str = write_expr_to_string(str, ia->return_type, shorthand);
  10569. }
  10570. if (ia->has_side_effects) {
  10571. str = gb_string_appendc(str, " #side_effects");
  10572. }
  10573. if (ia->is_align_stack) {
  10574. str = gb_string_appendc(str, " #stack_align");
  10575. }
  10576. if (ia->dialect) {
  10577. str = gb_string_appendc(str, " #");
  10578. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  10579. }
  10580. str = gb_string_appendc(str, " {");
  10581. if (shorthand) {
  10582. str = gb_string_appendc(str, "...");
  10583. } else {
  10584. str = write_expr_to_string(str, ia->asm_string, shorthand);
  10585. str = gb_string_appendc(str, ", ");
  10586. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  10587. }
  10588. str = gb_string_appendc(str, "}");
  10589. case_end;
  10590. }
  10591. return str;
  10592. }
  10593. gb_internal gbString expr_to_string(Ast *expression) {
  10594. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  10595. }
  10596. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  10597. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  10598. }
  10599. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  10600. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  10601. }