check_expr.cpp 354 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153
  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 != nullptr && 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 != nullptr && 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. if (is_type_proc(vt)) {
  727. if (are_types_identical(base_type(vt), src)) {
  728. return 1;
  729. }
  730. }
  731. }
  732. if (dst->Union.variants.count == 1) {
  733. Type *vt = dst->Union.variants[0];
  734. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  735. if (score >= 0) {
  736. return score+2;
  737. }
  738. } else if (is_type_untyped(src)) {
  739. i64 prev_lowest_score = -1;
  740. i64 lowest_score = -1;
  741. for (Type *vt : dst->Union.variants) {
  742. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  743. if (score >= 0) {
  744. if (lowest_score < 0) {
  745. lowest_score = score;
  746. } else {
  747. if (prev_lowest_score < 0) {
  748. prev_lowest_score = lowest_score;
  749. } else {
  750. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  751. }
  752. lowest_score = gb_min(lowest_score, score);
  753. }
  754. }
  755. }
  756. if (lowest_score >= 0) {
  757. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  758. return lowest_score+2;
  759. }
  760. }
  761. }
  762. }
  763. if (is_type_proc(dst)) {
  764. if (are_types_identical(src, dst)) {
  765. return 3;
  766. }
  767. PolyProcData poly_proc_data = {};
  768. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  769. Entity *e = poly_proc_data.gen_entity;
  770. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  771. add_entity_use(c, operand->expr, e);
  772. return 4;
  773. }
  774. }
  775. if (is_type_complex_or_quaternion(dst)) {
  776. Type *elem = base_complex_elem_type(dst);
  777. if (are_types_identical(elem, base_type(src))) {
  778. return 5;
  779. }
  780. }
  781. if (allow_array_programming) {
  782. if (is_type_array(dst)) {
  783. Type *elem = base_array_type(dst);
  784. i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
  785. if (distance >= 0) {
  786. return distance + 6;
  787. }
  788. }
  789. if (is_type_simd_vector(dst)) {
  790. Type *dst_elem = base_array_type(dst);
  791. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  792. if (distance >= 0) {
  793. return distance + 6;
  794. }
  795. }
  796. }
  797. if (is_type_matrix(dst)) {
  798. if (are_types_identical(src, dst)) {
  799. return 5;
  800. }
  801. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  802. Type *dst_elem = base_array_type(dst);
  803. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  804. if (distance >= 0) {
  805. return distance + 7;
  806. }
  807. }
  808. }
  809. if (is_type_any(dst)) {
  810. if (!is_type_polymorphic(src)) {
  811. if (operand->mode == Addressing_Context && operand->type == t_context) {
  812. return -1;
  813. } else {
  814. // NOTE(bill): Anything can cast to 'Any'
  815. add_type_info_type(c, s);
  816. return MAXIMUM_TYPE_DISTANCE;
  817. }
  818. }
  819. }
  820. Ast *expr = unparen_expr(operand->expr);
  821. if (expr != nullptr) {
  822. if (expr->kind == Ast_AutoCast) {
  823. Operand x = *operand;
  824. x.expr = expr->AutoCast.expr;
  825. if (check_cast_internal(c, &x, type)) {
  826. return MAXIMUM_TYPE_DISTANCE;
  827. }
  828. }
  829. }
  830. return -1;
  831. }
  832. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  833. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  834. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  835. // TODO(bill): A decent score function
  836. i64 d = distance*distance; // x^2
  837. if (is_variadic && d >= 0) {
  838. d += distance + 1; // x^2 + x + 1
  839. }
  840. return gb_max(c - d, 0);
  841. }
  842. 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) {
  843. i64 score = 0;
  844. i64 distance = check_distance_between_types(c, operand, type, allow_array_programming);
  845. bool ok = distance >= 0;
  846. if (ok) {
  847. score = assign_score_function(distance, is_variadic);
  848. }
  849. if (score_) *score_ = score;
  850. return ok;
  851. }
  852. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming=true) {
  853. i64 score = 0;
  854. return check_is_assignable_to_with_score(c, operand, type, &score, /*is_variadic*/false, allow_array_programming);
  855. }
  856. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  857. Operand x = {};
  858. x.type = src;
  859. x.mode = Addressing_Value;
  860. return check_is_assignable_to(nullptr, &x, dst);
  861. }
  862. gb_internal AstPackage *get_package_of_type(Type *type) {
  863. for (;;) {
  864. if (type == nullptr) {
  865. return nullptr;
  866. }
  867. switch (type->kind) {
  868. case Type_Basic:
  869. return builtin_pkg;
  870. case Type_Named:
  871. if (type->Named.type_name != nullptr) {
  872. return type->Named.type_name->pkg;
  873. }
  874. return nullptr;
  875. case Type_Pointer:
  876. type = type->Pointer.elem;
  877. continue;
  878. case Type_Array:
  879. type = type->Array.elem;
  880. continue;
  881. case Type_Slice:
  882. type = type->Slice.elem;
  883. continue;
  884. case Type_DynamicArray:
  885. type = type->DynamicArray.elem;
  886. continue;
  887. }
  888. return nullptr;
  889. }
  890. }
  891. // NOTE(bill): 'context_name' is for debugging and error messages
  892. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  893. check_not_tuple(c, operand);
  894. if (operand->mode == Addressing_Invalid) {
  895. return;
  896. }
  897. // Grab definite or indefinite article matching `context_name`, or "" if not found.
  898. String article = error_article(context_name);
  899. if (is_type_untyped(operand->type)) {
  900. Type *target_type = type;
  901. if (type == nullptr || is_type_any(type)) {
  902. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  903. error(operand->expr, "Use of --- in %.*s%.*s", LIT(article), LIT(context_name));
  904. operand->mode = Addressing_Invalid;
  905. return;
  906. }
  907. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  908. error(operand->expr, "Use of untyped nil in %.*s%.*s", LIT(article), LIT(context_name));
  909. operand->mode = Addressing_Invalid;
  910. return;
  911. }
  912. target_type = default_type(operand->type);
  913. if (type != nullptr && !is_type_any(type)) {
  914. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  915. }
  916. add_type_info_type(c, type);
  917. add_type_info_type(c, target_type);
  918. }
  919. convert_to_typed(c, operand, target_type);
  920. if (operand->mode == Addressing_Invalid) {
  921. return;
  922. }
  923. }
  924. if (type == nullptr) {
  925. return;
  926. }
  927. if (operand->mode == Addressing_ProcGroup) {
  928. bool good = false;
  929. if (type != nullptr && is_type_proc(type)) {
  930. Array<Entity *> procs = proc_group_entities(c, *operand);
  931. // NOTE(bill): These should be done
  932. for (Entity *e : procs) {
  933. Type *t = base_type(e->type);
  934. if (t == t_invalid) {
  935. continue;
  936. }
  937. Operand x = {};
  938. x.mode = Addressing_Value;
  939. x.type = t;
  940. if (check_is_assignable_to(c, &x, type)) {
  941. add_entity_use(c, operand->expr, e);
  942. good = true;
  943. break;
  944. }
  945. }
  946. }
  947. if (!good) {
  948. gbString expr_str = expr_to_string(operand->expr);
  949. gbString op_type_str = type_to_string(operand->type);
  950. gbString type_str = type_to_string(type);
  951. defer (gb_string_free(type_str));
  952. defer (gb_string_free(op_type_str));
  953. defer (gb_string_free(expr_str));
  954. // TODO(bill): is this a good enough error message?
  955. error(operand->expr,
  956. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s%.*s",
  957. expr_str,
  958. op_type_str,
  959. LIT(article),
  960. LIT(context_name));
  961. operand->mode = Addressing_Invalid;
  962. }
  963. convert_to_typed(c, operand, type);
  964. return;
  965. }
  966. if (check_is_assignable_to(c, operand, type)) {
  967. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  968. add_type_info_type(c, operand->type);
  969. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  970. }
  971. } else {
  972. gbString expr_str = expr_to_string(operand->expr);
  973. gbString op_type_str = type_to_string(operand->type);
  974. gbString type_str = type_to_string(type);
  975. defer (gb_string_free(type_str));
  976. defer (gb_string_free(op_type_str));
  977. defer (gb_string_free(expr_str));
  978. switch (operand->mode) {
  979. case Addressing_Builtin:
  980. error(operand->expr,
  981. "Cannot assign built-in procedure '%s' to %.*s%.*s",
  982. expr_str,
  983. LIT(article),
  984. LIT(context_name));
  985. break;
  986. case Addressing_Type:
  987. if (is_type_polymorphic(operand->type)) {
  988. error(operand->expr,
  989. "Cannot assign '%s', a polymorphic type, to %.*s%.*s",
  990. op_type_str,
  991. LIT(article),
  992. LIT(context_name));
  993. } else {
  994. ERROR_BLOCK();
  995. error(operand->expr,
  996. "Cannot assign '%s', a type, to %.*s%.*s",
  997. op_type_str,
  998. LIT(article),
  999. LIT(context_name));
  1000. if (type && are_types_identical(type, t_any)) {
  1001. error_line("\tSuggestion: 'typeid_of(%s)'", expr_str);
  1002. }
  1003. }
  1004. break;
  1005. default:
  1006. // TODO(bill): is this a good enough error message?
  1007. {
  1008. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  1009. gbString type_extra = gb_string_make(heap_allocator(), "");
  1010. defer (gb_string_free(op_type_extra));
  1011. defer (gb_string_free(type_extra));
  1012. isize on = gb_string_length(op_type_str);
  1013. isize tn = gb_string_length(type_str);
  1014. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  1015. AstPackage *op_pkg = get_package_of_type(operand->type);
  1016. AstPackage *type_pkg = get_package_of_type(type);
  1017. if (op_pkg != nullptr) {
  1018. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  1019. }
  1020. if (type_pkg != nullptr) {
  1021. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  1022. }
  1023. }
  1024. ERROR_BLOCK();
  1025. error(operand->expr,
  1026. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s%.*s",
  1027. expr_str,
  1028. op_type_str, op_type_extra,
  1029. type_str, type_extra,
  1030. LIT(article),
  1031. LIT(context_name));
  1032. check_assignment_error_suggestion(c, operand, type);
  1033. Type *src = base_type(operand->type);
  1034. Type *dst = base_type(type);
  1035. if (context_name == "procedure argument") {
  1036. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  1037. gbString a = expr_to_string(operand->expr);
  1038. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  1039. gb_string_free(a);
  1040. }
  1041. }
  1042. if (src->kind == dst->kind && src->kind == Type_Proc) {
  1043. Type *x = src;
  1044. Type *y = dst;
  1045. bool same_inputs = are_types_identical_internal(x->Proc.params, y->Proc.params, false);
  1046. bool same_outputs = are_types_identical_internal(x->Proc.results, y->Proc.results, false);
  1047. if (same_inputs && same_outputs &&
  1048. x->Proc.calling_convention != y->Proc.calling_convention) {
  1049. gbString s_expected = type_to_string(y);
  1050. gbString s_got = type_to_string(x);
  1051. error_line("\tNote: The calling conventions differ between the procedure signature types\n");
  1052. error_line("\t Expected \"%s\", got \"%s\"\n",
  1053. proc_calling_convention_strings[y->Proc.calling_convention],
  1054. proc_calling_convention_strings[x->Proc.calling_convention]);
  1055. error_line("\t Expected: %s\n", s_expected);
  1056. error_line("\t Got: %s\n", s_got);
  1057. gb_string_free(s_got);
  1058. gb_string_free(s_expected);
  1059. } else if (same_inputs && same_outputs &&
  1060. x->Proc.diverging != y->Proc.diverging) {
  1061. gbString s_expected = type_to_string(y);
  1062. if (y->Proc.diverging) {
  1063. s_expected = gb_string_appendc(s_expected, " -> !");
  1064. }
  1065. gbString s_got = type_to_string(x);
  1066. if (x->Proc.diverging) {
  1067. s_got = gb_string_appendc(s_got, " -> !");
  1068. }
  1069. error_line("\tNote: One of the procedures is diverging while the other isn't\n");
  1070. error_line("\t Expected: %s\n", s_expected);
  1071. error_line("\t Got: %s\n", s_got);
  1072. gb_string_free(s_got);
  1073. gb_string_free(s_expected);
  1074. } else if (same_inputs && !same_outputs) {
  1075. gbString s_expected = type_to_string(y->Proc.results);
  1076. gbString s_got = type_to_string(x->Proc.results);
  1077. error_line("\tNote: The return types differ between the procedure signature types\n");
  1078. error_line("\t Expected: %s\n", s_expected);
  1079. error_line("\t Got: %s\n", s_got);
  1080. gb_string_free(s_got);
  1081. gb_string_free(s_expected);
  1082. } else if (!same_inputs && same_outputs) {
  1083. gbString s_expected = type_to_string(y->Proc.params);
  1084. gbString s_got = type_to_string(x->Proc.params);
  1085. error_line("\tNote: The input parameter types differ between the procedure signature types\n");
  1086. error_line("\t Expected: %s\n", s_expected);
  1087. error_line("\t Got: %s\n", s_got);
  1088. gb_string_free(s_got);
  1089. gb_string_free(s_expected);
  1090. } else {
  1091. gbString s_expected = type_to_string(y);
  1092. gbString s_got = type_to_string(x);
  1093. error_line("\tNote: The signature type do not match whatsoever\n");
  1094. error_line("\t Expected: %s\n", s_expected);
  1095. error_line("\t Got: %s\n", s_got);
  1096. gb_string_free(s_got);
  1097. gb_string_free(s_expected);
  1098. }
  1099. }
  1100. }
  1101. break;
  1102. }
  1103. operand->mode = Addressing_Invalid;
  1104. return;
  1105. }
  1106. }
  1107. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1108. Type *gt = *gt_;
  1109. GB_ASSERT(gt->kind == Type_Generic);
  1110. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1111. GB_ASSERT(e != nullptr);
  1112. if (e->kind == Entity_TypeName) {
  1113. *gt_ = nullptr;
  1114. *dst_count = source_count;
  1115. e->kind = Entity_Constant;
  1116. e->Constant.value = exact_value_i64(source_count);
  1117. e->type = t_untyped_integer;
  1118. return true;
  1119. } else if (e->kind == Entity_Constant) {
  1120. *gt_ = nullptr;
  1121. if (e->Constant.value.kind != ExactValue_Integer) {
  1122. return false;
  1123. }
  1124. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1125. if (count != source_count) {
  1126. return false;
  1127. }
  1128. *dst_count = source_count;
  1129. return true;
  1130. }
  1131. return false;
  1132. }
  1133. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1134. Operand o = {Addressing_Value};
  1135. o.type = source;
  1136. switch (poly->kind) {
  1137. case Type_Basic:
  1138. if (compound) return are_types_identical(poly, source);
  1139. return check_is_assignable_to(c, &o, poly);
  1140. case Type_Named: {
  1141. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1142. return true;
  1143. }
  1144. if (compound || !is_type_generic(poly)) {
  1145. return are_types_identical(poly, source);
  1146. }
  1147. return check_is_assignable_to(c, &o, poly);
  1148. }
  1149. case Type_Generic: {
  1150. if (poly->Generic.specialized != nullptr) {
  1151. Type *s = poly->Generic.specialized;
  1152. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1153. return false;
  1154. }
  1155. }
  1156. if (modify_type) {
  1157. Type *ds = default_type(source);
  1158. gb_memmove(poly, ds, gb_size_of(Type));
  1159. }
  1160. return true;
  1161. }
  1162. case Type_Pointer:
  1163. if (source->kind == Type_Pointer) {
  1164. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1165. if (level > 0) {
  1166. return true;
  1167. }
  1168. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1169. } else if (source->kind == Type_MultiPointer) {
  1170. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1171. if (level > 0) {
  1172. return true;
  1173. }
  1174. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1175. }
  1176. return false;
  1177. case Type_MultiPointer:
  1178. if (source->kind == Type_MultiPointer) {
  1179. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1180. if (level > 0) {
  1181. return true;
  1182. }
  1183. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1184. } else if (source->kind == Type_Pointer) {
  1185. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1186. if (level > 0) {
  1187. return true;
  1188. }
  1189. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1190. }
  1191. return false;
  1192. case Type_Array:
  1193. if (source->kind == Type_Array) {
  1194. if (poly->Array.generic_count != nullptr) {
  1195. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1196. return false;
  1197. }
  1198. }
  1199. if (poly->Array.count == source->Array.count) {
  1200. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1201. }
  1202. } else if (source->kind == Type_EnumeratedArray) {
  1203. if (poly->Array.generic_count != nullptr) {
  1204. Type *gt = poly->Array.generic_count;
  1205. GB_ASSERT(gt->kind == Type_Generic);
  1206. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1207. GB_ASSERT(e != nullptr);
  1208. if (e->kind == Entity_TypeName) {
  1209. Type *index = source->EnumeratedArray.index;
  1210. Type *it = base_type(index);
  1211. if (it->kind != Type_Enum) {
  1212. return false;
  1213. }
  1214. poly->kind = Type_EnumeratedArray;
  1215. poly->cached_size = -1;
  1216. poly->cached_align = -1;
  1217. poly->flags.exchange(source->flags);
  1218. poly->failure = false;
  1219. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1220. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1221. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1222. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1223. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1224. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1225. e->kind = Entity_TypeName;
  1226. e->TypeName.is_type_alias = true;
  1227. e->type = index;
  1228. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1229. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1230. }
  1231. }
  1232. }
  1233. }
  1234. return false;
  1235. case Type_EnumeratedArray:
  1236. if (source->kind == Type_EnumeratedArray) {
  1237. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1238. return false;
  1239. }
  1240. if (poly->EnumeratedArray.op) {
  1241. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1242. return false;
  1243. }
  1244. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1245. return false;
  1246. }
  1247. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1248. return false;
  1249. }
  1250. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1251. }
  1252. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1253. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1254. return index || elem;
  1255. }
  1256. return false;
  1257. case Type_DynamicArray:
  1258. if (source->kind == Type_DynamicArray) {
  1259. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1260. }
  1261. return false;
  1262. case Type_Slice:
  1263. if (source->kind == Type_Slice) {
  1264. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1265. }
  1266. return false;
  1267. case Type_Enum:
  1268. return false;
  1269. case Type_BitSet:
  1270. if (source->kind == Type_BitSet) {
  1271. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1272. return false;
  1273. }
  1274. // For generic types like bit_set[$T] the upper and lower of the poly type will be zeroes since
  1275. // it could not figure that stuff out when the poly type was created.
  1276. if (poly->BitSet.upper == 0 && modify_type) {
  1277. poly->BitSet.upper = source->BitSet.upper;
  1278. }
  1279. if (poly->BitSet.lower == 0 && modify_type) {
  1280. poly->BitSet.lower = source->BitSet.lower;
  1281. }
  1282. if (poly->BitSet.underlying == nullptr) {
  1283. if (modify_type) {
  1284. poly->BitSet.underlying = source->BitSet.underlying;
  1285. }
  1286. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1287. return false;
  1288. }
  1289. return true;
  1290. }
  1291. return false;
  1292. case Type_Union:
  1293. if (source->kind == Type_Union) {
  1294. TypeUnion *x = &poly->Union;
  1295. TypeUnion *y = &source->Union;
  1296. if (x->variants.count != y->variants.count) {
  1297. return false;
  1298. }
  1299. for_array(i, x->variants) {
  1300. Type *a = x->variants[i];
  1301. Type *b = y->variants[i];
  1302. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1303. if (!ok) return false;
  1304. }
  1305. return true;
  1306. }
  1307. return false;
  1308. case Type_Struct:
  1309. if (source->kind == Type_Struct) {
  1310. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1311. poly->Struct.soa_kind != StructSoa_None) {
  1312. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1313. if (ok) switch (source->Struct.soa_kind) {
  1314. case StructSoa_None:
  1315. default:
  1316. GB_PANIC("Unhandled SOA Kind");
  1317. break;
  1318. case StructSoa_Fixed:
  1319. if (modify_type) {
  1320. Type *type = make_soa_struct_fixed(c, nullptr, poly->Struct.node, poly->Struct.soa_elem, poly->Struct.soa_count, nullptr);
  1321. gb_memmove(poly, type, gb_size_of(*type));
  1322. }
  1323. break;
  1324. case StructSoa_Slice:
  1325. if (modify_type) {
  1326. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1327. gb_memmove(poly, type, gb_size_of(*type));
  1328. }
  1329. break;
  1330. case StructSoa_Dynamic:
  1331. if (modify_type) {
  1332. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1333. gb_memmove(poly, type, gb_size_of(*type));
  1334. }
  1335. break;
  1336. }
  1337. return ok;
  1338. }
  1339. // NOTE(bill): Check for subtypes of
  1340. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1341. }
  1342. return false;
  1343. case Type_BitField:
  1344. if (source->kind == Type_BitField) {
  1345. return is_polymorphic_type_assignable(c, poly->BitField.backing_type, source->BitField.backing_type, true, modify_type);
  1346. }
  1347. return false;
  1348. case Type_Tuple:
  1349. GB_PANIC("This should never happen");
  1350. return false;
  1351. case Type_Proc:
  1352. if (source->kind == Type_Proc) {
  1353. TypeProc *x = &poly->Proc;
  1354. TypeProc *y = &source->Proc;
  1355. if (x->calling_convention != y->calling_convention) {
  1356. return false;
  1357. }
  1358. if (x->c_vararg != y->c_vararg) {
  1359. return false;
  1360. }
  1361. if (x->variadic != y->variadic) {
  1362. return false;
  1363. }
  1364. if (x->param_count != y->param_count) {
  1365. return false;
  1366. }
  1367. if (x->result_count != y->result_count) {
  1368. return false;
  1369. }
  1370. for (isize i = 0; i < x->param_count; i++) {
  1371. Entity *a = x->params->Tuple.variables[i];
  1372. Entity *b = y->params->Tuple.variables[i];
  1373. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1374. if (!ok) return false;
  1375. }
  1376. for (isize i = 0; i < x->result_count; i++) {
  1377. Entity *a = x->results->Tuple.variables[i];
  1378. Entity *b = y->results->Tuple.variables[i];
  1379. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1380. if (!ok) return false;
  1381. }
  1382. return true;
  1383. }
  1384. return false;
  1385. case Type_Map:
  1386. if (source->kind == Type_Map) {
  1387. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1388. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1389. if (key || value) {
  1390. poly->Map.lookup_result_type = nullptr;
  1391. init_map_internal_types(poly);
  1392. return true;
  1393. }
  1394. }
  1395. return false;
  1396. case Type_Matrix:
  1397. if (source->kind == Type_Matrix) {
  1398. if (poly->Matrix.generic_row_count != nullptr) {
  1399. poly->Matrix.stride_in_bytes = 0;
  1400. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1401. return false;
  1402. }
  1403. }
  1404. if (poly->Matrix.generic_column_count != nullptr) {
  1405. poly->Matrix.stride_in_bytes = 0;
  1406. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1407. return false;
  1408. }
  1409. }
  1410. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1411. poly->Matrix.column_count == source->Matrix.column_count) {
  1412. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1413. }
  1414. }
  1415. return false;
  1416. case Type_SimdVector:
  1417. if (source->kind == Type_SimdVector) {
  1418. if (poly->SimdVector.generic_count != nullptr) {
  1419. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1420. return false;
  1421. }
  1422. }
  1423. if (poly->SimdVector.count == source->SimdVector.count) {
  1424. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1425. }
  1426. }
  1427. return false;
  1428. }
  1429. return false;
  1430. }
  1431. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1432. if (curr->state != EntityState_InProgress) {
  1433. return false;
  1434. }
  1435. for_array(i, *c->type_path) {
  1436. Entity *prev = c->type_path->data[i];
  1437. if (prev == curr) {
  1438. if (report) {
  1439. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1440. for (isize j = i; j < c->type_path->count; j++) {
  1441. Entity *curr = (*c->type_path)[j];
  1442. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1443. }
  1444. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1445. curr->type = t_invalid;
  1446. }
  1447. return true;
  1448. }
  1449. }
  1450. return false;
  1451. }
  1452. struct CIdentSuggestion {
  1453. String name;
  1454. String msg;
  1455. };
  1456. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1457. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1458. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1459. {str_lit("sizeof"), str_lit("'size_of'?")},
  1460. {str_lit("alignof"), str_lit("'align_of'?")},
  1461. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1462. {str_lit("_Bool"), str_lit("'bool'?")},
  1463. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1464. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1465. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1466. {str_lit("float"), str_lit("'f32'?")},
  1467. {str_lit("double"), str_lit("'f64'?")},
  1468. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1469. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1470. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1471. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1472. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1473. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1474. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1475. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1476. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1477. {str_lit("uint8_t"), str_lit("'u8'?")},
  1478. {str_lit("int8_t"), str_lit("'i8'?")},
  1479. {str_lit("uint16_t"), str_lit("'u16'?")},
  1480. {str_lit("int16_t"), str_lit("'i16'?")},
  1481. {str_lit("uint32_t"), str_lit("'u32'?")},
  1482. {str_lit("int32_t"), str_lit("'i32'?")},
  1483. {str_lit("uint64_t"), str_lit("'u64'?")},
  1484. {str_lit("int64_t"), str_lit("'i64'?")},
  1485. {str_lit("uint128_t"), str_lit("'u128'?")},
  1486. {str_lit("int128_t"), str_lit("'i128'?")},
  1487. {str_lit("float32"), str_lit("'f32'?")},
  1488. {str_lit("float64"), str_lit("'f64'?")},
  1489. {str_lit("float32_t"), str_lit("'f32'?")},
  1490. {str_lit("float64_t"), str_lit("'f64'?")},
  1491. };
  1492. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1493. GB_ASSERT(n->kind == Ast_Ident);
  1494. o->mode = Addressing_Invalid;
  1495. o->expr = n;
  1496. String name = n->Ident.token.string;
  1497. Entity *e = scope_lookup(c->scope, name);
  1498. if (e == nullptr) {
  1499. if (is_blank_ident(name)) {
  1500. error(n, "'_' cannot be used as a value");
  1501. } else {
  1502. ERROR_BLOCK();
  1503. error(n, "Undeclared name: %.*s", LIT(name));
  1504. // NOTE(bill): Loads of checks for C programmers
  1505. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1506. if (name == suggestion.name) {
  1507. error_line("\tSuggestion: Did you mean %.*s\n", LIT(suggestion.msg));
  1508. }
  1509. }
  1510. }
  1511. o->type = t_invalid;
  1512. o->mode = Addressing_Invalid;
  1513. if (named_type != nullptr) {
  1514. set_base_type(named_type, t_invalid);
  1515. }
  1516. return nullptr;
  1517. }
  1518. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1519. if (e->parent_proc_decl != nullptr &&
  1520. e->parent_proc_decl != c->curr_proc_decl) {
  1521. if (e->kind == Entity_Variable) {
  1522. if ((e->flags & EntityFlag_Static) == 0) {
  1523. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1524. return nullptr;
  1525. }
  1526. } else if (e->kind == Entity_Label) {
  1527. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1528. return nullptr;
  1529. }
  1530. }
  1531. if (e->kind == Entity_ProcGroup) {
  1532. auto *pge = &e->ProcGroup;
  1533. DeclInfo *d = decl_info_of_entity(e);
  1534. check_entity_decl(c, e, d, nullptr);
  1535. Array<Entity *> procs = pge->entities;
  1536. bool skip = false;
  1537. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1538. // NOTE(bill): These should be done
  1539. for (Entity *proc : procs) {
  1540. Type *t = base_type(proc->type);
  1541. if (t == t_invalid) {
  1542. continue;
  1543. }
  1544. Operand x = {};
  1545. x.mode = Addressing_Value;
  1546. x.type = t;
  1547. if (check_is_assignable_to(c, &x, type_hint)) {
  1548. e = proc;
  1549. add_entity_use(c, n, e);
  1550. skip = true;
  1551. break;
  1552. }
  1553. }
  1554. }
  1555. if (!skip) {
  1556. o->mode = Addressing_ProcGroup;
  1557. o->type = t_invalid;
  1558. o->proc_group = e;
  1559. return nullptr;
  1560. }
  1561. }
  1562. add_entity_use(c, n, e);
  1563. if (e->state == EntityState_Unresolved) {
  1564. check_entity_decl(c, e, nullptr, named_type);
  1565. }
  1566. if (e->type == nullptr) {
  1567. // TODO(bill): Which is correct? return or compiler_error?
  1568. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1569. return nullptr;
  1570. }
  1571. e->flags |= EntityFlag_Used;
  1572. Type *type = e->type;
  1573. o->type = type;
  1574. switch (e->kind) {
  1575. case Entity_Constant:
  1576. if (type == t_invalid) {
  1577. o->type = t_invalid;
  1578. return e;
  1579. }
  1580. o->value = e->Constant.value;
  1581. if (o->value.kind == ExactValue_Invalid) {
  1582. return e;
  1583. }
  1584. if (o->value.kind == ExactValue_Procedure) {
  1585. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1586. if (proc != nullptr) {
  1587. o->mode = Addressing_Value;
  1588. o->type = proc->type;
  1589. return proc;
  1590. }
  1591. }
  1592. o->mode = Addressing_Constant;
  1593. break;
  1594. case Entity_Variable:
  1595. e->flags |= EntityFlag_Used;
  1596. if (type == t_invalid) {
  1597. o->type = t_invalid;
  1598. return e;
  1599. }
  1600. o->mode = Addressing_Variable;
  1601. if (e->flags & EntityFlag_Value) {
  1602. o->mode = Addressing_Value;
  1603. }
  1604. break;
  1605. case Entity_Procedure:
  1606. o->mode = Addressing_Value;
  1607. o->value = exact_value_procedure(n);
  1608. break;
  1609. case Entity_Builtin:
  1610. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1611. o->mode = Addressing_Builtin;
  1612. break;
  1613. case Entity_TypeName:
  1614. o->mode = Addressing_Type;
  1615. if (check_cycle(c, e, true)) {
  1616. o->type = t_invalid;
  1617. }
  1618. if (o->type != nullptr && o->type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1619. o->type = base_type(o->type);
  1620. }
  1621. break;
  1622. case Entity_ImportName:
  1623. if (!allow_import_name) {
  1624. error(n, "Use of import name '%.*s' not in the form of 'x.y'", LIT(name));
  1625. }
  1626. return e;
  1627. case Entity_LibraryName:
  1628. if (!allow_import_name) {
  1629. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1630. }
  1631. return e;
  1632. case Entity_Label:
  1633. o->mode = Addressing_NoValue;
  1634. break;
  1635. case Entity_Nil:
  1636. o->mode = Addressing_Value;
  1637. break;
  1638. default:
  1639. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1640. break;
  1641. }
  1642. return e;
  1643. }
  1644. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1645. if (o->type == nullptr) {
  1646. gbString str = expr_to_string(o->expr);
  1647. error(o->expr, "Expression has no value '%s'", str);
  1648. gb_string_free(str);
  1649. return false;
  1650. }
  1651. if (o->mode == Addressing_Type) {
  1652. gbString str = type_to_string(o->type);
  1653. error(o->expr, "Expected an expression for operator '%.*s', got type '%s'", LIT(op.string), str);
  1654. gb_string_free(str);
  1655. return false;
  1656. }
  1657. Type *type = base_type(core_array_type(o->type));
  1658. gbString str = nullptr;
  1659. switch (op.kind) {
  1660. case Token_Add:
  1661. case Token_Sub:
  1662. if (!is_type_numeric(type)) {
  1663. str = expr_to_string(o->expr);
  1664. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1665. gb_string_free(str);
  1666. }
  1667. break;
  1668. case Token_Xor:
  1669. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1670. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1671. }
  1672. break;
  1673. case Token_Not:
  1674. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1675. ERROR_BLOCK();
  1676. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1677. if (is_type_integer(type)) {
  1678. str = expr_to_string(o->expr);
  1679. error_line("\tSuggestion: Did you mean to do one of the following?\n");
  1680. error_line("\t\t'%s == 0'?\n", str);
  1681. error_line("\t\tUse of the bitwise not operator '~'?\n");
  1682. gb_string_free(str);
  1683. }
  1684. } else {
  1685. o->type = t_untyped_bool;
  1686. }
  1687. break;
  1688. case Token_Mul:
  1689. {
  1690. ERROR_BLOCK();
  1691. error(op, "Operator '%.*s' is not a valid unary operator in Odin", LIT(op.string));
  1692. if (is_type_pointer(o->type)) {
  1693. str = expr_to_string(o->expr);
  1694. error_line("\tSuggestion: Did you mean '%s^'?\n", str);
  1695. o->type = type_deref(o->type);
  1696. } else if (is_type_multi_pointer(o->type)) {
  1697. str = expr_to_string(o->expr);
  1698. error_line("\tSuggestion: The value is a multi-pointer, did you mean '%s[0]'?\n", str);
  1699. o->type = type_deref(o->type, true);
  1700. }
  1701. }
  1702. break;
  1703. default:
  1704. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1705. return false;
  1706. }
  1707. return true;
  1708. }
  1709. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1710. Type *main_type = o->type;
  1711. Type *type = base_type(core_array_type(main_type));
  1712. Type *ct = core_type(type);
  1713. switch (op.kind) {
  1714. case Token_Sub:
  1715. case Token_SubEq:
  1716. if (is_type_bit_set(type)) {
  1717. return true;
  1718. } else if (!is_type_numeric(type)) {
  1719. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1720. return false;
  1721. }
  1722. break;
  1723. case Token_Quo:
  1724. case Token_QuoEq:
  1725. if (is_type_matrix(main_type)) {
  1726. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1727. return false;
  1728. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1729. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1730. return false;
  1731. }
  1732. /*fallthrough*/
  1733. case Token_Mul:
  1734. case Token_MulEq:
  1735. case Token_AddEq:
  1736. if (is_type_bit_set(type)) {
  1737. return true;
  1738. } else if (!is_type_numeric(type)) {
  1739. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1740. return false;
  1741. }
  1742. break;
  1743. case Token_Add:
  1744. if (is_type_string(type)) {
  1745. if (o->mode == Addressing_Constant) {
  1746. return true;
  1747. }
  1748. error(op, "String concatenation is only allowed with constant strings");
  1749. return false;
  1750. } else if (is_type_bit_set(type)) {
  1751. return true;
  1752. } else if (!is_type_numeric(type)) {
  1753. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1754. return false;
  1755. }
  1756. break;
  1757. case Token_And:
  1758. case Token_Or:
  1759. case Token_AndEq:
  1760. case Token_OrEq:
  1761. case Token_Xor:
  1762. case Token_XorEq:
  1763. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1764. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1765. return false;
  1766. }
  1767. break;
  1768. case Token_Mod:
  1769. case Token_ModMod:
  1770. case Token_ModEq:
  1771. case Token_ModModEq:
  1772. if (is_type_matrix(main_type)) {
  1773. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1774. return false;
  1775. }
  1776. if (!is_type_integer(type)) {
  1777. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1778. return false;
  1779. } else if (is_type_simd_vector(main_type)) {
  1780. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1781. return false;
  1782. }
  1783. break;
  1784. case Token_AndNot:
  1785. case Token_AndNotEq:
  1786. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1787. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1788. return false;
  1789. }
  1790. break;
  1791. case Token_CmpAnd:
  1792. case Token_CmpOr:
  1793. case Token_CmpAndEq:
  1794. case Token_CmpOrEq:
  1795. if (!is_type_boolean(type)) {
  1796. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1797. return false;
  1798. }
  1799. break;
  1800. default:
  1801. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1802. return false;
  1803. }
  1804. return true;
  1805. }
  1806. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1807. if (in_value.kind == ExactValue_Invalid) {
  1808. // NOTE(bill): There's already been an error
  1809. return true;
  1810. }
  1811. type = core_type(type);
  1812. if (type == t_invalid) {
  1813. return false;
  1814. } else if (is_type_boolean(type)) {
  1815. return in_value.kind == ExactValue_Bool;
  1816. } else if (is_type_string(type)) {
  1817. return in_value.kind == ExactValue_String;
  1818. } else if (is_type_integer(type) || is_type_rune(type)) {
  1819. if (in_value.kind == ExactValue_Bool) {
  1820. return false;
  1821. }
  1822. ExactValue v = exact_value_to_integer(in_value);
  1823. if (v.kind != ExactValue_Integer) {
  1824. return false;
  1825. }
  1826. if (out_value) *out_value = v;
  1827. if (is_type_untyped(type)) {
  1828. return true;
  1829. }
  1830. BigInt i = v.value_integer;
  1831. i64 byte_size = type_size_of(type);
  1832. BigInt umax = {};
  1833. BigInt imin = {};
  1834. BigInt imax = {};
  1835. if (c->bit_field_bit_size > 0) {
  1836. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1837. big_int_from_u64(&umax, 1);
  1838. big_int_from_i64(&imin, 1);
  1839. big_int_from_i64(&imax, 1);
  1840. BigInt bu = {};
  1841. BigInt bi = {};
  1842. big_int_from_i64(&bu, bit_size);
  1843. big_int_from_i64(&bi, bit_size-1);
  1844. big_int_shl_eq(&umax, &bu);
  1845. mp_decr(&umax);
  1846. big_int_shl_eq(&imin, &bi);
  1847. big_int_neg(&imin, &imin);
  1848. big_int_shl_eq(&imax, &bi);
  1849. mp_decr(&imax);
  1850. } else {
  1851. if (byte_size < 16) {
  1852. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1853. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1854. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1855. } else {
  1856. big_int_from_u64(&umax, 1);
  1857. big_int_from_i64(&imin, 1);
  1858. big_int_from_i64(&imax, 1);
  1859. BigInt bi128 = {};
  1860. BigInt bi127 = {};
  1861. big_int_from_i64(&bi128, 128);
  1862. big_int_from_i64(&bi127, 127);
  1863. big_int_shl_eq(&umax, &bi128);
  1864. mp_decr(&umax);
  1865. big_int_shl_eq(&imin, &bi127);
  1866. big_int_neg(&imin, &imin);
  1867. big_int_shl_eq(&imax, &bi127);
  1868. mp_decr(&imax);
  1869. }
  1870. }
  1871. switch (type->Basic.kind) {
  1872. case Basic_rune:
  1873. case Basic_i8:
  1874. case Basic_i16:
  1875. case Basic_i32:
  1876. case Basic_i64:
  1877. case Basic_i128:
  1878. case Basic_int:
  1879. case Basic_i16le:
  1880. case Basic_i32le:
  1881. case Basic_i64le:
  1882. case Basic_i128le:
  1883. case Basic_i16be:
  1884. case Basic_i32be:
  1885. case Basic_i64be:
  1886. case Basic_i128be:
  1887. {
  1888. // return imin <= i && i <= imax;
  1889. int a = big_int_cmp(&imin, &i);
  1890. int b = big_int_cmp(&i, &imax);
  1891. return (a <= 0) && (b <= 0);
  1892. }
  1893. case Basic_u8:
  1894. case Basic_u16:
  1895. case Basic_u32:
  1896. case Basic_u64:
  1897. case Basic_u128:
  1898. case Basic_uint:
  1899. case Basic_uintptr:
  1900. case Basic_u16le:
  1901. case Basic_u32le:
  1902. case Basic_u64le:
  1903. case Basic_u128le:
  1904. case Basic_u16be:
  1905. case Basic_u32be:
  1906. case Basic_u64be:
  1907. case Basic_u128be:
  1908. {
  1909. // return 0ull <= i && i <= umax;
  1910. int b = big_int_cmp(&i, &umax);
  1911. return !i.sign && (b <= 0);
  1912. }
  1913. case Basic_UntypedInteger:
  1914. return true;
  1915. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1916. }
  1917. } else if (is_type_float(type)) {
  1918. ExactValue v = exact_value_to_float(in_value);
  1919. if (v.kind != ExactValue_Float) {
  1920. return false;
  1921. }
  1922. if (out_value) *out_value = v;
  1923. switch (type->Basic.kind) {
  1924. case Basic_f16:
  1925. case Basic_f32:
  1926. case Basic_f64:
  1927. return true;
  1928. case Basic_f16le:
  1929. case Basic_f16be:
  1930. case Basic_f32le:
  1931. case Basic_f32be:
  1932. case Basic_f64le:
  1933. case Basic_f64be:
  1934. return true;
  1935. case Basic_UntypedFloat:
  1936. return true;
  1937. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1938. }
  1939. } else if (is_type_complex(type)) {
  1940. ExactValue v = exact_value_to_complex(in_value);
  1941. if (v.kind != ExactValue_Complex) {
  1942. return false;
  1943. }
  1944. switch (type->Basic.kind) {
  1945. case Basic_complex32:
  1946. case Basic_complex64:
  1947. case Basic_complex128: {
  1948. ExactValue real = exact_value_real(v);
  1949. ExactValue imag = exact_value_imag(v);
  1950. if (real.kind != ExactValue_Invalid &&
  1951. imag.kind != ExactValue_Invalid) {
  1952. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1953. return true;
  1954. }
  1955. break;
  1956. }
  1957. case Basic_UntypedComplex:
  1958. return true;
  1959. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1960. }
  1961. return false;
  1962. } else if (is_type_quaternion(type)) {
  1963. ExactValue v = exact_value_to_quaternion(in_value);
  1964. if (v.kind != ExactValue_Quaternion) {
  1965. return false;
  1966. }
  1967. switch (type->Basic.kind) {
  1968. case Basic_quaternion64:
  1969. case Basic_quaternion128:
  1970. case Basic_quaternion256: {
  1971. ExactValue real = exact_value_real(v);
  1972. ExactValue imag = exact_value_imag(v);
  1973. ExactValue jmag = exact_value_jmag(v);
  1974. ExactValue kmag = exact_value_kmag(v);
  1975. if (real.kind != ExactValue_Invalid &&
  1976. imag.kind != ExactValue_Invalid) {
  1977. 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));
  1978. return true;
  1979. }
  1980. break;
  1981. }
  1982. case Basic_UntypedComplex:
  1983. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  1984. return true;
  1985. case Basic_UntypedQuaternion:
  1986. return true;
  1987. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1988. }
  1989. return false;
  1990. } else if (is_type_pointer(type)) {
  1991. if (in_value.kind == ExactValue_Pointer) {
  1992. return true;
  1993. }
  1994. if (in_value.kind == ExactValue_Integer) {
  1995. return false;
  1996. // return true;
  1997. }
  1998. if (in_value.kind == ExactValue_String) {
  1999. return false;
  2000. }
  2001. if (out_value) *out_value = in_value;
  2002. } else if (is_type_bit_set(type)) {
  2003. if (in_value.kind == ExactValue_Integer) {
  2004. return true;
  2005. }
  2006. }
  2007. return false;
  2008. }
  2009. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  2010. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  2011. gbString b = type_to_string(type);
  2012. defer (gb_string_free(b));
  2013. if (is_type_enum(o->type)) {
  2014. if (check_is_castable_to(c, o, type)) {
  2015. gbString ot = type_to_string(o->type);
  2016. error_line("\tSuggestion: Try casting the '%s' expression to '%s'", ot, b);
  2017. gb_string_free(ot);
  2018. }
  2019. return true;
  2020. }
  2021. i64 sz = type_size_of(type);
  2022. i64 bit_size = 8*sz;
  2023. bool size_changed = false;
  2024. if (max_bit_size > 0) {
  2025. size_changed = (bit_size != max_bit_size);
  2026. bit_size = gb_min(bit_size, max_bit_size);
  2027. }
  2028. BigInt *bi = &o->value.value_integer;
  2029. if (is_type_unsigned(type)) {
  2030. BigInt one = big_int_make_u64(1);
  2031. BigInt max_size = big_int_make_u64(1);
  2032. BigInt bits = big_int_make_i64(bit_size);
  2033. big_int_shl_eq(&max_size, &bits);
  2034. big_int_sub_eq(&max_size, &one);
  2035. if (big_int_is_neg(bi)) {
  2036. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  2037. BigInt dst = {};
  2038. big_int_neg(&dst, bi);
  2039. if (big_int_cmp(&dst, &max_size) < 0) {
  2040. big_int_sub_eq(&dst, &one);
  2041. String dst_str = big_int_to_string(temporary_allocator(), &dst);
  2042. gbString t = type_to_string(type);
  2043. error_line("\tSuggestion: ~%s(%.*s)\n", t, LIT(dst_str));
  2044. gb_string_free(t);
  2045. }
  2046. } else {
  2047. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2048. if (size_changed) {
  2049. 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));
  2050. } else {
  2051. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2052. }
  2053. }
  2054. } else {
  2055. BigInt zero = big_int_make_u64(0);
  2056. BigInt one = big_int_make_u64(1);
  2057. BigInt max_size = big_int_make_u64(1);
  2058. BigInt bits = big_int_make_i64(bit_size - 1);
  2059. big_int_shl_eq(&max_size, &bits);
  2060. String max_size_str = {};
  2061. if (big_int_is_neg(bi)) {
  2062. big_int_neg(&max_size, &max_size);
  2063. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2064. } else {
  2065. big_int_sub_eq(&max_size, &one);
  2066. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2067. }
  2068. if (size_changed) {
  2069. 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));
  2070. } else {
  2071. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2072. }
  2073. }
  2074. return true;
  2075. }
  2076. return false;
  2077. }
  2078. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  2079. gbString a = expr_to_string(o->expr);
  2080. gbString b = type_to_string(type);
  2081. defer(
  2082. gb_string_free(b);
  2083. gb_string_free(a);
  2084. );
  2085. Type *src = base_type(o->type);
  2086. Type *dst = base_type(type);
  2087. if (is_type_array(src) && is_type_slice(dst)) {
  2088. Type *s = src->Array.elem;
  2089. Type *d = dst->Slice.elem;
  2090. if (are_types_identical(s, d)) {
  2091. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2092. }
  2093. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  2094. Type *s = src->DynamicArray.elem;
  2095. Type *d = dst->Slice.elem;
  2096. if (are_types_identical(s, d)) {
  2097. error_line("\tSuggestion: the dynamic array expression may be sliced with %s[:]\n", a);
  2098. }
  2099. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  2100. error_line("\tSuggestion: the expression may be directly casted to type %s\n", b);
  2101. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2102. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2103. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable, \n");
  2104. error_line("\t whereas slices in general are assumed to be mutable.\n");
  2105. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  2106. error_line("\tSuggestion: the expression may be casted to %s\n", b);
  2107. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  2108. return;
  2109. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  2110. gbString s = expr_to_string(c->type_hint_expr);
  2111. error_line("\tSuggestion: make sure that `%s` is attached to the compound literal directly\n", s);
  2112. gb_string_free(s);
  2113. } else if (is_type_pointer(type) &&
  2114. o->mode == Addressing_Variable &&
  2115. are_types_identical(type_deref(type), o->type)) {
  2116. gbString s = expr_to_string(o->expr);
  2117. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  2118. gb_string_free(s);
  2119. } else if (is_type_pointer(o->type) &&
  2120. are_types_identical(type_deref(o->type), type)) {
  2121. gbString s = expr_to_string(o->expr);
  2122. error_line("\tSuggestion: Did you mean `%s^`\n", s);
  2123. gb_string_free(s);
  2124. }
  2125. }
  2126. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  2127. gbString a = expr_to_string(o->expr);
  2128. gbString b = type_to_string(type);
  2129. defer(
  2130. gb_string_free(b);
  2131. gb_string_free(a);
  2132. );
  2133. Type *src = base_type(o->type);
  2134. Type *dst = base_type(type);
  2135. if (is_type_array(src) && is_type_slice(dst)) {
  2136. Type *s = src->Array.elem;
  2137. Type *d = dst->Slice.elem;
  2138. if (are_types_identical(s, d)) {
  2139. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2140. }
  2141. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  2142. if (is_type_uintptr(type)) {
  2143. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  2144. } else {
  2145. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  2146. i64 x = type_size_of(o->type);
  2147. i64 y = type_size_of(type);
  2148. if (x != y) {
  2149. 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);
  2150. }
  2151. }
  2152. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2153. if (is_type_uintptr(o->type)) {
  2154. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2155. } else {
  2156. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2157. }
  2158. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2159. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2160. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2161. return;
  2162. }
  2163. }
  2164. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2165. GB_ASSERT(o->mode == Addressing_Constant);
  2166. ExactValue out_value = o->value;
  2167. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2168. o->value = out_value;
  2169. return true;
  2170. } else {
  2171. o->value = out_value;
  2172. gbString a = expr_to_string(o->expr);
  2173. gbString b = type_to_string(type);
  2174. gbString c = type_to_string(o->type);
  2175. gbString s = exact_value_to_string(o->value);
  2176. defer(
  2177. gb_string_free(s);
  2178. gb_string_free(c);
  2179. gb_string_free(b);
  2180. gb_string_free(a);
  2181. o->mode = Addressing_Invalid;
  2182. );
  2183. ERROR_BLOCK();
  2184. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2185. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2186. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2187. } else {
  2188. i64 max_bit_size = 0;
  2189. if (ctx->bit_field_bit_size) {
  2190. max_bit_size = ctx->bit_field_bit_size;
  2191. }
  2192. if (are_types_identical(o->type, type)) {
  2193. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2194. } else {
  2195. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2196. }
  2197. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2198. }
  2199. } else {
  2200. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2201. check_assignment_error_suggestion(ctx, o, type);
  2202. }
  2203. return false;
  2204. }
  2205. }
  2206. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2207. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2208. if (o->expr->SelectorExpr.is_bit_field) {
  2209. return true;
  2210. }
  2211. }
  2212. if (o->mode == Addressing_OptionalOk) {
  2213. Ast *expr = unselector_expr(o->expr);
  2214. if (expr->kind != Ast_TypeAssertion) {
  2215. return true;
  2216. }
  2217. ast_node(ta, TypeAssertion, expr);
  2218. TypeAndValue tv = ta->expr->tav;
  2219. if (is_type_pointer(tv.type)) {
  2220. return false;
  2221. }
  2222. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2223. return false;
  2224. }
  2225. if (is_type_any(tv.type)) {
  2226. return false;
  2227. }
  2228. return true;
  2229. }
  2230. if (o->mode == Addressing_MapIndex) {
  2231. return false;
  2232. }
  2233. Ast *expr = unparen_expr(o->expr);
  2234. if (expr->kind == Ast_CompoundLit) {
  2235. return false;
  2236. }
  2237. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2238. }
  2239. gb_internal ExactValue exact_bit_set_all_set_mask(Type *type) {
  2240. type = base_type(type);
  2241. GB_ASSERT(type->kind == Type_BitSet);
  2242. i64 lower = type->BitSet.lower;
  2243. i64 upper = type->BitSet.upper;
  2244. Type *elem = type->BitSet.elem;
  2245. Type *underlying = type->BitSet.underlying;
  2246. bool is_backed = underlying != nullptr;
  2247. gb_unused(is_backed);
  2248. BigInt b_lower = {};
  2249. BigInt b_upper = {};
  2250. big_int_from_i64(&b_lower, lower);
  2251. big_int_from_i64(&b_upper, upper);
  2252. BigInt one = {};
  2253. big_int_from_u64(&one, 1);
  2254. BigInt mask = {};
  2255. if (elem == nullptr) {
  2256. big_int_from_i64(&mask, -1);
  2257. } else if (is_type_enum(elem)) {
  2258. Type *e = base_type(elem);
  2259. GB_ASSERT(e->kind == Type_Enum);
  2260. gb_unused(e);
  2261. if ((big_int_cmp(&e->Enum.min_value->value_integer, &b_lower) == 0 || is_backed) &&
  2262. big_int_cmp(&e->Enum.max_value->value_integer, &b_upper) == 0) {
  2263. i64 lower_base = is_backed ? gb_min(0, lower) : lower;
  2264. BigInt b_lower_base = {};
  2265. big_int_from_i64(&b_lower_base, lower_base);
  2266. for (Entity *f : e->Enum.fields) {
  2267. if (f->kind != Entity_Constant) {
  2268. continue;
  2269. }
  2270. if (f->Constant.value.kind != ExactValue_Integer) {
  2271. continue;
  2272. }
  2273. BigInt shift_amount = {};
  2274. big_int_sub(&shift_amount, &f->Constant.value.value_integer, &b_lower_base);
  2275. BigInt value = {};
  2276. big_int_shl(&value, &one, &shift_amount);
  2277. big_int_or(&mask, &mask, &value);
  2278. }
  2279. } else {
  2280. // TODO(bill): enum range based");
  2281. big_int_from_i64(&mask, -1);
  2282. }
  2283. } else {
  2284. i64 lower_base = lower;
  2285. for (i64 x = lower; x <= upper; x++) {
  2286. BigInt shift_amount = {};
  2287. big_int_from_i64(&shift_amount, x - lower_base);
  2288. BigInt value = {};
  2289. big_int_shl(&value, &one, &shift_amount);
  2290. big_int_or(&mask, &mask, &value);
  2291. }
  2292. }
  2293. ExactValue res = {};
  2294. res.kind = ExactValue_Integer;
  2295. res.value_integer = mask;
  2296. return res;
  2297. }
  2298. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2299. switch (op.kind) {
  2300. case Token_And: { // Pointer address
  2301. if (check_is_not_addressable(c, o)) {
  2302. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2303. ast_node(ue, UnaryExpr, node);
  2304. gbString str = expr_to_string(ue->expr);
  2305. defer (gb_string_free(str));
  2306. Entity *e = entity_of_node(ue->expr);
  2307. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2308. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2309. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2310. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2311. } else {
  2312. switch (o->mode) {
  2313. case Addressing_Constant:
  2314. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2315. break;
  2316. case Addressing_SwizzleValue:
  2317. case Addressing_SwizzleVariable:
  2318. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2319. break;
  2320. default:
  2321. {
  2322. ERROR_BLOCK();
  2323. error(op, "Cannot take the pointer address of '%s'", str);
  2324. if (e == nullptr) {
  2325. break;
  2326. }
  2327. if ((e->flags & EntityFlag_ForValue) != 0) {
  2328. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2329. if (parent_type != nullptr && is_type_string(parent_type)) {
  2330. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2331. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2332. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2333. } else {
  2334. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2335. }
  2336. if (parent_type != nullptr && is_type_map(parent_type)) {
  2337. error_line("\t Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2338. } else {
  2339. error_line("\t Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2340. }
  2341. }
  2342. if ((e->flags & EntityFlag_SwitchValue) != 0) {
  2343. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2344. error_line("\t Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2345. }
  2346. }
  2347. break;
  2348. }
  2349. }
  2350. }
  2351. o->mode = Addressing_Invalid;
  2352. return;
  2353. }
  2354. if (o->mode == Addressing_SoaVariable) {
  2355. ast_node(ue, UnaryExpr, node);
  2356. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2357. ast_node(ie, IndexExpr, ue->expr);
  2358. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2359. GB_ASSERT(is_type_soa_struct(soa_type));
  2360. o->type = alloc_type_soa_pointer(soa_type);
  2361. } else {
  2362. o->type = alloc_type_pointer(o->type);
  2363. }
  2364. } else {
  2365. o->type = alloc_type_pointer(o->type);
  2366. }
  2367. switch (o->mode) {
  2368. case Addressing_OptionalOk:
  2369. case Addressing_MapIndex:
  2370. o->mode = Addressing_OptionalOkPtr;
  2371. break;
  2372. default:
  2373. o->mode = Addressing_Value;
  2374. break;
  2375. }
  2376. return;
  2377. }
  2378. }
  2379. if (!check_unary_op(c, o, op)) {
  2380. o->mode = Addressing_Invalid;
  2381. return;
  2382. }
  2383. if (o->mode == Addressing_Constant) {
  2384. Type *type = base_type(o->type);
  2385. if (!is_type_constant_type(o->type)) {
  2386. if (is_type_array_like(o->type)) {
  2387. o->mode = Addressing_Value;
  2388. return;
  2389. }
  2390. gbString xt = type_to_string(o->type);
  2391. gbString err_str = expr_to_string(node);
  2392. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2393. gb_string_free(err_str);
  2394. gb_string_free(xt);
  2395. o->mode = Addressing_Invalid;
  2396. return;
  2397. }
  2398. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2399. gbString err_str = expr_to_string(node);
  2400. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2401. gb_string_free(err_str);
  2402. o->mode = Addressing_Invalid;
  2403. return;
  2404. }
  2405. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2406. gbString err_str = expr_to_string(node);
  2407. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2408. gb_string_free(err_str);
  2409. o->mode = Addressing_Invalid;
  2410. return;
  2411. }
  2412. i32 precision = 0;
  2413. if (is_type_typed(type)) {
  2414. precision = cast(i32)(8 * type_size_of(type));
  2415. }
  2416. bool is_unsigned = is_type_unsigned(type);
  2417. if (is_type_rune(type)) {
  2418. GB_ASSERT(!is_unsigned);
  2419. }
  2420. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2421. if (op.kind == Token_Xor && is_type_bit_set(type)) {
  2422. ExactValue mask = exact_bit_set_all_set_mask(type);
  2423. o->value = exact_binary_operator_value(Token_And, o->value, mask);
  2424. }
  2425. if (is_type_typed(type)) {
  2426. if (node != nullptr) {
  2427. o->expr = node;
  2428. }
  2429. check_is_expressible(c, o, type);
  2430. }
  2431. return;
  2432. }
  2433. o->mode = Addressing_Value;
  2434. }
  2435. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2436. if (t == nullptr) {
  2437. return;
  2438. }
  2439. t = base_type(t);
  2440. if (!is_type_comparable(t)) {
  2441. return;
  2442. }
  2443. switch (t->kind) {
  2444. case Type_Basic:
  2445. switch (t->Basic.kind) {
  2446. case Basic_complex32:
  2447. add_package_dependency(c, "runtime", "complex32_eq");
  2448. add_package_dependency(c, "runtime", "complex32_ne");
  2449. break;
  2450. case Basic_complex64:
  2451. add_package_dependency(c, "runtime", "complex64_eq");
  2452. add_package_dependency(c, "runtime", "complex64_ne");
  2453. break;
  2454. case Basic_complex128:
  2455. add_package_dependency(c, "runtime", "complex128_eq");
  2456. add_package_dependency(c, "runtime", "complex128_ne");
  2457. break;
  2458. case Basic_quaternion64:
  2459. add_package_dependency(c, "runtime", "quaternion64_eq");
  2460. add_package_dependency(c, "runtime", "quaternion64_ne");
  2461. break;
  2462. case Basic_quaternion128:
  2463. add_package_dependency(c, "runtime", "quaternion128_eq");
  2464. add_package_dependency(c, "runtime", "quaternion128_ne");
  2465. break;
  2466. case Basic_quaternion256:
  2467. add_package_dependency(c, "runtime", "quaternion256_eq");
  2468. add_package_dependency(c, "runtime", "quaternion256_ne");
  2469. break;
  2470. case Basic_cstring:
  2471. add_package_dependency(c, "runtime", "cstring_eq");
  2472. add_package_dependency(c, "runtime", "cstring_ne");
  2473. break;
  2474. case Basic_string:
  2475. add_package_dependency(c, "runtime", "string_eq");
  2476. add_package_dependency(c, "runtime", "string_ne");
  2477. break;
  2478. }
  2479. break;
  2480. case Type_Struct:
  2481. for (Entity *field : t->Struct.fields) {
  2482. add_comparison_procedures_for_fields(c, field->type);
  2483. }
  2484. break;
  2485. }
  2486. }
  2487. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2488. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2489. bool comp = are_types_identical(x->type, y->type);
  2490. switch (op) {
  2491. case Token_CmpEq: /* comp = comp; */ break;
  2492. case Token_NotEq: comp = !comp; break;
  2493. }
  2494. x->mode = Addressing_Constant;
  2495. x->type = t_untyped_bool;
  2496. x->value = exact_value_bool(comp);
  2497. return;
  2498. }
  2499. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2500. add_type_info_type(c, x->type);
  2501. add_type_info_type(c, y->type);
  2502. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2503. x->mode = Addressing_Value;
  2504. x->type = t_untyped_bool;
  2505. return;
  2506. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2507. add_type_info_type(c, x->type);
  2508. add_type_info_type(c, y->type);
  2509. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2510. x->mode = Addressing_Value;
  2511. x->type = t_untyped_bool;
  2512. return;
  2513. }
  2514. TEMPORARY_ALLOCATOR_GUARD();
  2515. gbString err_str = nullptr;
  2516. if (check_is_assignable_to(c, x, y->type) ||
  2517. check_is_assignable_to(c, y, x->type)) {
  2518. Type *err_type = x->type;
  2519. bool defined = false;
  2520. switch (op) {
  2521. case Token_CmpEq:
  2522. case Token_NotEq:
  2523. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2524. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2525. (is_operand_nil(*y) && type_has_nil(x->type));
  2526. break;
  2527. case Token_Lt:
  2528. case Token_Gt:
  2529. case Token_LtEq:
  2530. case Token_GtEq:
  2531. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2532. defined = true;
  2533. } else {
  2534. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2535. }
  2536. break;
  2537. }
  2538. if (!defined) {
  2539. gbString xs = type_to_string(x->type, temporary_allocator());
  2540. gbString ys = type_to_string(y->type, temporary_allocator());
  2541. err_str = gb_string_make(temporary_allocator(),
  2542. gb_bprintf("operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2543. );
  2544. } else {
  2545. Type *comparison_type = x->type;
  2546. if (x->type == err_type && is_operand_nil(*x)) {
  2547. comparison_type = y->type;
  2548. }
  2549. add_comparison_procedures_for_fields(c, comparison_type);
  2550. }
  2551. } else {
  2552. gbString xt, yt;
  2553. if (x->mode == Addressing_ProcGroup) {
  2554. xt = gb_string_make(temporary_allocator(), "procedure group");
  2555. } else {
  2556. xt = type_to_string(x->type);
  2557. }
  2558. if (y->mode == Addressing_ProcGroup) {
  2559. yt = gb_string_make(temporary_allocator(), "procedure group");
  2560. } else {
  2561. yt = type_to_string(y->type);
  2562. }
  2563. err_str = gb_string_make(temporary_allocator(), gb_bprintf("mismatched types '%s' and '%s'", xt, yt));
  2564. }
  2565. if (err_str != nullptr) {
  2566. error(node, "Cannot compare expression, %s", err_str);
  2567. x->type = t_untyped_bool;
  2568. } else {
  2569. if (x->mode == Addressing_Constant &&
  2570. y->mode == Addressing_Constant) {
  2571. if (is_type_constant_type(x->type)) {
  2572. if (is_type_bit_set(x->type)) {
  2573. switch (op) {
  2574. case Token_CmpEq:
  2575. case Token_NotEq:
  2576. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2577. break;
  2578. case Token_Lt:
  2579. case Token_LtEq:
  2580. {
  2581. ExactValue lhs = x->value;
  2582. ExactValue rhs = y->value;
  2583. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2584. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2585. if (op == Token_Lt) {
  2586. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2587. }
  2588. x->value = res;
  2589. break;
  2590. }
  2591. case Token_Gt:
  2592. case Token_GtEq:
  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, rhs));
  2598. if (op == Token_Gt) {
  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. }
  2605. } else {
  2606. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2607. }
  2608. } else {
  2609. x->mode = Addressing_Value;
  2610. }
  2611. } else {
  2612. x->mode = Addressing_Value;
  2613. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2614. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2615. i64 size = 0;
  2616. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2617. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2618. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2619. switch (op) {
  2620. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2621. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2622. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2623. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2624. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2625. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2626. }
  2627. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2628. switch (op) {
  2629. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2630. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2631. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2632. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2633. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2634. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2635. }
  2636. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2637. switch (op) {
  2638. case Token_CmpEq:
  2639. switch (8*size) {
  2640. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2641. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2642. }
  2643. break;
  2644. case Token_NotEq:
  2645. switch (8*size) {
  2646. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2647. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2648. }
  2649. break;
  2650. }
  2651. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2652. switch (op) {
  2653. case Token_CmpEq:
  2654. switch (8*size) {
  2655. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2656. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2657. }
  2658. break;
  2659. case Token_NotEq:
  2660. switch (8*size) {
  2661. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2662. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2663. }
  2664. break;
  2665. }
  2666. }
  2667. }
  2668. x->type = t_untyped_bool;
  2669. }
  2670. }
  2671. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2672. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2673. ast_node(be, BinaryExpr, node);
  2674. ExactValue x_val = {};
  2675. if (x->mode == Addressing_Constant) {
  2676. x_val = exact_value_to_integer(x->value);
  2677. }
  2678. bool x_is_untyped = is_type_untyped(x->type);
  2679. if (!(is_type_integer(x->type) || (x_is_untyped && x_val.kind == ExactValue_Integer))) {
  2680. gbString err_str = expr_to_string(x->expr);
  2681. error(node, "Shifted operand '%s' must be an integer", err_str);
  2682. gb_string_free(err_str);
  2683. x->mode = Addressing_Invalid;
  2684. return;
  2685. }
  2686. if (is_type_unsigned(y->type)) {
  2687. } else if (is_type_untyped(y->type)) {
  2688. convert_to_typed(c, y, t_untyped_integer);
  2689. if (y->mode == Addressing_Invalid) {
  2690. x->mode = Addressing_Invalid;
  2691. return;
  2692. }
  2693. } else {
  2694. gbString err_str = expr_to_string(y->expr);
  2695. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2696. gb_string_free(err_str);
  2697. x->mode = Addressing_Invalid;
  2698. return;
  2699. }
  2700. if (x->mode == Addressing_Constant) {
  2701. if (y->mode == Addressing_Constant) {
  2702. ExactValue y_val = exact_value_to_integer(y->value);
  2703. if (y_val.kind != ExactValue_Integer) {
  2704. gbString err_str = expr_to_string(y->expr);
  2705. error(node, "Shift amount '%s' must be an unsigned integer", err_str);
  2706. gb_string_free(err_str);
  2707. x->mode = Addressing_Invalid;
  2708. return;
  2709. }
  2710. BigInt max_shift = {};
  2711. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2712. if (big_int_cmp(&y_val.value_integer, &max_shift) > 0) {
  2713. gbString err_str = expr_to_string(y->expr);
  2714. error(node, "Shift amount too large: '%s'", err_str);
  2715. gb_string_free(err_str);
  2716. x->mode = Addressing_Invalid;
  2717. return;
  2718. }
  2719. if (!is_type_integer(x->type)) {
  2720. // NOTE(bill): It could be an untyped float but still representable
  2721. // as an integer
  2722. x->type = t_untyped_integer;
  2723. }
  2724. x->expr = node;
  2725. x->value = exact_value_shift(be->op.kind, x_val, y_val);
  2726. if (is_type_typed(x->type)) {
  2727. check_is_expressible(c, x, x->type);
  2728. }
  2729. return;
  2730. }
  2731. TokenPos pos = ast_token(x->expr).pos;
  2732. if (x_is_untyped) {
  2733. if (x->expr != nullptr) {
  2734. x->expr->tav.is_lhs = true;
  2735. }
  2736. x->mode = Addressing_Value;
  2737. if (type_hint) {
  2738. if (is_type_integer(type_hint)) {
  2739. convert_to_typed(c, x, type_hint);
  2740. } else {
  2741. gbString x_str = expr_to_string(x->expr);
  2742. gbString to_type = type_to_string(type_hint);
  2743. error(node, "Conversion of shifted operand '%s' to '%s' is not allowed", x_str, to_type);
  2744. gb_string_free(x_str);
  2745. gb_string_free(to_type);
  2746. x->mode = Addressing_Invalid;
  2747. }
  2748. } else if (!is_type_integer(x->type)) {
  2749. gbString x_str = expr_to_string(x->expr);
  2750. error(node, "Non-integer shifted operand '%s' is not allowed", x_str);
  2751. gb_string_free(x_str);
  2752. x->mode = Addressing_Invalid;
  2753. }
  2754. // x->value = x_val;
  2755. return;
  2756. }
  2757. }
  2758. if (y->mode == Addressing_Constant && big_int_is_neg(&y->value.value_integer)) {
  2759. gbString err_str = expr_to_string(y->expr);
  2760. error(node, "Shift amount cannot be negative: '%s'", err_str);
  2761. gb_string_free(err_str);
  2762. }
  2763. if (!is_type_integer(x->type)) {
  2764. gbString err_str = expr_to_string(x->expr);
  2765. error(node, "Shift operand '%s' must be an integer", err_str);
  2766. gb_string_free(err_str);
  2767. x->mode = Addressing_Invalid;
  2768. return;
  2769. }
  2770. if (is_type_untyped(y->type)) {
  2771. convert_to_typed(c, y, t_uint);
  2772. }
  2773. x->mode = Addressing_Value;
  2774. }
  2775. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2776. if (check_is_assignable_to(c, operand, y)) {
  2777. return true;
  2778. }
  2779. bool is_constant = operand->mode == Addressing_Constant;
  2780. Type *x = operand->type;
  2781. Type *src = core_type(x);
  2782. Type *dst = core_type(y);
  2783. if (are_types_identical(src, dst)) {
  2784. return true;
  2785. }
  2786. // if (is_type_tuple(src)) {
  2787. // Ast *expr = unparen_expr(operand->expr);
  2788. // if (expr && expr->kind == Ast_CallExpr) {
  2789. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2790. // ast_node(ce, CallExpr, expr);
  2791. // Type *pt = base_type(type_of_expr(ce->proc));
  2792. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2793. // if (pt->Proc.result_count > 0) {
  2794. // Operand op = *operand;
  2795. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2796. // bool ok = check_is_castable_to(c, &op, y);
  2797. // if (ok) {
  2798. // ce->optional_ok_one = true;
  2799. // }
  2800. // return ok;
  2801. // }
  2802. // }
  2803. // }
  2804. // }
  2805. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2806. if (is_type_u8_array(dst)) {
  2807. String s = operand->value.value_string;
  2808. return s.len == dst->Array.count;
  2809. }
  2810. if (is_type_rune_array(dst)) {
  2811. String s = operand->value.value_string;
  2812. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2813. }
  2814. }
  2815. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2816. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2817. return dst->Array.count == src->Array.count;
  2818. }
  2819. }
  2820. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2821. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2822. }
  2823. // Cast between booleans and integers
  2824. if (is_type_boolean(src) || is_type_integer(src)) {
  2825. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2826. return true;
  2827. }
  2828. }
  2829. // Cast between numbers
  2830. if (is_type_integer(src) || is_type_float(src)) {
  2831. if (is_type_integer(dst) || is_type_float(dst)) {
  2832. return true;
  2833. }
  2834. }
  2835. if (is_type_bit_field(src)) {
  2836. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2837. }
  2838. if (is_type_bit_field(dst)) {
  2839. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2840. }
  2841. if (is_type_integer(src) && is_type_rune(dst)) {
  2842. return true;
  2843. }
  2844. if (is_type_rune(src) && is_type_integer(dst)) {
  2845. return true;
  2846. }
  2847. if (is_type_complex(src) && is_type_complex(dst)) {
  2848. return true;
  2849. }
  2850. if (is_type_float(src) && is_type_complex(dst)) {
  2851. return true;
  2852. }
  2853. if (is_type_float(src) && is_type_quaternion(dst)) {
  2854. return true;
  2855. }
  2856. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2857. return true;
  2858. }
  2859. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2860. return true;
  2861. }
  2862. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2863. GB_ASSERT(src->kind == Type_Matrix);
  2864. GB_ASSERT(dst->kind == Type_Matrix);
  2865. Operand op = *operand;
  2866. op.type = src->Matrix.elem;
  2867. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2868. return false;
  2869. }
  2870. if (src->Matrix.row_count != src->Matrix.column_count) {
  2871. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2872. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2873. return src_count == dst_count;
  2874. }
  2875. return is_matrix_square(dst) && is_matrix_square(src);
  2876. }
  2877. // Cast between pointers
  2878. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2879. return true;
  2880. }
  2881. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2882. return true;
  2883. }
  2884. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2885. return true;
  2886. }
  2887. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2888. return true;
  2889. }
  2890. // uintptr <-> pointer
  2891. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2892. return true;
  2893. }
  2894. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2895. return true;
  2896. }
  2897. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2898. return true;
  2899. }
  2900. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2901. return true;
  2902. }
  2903. // []byte/[]u8 <-> string (not cstring)
  2904. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2905. return true;
  2906. }
  2907. // cstring -> string
  2908. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2909. if (operand->mode != Addressing_Constant) {
  2910. add_package_dependency(c, "runtime", "cstring_to_string");
  2911. }
  2912. return true;
  2913. }
  2914. // cstring -> ^u8
  2915. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2916. return !is_constant;
  2917. }
  2918. // cstring -> [^]u8
  2919. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2920. return !is_constant;
  2921. }
  2922. // cstring -> rawptr
  2923. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2924. return !is_constant;
  2925. }
  2926. // ^u8 -> cstring
  2927. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2928. return !is_constant;
  2929. }
  2930. // [^]u8 -> cstring
  2931. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2932. return !is_constant;
  2933. }
  2934. // rawptr -> cstring
  2935. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2936. return !is_constant;
  2937. }
  2938. // proc <-> proc
  2939. if (is_type_proc(src) && is_type_proc(dst)) {
  2940. if (is_type_polymorphic(dst)) {
  2941. if (is_type_polymorphic(src) &&
  2942. operand->mode == Addressing_Variable) {
  2943. return true;
  2944. }
  2945. return false;
  2946. }
  2947. return true;
  2948. }
  2949. // proc -> rawptr
  2950. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2951. return true;
  2952. }
  2953. // rawptr -> proc
  2954. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2955. return true;
  2956. }
  2957. if (is_type_array(dst)) {
  2958. Type *elem = base_array_type(dst);
  2959. if (check_is_castable_to(c, operand, elem)) {
  2960. return true;
  2961. }
  2962. }
  2963. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2964. if (src->SimdVector.count != dst->SimdVector.count) {
  2965. return false;
  2966. }
  2967. Type *elem_src = base_array_type(src);
  2968. Type *elem_dst = base_array_type(dst);
  2969. Operand x = {};
  2970. x.type = elem_src;
  2971. x.mode = Addressing_Value;
  2972. return check_is_castable_to(c, &x, elem_dst);
  2973. }
  2974. if (is_type_simd_vector(dst)) {
  2975. Type *elem = base_array_type(dst);
  2976. if (check_is_castable_to(c, operand, elem)) {
  2977. return true;
  2978. }
  2979. }
  2980. return false;
  2981. }
  2982. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  2983. bool is_const_expr = x->mode == Addressing_Constant;
  2984. Type *bt = base_type(type);
  2985. if (is_const_expr && is_type_constant_type(bt)) {
  2986. if (core_type(bt)->kind == Type_Basic) {
  2987. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  2988. return true;
  2989. } else if (check_is_castable_to(c, x, type)) {
  2990. if (is_type_pointer(type)) {
  2991. return true;
  2992. }
  2993. }
  2994. } else if (check_is_castable_to(c, x, type)) {
  2995. x->value = {};
  2996. x->mode = Addressing_Value;
  2997. return true;
  2998. }
  2999. } else if (check_is_castable_to(c, x, type)) {
  3000. if (x->mode != Addressing_Constant) {
  3001. x->mode = Addressing_Value;
  3002. } else if (is_type_slice(type) && is_type_string(x->type)) {
  3003. x->mode = Addressing_Value;
  3004. } else if (is_type_union(type)) {
  3005. x->mode = Addressing_Value;
  3006. }
  3007. if (x->mode == Addressing_Value) {
  3008. x->value = {};
  3009. }
  3010. return true;
  3011. }
  3012. return false;
  3013. }
  3014. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type, bool forbid_identical = false) {
  3015. if (!is_operand_value(*x)) {
  3016. error(x->expr, "Only values can be casted");
  3017. x->mode = Addressing_Invalid;
  3018. return;
  3019. }
  3020. bool is_const_expr = x->mode == Addressing_Constant;
  3021. bool can_convert = check_cast_internal(c, x, type);
  3022. if (!can_convert) {
  3023. TEMPORARY_ALLOCATOR_GUARD();
  3024. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  3025. gbString to_type = type_to_string(type, temporary_allocator());
  3026. gbString from_type = type_to_string(x->type, temporary_allocator());
  3027. x->mode = Addressing_Invalid;
  3028. ERROR_BLOCK();
  3029. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  3030. if (is_const_expr) {
  3031. gbString val_str = exact_value_to_string(x->value);
  3032. if (is_type_float(x->type) && is_type_integer(type)) {
  3033. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  3034. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3035. x->mode = Addressing_Constant;
  3036. x->type = type;
  3037. } else {
  3038. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  3039. if (is_type_numeric(type)) {
  3040. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3041. x->mode = Addressing_Constant;
  3042. x->type = type;
  3043. }
  3044. }
  3045. gb_string_free(val_str);
  3046. }
  3047. check_cast_error_suggestion(c, x, type);
  3048. return;
  3049. }
  3050. if (is_type_untyped(x->type)) {
  3051. Type *final_type = type;
  3052. if (is_const_expr && !is_type_constant_type(type)) {
  3053. if (is_type_union(type)) {
  3054. convert_to_typed(c, x, type);
  3055. }
  3056. final_type = default_type(x->type);
  3057. }
  3058. update_untyped_expr_type(c, x->expr, final_type, true);
  3059. } else {
  3060. Type *src = core_type(x->type);
  3061. Type *dst = core_type(type);
  3062. if (src != dst) {
  3063. bool const REQUIRE = true;
  3064. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  3065. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  3066. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  3067. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  3068. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  3069. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  3070. } else if (src == t_f16 && is_type_float(dst)) {
  3071. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  3072. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  3073. } else if (is_type_float(dst) && dst == t_f16) {
  3074. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  3075. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  3076. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  3077. }
  3078. }
  3079. // If we check polymorphic procedures, we risk erring on
  3080. // identical casts that cannot be foreseen or otherwise
  3081. // forbidden, so just skip them.
  3082. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3083. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig))) {
  3084. Type *src_exact = x->type;
  3085. Type *dst_exact = type;
  3086. if (src_exact != nullptr &&
  3087. dst_exact != nullptr &&
  3088. are_types_identical(src_exact, dst_exact)
  3089. ) {
  3090. gbString oper_str = expr_to_string(x->expr);
  3091. gbString to_type = type_to_string(dst_exact);
  3092. error(x->expr, "Unneeded cast of '%s' to identical type '%s'", oper_str, to_type);
  3093. gb_string_free(oper_str);
  3094. gb_string_free(to_type);
  3095. }
  3096. }
  3097. }
  3098. x->type = type;
  3099. }
  3100. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t, bool forbid_identical = false) {
  3101. if (!is_operand_value(*o)) {
  3102. error(o->expr, "'transmute' can only be applied to values");
  3103. o->mode = Addressing_Invalid;
  3104. return false;
  3105. }
  3106. Operand src = *o;
  3107. Type *src_t = o->type;
  3108. Type *dst_t = t;
  3109. Type *src_bt = base_type(src_t);
  3110. Type *dst_bt = base_type(dst_t);
  3111. if (is_type_untyped(src_t)) {
  3112. gbString expr_str = expr_to_string(o->expr);
  3113. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  3114. gb_string_free(expr_str);
  3115. o->mode = Addressing_Invalid;
  3116. o->expr = node;
  3117. return false;
  3118. }
  3119. if (dst_bt == nullptr || dst_bt == t_invalid) {
  3120. GB_ASSERT(global_error_collector.count != 0);
  3121. o->mode = Addressing_Invalid;
  3122. o->expr = node;
  3123. return false;
  3124. }
  3125. if (src_bt == nullptr || src_bt == t_invalid) {
  3126. // NOTE(bill): this should be an error
  3127. GB_ASSERT(global_error_collector.count != 0);
  3128. o->mode = Addressing_Value;
  3129. o->expr = node;
  3130. o->type = dst_t;
  3131. return true;
  3132. }
  3133. i64 srcz = type_size_of(src_t);
  3134. i64 dstz = type_size_of(dst_t);
  3135. if (srcz != dstz) {
  3136. gbString expr_str = expr_to_string(o->expr);
  3137. gbString type_str = type_to_string(dst_t);
  3138. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  3139. gb_string_free(type_str);
  3140. gb_string_free(expr_str);
  3141. o->mode = Addressing_Invalid;
  3142. o->expr = node;
  3143. return false;
  3144. }
  3145. o->expr = node;
  3146. o->type = dst_t;
  3147. if (o->mode == Addressing_Constant) {
  3148. if (are_types_identical(src_bt, dst_bt)) {
  3149. return true;
  3150. }
  3151. if ((is_type_integer(src_t) && is_type_integer(dst_t)) ||
  3152. is_type_integer(src_t) && is_type_bit_set(dst_t)) {
  3153. if (types_have_same_internal_endian(src_t, dst_t)) {
  3154. ExactValue src_v = exact_value_to_integer(o->value);
  3155. GB_ASSERT(src_v.kind == ExactValue_Integer || src_v.kind == ExactValue_Invalid);
  3156. BigInt v = src_v.value_integer;
  3157. BigInt smax = {};
  3158. BigInt umax = {};
  3159. big_int_from_u64(&smax, 0);
  3160. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  3161. big_int_from_u64(&umax, 1);
  3162. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  3163. big_int_shl_eq(&umax, &sz_in_bits);
  3164. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  3165. if (big_int_cmp(&v, &smax) >= 0) {
  3166. big_int_sub_eq(&v, &umax);
  3167. }
  3168. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  3169. if (big_int_is_neg(&v)) {
  3170. big_int_add_eq(&v, &umax);
  3171. }
  3172. }
  3173. o->value.kind = ExactValue_Integer;
  3174. o->value.value_integer = v;
  3175. return true;
  3176. }
  3177. }
  3178. } else {
  3179. // If we check polymorphic procedures, we risk erring on
  3180. // identical casts that cannot be foreseen or otherwise
  3181. // forbidden, so just skip them.
  3182. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3183. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig)) &&
  3184. check_is_castable_to(c, &src, dst_t)) {
  3185. if (are_types_identical(src_t, dst_t)) {
  3186. gbString oper_str = expr_to_string(o->expr);
  3187. gbString to_type = type_to_string(dst_t);
  3188. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3189. gb_string_free(oper_str);
  3190. gb_string_free(to_type);
  3191. } else if (is_type_internally_pointer_like(src_t) &&
  3192. is_type_internally_pointer_like(dst_t)) {
  3193. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since the types are pointer-like");
  3194. } else if (are_types_identical(src_bt, dst_bt)) {
  3195. gbString oper_str = expr_to_string(o->expr);
  3196. gbString to_type = type_to_string(dst_t);
  3197. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3198. gb_string_free(oper_str);
  3199. gb_string_free(to_type);
  3200. } else if (is_type_integer(src_t) && is_type_integer(dst_t) &&
  3201. types_have_same_internal_endian(src_t, dst_t) &&
  3202. type_endian_kind_of(src_t) == type_endian_kind_of(dst_t)) {
  3203. gbString oper_type = type_to_string(src_t);
  3204. gbString to_type = type_to_string(dst_t);
  3205. 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);
  3206. gb_string_free(to_type);
  3207. gb_string_free(oper_type);
  3208. }
  3209. }
  3210. }
  3211. o->mode = Addressing_Value;
  3212. o->value = {};
  3213. return true;
  3214. }
  3215. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  3216. if (is_type_array_like(x->type) || is_type_array_like(y->type)) {
  3217. if (op.kind == Token_CmpAnd || op.kind == Token_CmpOr) {
  3218. error(op, "Array programming is not allowed with the operator '%.*s'", LIT(op.string));
  3219. }
  3220. }
  3221. if (is_type_array(x->type) && !is_type_array(y->type)) {
  3222. if (check_is_assignable_to(c, y, x->type)) {
  3223. if (check_binary_op(c, x, op)) {
  3224. return true;
  3225. }
  3226. }
  3227. }
  3228. if (is_type_simd_vector(x->type) && !is_type_simd_vector(y->type)) {
  3229. if (check_is_assignable_to(c, y, x->type)) {
  3230. if (check_binary_op(c, x, op)) {
  3231. return true;
  3232. }
  3233. }
  3234. }
  3235. return false;
  3236. }
  3237. gb_internal bool is_ise_expr(Ast *node) {
  3238. node = unparen_expr(node);
  3239. return node->kind == Ast_ImplicitSelectorExpr;
  3240. }
  3241. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  3242. if (use_lhs_as_type_hint) { // RHS in this case
  3243. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  3244. }
  3245. return false;
  3246. }
  3247. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  3248. Type *xt = base_type(matrix);
  3249. if (type_hint != nullptr) {
  3250. Type *th = base_type(type_hint);
  3251. if (are_types_identical(th, xt)) {
  3252. return type_hint;
  3253. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  3254. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  3255. // ignore
  3256. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  3257. xt->Matrix.column_count == th->Matrix.column_count) {
  3258. return type_hint;
  3259. }
  3260. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  3261. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  3262. // ignore
  3263. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  3264. return type_hint;
  3265. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3266. return type_hint;
  3267. }
  3268. }
  3269. }
  3270. return matrix;
  3271. }
  3272. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3273. if (!check_binary_op(c, x, op)) {
  3274. x->mode = Addressing_Invalid;
  3275. return;
  3276. }
  3277. Type *xt = base_type(x->type);
  3278. Type *yt = base_type(y->type);
  3279. if (is_type_matrix(x->type)) {
  3280. GB_ASSERT(xt->kind == Type_Matrix);
  3281. if (op.kind == Token_Mul) {
  3282. if (yt->kind == Type_Matrix) {
  3283. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3284. goto matrix_error;
  3285. }
  3286. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3287. goto matrix_error;
  3288. }
  3289. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3290. goto matrix_error;
  3291. }
  3292. x->mode = Addressing_Value;
  3293. if (are_types_identical(xt, yt)) {
  3294. if (are_types_identical(x->type, y->type)) {
  3295. return;
  3296. }
  3297. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3298. // prefer the named type
  3299. x->type = y->type;
  3300. }
  3301. } else {
  3302. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3303. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3304. }
  3305. goto matrix_success;
  3306. } else if (yt->kind == Type_Array) {
  3307. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3308. goto matrix_error;
  3309. }
  3310. if (xt->Matrix.column_count != yt->Array.count) {
  3311. goto matrix_error;
  3312. }
  3313. // Treat arrays as column vectors
  3314. x->mode = Addressing_Value;
  3315. if (xt->Matrix.row_count == yt->Array.count) {
  3316. x->type = y->type;
  3317. } else {
  3318. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3319. }
  3320. goto matrix_success;
  3321. }
  3322. }
  3323. if (!are_types_identical(xt, yt)) {
  3324. goto matrix_error;
  3325. }
  3326. x->mode = Addressing_Value;
  3327. x->type = xt;
  3328. goto matrix_success;
  3329. } else {
  3330. GB_ASSERT(!is_type_matrix(xt));
  3331. GB_ASSERT(is_type_matrix(yt));
  3332. if (op.kind == Token_Mul) {
  3333. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3334. if (xt->kind == Type_Array) {
  3335. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3336. goto matrix_error;
  3337. }
  3338. if (xt->Array.count != yt->Matrix.row_count) {
  3339. goto matrix_error;
  3340. }
  3341. // Treat arrays as row vectors
  3342. x->mode = Addressing_Value;
  3343. if (yt->Matrix.column_count == xt->Array.count) {
  3344. x->type = x->type;
  3345. } else {
  3346. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3347. }
  3348. goto matrix_success;
  3349. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3350. x->type = check_matrix_type_hint(y->type, type_hint);
  3351. return;
  3352. }
  3353. }
  3354. if (!are_types_identical(xt, yt)) {
  3355. goto matrix_error;
  3356. }
  3357. x->mode = Addressing_Value;
  3358. x->type = xt;
  3359. goto matrix_success;
  3360. }
  3361. matrix_success:
  3362. x->type = check_matrix_type_hint(x->type, type_hint);
  3363. return;
  3364. matrix_error:
  3365. gbString xts = type_to_string(x->type);
  3366. gbString yts = type_to_string(y->type);
  3367. gbString expr_str = expr_to_string(x->expr);
  3368. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3369. gb_string_free(expr_str);
  3370. gb_string_free(yts);
  3371. gb_string_free(xts);
  3372. x->type = t_invalid;
  3373. x->mode = Addressing_Invalid;
  3374. return;
  3375. }
  3376. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3377. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3378. Operand y_ = {}, *y = &y_;
  3379. ast_node(be, BinaryExpr, node);
  3380. defer({
  3381. node->viral_state_flags |= be->left->viral_state_flags;
  3382. node->viral_state_flags |= be->right->viral_state_flags;
  3383. });
  3384. Token op = be->op;
  3385. switch (op.kind) {
  3386. case Token_CmpEq:
  3387. case Token_NotEq: {
  3388. // NOTE(bill): Allow comparisons between types
  3389. if (is_ise_expr(be->left)) {
  3390. // Evalute the right before the left for an '.X' expression
  3391. check_expr_or_type(c, y, be->right, nullptr /* ignore type hint */);
  3392. check_expr_or_type(c, x, be->left, y->type);
  3393. } else {
  3394. check_expr_or_type(c, x, be->left, nullptr /* ignore type hint */);
  3395. check_expr_or_type(c, y, be->right, x->type);
  3396. }
  3397. bool xt = x->mode == Addressing_Type;
  3398. bool yt = y->mode == Addressing_Type;
  3399. // If only one is a type, this is an error
  3400. if (xt ^ yt) {
  3401. GB_ASSERT(xt != yt);
  3402. if (xt) {
  3403. if (!is_type_typeid(y->type)) {
  3404. error_operand_not_expression(x);
  3405. }
  3406. }
  3407. if (yt) {
  3408. if (!is_type_typeid(x->type)) {
  3409. error_operand_not_expression(y);
  3410. }
  3411. }
  3412. }
  3413. break;
  3414. }
  3415. case Token_in:
  3416. case Token_not_in:
  3417. {
  3418. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3419. check_expr(c, y, be->right);
  3420. Type *rhs_type = type_deref(y->type);
  3421. if (rhs_type == nullptr) {
  3422. error(y->expr, "Cannot use '%.*s' on an expression with no value", LIT(op.string));
  3423. x->mode = Addressing_Invalid;
  3424. x->expr = node;
  3425. return;
  3426. }
  3427. if (is_type_bit_set(rhs_type)) {
  3428. Type *elem = base_type(rhs_type)->BitSet.elem;
  3429. check_expr_with_type_hint(c, x, be->left, elem);
  3430. } else if (is_type_map(rhs_type)) {
  3431. Type *key = base_type(rhs_type)->Map.key;
  3432. check_expr_with_type_hint(c, x, be->left, key);
  3433. } else {
  3434. check_expr(c, x, be->left);
  3435. }
  3436. if (x->mode == Addressing_Invalid) {
  3437. return;
  3438. }
  3439. if (y->mode == Addressing_Invalid) {
  3440. x->mode = Addressing_Invalid;
  3441. x->expr = y->expr;
  3442. return;
  3443. }
  3444. if (is_type_map(rhs_type)) {
  3445. Type *yt = base_type(rhs_type);
  3446. if (op.kind == Token_in) {
  3447. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3448. } else {
  3449. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3450. }
  3451. add_map_get_dependencies(c);
  3452. } else if (is_type_bit_set(rhs_type)) {
  3453. Type *yt = base_type(rhs_type);
  3454. if (op.kind == Token_in) {
  3455. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3456. } else {
  3457. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3458. }
  3459. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3460. ExactValue k = exact_value_to_integer(x->value);
  3461. ExactValue v = exact_value_to_integer(y->value);
  3462. GB_ASSERT(k.kind == ExactValue_Integer);
  3463. GB_ASSERT(v.kind == ExactValue_Integer);
  3464. i64 key = big_int_to_i64(&k.value_integer);
  3465. i64 lower = yt->BitSet.lower;
  3466. i64 upper = yt->BitSet.upper;
  3467. if (lower <= key && key <= upper) {
  3468. i64 bit = 1ll<<key;
  3469. i64 bits = big_int_to_i64(&v.value_integer);
  3470. x->mode = Addressing_Constant;
  3471. x->type = t_untyped_bool;
  3472. if (op.kind == Token_in) {
  3473. x->value = exact_value_bool((bit & bits) != 0);
  3474. } else {
  3475. x->value = exact_value_bool((bit & bits) == 0);
  3476. }
  3477. x->expr = node;
  3478. return;
  3479. } else {
  3480. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3481. x->mode = Addressing_Invalid;
  3482. }
  3483. }
  3484. } else {
  3485. gbString t = type_to_string(y->type);
  3486. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3487. gb_string_free(t);
  3488. x->expr = node;
  3489. x->mode = Addressing_Invalid;
  3490. return;
  3491. }
  3492. if (x->mode != Addressing_Invalid) {
  3493. x->mode = Addressing_Value;
  3494. x->type = t_untyped_bool;
  3495. }
  3496. x->expr = node;
  3497. return;
  3498. }
  3499. default:
  3500. if (is_ise_expr(be->left)) {
  3501. // Evalute the right before the left for an '.X' expression
  3502. check_expr_or_type(c, y, be->right, type_hint);
  3503. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3504. check_expr_or_type(c, x, be->left, y->type);
  3505. } else {
  3506. check_expr_with_type_hint(c, x, be->left, type_hint);
  3507. }
  3508. } else {
  3509. check_expr_with_type_hint(c, x, be->left, type_hint);
  3510. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3511. check_expr_with_type_hint(c, y, be->right, x->type);
  3512. } else {
  3513. check_expr_with_type_hint(c, y, be->right, type_hint);
  3514. }
  3515. }
  3516. break;
  3517. }
  3518. if (x->mode == Addressing_Invalid) {
  3519. return;
  3520. }
  3521. if (y->mode == Addressing_Invalid) {
  3522. x->mode = Addressing_Invalid;
  3523. x->expr = y->expr;
  3524. return;
  3525. }
  3526. if (x->mode == Addressing_Builtin) {
  3527. x->mode = Addressing_Invalid;
  3528. error(x->expr, "built-in expression in binary expression");
  3529. return;
  3530. }
  3531. if (y->mode == Addressing_Builtin) {
  3532. x->mode = Addressing_Invalid;
  3533. error(y->expr, "built-in expression in binary expression");
  3534. return;
  3535. }
  3536. if (x->mode == Addressing_ProcGroup) {
  3537. x->mode = Addressing_Invalid;
  3538. if (x->proc_group != nullptr) {
  3539. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3540. } else {
  3541. error(x->expr, "procedure group used in binary expression");
  3542. }
  3543. return;
  3544. }
  3545. if (y->mode == Addressing_ProcGroup) {
  3546. x->mode = Addressing_Invalid;
  3547. if (x->proc_group != nullptr) {
  3548. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3549. } else {
  3550. error(y->expr, "procedure group used in binary expression");
  3551. }
  3552. return;
  3553. }
  3554. bool REQUIRE = true;
  3555. Type *bt = base_type(x->type);
  3556. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3557. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3558. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3559. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3560. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3561. }
  3562. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3563. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3564. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3565. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3566. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3567. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3568. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3569. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3570. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3571. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3572. }
  3573. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3574. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3575. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3576. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3577. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3578. case Basic_u128:
  3579. case Basic_i128:
  3580. if (is_arch_wasm()) {
  3581. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3582. }
  3583. break;
  3584. }
  3585. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  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", "__ashlti3", REQUIRE);
  3591. }
  3592. break;
  3593. }
  3594. } else if (op.kind == Token_Shr || op.kind == Token_ShrEq) {
  3595. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3596. case Basic_u128:
  3597. case Basic_i128:
  3598. if (is_arch_wasm()) {
  3599. add_package_dependency(c, "runtime", "__lshrti3", REQUIRE);
  3600. }
  3601. break;
  3602. }
  3603. }
  3604. if (token_is_shift(op.kind)) {
  3605. check_shift(c, x, y, node, type_hint);
  3606. return;
  3607. }
  3608. switch (op.kind) {
  3609. case Token_Quo:
  3610. case Token_Mod:
  3611. case Token_ModMod:
  3612. case Token_QuoEq:
  3613. case Token_ModEq:
  3614. case Token_ModModEq:
  3615. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3616. is_type_float(x->type) && is_type_untyped(x->type)) {
  3617. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3618. gbString t = type_to_string(y->type);
  3619. if (x->value.kind != ExactValue_Invalid) {
  3620. gbString s = exact_value_to_string(x->value);
  3621. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3622. gb_string_free(s);
  3623. } else {
  3624. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3625. }
  3626. gb_string_free(t);
  3627. }
  3628. break;
  3629. }
  3630. convert_to_typed(c, x, y->type);
  3631. if (x->mode == Addressing_Invalid) {
  3632. return;
  3633. }
  3634. convert_to_typed(c, y, x->type);
  3635. if (y->mode == Addressing_Invalid) {
  3636. x->mode = Addressing_Invalid;
  3637. return;
  3638. }
  3639. if (token_is_comparison(op.kind)) {
  3640. check_comparison(c, node, x, y, op.kind);
  3641. return;
  3642. }
  3643. if (check_binary_array_expr(c, op, x, y)) {
  3644. x->mode = Addressing_Value;
  3645. x->type = x->type;
  3646. return;
  3647. }
  3648. if (check_binary_array_expr(c, op, y, x)) {
  3649. x->mode = Addressing_Value;
  3650. x->type = y->type;
  3651. return;
  3652. }
  3653. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3654. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3655. x->expr = node;
  3656. return;
  3657. }
  3658. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3659. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3660. // NOTE(bill, 2022-06-26)
  3661. // Allow any boolean types within `&&` and `||`
  3662. // This is an exception to all other binary expressions since the result
  3663. // of a comparison will always be an untyped boolean, and allowing
  3664. // any boolean between these two simplifies a lot of expressions
  3665. } else if (!are_types_identical(x->type, y->type)) {
  3666. if (x->type != t_invalid &&
  3667. y->type != t_invalid) {
  3668. gbString xt = type_to_string(x->type);
  3669. gbString yt = type_to_string(y->type);
  3670. gbString expr_str = expr_to_string(node);
  3671. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3672. gb_string_free(expr_str);
  3673. gb_string_free(yt);
  3674. gb_string_free(xt);
  3675. }
  3676. x->mode = Addressing_Invalid;
  3677. return;
  3678. }
  3679. if (!check_binary_op(c, x, op)) {
  3680. x->mode = Addressing_Invalid;
  3681. return;
  3682. }
  3683. switch (op.kind) {
  3684. case Token_Quo:
  3685. case Token_Mod:
  3686. case Token_ModMod:
  3687. case Token_QuoEq:
  3688. case Token_ModEq:
  3689. case Token_ModModEq:
  3690. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3691. y->mode == Addressing_Constant) {
  3692. bool fail = false;
  3693. switch (y->value.kind) {
  3694. case ExactValue_Integer:
  3695. if (big_int_is_zero(&y->value.value_integer)) {
  3696. fail = true;
  3697. }
  3698. break;
  3699. case ExactValue_Float:
  3700. if (y->value.value_float == 0.0) {
  3701. fail = true;
  3702. }
  3703. break;
  3704. }
  3705. if (fail) {
  3706. error(y->expr, "Division by zero not allowed");
  3707. x->mode = Addressing_Invalid;
  3708. return;
  3709. }
  3710. }
  3711. break;
  3712. case Token_CmpAnd:
  3713. case Token_CmpOr:
  3714. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3715. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3716. }
  3717. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3718. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3719. }
  3720. break;
  3721. }
  3722. if (x->mode == Addressing_Constant &&
  3723. y->mode == Addressing_Constant) {
  3724. ExactValue a = x->value;
  3725. ExactValue b = y->value;
  3726. if (!is_type_constant_type(x->type)) {
  3727. x->mode = Addressing_Value;
  3728. return;
  3729. }
  3730. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3731. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3732. }
  3733. if (is_type_bit_set(x->type)) {
  3734. switch (op.kind) {
  3735. case Token_Add: op.kind = Token_Or; break;
  3736. case Token_Sub: op.kind = Token_AndNot; break;
  3737. }
  3738. }
  3739. x->value = exact_binary_operator_value(op.kind, a, b);
  3740. if (is_type_typed(x->type)) {
  3741. if (node != nullptr) {
  3742. x->expr = node;
  3743. }
  3744. check_is_expressible(c, x, x->type);
  3745. }
  3746. return;
  3747. } else if (is_type_string(x->type)) {
  3748. error(node, "String concatenation is only allowed with constant strings");
  3749. x->mode = Addressing_Invalid;
  3750. return;
  3751. }
  3752. x->mode = Addressing_Value;
  3753. }
  3754. gb_internal Operand make_operand_from_node(Ast *node) {
  3755. GB_ASSERT(node != nullptr);
  3756. Operand x = {};
  3757. x.expr = node;
  3758. x.mode = node->tav.mode;
  3759. x.type = node->tav.type;
  3760. x.value = node->tav.value;
  3761. return x;
  3762. }
  3763. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3764. GB_ASSERT(e != nullptr);
  3765. ExprInfo *old = check_get_expr_info(c, e);
  3766. if (old == nullptr) {
  3767. if (type != nullptr && type != t_invalid) {
  3768. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3769. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3770. if (e->kind == Ast_TernaryIfExpr) {
  3771. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3772. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3773. }
  3774. }
  3775. }
  3776. return;
  3777. }
  3778. switch (e->kind) {
  3779. case_ast_node(ue, UnaryExpr, e);
  3780. if (old->value.kind != ExactValue_Invalid) {
  3781. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3782. // They don't need to be updated as they will be updated later and
  3783. // checked at the end of general checking stage.
  3784. break;
  3785. }
  3786. update_untyped_expr_type(c, ue->expr, type, final);
  3787. case_end;
  3788. case_ast_node(be, BinaryExpr, e);
  3789. if (old->value.kind != ExactValue_Invalid) {
  3790. // See above note in UnaryExpr case
  3791. break;
  3792. }
  3793. if (token_is_comparison(be->op.kind)) {
  3794. // NOTE(bill): Do nothing as the types are fine
  3795. } else if (token_is_shift(be->op.kind)) {
  3796. update_untyped_expr_type(c, be->left, type, final);
  3797. } else {
  3798. update_untyped_expr_type(c, be->left, type, final);
  3799. update_untyped_expr_type(c, be->right, type, final);
  3800. }
  3801. case_end;
  3802. case_ast_node(te, TernaryIfExpr, e);
  3803. if (old->value.kind != ExactValue_Invalid) {
  3804. // See above note in UnaryExpr case
  3805. break;
  3806. }
  3807. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3808. // having an untyped value
  3809. Operand x = make_operand_from_node(te->x);
  3810. Operand y = make_operand_from_node(te->y);
  3811. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3812. update_untyped_expr_type(c, te->x, type, final);
  3813. }
  3814. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3815. update_untyped_expr_type(c, te->y, type, final);
  3816. }
  3817. case_end;
  3818. case_ast_node(te, TernaryWhenExpr, e);
  3819. if (old->value.kind != ExactValue_Invalid) {
  3820. // See above note in UnaryExpr case
  3821. break;
  3822. }
  3823. update_untyped_expr_type(c, te->x, type, final);
  3824. update_untyped_expr_type(c, te->y, type, final);
  3825. case_end;
  3826. case_ast_node(ore, OrReturnExpr, e);
  3827. if (old->value.kind != ExactValue_Invalid) {
  3828. // See above note in UnaryExpr case
  3829. break;
  3830. }
  3831. update_untyped_expr_type(c, ore->expr, type, final);
  3832. case_end;
  3833. case_ast_node(obe, OrBranchExpr, e);
  3834. if (old->value.kind != ExactValue_Invalid) {
  3835. // See above note in UnaryExpr case
  3836. break;
  3837. }
  3838. update_untyped_expr_type(c, obe->expr, type, final);
  3839. case_end;
  3840. case_ast_node(oee, OrElseExpr, e);
  3841. if (old->value.kind != ExactValue_Invalid) {
  3842. // See above note in UnaryExpr case
  3843. break;
  3844. }
  3845. update_untyped_expr_type(c, oee->x, type, final);
  3846. update_untyped_expr_type(c, oee->y, type, final);
  3847. case_end;
  3848. case_ast_node(pe, ParenExpr, e);
  3849. update_untyped_expr_type(c, pe->expr, type, final);
  3850. case_end;
  3851. }
  3852. if (!final && is_type_untyped(type)) {
  3853. old->type = base_type(type);
  3854. return;
  3855. }
  3856. // We need to remove it and then give it a new one
  3857. check_remove_expr_info(c, e);
  3858. if (old->is_lhs && !is_type_integer(type)) {
  3859. gbString expr_str = expr_to_string(e);
  3860. gbString type_str = type_to_string(type);
  3861. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3862. gb_string_free(type_str);
  3863. gb_string_free(expr_str);
  3864. return;
  3865. }
  3866. add_type_and_value(c, e, old->mode, type, old->value);
  3867. }
  3868. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3869. GB_ASSERT(e != nullptr);
  3870. ExprInfo *found = check_get_expr_info(c, e);
  3871. if (found) {
  3872. found->value = value;
  3873. }
  3874. }
  3875. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type, bool ignore_error_block=false) {
  3876. gbString expr_str = expr_to_string(operand->expr);
  3877. gbString type_str = type_to_string(target_type);
  3878. gbString from_type_str = type_to_string(operand->type);
  3879. char const *extra_text = "";
  3880. if (operand->mode == Addressing_Constant) {
  3881. if (big_int_is_zero(&operand->value.value_integer)) {
  3882. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3883. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3884. extra_text = " - Did you want 'nil'?";
  3885. }
  3886. }
  3887. }
  3888. if (!ignore_error_block) {
  3889. begin_error_block();
  3890. }
  3891. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3892. if (operand->value.kind == ExactValue_String) {
  3893. String key = operand->value.value_string;
  3894. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3895. Type *et = base_type(target_type);
  3896. check_did_you_mean_type(key, et->Enum.fields, ".");
  3897. }
  3898. }
  3899. gb_string_free(from_type_str);
  3900. gb_string_free(type_str);
  3901. gb_string_free(expr_str);
  3902. operand->mode = Addressing_Invalid;
  3903. if (!ignore_error_block) {
  3904. end_error_block();
  3905. }
  3906. }
  3907. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3908. Type *t = core_type(type);
  3909. if (is_type_boolean(t)) {
  3910. // v = exact_value_to_boolean(v);
  3911. } else if (is_type_float(t)) {
  3912. v = exact_value_to_float(v);
  3913. } else if (is_type_integer(t)) {
  3914. v = exact_value_to_integer(v);
  3915. } else if (is_type_pointer(t)) {
  3916. v = exact_value_to_integer(v);
  3917. } else if (is_type_complex(t)) {
  3918. v = exact_value_to_complex(v);
  3919. } else if (is_type_quaternion(t)) {
  3920. v = exact_value_to_quaternion(v);
  3921. }
  3922. return v;
  3923. }
  3924. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3925. // GB_ASSERT_NOT_NULL(target_type);
  3926. if (target_type == nullptr || operand->mode == Addressing_Invalid ||
  3927. operand->mode == Addressing_Type ||
  3928. is_type_typed(operand->type) ||
  3929. target_type == t_invalid) {
  3930. return;
  3931. }
  3932. if (is_type_untyped(target_type)) {
  3933. GB_ASSERT(operand->type->kind == Type_Basic);
  3934. GB_ASSERT(target_type->kind == Type_Basic);
  3935. BasicKind x_kind = operand->type->Basic.kind;
  3936. BasicKind y_kind = target_type->Basic.kind;
  3937. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3938. if (x_kind < y_kind) {
  3939. operand->type = target_type;
  3940. update_untyped_expr_type(c, operand->expr, target_type, false);
  3941. }
  3942. } else if (x_kind != y_kind) {
  3943. operand->mode = Addressing_Invalid;
  3944. convert_untyped_error(c, operand, target_type);
  3945. return;
  3946. }
  3947. return;
  3948. }
  3949. Type *t = base_type(target_type);
  3950. if (c->in_enum_type) {
  3951. t = core_type(target_type);
  3952. }
  3953. switch (t->kind) {
  3954. case Type_Basic:
  3955. if (operand->mode == Addressing_Constant) {
  3956. check_is_expressible(c, operand, t);
  3957. if (operand->mode == Addressing_Invalid) {
  3958. return;
  3959. }
  3960. update_untyped_expr_value(c, operand->expr, operand->value);
  3961. } else {
  3962. switch (operand->type->Basic.kind) {
  3963. case Basic_UntypedBool:
  3964. if (!is_type_boolean(target_type)) {
  3965. operand->mode = Addressing_Invalid;
  3966. convert_untyped_error(c, operand, target_type);
  3967. return;
  3968. }
  3969. break;
  3970. case Basic_UntypedInteger:
  3971. case Basic_UntypedFloat:
  3972. case Basic_UntypedComplex:
  3973. case Basic_UntypedQuaternion:
  3974. case Basic_UntypedRune:
  3975. if (!is_type_numeric(target_type)) {
  3976. operand->mode = Addressing_Invalid;
  3977. convert_untyped_error(c, operand, target_type);
  3978. return;
  3979. }
  3980. break;
  3981. case Basic_UntypedNil:
  3982. if (is_type_any(target_type)) {
  3983. // target_type = t_untyped_nil;
  3984. } else if (is_type_cstring(target_type)) {
  3985. // target_type = t_untyped_nil;
  3986. } else if (!type_has_nil(target_type)) {
  3987. operand->mode = Addressing_Invalid;
  3988. convert_untyped_error(c, operand, target_type);
  3989. return;
  3990. }
  3991. break;
  3992. }
  3993. }
  3994. break;
  3995. case Type_Array: {
  3996. Type *elem = base_array_type(t);
  3997. if (check_is_assignable_to(c, operand, elem)) {
  3998. operand->mode = Addressing_Value;
  3999. } else {
  4000. if (operand->value.kind == ExactValue_String) {
  4001. String s = operand->value.value_string;
  4002. if (is_type_u8_array(t)) {
  4003. if (s.len == t->Array.count) {
  4004. break;
  4005. }
  4006. } else if (is_type_rune_array(t)) {
  4007. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  4008. if (rune_count == t->Array.count) {
  4009. break;
  4010. }
  4011. }
  4012. }
  4013. operand->mode = Addressing_Invalid;
  4014. convert_untyped_error(c, operand, target_type);
  4015. return;
  4016. }
  4017. break;
  4018. }
  4019. case Type_SimdVector: {
  4020. Type *elem = base_array_type(t);
  4021. if (check_is_assignable_to(c, operand, elem)) {
  4022. operand->mode = Addressing_Value;
  4023. } else {
  4024. operand->mode = Addressing_Invalid;
  4025. convert_untyped_error(c, operand, target_type);
  4026. return;
  4027. }
  4028. break;
  4029. }
  4030. case Type_Matrix: {
  4031. Type *elem = base_array_type(t);
  4032. if (check_is_assignable_to(c, operand, elem)) {
  4033. if (t->Matrix.row_count != t->Matrix.column_count) {
  4034. operand->mode = Addressing_Invalid;
  4035. ERROR_BLOCK();
  4036. convert_untyped_error(c, operand, target_type, true);
  4037. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  4038. return;
  4039. } else {
  4040. operand->mode = Addressing_Value;
  4041. }
  4042. } else {
  4043. operand->mode = Addressing_Invalid;
  4044. convert_untyped_error(c, operand, target_type);
  4045. return;
  4046. }
  4047. break;
  4048. }
  4049. case Type_Union:
  4050. // IMPORTANT NOTE HACK(bill): This is just to allow for comparisons against `0` with the `os.Error` type
  4051. // as a kind of transition period
  4052. if (!build_context.strict_style &&
  4053. operand->mode == Addressing_Constant &&
  4054. target_type->kind == Type_Named &&
  4055. (c->pkg == nullptr || c->pkg->name != "os") &&
  4056. target_type->Named.name == "Error") {
  4057. Entity *e = target_type->Named.type_name;
  4058. if (e->pkg && e->pkg->name == "os") {
  4059. if (is_exact_value_zero(operand->value) &&
  4060. (operand->value.kind == ExactValue_Integer ||
  4061. operand->value.kind == ExactValue_Float)) {
  4062. operand->mode = Addressing_Value;
  4063. // target_type = t_untyped_nil;
  4064. operand->value = empty_exact_value;
  4065. update_untyped_expr_value(c, operand->expr, operand->value);
  4066. break;
  4067. }
  4068. }
  4069. }
  4070. // "fallthrough"
  4071. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  4072. TEMPORARY_ALLOCATOR_GUARD();
  4073. isize count = t->Union.variants.count;
  4074. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  4075. isize valid_count = 0;
  4076. isize first_success_index = -1;
  4077. for_array(i, t->Union.variants) {
  4078. Type *vt = t->Union.variants[i];
  4079. i64 score = 0;
  4080. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  4081. valids[valid_count].index = i;
  4082. valids[valid_count].score = score;
  4083. valid_count += 1;
  4084. if (first_success_index < 0) {
  4085. first_success_index = i;
  4086. }
  4087. }
  4088. }
  4089. if (valid_count > 1) {
  4090. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  4091. i64 best_score = valids[0].score;
  4092. for (isize i = 1; i < valid_count; i++) {
  4093. auto v = valids[i];
  4094. if (best_score > v.score) {
  4095. valid_count = i;
  4096. break;
  4097. }
  4098. best_score = v.score;
  4099. }
  4100. first_success_index = valids[0].index;
  4101. }
  4102. gbString type_str = type_to_string(target_type);
  4103. defer (gb_string_free(type_str));
  4104. if (valid_count == 1) {
  4105. Type *new_type = t->Union.variants[first_success_index];
  4106. target_type = new_type;
  4107. if (is_type_union(new_type)) {
  4108. convert_to_typed(c, operand, new_type);
  4109. break;
  4110. }
  4111. operand->type = new_type;
  4112. operand->mode = Addressing_Value;
  4113. break;
  4114. } else if (valid_count > 1) {
  4115. ERROR_BLOCK();
  4116. GB_ASSERT(first_success_index >= 0);
  4117. operand->mode = Addressing_Invalid;
  4118. convert_untyped_error(c, operand, target_type, true);
  4119. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  4120. i32 j = 0;
  4121. for (i32 i = 0; i < valid_count; i++) {
  4122. ValidIndexAndScore valid = valids[i];
  4123. if (j > 0 && valid_count > 2) error_line(", ");
  4124. if (j == valid_count-1) {
  4125. if (valid_count == 2) error_line(" ");
  4126. error_line("or ");
  4127. }
  4128. gbString str = type_to_string(t->Union.variants[valid.index]);
  4129. error_line("'%s'", str);
  4130. gb_string_free(str);
  4131. j++;
  4132. }
  4133. error_line("\n\n");
  4134. return;
  4135. } else if (is_type_untyped_uninit(operand->type)) {
  4136. target_type = t_untyped_uninit;
  4137. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  4138. ERROR_BLOCK();
  4139. operand->mode = Addressing_Invalid;
  4140. convert_untyped_error(c, operand, target_type, true);
  4141. if (count > 0) {
  4142. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  4143. error_line("\t");
  4144. for (i32 i = 0; i < count; i++) {
  4145. Type *v = t->Union.variants[i];
  4146. if (i > 0 && count > 2) error_line(", ");
  4147. if (i == count-1) {
  4148. if (count == 2) error_line(" ");
  4149. if (count > 1) {
  4150. error_line("or ");
  4151. }
  4152. }
  4153. gbString str = type_to_string(v);
  4154. error_line("'%s'", str);
  4155. gb_string_free(str);
  4156. }
  4157. error_line("\n\n");
  4158. }
  4159. return;
  4160. }
  4161. }
  4162. /* fallthrough */
  4163. default:
  4164. if (is_type_untyped_uninit(operand->type)) {
  4165. target_type = t_untyped_uninit;
  4166. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  4167. target_type = t_untyped_nil;
  4168. } else {
  4169. operand->mode = Addressing_Invalid;
  4170. convert_untyped_error(c, operand, target_type);
  4171. return;
  4172. }
  4173. break;
  4174. }
  4175. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  4176. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  4177. } else {
  4178. target_type = default_type(operand->type);
  4179. }
  4180. }
  4181. update_untyped_expr_type(c, operand->expr, target_type, true);
  4182. operand->type = target_type;
  4183. }
  4184. 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) {
  4185. Operand operand = {Addressing_Invalid};
  4186. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  4187. if (operand.mode == Addressing_Invalid) {
  4188. if (value) *value = 0;
  4189. // NOTE(bill): return true here to propagate the errors better
  4190. return true;
  4191. }
  4192. Type *index_type = t_int;
  4193. if (type_hint != nullptr) {
  4194. index_type = type_hint;
  4195. }
  4196. convert_to_typed(c, &operand, index_type);
  4197. if (operand.mode == Addressing_Invalid) {
  4198. if (value) *value = 0;
  4199. return false;
  4200. }
  4201. if (type_hint != nullptr) {
  4202. if (!check_is_assignable_to(c, &operand, type_hint)) {
  4203. gbString expr_str = expr_to_string(operand.expr);
  4204. gbString index_type_str = type_to_string(type_hint);
  4205. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  4206. gb_string_free(index_type_str);
  4207. gb_string_free(expr_str);
  4208. if (value) *value = 0;
  4209. return false;
  4210. }
  4211. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  4212. gbString expr_str = expr_to_string(operand.expr);
  4213. gbString type_str = type_to_string(operand.type);
  4214. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  4215. gb_string_free(type_str);
  4216. gb_string_free(expr_str);
  4217. if (value) *value = 0;
  4218. return false;
  4219. }
  4220. if (operand.mode == Addressing_Constant &&
  4221. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  4222. BigInt i = exact_value_to_integer(operand.value).value_integer;
  4223. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  4224. TEMPORARY_ALLOCATOR_GUARD();
  4225. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4226. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4227. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  4228. if (value) *value = 0;
  4229. return false;
  4230. }
  4231. if (max_count >= 0) {
  4232. if (is_type_enum(index_type)) {
  4233. Type *bt = base_type(index_type);
  4234. GB_ASSERT(bt->kind == Type_Enum);
  4235. ExactValue const &lo = *bt->Enum.min_value;
  4236. ExactValue const &hi = *bt->Enum.max_value;
  4237. String lo_str = {};
  4238. String hi_str = {};
  4239. if (bt->Enum.fields.count > 0) {
  4240. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  4241. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  4242. lo_str = bt->Enum.fields[lo_idx]->token.string;
  4243. hi_str = bt->Enum.fields[hi_idx]->token.string;
  4244. }
  4245. bool out_of_bounds = false;
  4246. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  4247. out_of_bounds = true;
  4248. }
  4249. if (out_of_bounds) {
  4250. gbString expr_str = expr_to_string(operand.expr);
  4251. if (lo_str.len > 0) {
  4252. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  4253. } else {
  4254. gbString index_type_str = type_to_string(index_type);
  4255. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  4256. gb_string_free(index_type_str);
  4257. }
  4258. gb_string_free(expr_str);
  4259. return false;
  4260. }
  4261. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  4262. return true;
  4263. } else { // NOTE(bill): Do array bound checking
  4264. i64 v = -1;
  4265. if (i.used <= 1) {
  4266. v = big_int_to_i64(&i);
  4267. }
  4268. if (value) *value = v;
  4269. bool out_of_bounds = false;
  4270. if (v < 0) {
  4271. out_of_bounds = true;
  4272. } else if (open_range) {
  4273. out_of_bounds = v > max_count;
  4274. } else {
  4275. out_of_bounds = v >= max_count;
  4276. }
  4277. if (out_of_bounds) {
  4278. TEMPORARY_ALLOCATOR_GUARD();
  4279. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4280. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4281. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  4282. return false;
  4283. }
  4284. return true;
  4285. }
  4286. } else {
  4287. if (value) *value = exact_value_to_i64(operand.value);
  4288. return true;
  4289. }
  4290. }
  4291. // NOTE(bill): It's alright :D
  4292. if (value) *value = -1;
  4293. return true;
  4294. }
  4295. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  4296. if (value.kind == ExactValue_String) {
  4297. GB_ASSERT(0 <= index && index < value.value_string.len);
  4298. u8 val = value.value_string[index];
  4299. if (success_) *success_ = true;
  4300. if (finish_) *finish_ = true;
  4301. return exact_value_u64(val);
  4302. }
  4303. if (value.kind != ExactValue_Compound) {
  4304. if (success_) *success_ = true;
  4305. if (finish_) *finish_ = true;
  4306. return value;
  4307. }
  4308. Ast *node = value.value_compound;
  4309. switch (node->kind) {
  4310. case_ast_node(cl, CompoundLit, node);
  4311. if (cl->elems.count == 0) {
  4312. if (success_) *success_ = true;
  4313. if (finish_) *finish_ = true;
  4314. return empty_exact_value;
  4315. }
  4316. if (cl->elems[0]->kind == Ast_FieldValue) {
  4317. if (is_type_struct(node->tav.type)) {
  4318. bool found = false;
  4319. for (Ast *elem : cl->elems) {
  4320. if (elem->kind != Ast_FieldValue) {
  4321. continue;
  4322. }
  4323. ast_node(fv, FieldValue, elem);
  4324. String name = fv->field->Ident.token.string;
  4325. Selection sub_sel = lookup_field(node->tav.type, name, false);
  4326. defer (array_free(&sub_sel.index));
  4327. if (sub_sel.index.count > 0 &&
  4328. sub_sel.index[0] == index) {
  4329. value = fv->value->tav.value;
  4330. found = true;
  4331. break;
  4332. }
  4333. }
  4334. if (!found) {
  4335. // Use the zero value if it is not found
  4336. value = {};
  4337. }
  4338. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4339. for (Ast *elem : cl->elems) {
  4340. if (elem->kind != Ast_FieldValue) {
  4341. continue;
  4342. }
  4343. ast_node(fv, FieldValue, elem);
  4344. if (is_ast_range(fv->field)) {
  4345. ast_node(ie, BinaryExpr, fv->field);
  4346. TypeAndValue lo_tav = ie->left->tav;
  4347. TypeAndValue hi_tav = ie->right->tav;
  4348. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4349. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4350. TokenKind op = ie->op.kind;
  4351. i64 lo = exact_value_to_i64(lo_tav.value);
  4352. i64 hi = exact_value_to_i64(hi_tav.value);
  4353. i64 corrected_index = index;
  4354. if (is_type_enumerated_array(node->tav.type)) {
  4355. Type *bt = base_type(node->tav.type);
  4356. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4357. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4358. }
  4359. if (op != Token_RangeHalf) {
  4360. if (lo <= corrected_index && corrected_index <= hi) {
  4361. TypeAndValue tav = fv->value->tav;
  4362. if (success_) *success_ = true;
  4363. if (finish_) *finish_ = false;
  4364. return tav.value;
  4365. }
  4366. } else {
  4367. if (lo <= corrected_index && corrected_index < hi) {
  4368. TypeAndValue tav = fv->value->tav;
  4369. if (success_) *success_ = true;
  4370. if (finish_) *finish_ = false;
  4371. return tav.value;
  4372. }
  4373. }
  4374. } else {
  4375. TypeAndValue index_tav = fv->field->tav;
  4376. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4377. ExactValue index_value = index_tav.value;
  4378. if (is_type_enumerated_array(node->tav.type)) {
  4379. Type *bt = base_type(node->tav.type);
  4380. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4381. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4382. }
  4383. i64 field_index = exact_value_to_i64(index_value);
  4384. if (index == field_index) {
  4385. TypeAndValue tav = fv->value->tav;
  4386. if (success_) *success_ = true;
  4387. if (finish_) *finish_ = false;
  4388. return tav.value;
  4389. }
  4390. }
  4391. }
  4392. }
  4393. } else {
  4394. i32 count = (i32)cl->elems.count;
  4395. if (count < index) {
  4396. if (success_) *success_ = false;
  4397. if (finish_) *finish_ = true;
  4398. return empty_exact_value;
  4399. }
  4400. if (cl->elems.count <= index) {
  4401. if (success_) *success_ = false;
  4402. if (finish_) *finish_ = false;
  4403. return value;
  4404. }
  4405. TypeAndValue tav = cl->elems[index]->tav;
  4406. if (tav.mode == Addressing_Constant) {
  4407. if (success_) *success_ = true;
  4408. if (finish_) *finish_ = false;
  4409. return tav.value;
  4410. } else if (is_type_proc(tav.type)) {
  4411. if (success_) *success_ = true;
  4412. if (finish_) *finish_ = false;
  4413. return tav.value;
  4414. } else {
  4415. GB_ASSERT_MSG(is_type_untyped_nil(tav.type), "%s", type_to_string(tav.type));
  4416. if (success_) *success_ = true;
  4417. if (finish_) *finish_ = false;
  4418. return tav.value;
  4419. }
  4420. }
  4421. case_end;
  4422. default:
  4423. if (success_) *success_ = true;
  4424. if (finish_) *finish_ = true;
  4425. return empty_exact_value;
  4426. }
  4427. if (finish_) *finish_ = false;
  4428. return value;
  4429. }
  4430. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4431. if (operand->mode != Addressing_Constant) {
  4432. if (success_) *success_ = false;
  4433. return empty_exact_value;
  4434. }
  4435. if (sel.indirect) {
  4436. if (success_) *success_ = false;
  4437. return empty_exact_value;
  4438. }
  4439. if (sel.index.count == 0) {
  4440. if (success_) *success_ = false;
  4441. return empty_exact_value;
  4442. }
  4443. ExactValue value = operand->value;
  4444. if (value.kind == ExactValue_Compound) {
  4445. while (sel.index.count > 0) {
  4446. i32 index = sel.index[0];
  4447. sel = sub_selection(sel, 1);
  4448. bool finish = false;
  4449. value = get_constant_field_single(c, value, index, success_, &finish);
  4450. if (finish) {
  4451. return value;
  4452. }
  4453. }
  4454. if (success_) *success_ = true;
  4455. return value;
  4456. } else if (value.kind == ExactValue_Quaternion) {
  4457. // @QuaternionLayout
  4458. Quaternion256 q = *value.value_quaternion;
  4459. GB_ASSERT(sel.index.count == 1);
  4460. switch (sel.index[0]) {
  4461. case 3: // w
  4462. if (success_) *success_ = true;
  4463. return exact_value_float(q.real);
  4464. case 0: // x
  4465. if (success_) *success_ = true;
  4466. return exact_value_float(q.imag);
  4467. case 1: // y
  4468. if (success_) *success_ = true;
  4469. return exact_value_float(q.jmag);
  4470. case 2: // z
  4471. if (success_) *success_ = true;
  4472. return exact_value_float(q.kmag);
  4473. }
  4474. if (success_) *success_ = false;
  4475. return empty_exact_value;
  4476. } else if (value.kind == ExactValue_Complex) {
  4477. // @QuaternionLayout
  4478. Complex128 c = *value.value_complex;
  4479. GB_ASSERT(sel.index.count == 1);
  4480. switch (sel.index[0]) {
  4481. case 0: // real
  4482. if (success_) *success_ = true;
  4483. return exact_value_float(c.real);
  4484. case 1: // imag
  4485. if (success_) *success_ = true;
  4486. return exact_value_float(c.imag);
  4487. }
  4488. if (success_) *success_ = false;
  4489. return empty_exact_value;
  4490. }
  4491. if (success_) *success_ = true;
  4492. return empty_exact_value;
  4493. }
  4494. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4495. Type *array_type = base_type(type_deref(original_type));
  4496. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4497. if (array_type->kind == Type_SimdVector) {
  4498. Type *elem_type = array_type->SimdVector.elem;
  4499. return alloc_type_simd_vector(new_count, elem_type);
  4500. }
  4501. Type *elem_type = array_type->Array.elem;
  4502. Type *swizzle_array_type = nullptr;
  4503. Type *bth = base_type(type_deref(type_hint));
  4504. if (bth != nullptr && bth->kind == Type_Array &&
  4505. bth->Array.count == new_count &&
  4506. are_types_identical(bth->Array.elem, elem_type)) {
  4507. swizzle_array_type = type_hint;
  4508. } else {
  4509. i64 max_count = array_type->Array.count;
  4510. if (new_count == max_count) {
  4511. swizzle_array_type = original_type;
  4512. } else {
  4513. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4514. }
  4515. }
  4516. return swizzle_array_type;
  4517. }
  4518. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4519. bool is_declared = entity != nullptr;
  4520. if (is_declared) {
  4521. if (entity->kind == Entity_Builtin) {
  4522. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4523. // This means that we should just ignore the found result through it
  4524. *allow_builtin = entity->scope == import_scope ||
  4525. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4526. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4527. is_declared = false;
  4528. }
  4529. }
  4530. return is_declared;
  4531. }
  4532. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4533. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4534. if (node == nullptr) {
  4535. return nullptr;
  4536. }
  4537. /*if (node->kind == Ast_TernaryWhenExpr) {
  4538. ast_node(we, TernaryWhenExpr, node);
  4539. if (we->cond == nullptr) {
  4540. return nullptr;
  4541. }
  4542. if (we->cond->tav.mode != Addressing_Constant) {
  4543. return nullptr;
  4544. }
  4545. if (we->cond->tav.value.kind != ExactValue_Bool) {
  4546. return nullptr;
  4547. }
  4548. if (we->cond->tav.value.value_bool) {
  4549. return check_entity_from_ident_or_selector(c, we->x, ident_only);
  4550. } else {
  4551. Entity *e = check_entity_from_ident_or_selector(c, we->y, ident_only);
  4552. return e;
  4553. }
  4554. } else */if (node->kind == Ast_Ident) {
  4555. String name = node->Ident.token.string;
  4556. return scope_lookup(c->scope, name);
  4557. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4558. ast_node(se, SelectorExpr, node);
  4559. if (se->token.kind == Token_ArrowRight) {
  4560. return nullptr;
  4561. }
  4562. Ast *op_expr = se->expr;
  4563. Ast *selector = unparen_expr(se->selector);
  4564. if (selector == nullptr) {
  4565. return nullptr;
  4566. }
  4567. if (selector->kind != Ast_Ident) {
  4568. return nullptr;
  4569. }
  4570. Entity *entity = nullptr;
  4571. Entity *expr_entity = nullptr;
  4572. bool check_op_expr = true;
  4573. if (op_expr->kind == Ast_Ident) {
  4574. String op_name = op_expr->Ident.token.string;
  4575. Entity *e = scope_lookup(c->scope, op_name);
  4576. if (e == nullptr) {
  4577. return nullptr;
  4578. }
  4579. add_entity_use(c, op_expr, e);
  4580. expr_entity = e;
  4581. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4582. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4583. // It pretty much needs to be in this order and this way
  4584. // If you can clean this up, please do but be really careful
  4585. String import_name = op_name;
  4586. Scope *import_scope = e->ImportName.scope;
  4587. String entity_name = selector->Ident.token.string;
  4588. check_op_expr = false;
  4589. entity = scope_lookup_current(import_scope, entity_name);
  4590. bool allow_builtin = false;
  4591. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4592. return nullptr;
  4593. }
  4594. check_entity_decl(c, entity, nullptr, nullptr);
  4595. if (entity->kind == Entity_ProcGroup) {
  4596. return entity;
  4597. }
  4598. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4599. }
  4600. }
  4601. Operand operand = {};
  4602. if (check_op_expr) {
  4603. check_expr_base(c, &operand, op_expr, nullptr);
  4604. if (operand.mode == Addressing_Invalid) {
  4605. return nullptr;
  4606. }
  4607. }
  4608. if (entity == nullptr && selector->kind == Ast_Ident) {
  4609. String field_name = selector->Ident.token.string;
  4610. if (is_type_dynamic_array(type_deref(operand.type))) {
  4611. init_mem_allocator(c->checker);
  4612. }
  4613. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4614. entity = sel.entity;
  4615. }
  4616. if (entity != nullptr) {
  4617. return entity;
  4618. }
  4619. }
  4620. return nullptr;
  4621. }
  4622. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4623. ast_node(se, SelectorExpr, node);
  4624. bool check_op_expr = true;
  4625. Entity *expr_entity = nullptr;
  4626. Entity *entity = nullptr;
  4627. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4628. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4629. ERROR_BLOCK();
  4630. error(node, "Illegal use of -> selector shorthand outside of a call");
  4631. gbString x = expr_to_string(se->expr);
  4632. gbString y = expr_to_string(se->selector);
  4633. error_line("\tSuggestion: Did you mean '%s.%s'?\n", x, y);
  4634. gb_string_free(y);
  4635. gb_string_free(x);
  4636. // TODO(bill): Should this terminate here or propagate onwards?
  4637. // operand->mode = Addressing_Invalid;
  4638. // operand->expr = node;
  4639. // return nullptr;
  4640. }
  4641. operand->expr = node;
  4642. Ast *op_expr = se->expr;
  4643. Ast *selector = unparen_expr(se->selector);
  4644. if (selector == nullptr) {
  4645. operand->mode = Addressing_Invalid;
  4646. operand->expr = node;
  4647. return nullptr;
  4648. }
  4649. if (selector->kind != Ast_Ident) {
  4650. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4651. operand->mode = Addressing_Invalid;
  4652. operand->expr = node;
  4653. return nullptr;
  4654. }
  4655. if (op_expr->kind == Ast_Ident) {
  4656. String op_name = op_expr->Ident.token.string;
  4657. Entity *e = scope_lookup(c->scope, op_name);
  4658. add_entity_use(c, op_expr, e);
  4659. expr_entity = e;
  4660. if (e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup) && selector->kind == Ast_Ident) {
  4661. gbString sel_str = expr_to_string(selector);
  4662. error(node, "'%s' is not declared by by '%.*s'", sel_str, LIT(e->token.string));
  4663. gb_string_free(sel_str);
  4664. operand->mode = Addressing_Invalid;
  4665. operand->expr = node;
  4666. return nullptr;
  4667. } else if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4668. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4669. // It pretty much needs to be in this order and this way
  4670. // If you can clean this up, please do but be really careful
  4671. String import_name = op_name;
  4672. Scope *import_scope = e->ImportName.scope;
  4673. String entity_name = selector->Ident.token.string;
  4674. if (import_scope == nullptr) {
  4675. ERROR_BLOCK();
  4676. error(node, "'%.*s' is not imported in this file, '%.*s' is unavailable", LIT(import_name), LIT(entity_name));
  4677. operand->mode = Addressing_Invalid;
  4678. operand->expr = node;
  4679. return nullptr;
  4680. }
  4681. check_op_expr = false;
  4682. entity = scope_lookup_current(import_scope, entity_name);
  4683. bool allow_builtin = false;
  4684. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4685. ERROR_BLOCK();
  4686. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4687. operand->mode = Addressing_Invalid;
  4688. operand->expr = node;
  4689. check_did_you_mean_scope(entity_name, import_scope);
  4690. return nullptr;
  4691. }
  4692. check_entity_decl(c, entity, nullptr, nullptr);
  4693. if (entity->kind == Entity_ProcGroup) {
  4694. operand->mode = Addressing_ProcGroup;
  4695. operand->proc_group = entity;
  4696. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4697. return entity;
  4698. }
  4699. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4700. if (!is_entity_exported(entity, allow_builtin)) {
  4701. gbString sel_str = expr_to_string(selector);
  4702. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4703. gb_string_free(sel_str);
  4704. // NOTE(bill): make the state valid still, even if it's "invalid"
  4705. // operand->mode = Addressing_Invalid;
  4706. // operand->expr = node;
  4707. // return nullptr;
  4708. }
  4709. if (entity->kind == Entity_ProcGroup) {
  4710. Array<Entity *> procs = entity->ProcGroup.entities;
  4711. bool skip = false;
  4712. for (Entity *p : procs) {
  4713. Type *t = base_type(p->type);
  4714. if (t == t_invalid) {
  4715. continue;
  4716. }
  4717. Operand x = {};
  4718. x.mode = Addressing_Value;
  4719. x.type = t;
  4720. if (type_hint != nullptr) {
  4721. if (check_is_assignable_to(c, &x, type_hint)) {
  4722. entity = p;
  4723. skip = true;
  4724. break;
  4725. }
  4726. }
  4727. }
  4728. if (!skip) {
  4729. GB_ASSERT(entity != nullptr);
  4730. operand->mode = Addressing_ProcGroup;
  4731. operand->type = t_invalid;
  4732. operand->expr = node;
  4733. operand->proc_group = entity;
  4734. return entity;
  4735. }
  4736. }
  4737. }
  4738. }
  4739. if (check_op_expr) {
  4740. check_expr_base(c, operand, op_expr, nullptr);
  4741. if (operand->mode == Addressing_Invalid) {
  4742. operand->mode = Addressing_Invalid;
  4743. operand->expr = node;
  4744. return nullptr;
  4745. }
  4746. }
  4747. if (operand->type && is_type_soa_struct(type_deref(operand->type))) {
  4748. complete_soa_type(c->checker, type_deref(operand->type), false);
  4749. }
  4750. if (entity == nullptr && selector->kind == Ast_Ident) {
  4751. String field_name = selector->Ident.token.string;
  4752. Type *t = type_deref(operand->type);
  4753. if (t == nullptr) {
  4754. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4755. } else {
  4756. if (is_type_dynamic_array(t)) {
  4757. init_mem_allocator(c->checker);
  4758. }
  4759. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4760. entity = sel.entity;
  4761. // NOTE(bill): Add type info needed for fields like 'names'
  4762. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4763. add_type_info_type(c, operand->type);
  4764. }
  4765. if (is_type_enum(operand->type)) {
  4766. add_type_info_type(c, operand->type);
  4767. }
  4768. }
  4769. }
  4770. if (entity == nullptr && selector->kind == Ast_Ident && operand->type != nullptr &&
  4771. (is_type_array(type_deref(operand->type)) || is_type_simd_vector(type_deref(operand->type)))) {
  4772. String field_name = selector->Ident.token.string;
  4773. if (1 < field_name.len && field_name.len <= 4) {
  4774. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4775. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4776. bool found_xyzw = false;
  4777. bool found_rgba = false;
  4778. for (isize i = 0; i < field_name.len; i++) {
  4779. bool valid = false;
  4780. for (isize j = 0; j < 4; j++) {
  4781. if (field_name.text[i] == swizzles_xyzw[j]) {
  4782. found_xyzw = true;
  4783. valid = true;
  4784. break;
  4785. }
  4786. if (field_name.text[i] == swizzles_rgba[j]) {
  4787. found_rgba = true;
  4788. valid = true;
  4789. break;
  4790. }
  4791. }
  4792. if (!valid) {
  4793. goto end_of_array_selector_swizzle;
  4794. }
  4795. }
  4796. u8 *swizzles = nullptr;
  4797. u8 index_count = cast(u8)field_name.len;
  4798. if (found_xyzw && found_rgba) {
  4799. gbString op_str = expr_to_string(op_expr);
  4800. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4801. gb_string_free(op_str);
  4802. operand->mode = Addressing_Invalid;
  4803. operand->expr = node;
  4804. return nullptr;
  4805. }
  4806. u8 indices = 0;
  4807. if (found_xyzw) {
  4808. swizzles = swizzles_xyzw;
  4809. } else if (found_rgba) {
  4810. swizzles = swizzles_rgba;
  4811. }
  4812. for (isize i = 0; i < field_name.len; i++) {
  4813. for (isize j = 0; j < 4; j++) {
  4814. if (field_name.text[i] == swizzles[j]) {
  4815. indices |= cast(u8)(j)<<(i*2);
  4816. break;
  4817. }
  4818. }
  4819. }
  4820. Type *original_type = operand->type;
  4821. Type *array_type = base_type(type_deref(original_type));
  4822. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4823. i64 array_count = get_array_type_count(array_type);
  4824. for (u8 i = 0; i < index_count; i++) {
  4825. u8 idx = indices>>(i*2) & 3;
  4826. if (idx >= array_count) {
  4827. char c = 0;
  4828. if (found_xyzw) {
  4829. c = swizzles_xyzw[idx];
  4830. } else if (found_rgba) {
  4831. c = swizzles_rgba[idx];
  4832. } else {
  4833. GB_PANIC("unknown swizzle kind");
  4834. }
  4835. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4836. break;
  4837. }
  4838. }
  4839. se->swizzle_count = index_count;
  4840. se->swizzle_indices = indices;
  4841. AddressingMode prev_mode = operand->mode;
  4842. operand->mode = Addressing_SwizzleValue;
  4843. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4844. operand->expr = node;
  4845. switch (prev_mode) {
  4846. case Addressing_Variable:
  4847. case Addressing_SoaVariable:
  4848. case Addressing_SwizzleVariable:
  4849. operand->mode = Addressing_SwizzleVariable;
  4850. break;
  4851. case Addressing_Value:
  4852. if (is_type_pointer(original_type)) {
  4853. operand->mode = Addressing_SwizzleVariable;
  4854. }
  4855. break;
  4856. }
  4857. if (array_type->kind == Type_SimdVector) {
  4858. operand->mode = Addressing_Value;
  4859. }
  4860. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4861. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4862. return swizzle_entity;
  4863. }
  4864. end_of_array_selector_swizzle:;
  4865. }
  4866. if (entity == nullptr) {
  4867. gbString op_str = expr_to_string(op_expr);
  4868. gbString type_str = type_to_string_shorthand(operand->type);
  4869. gbString sel_str = expr_to_string(selector);
  4870. if (operand->mode == Addressing_Type) {
  4871. if (is_type_polymorphic(operand->type, true)) {
  4872. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4873. } else {
  4874. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4875. }
  4876. } else {
  4877. ERROR_BLOCK();
  4878. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4879. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4880. String const &name = selector->Ident.token.string;
  4881. Type *bt = base_type(operand->type);
  4882. if (operand->type->kind == Type_Named &&
  4883. operand->type->Named.type_name &&
  4884. operand->type->Named.type_name->kind == Entity_TypeName &&
  4885. operand->type->Named.type_name->TypeName.objc_metadata) {
  4886. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  4887. } else if (bt->kind == Type_Struct) {
  4888. check_did_you_mean_type(name, bt->Struct.fields);
  4889. } else if (bt->kind == Type_Enum) {
  4890. check_did_you_mean_type(name, bt->Enum.fields);
  4891. }
  4892. }
  4893. }
  4894. gb_string_free(sel_str);
  4895. gb_string_free(type_str);
  4896. gb_string_free(op_str);
  4897. operand->mode = Addressing_Invalid;
  4898. operand->expr = node;
  4899. return nullptr;
  4900. }
  4901. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  4902. bool success = false;
  4903. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4904. if (success) {
  4905. operand->mode = Addressing_Constant;
  4906. operand->expr = node;
  4907. operand->value = field_value;
  4908. operand->type = entity->type;
  4909. add_entity_use(c, selector, entity);
  4910. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4911. return entity;
  4912. }
  4913. gbString op_str = expr_to_string(op_expr);
  4914. gbString type_str = type_to_string_shorthand(operand->type);
  4915. gbString sel_str = expr_to_string(selector);
  4916. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4917. gb_string_free(sel_str);
  4918. gb_string_free(type_str);
  4919. gb_string_free(op_str);
  4920. operand->mode = Addressing_Invalid;
  4921. operand->expr = node;
  4922. return nullptr;
  4923. }
  4924. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  4925. bool success = false;
  4926. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  4927. if (success) {
  4928. operand->mode = Addressing_Constant;
  4929. operand->expr = node;
  4930. operand->value = field_value;
  4931. operand->type = entity->type;
  4932. add_entity_use(c, selector, entity);
  4933. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4934. return entity;
  4935. }
  4936. gbString op_str = expr_to_string(op_expr);
  4937. gbString type_str = type_to_string_shorthand(operand->type);
  4938. gbString sel_str = expr_to_string(selector);
  4939. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  4940. gb_string_free(sel_str);
  4941. gb_string_free(type_str);
  4942. gb_string_free(op_str);
  4943. operand->mode = Addressing_Invalid;
  4944. operand->expr = node;
  4945. return nullptr;
  4946. }
  4947. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  4948. gbString op_str = expr_to_string(op_expr);
  4949. gbString type_str = type_to_string_shorthand(operand->type);
  4950. gbString sel_str = expr_to_string(selector);
  4951. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  4952. gb_string_free(sel_str);
  4953. gb_string_free(type_str);
  4954. gb_string_free(op_str);
  4955. operand->mode = Addressing_Invalid;
  4956. operand->expr = node;
  4957. return nullptr;
  4958. }
  4959. add_entity_use(c, selector, entity);
  4960. operand->type = entity->type;
  4961. operand->expr = node;
  4962. if (entity->flags & EntityFlag_BitFieldField) {
  4963. add_package_dependency(c, "runtime", "__write_bits");
  4964. add_package_dependency(c, "runtime", "__read_bits");
  4965. }
  4966. switch (entity->kind) {
  4967. case Entity_Constant:
  4968. operand->value = entity->Constant.value;
  4969. operand->mode = Addressing_Constant;
  4970. if (operand->value.kind == ExactValue_Procedure) {
  4971. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  4972. if (proc != nullptr) {
  4973. operand->mode = Addressing_Value;
  4974. operand->type = proc->type;
  4975. }
  4976. }
  4977. break;
  4978. case Entity_Variable:
  4979. if (sel.is_bit_field) {
  4980. se->is_bit_field = true;
  4981. }
  4982. if (sel.indirect) {
  4983. operand->mode = Addressing_Variable;
  4984. } else if (operand->mode == Addressing_Context) {
  4985. // Do nothing
  4986. } else if (operand->mode == Addressing_MapIndex) {
  4987. operand->mode = Addressing_Value;
  4988. } else if (entity->flags & EntityFlag_SoaPtrField) {
  4989. operand->mode = Addressing_SoaVariable;
  4990. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  4991. operand->mode = Addressing_Value;
  4992. } else if (operand->mode == Addressing_SoaVariable) {
  4993. operand->mode = Addressing_Variable;
  4994. } else if (operand->mode != Addressing_Value) {
  4995. operand->mode = Addressing_Variable;
  4996. } else {
  4997. operand->mode = Addressing_Value;
  4998. }
  4999. break;
  5000. case Entity_TypeName:
  5001. operand->mode = Addressing_Type;
  5002. break;
  5003. case Entity_Procedure:
  5004. operand->mode = Addressing_Value;
  5005. operand->value = exact_value_procedure(node);
  5006. break;
  5007. case Entity_Builtin:
  5008. operand->mode = Addressing_Builtin;
  5009. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  5010. break;
  5011. case Entity_ProcGroup:
  5012. operand->mode = Addressing_ProcGroup;
  5013. operand->proc_group = entity;
  5014. break;
  5015. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  5016. case Entity_Nil:
  5017. operand->mode = Addressing_Value;
  5018. break;
  5019. }
  5020. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5021. return entity;
  5022. }
  5023. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  5024. ptr = base_type(ptr);
  5025. if (is_type_pointer(ptr)) {
  5026. if (is_type_rawptr(ptr)) {
  5027. return false;
  5028. }
  5029. if (elem) *elem = ptr->Pointer.elem;
  5030. return true;
  5031. }
  5032. return false;
  5033. }
  5034. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  5035. elem = core_type(elem);
  5036. if (is_type_internally_pointer_like(elem)) {
  5037. return true;
  5038. }
  5039. if (elem->kind == Type_BitSet) {
  5040. elem = bit_set_to_int(elem);
  5041. }
  5042. if (elem->kind != Type_Basic) {
  5043. return false;
  5044. }
  5045. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  5046. }
  5047. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  5048. switch (node->kind) {
  5049. case_ast_node(i, Ident, node);
  5050. String name = i->token.string;
  5051. if (nested) {
  5052. Entity *e = scope_lookup_current(s, name);
  5053. if (e != nullptr) {
  5054. if (out_scope) *out_scope = e->scope;
  5055. return true;
  5056. }
  5057. } else {
  5058. Entity *e = scope_lookup(s, name);
  5059. if (e != nullptr) {
  5060. if (out_scope) *out_scope = e->scope;
  5061. return true;
  5062. }
  5063. }
  5064. case_end;
  5065. case_ast_node(se, SelectorExpr, node);
  5066. Ast *lhs = se->expr;
  5067. Ast *rhs = se->selector;
  5068. Scope *lhs_scope = nullptr;
  5069. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  5070. return check_identifier_exists(lhs_scope, rhs, true);
  5071. }
  5072. case_end;
  5073. }
  5074. return false;
  5075. }
  5076. gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) {
  5077. if (o.type && is_type_no_copy(o.type)) {
  5078. Ast *expr = unparen_expr(o.expr);
  5079. if (expr && o.mode != Addressing_Constant && o.mode != Addressing_Type) {
  5080. if (expr->kind == Ast_CallExpr) {
  5081. // Okay
  5082. } else {
  5083. error(o.expr, "Invalid use of #no_copy value in %.*s", LIT(context));
  5084. return true;
  5085. }
  5086. }
  5087. }
  5088. return false;
  5089. }
  5090. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  5091. bool optional_ok = false;
  5092. isize tuple_index = 0;
  5093. for (Ast *rhs_expr : rhs) {
  5094. CheckerContext c_ = *ctx;
  5095. CheckerContext *c = &c_;
  5096. Operand o = {};
  5097. Type *type_hint = nullptr;
  5098. if (tuple_index < lhs.count) {
  5099. type_hint = lhs[tuple_index].type;
  5100. }
  5101. check_expr_base(c, &o, rhs_expr, type_hint);
  5102. if (o.mode == Addressing_NoValue) {
  5103. error_operand_no_value(&o);
  5104. o.mode = Addressing_Invalid;
  5105. }
  5106. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5107. if (lhs.count == 2 && rhs.count == 1 &&
  5108. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5109. Ast *expr = unparen_expr(o.expr);
  5110. Operand val0 = o;
  5111. Operand val1 = o;
  5112. val0.mode = Addressing_Value;
  5113. val1.mode = Addressing_Value;
  5114. val1.type = t_untyped_bool;
  5115. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5116. if (expr->kind == Ast_TypeAssertion &&
  5117. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5118. // NOTE(bill): Used only for optimizations in the backend
  5119. if (is_blank_ident(lhs[0].expr)) {
  5120. expr->TypeAssertion.ignores[0] = true;
  5121. }
  5122. if (is_blank_ident(lhs[1].expr)) {
  5123. expr->TypeAssertion.ignores[1] = true;
  5124. }
  5125. }
  5126. array_add(operands, val0);
  5127. array_add(operands, val1);
  5128. optional_ok = true;
  5129. tuple_index += 2;
  5130. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  5131. Type *tuple = o.type;
  5132. GB_ASSERT(tuple->Tuple.variables.count == 2);
  5133. Ast *expr = unparen_expr(o.expr);
  5134. if (expr->kind == Ast_CallExpr) {
  5135. expr->CallExpr.optional_ok_one = true;
  5136. }
  5137. Operand val = o;
  5138. val.type = tuple->Tuple.variables[0]->type;
  5139. val.mode = Addressing_Value;
  5140. array_add(operands, val);
  5141. tuple_index += tuple->Tuple.variables.count;
  5142. } else {
  5143. array_add(operands, o);
  5144. tuple_index += 1;
  5145. }
  5146. } else {
  5147. TypeTuple *tuple = &o.type->Tuple;
  5148. for (Entity *e : tuple->variables) {
  5149. o.type = e->type;
  5150. array_add(operands, o);
  5151. check_no_copy_assignment(o, str_lit("assignment"));
  5152. }
  5153. tuple_index += tuple->variables.count;
  5154. }
  5155. }
  5156. return optional_ok;
  5157. }
  5158. typedef u32 UnpackFlags;
  5159. enum UnpackFlag : u32 {
  5160. UnpackFlag_None = 0,
  5161. UnpackFlag_AllowOk = 1<<0,
  5162. UnpackFlag_IsVariadic = 1<<1,
  5163. UnpackFlag_AllowUndef = 1<<2,
  5164. };
  5165. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags) {
  5166. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  5167. if (lhs == nullptr || c->decl == nullptr) {
  5168. return tuple_count;
  5169. }
  5170. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  5171. Entity *e = lhs[tuple_index + j];
  5172. if (e == nullptr) {
  5173. continue;
  5174. }
  5175. DeclInfo *decl = decl_info_of_entity(e);
  5176. if (decl == nullptr) {
  5177. continue;
  5178. }
  5179. rw_mutex_shared_lock(&decl->deps_mutex);
  5180. rw_mutex_lock(&c->decl->deps_mutex);
  5181. for (Entity *dep : decl->deps) {
  5182. ptr_set_add(&c->decl->deps, dep);
  5183. }
  5184. rw_mutex_unlock(&c->decl->deps_mutex);
  5185. rw_mutex_shared_unlock(&decl->deps_mutex);
  5186. }
  5187. return tuple_count;
  5188. };
  5189. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  5190. bool is_variadic = (flags & UnpackFlag_IsVariadic) != 0;
  5191. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  5192. bool optional_ok = false;
  5193. isize tuple_index = 0;
  5194. for (Ast *rhs : rhs_arguments) {
  5195. if (rhs->kind == Ast_FieldValue) {
  5196. error(rhs, "Invalid use of 'field = value'");
  5197. rhs = rhs->FieldValue.value;
  5198. }
  5199. CheckerContext c_ = *ctx;
  5200. CheckerContext *c = &c_;
  5201. Operand o = {};
  5202. Type *type_hint = nullptr;
  5203. if (lhs != nullptr && tuple_index < lhs_count) {
  5204. // NOTE(bill): override DeclInfo for dependency
  5205. Entity *e = lhs[tuple_index];
  5206. if (e != nullptr) {
  5207. type_hint = e->type;
  5208. if (e->flags & EntityFlag_Ellipsis) {
  5209. GB_ASSERT(is_type_slice(e->type));
  5210. GB_ASSERT(e->type->kind == Type_Slice);
  5211. type_hint = e->type->Slice.elem;
  5212. }
  5213. }
  5214. } else if (lhs != nullptr && tuple_index >= lhs_count && is_variadic) {
  5215. // NOTE(bill): override DeclInfo for dependency
  5216. Entity *e = lhs[lhs_count-1];
  5217. if (e != nullptr) {
  5218. type_hint = e->type;
  5219. if (e->flags & EntityFlag_Ellipsis) {
  5220. GB_ASSERT(is_type_slice(e->type));
  5221. GB_ASSERT(e->type->kind == Type_Slice);
  5222. type_hint = e->type->Slice.elem;
  5223. }
  5224. }
  5225. }
  5226. Ast *rhs_expr = unparen_expr(rhs);
  5227. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  5228. // NOTE(bill): Just handle this very specific logic here
  5229. o.type = t_untyped_uninit;
  5230. o.mode = Addressing_Value;
  5231. o.expr = rhs;
  5232. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  5233. } else {
  5234. check_expr_base(c, &o, rhs, type_hint);
  5235. }
  5236. if (o.mode == Addressing_NoValue) {
  5237. error_operand_no_value(&o);
  5238. o.mode = Addressing_Invalid;
  5239. }
  5240. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5241. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  5242. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5243. Ast *expr = unparen_expr(o.expr);
  5244. Operand val0 = o;
  5245. Operand val1 = o;
  5246. val0.mode = Addressing_Value;
  5247. val1.mode = Addressing_Value;
  5248. val1.type = t_untyped_bool;
  5249. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5250. if (expr->kind == Ast_TypeAssertion &&
  5251. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5252. // NOTE(bill): Used only for optimizations in the backend
  5253. if (is_blank_ident(lhs[0]->token)) {
  5254. expr->TypeAssertion.ignores[0] = true;
  5255. }
  5256. if (is_blank_ident(lhs[1]->token)) {
  5257. expr->TypeAssertion.ignores[1] = true;
  5258. }
  5259. }
  5260. array_add(operands, val0);
  5261. array_add(operands, val1);
  5262. optional_ok = true;
  5263. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  5264. } else {
  5265. array_add(operands, o);
  5266. tuple_index += 1;
  5267. }
  5268. } else {
  5269. TypeTuple *tuple = &o.type->Tuple;
  5270. for (Entity *e : tuple->variables) {
  5271. o.type = e->type;
  5272. array_add(operands, o);
  5273. }
  5274. isize count = tuple->variables.count;
  5275. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  5276. }
  5277. }
  5278. return optional_ok;
  5279. }
  5280. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  5281. GB_ASSERT(pt != nullptr);
  5282. GB_ASSERT(pt->kind == Type_Proc);
  5283. isize param_count = 0;
  5284. isize param_count_excluding_defaults = 0;
  5285. bool variadic = pt->Proc.variadic;
  5286. TypeTuple *param_tuple = nullptr;
  5287. if (pt->Proc.params != nullptr) {
  5288. param_tuple = &pt->Proc.params->Tuple;
  5289. param_count = param_tuple->variables.count;
  5290. if (variadic) {
  5291. for (isize i = param_count-1; i >= 0; i--) {
  5292. Entity *e = param_tuple->variables[i];
  5293. if (e->kind == Entity_TypeName) {
  5294. break;
  5295. }
  5296. if (e->kind == Entity_Variable) {
  5297. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5298. param_count--;
  5299. continue;
  5300. }
  5301. }
  5302. break;
  5303. }
  5304. param_count--;
  5305. }
  5306. }
  5307. param_count_excluding_defaults = param_count;
  5308. if (param_tuple != nullptr) {
  5309. for (isize i = param_count-1; i >= 0; i--) {
  5310. Entity *e = param_tuple->variables[i];
  5311. if (e->kind == Entity_TypeName) {
  5312. break;
  5313. }
  5314. if (e->kind == Entity_Variable) {
  5315. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5316. param_count_excluding_defaults--;
  5317. continue;
  5318. }
  5319. }
  5320. break;
  5321. }
  5322. }
  5323. if (param_count_) *param_count_ = param_count;
  5324. return param_count_excluding_defaults;
  5325. }
  5326. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  5327. isize param_count = pt->param_count;
  5328. for (isize i = 0; i < param_count; i++) {
  5329. Entity *e = pt->params->Tuple.variables[i];
  5330. String name = e->token.string;
  5331. if (is_blank_ident(name)) {
  5332. continue;
  5333. }
  5334. if (name == parameter_name) {
  5335. return i;
  5336. }
  5337. }
  5338. return -1;
  5339. }
  5340. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  5341. type = base_type(type);
  5342. GB_ASSERT(type->kind == Type_Proc);
  5343. return lookup_procedure_parameter(&type->Proc, parameter_name);
  5344. }
  5345. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  5346. Entity *entity, Type *proc_type,
  5347. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  5348. CallArgumentErrorMode show_error_mode,
  5349. CallArgumentData *data) {
  5350. TEMPORARY_ALLOCATOR_GUARD();
  5351. CallArgumentError err = CallArgumentError_None;
  5352. ast_node(ce, CallExpr, call);
  5353. GB_ASSERT(is_type_proc(proc_type));
  5354. proc_type = base_type(proc_type);
  5355. TypeProc *pt = &proc_type->Proc;
  5356. isize param_count = 0;
  5357. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  5358. bool variadic = pt->variadic;
  5359. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5360. i64 score = 0;
  5361. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  5362. Type *final_proc_type = proc_type;
  5363. Entity *gen_entity = nullptr;
  5364. if (vari_expand && !variadic) {
  5365. if (show_error) {
  5366. error(ce->ellipsis,
  5367. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  5368. LIT(ce->proc->Ident.token.string));
  5369. }
  5370. err = CallArgumentError_NonVariadicExpand;
  5371. } else if (vari_expand && pt->c_vararg) {
  5372. if (show_error) {
  5373. error(ce->ellipsis,
  5374. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  5375. LIT(ce->proc->Ident.token.string));
  5376. }
  5377. err = CallArgumentError_NonVariadicExpand;
  5378. }
  5379. GB_ASSERT(ce->split_args);
  5380. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  5381. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  5382. defer ({
  5383. for (Operand const &o : ordered_operands) {
  5384. if (o.expr != nullptr) {
  5385. call->viral_state_flags |= o.expr->viral_state_flags;
  5386. }
  5387. }
  5388. });
  5389. isize positional_operand_count = positional_operands.count;
  5390. if (variadic) {
  5391. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5392. } else if (positional_operand_count > pt->param_count) {
  5393. err = CallArgumentError_TooManyArguments;
  5394. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5395. if (show_error) {
  5396. gbString proc_str = expr_to_string(ce->proc);
  5397. defer (gb_string_free(proc_str));
  5398. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5399. }
  5400. return err;
  5401. }
  5402. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5403. for (isize i = 0; i < positional_operand_count; i++) {
  5404. ordered_operands[i] = positional_operands[i];
  5405. visited[i] = true;
  5406. }
  5407. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5408. bool named_variadic_param = false;
  5409. if (named_operands.count != 0) {
  5410. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5411. for_array(i, ce->split_args->named) {
  5412. Ast *arg = ce->split_args->named[i];
  5413. Operand operand = named_operands[i];
  5414. ast_node(fv, FieldValue, arg);
  5415. if (fv->field->kind != Ast_Ident) {
  5416. if (show_error) {
  5417. gbString expr_str = expr_to_string(fv->field);
  5418. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5419. gb_string_free(expr_str);
  5420. }
  5421. err = CallArgumentError_InvalidFieldValue;
  5422. continue;
  5423. }
  5424. String name = fv->field->Ident.token.string;
  5425. isize param_index = lookup_procedure_parameter(pt, name);
  5426. if (param_index < 0) {
  5427. if (show_error) {
  5428. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5429. }
  5430. err = CallArgumentError_ParameterNotFound;
  5431. continue;
  5432. }
  5433. if (pt->variadic && param_index == pt->variadic_index) {
  5434. named_variadic_param = true;
  5435. }
  5436. if (visited[param_index]) {
  5437. if (show_error) {
  5438. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5439. }
  5440. err = CallArgumentError_DuplicateParameter;
  5441. continue;
  5442. }
  5443. visited[param_index] = true;
  5444. ordered_operands[param_index] = operand;
  5445. }
  5446. }
  5447. isize dummy_argument_count = 0;
  5448. bool actually_variadic = false;
  5449. if (variadic) {
  5450. if (visited[pt->variadic_index] &&
  5451. positional_operand_count < positional_operands.count) {
  5452. if (show_error) {
  5453. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5454. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5455. }
  5456. err = CallArgumentError_DuplicateParameter;
  5457. } else if (!visited[pt->variadic_index]) {
  5458. visited[pt->variadic_index] = true;
  5459. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5460. if (vari_expand) {
  5461. if (variadic_operands.count == 0) {
  5462. error(call, "'..' in the wrong position");
  5463. } else {
  5464. GB_ASSERT(variadic_operands.count != 0);
  5465. *variadic_operand = variadic_operands[0];
  5466. variadic_operand->type = default_type(variadic_operand->type);
  5467. actually_variadic = true;
  5468. }
  5469. } else {
  5470. AstFile *f = call->file();
  5471. // HACK(bill): this is an awful hack
  5472. Operand o = {};
  5473. o.mode = Addressing_Value;
  5474. o.expr = ast_ident(f, make_token_ident("nil"));
  5475. o.expr->Ident.token.pos = ast_token(call).pos;
  5476. if (variadic_operands.count != 0) {
  5477. actually_variadic = true;
  5478. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5479. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5480. o.type = vt->type;
  5481. } else {
  5482. dummy_argument_count += 1;
  5483. o.type = t_untyped_nil;
  5484. }
  5485. *variadic_operand = o;
  5486. }
  5487. }
  5488. }
  5489. for (Operand const &o : ordered_operands) {
  5490. if (o.mode != Addressing_Invalid) {
  5491. check_no_copy_assignment(o, str_lit("procedure call expression"));
  5492. }
  5493. }
  5494. for (isize i = 0; i < pt->param_count; i++) {
  5495. if (!visited[i]) {
  5496. Entity *e = pt->params->Tuple.variables[i];
  5497. if (e->kind == Entity_Variable) {
  5498. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5499. ordered_operands[i].mode = Addressing_Value;
  5500. ordered_operands[i].type = e->type;
  5501. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5502. dummy_argument_count += 1;
  5503. score += assign_score_function(1);
  5504. continue;
  5505. }
  5506. }
  5507. if (show_error) {
  5508. if (e->kind == Entity_TypeName) {
  5509. error(call, "Type parameter '%.*s' is missing in procedure call",
  5510. LIT(e->token.string));
  5511. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5512. // Ignore
  5513. } else {
  5514. gbString str = type_to_string(e->type);
  5515. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5516. LIT(e->token.string), str);
  5517. gb_string_free(str);
  5518. }
  5519. }
  5520. err = CallArgumentError_ParameterMissing;
  5521. }
  5522. }
  5523. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5524. bool allow_array_programming = !(e && (e->flags & EntityFlag_NoBroadcast));
  5525. i64 s = 0;
  5526. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic, allow_array_programming)) {
  5527. bool ok = false;
  5528. if (e && (e->flags & EntityFlag_AnyInt)) {
  5529. if (is_type_integer(param_type)) {
  5530. ok = check_is_castable_to(c, o, param_type);
  5531. }
  5532. }
  5533. if (!allow_array_programming && check_is_assignable_to_with_score(c, o, param_type, nullptr, param_is_variadic, !allow_array_programming)) {
  5534. if (show_error) {
  5535. error(o->expr, "'#no_broadcast' disallows automatic broadcasting a value across all elements of an array-like type in a procedure argument");
  5536. }
  5537. }
  5538. if (ok) {
  5539. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5540. } else {
  5541. if (show_error) {
  5542. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5543. }
  5544. err = CallArgumentError_WrongTypes;
  5545. }
  5546. } else if (show_error) {
  5547. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5548. }
  5549. if (e && e->flags & EntityFlag_ConstInput) {
  5550. if (o->mode != Addressing_Constant) {
  5551. if (show_error) {
  5552. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5553. }
  5554. err = CallArgumentError_NoneConstantParameter;
  5555. }
  5556. }
  5557. if (!err && is_type_any(param_type)) {
  5558. add_type_info_type(c, o->type);
  5559. }
  5560. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5561. add_type_info_type(c, o->type);
  5562. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5563. } else if (show_error && is_type_untyped(o->type)) {
  5564. update_untyped_expr_type(c, o->expr, param_type, true);
  5565. }
  5566. return s;
  5567. };
  5568. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5569. err = CallArgumentError_None;
  5570. if (variadic) {
  5571. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5572. Type *t = pt->params->Tuple.variables[0]->type;
  5573. if (is_type_polymorphic(t)) {
  5574. if (show_error) {
  5575. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5576. }
  5577. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5578. }
  5579. }
  5580. } else {
  5581. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5582. PolyProcData poly_proc_data = {};
  5583. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5584. gen_entity = poly_proc_data.gen_entity;
  5585. Type *gept = base_type(gen_entity->type);
  5586. GB_ASSERT(is_type_proc(gept));
  5587. final_proc_type = gen_entity->type;
  5588. pt = &gept->Proc;
  5589. } else {
  5590. err = CallArgumentError_WrongTypes;
  5591. }
  5592. }
  5593. for (isize i = 0; i < pt->param_count; i++) {
  5594. Operand *o = &ordered_operands[i];
  5595. if (o->mode == Addressing_Invalid) {
  5596. continue;
  5597. }
  5598. Entity *e = pt->params->Tuple.variables[i];
  5599. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5600. if (e->kind == Entity_TypeName) {
  5601. GB_ASSERT(pt->is_polymorphic);
  5602. if (o->mode != Addressing_Type) {
  5603. if (show_error) {
  5604. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5605. }
  5606. err = CallArgumentError_WrongTypes;
  5607. }
  5608. if (are_types_identical(e->type, o->type)) {
  5609. score += assign_score_function(1);
  5610. } else {
  5611. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5612. }
  5613. continue;
  5614. }
  5615. if (param_is_variadic) {
  5616. if (!named_variadic_param) {
  5617. continue;
  5618. }
  5619. }
  5620. score += eval_param_and_score(c, o, e->type, err, false, e, show_error);
  5621. }
  5622. }
  5623. if (variadic) {
  5624. Entity *var_entity = pt->params->Tuple.variables[pt->variadic_index];
  5625. Type *slice = var_entity->type;
  5626. GB_ASSERT(is_type_slice(slice));
  5627. Type *elem = base_type(slice)->Slice.elem;
  5628. Type *t = elem;
  5629. if (is_type_polymorphic(t)) {
  5630. if (show_error) {
  5631. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5632. }
  5633. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5634. }
  5635. for_array(operand_index, variadic_operands) {
  5636. Operand *o = &variadic_operands[operand_index];
  5637. if (vari_expand) {
  5638. t = slice;
  5639. if (operand_index > 0) {
  5640. if (show_error) {
  5641. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5642. }
  5643. if (data) {
  5644. data->score = score;
  5645. data->result_type = final_proc_type->Proc.results;
  5646. data->gen_entity = gen_entity;
  5647. }
  5648. return CallArgumentError_MultipleVariadicExpand;
  5649. }
  5650. }
  5651. score += eval_param_and_score(c, o, t, err, true, var_entity, show_error);
  5652. }
  5653. if (!vari_expand && variadic_operands.count != 0) {
  5654. // NOTE(bill, 2024-07-14): minimize the stack usage for variadic parameters with the backing array
  5655. if (c->decl) {
  5656. bool found = false;
  5657. for (auto &vr : c->decl->variadic_reuses) {
  5658. if (are_types_identical(slice, vr.slice_type)) {
  5659. vr.max_count = gb_max(vr.max_count, variadic_operands.count);
  5660. found = true;
  5661. break;
  5662. }
  5663. }
  5664. if (!found) {
  5665. array_add(&c->decl->variadic_reuses, VariadicReuseData{slice, variadic_operands.count});
  5666. }
  5667. }
  5668. }
  5669. }
  5670. if (data) {
  5671. data->score = score;
  5672. data->result_type = final_proc_type->Proc.results;
  5673. data->gen_entity = gen_entity;
  5674. Ast *proc_lit = nullptr;
  5675. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5676. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5677. if (vp && vp->kind == Ast_ProcLit) {
  5678. proc_lit = vp;
  5679. }
  5680. }
  5681. if (proc_lit == nullptr) {
  5682. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5683. }
  5684. }
  5685. return err;
  5686. }
  5687. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5688. GB_ASSERT(ce != nullptr);
  5689. if (ce->args.count == 0) {
  5690. return false;
  5691. }
  5692. return ce->args[0]->kind == Ast_FieldValue;
  5693. }
  5694. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_, bool *is_variadic) {
  5695. Entity **lhs = nullptr;
  5696. isize lhs_count = -1;
  5697. if (proc_type == nullptr) {
  5698. return nullptr;
  5699. }
  5700. GB_ASSERT(is_type_proc(proc_type));
  5701. TypeProc *pt = &base_type(proc_type)->Proc;
  5702. *is_variadic = pt->variadic;
  5703. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5704. if (pt->params != nullptr) {
  5705. lhs = pt->params->Tuple.variables.data;
  5706. lhs_count = pt->params->Tuple.variables.count;
  5707. }
  5708. } else {
  5709. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5710. if (pt->params == nullptr) {
  5711. lhs_count = 0;
  5712. } else {
  5713. lhs_count = pt->params->Tuple.variables.count;
  5714. }
  5715. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5716. for (isize i = 0; i < lhs_count; i++) {
  5717. Entity *e = pt->params->Tuple.variables[i];
  5718. if (!is_type_polymorphic(e->type)) {
  5719. lhs[i] = e;
  5720. }
  5721. }
  5722. }
  5723. if (lhs_count_) *lhs_count_ = lhs_count;
  5724. return lhs;
  5725. }
  5726. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5727. if (clauses != nullptr) {
  5728. for (Ast *clause : *clauses) {
  5729. Operand o = {};
  5730. check_expr(ctx, &o, clause);
  5731. if (o.mode != Addressing_Constant) {
  5732. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5733. if (print_err && call_expr) error(call_expr, "at caller location");
  5734. return false;
  5735. } else if (o.value.kind != ExactValue_Bool) {
  5736. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5737. if (print_err && call_expr) error(call_expr, "at caller location");
  5738. return false;
  5739. } else if (!o.value.value_bool) {
  5740. if (print_err) {
  5741. ERROR_BLOCK();
  5742. gbString str = expr_to_string(clause);
  5743. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5744. gb_string_free(str);
  5745. if (scope != nullptr) {
  5746. isize print_count = 0;
  5747. for (auto const &entry : scope->elements) {
  5748. Entity *e = entry.value;
  5749. switch (e->kind) {
  5750. case Entity_TypeName: {
  5751. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5752. gbString str = type_to_string(e->type);
  5753. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5754. gb_string_free(str);
  5755. print_count += 1;
  5756. break;
  5757. }
  5758. case Entity_Constant: {
  5759. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5760. gbString str = exact_value_to_string(e->Constant.value);
  5761. if (is_type_untyped(e->type)) {
  5762. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5763. } else {
  5764. gbString t = type_to_string(e->type);
  5765. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5766. gb_string_free(t);
  5767. }
  5768. gb_string_free(str);
  5769. print_count += 1;
  5770. break;
  5771. }
  5772. }
  5773. }
  5774. }
  5775. if (call_expr) {
  5776. TokenPos pos = ast_token(call_expr).pos;
  5777. error_line("%s at caller location\n", token_pos_to_string(pos));
  5778. }
  5779. }
  5780. return false;
  5781. }
  5782. if (ast_file_vet_style(ctx->file)) {
  5783. Ast *c = unparen_expr(clause);
  5784. if (c->kind == Ast_BinaryExpr && c->BinaryExpr.op.kind == Token_CmpAnd) {
  5785. ERROR_BLOCK();
  5786. error(c, "Prefer to separate 'where' clauses with a comma rather than '&&'");
  5787. gbString x = expr_to_string(c->BinaryExpr.left);
  5788. gbString y = expr_to_string(c->BinaryExpr.right);
  5789. error_line("\tSuggestion: '%s, %s'\n", x, y);
  5790. gb_string_free(y);
  5791. gb_string_free(x);
  5792. }
  5793. }
  5794. }
  5795. }
  5796. return true;
  5797. }
  5798. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5799. bool success = true;
  5800. type = base_type(type);
  5801. if (named_args.count > 0) {
  5802. TypeProc *pt = nullptr;
  5803. if (is_type_proc(type)) {
  5804. pt = &type->Proc;
  5805. }
  5806. for_array(i, named_args) {
  5807. Ast *arg = named_args[i];
  5808. if (arg->kind != Ast_FieldValue) {
  5809. if (show_error) {
  5810. error(arg, "Expected a 'field = value'");
  5811. }
  5812. return false;
  5813. }
  5814. ast_node(fv, FieldValue, arg);
  5815. if (fv->field->kind != Ast_Ident) {
  5816. if (show_error) {
  5817. gbString expr_str = expr_to_string(fv->field);
  5818. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5819. gb_string_free(expr_str);
  5820. }
  5821. success = false;
  5822. continue;
  5823. }
  5824. String key = fv->field->Ident.token.string;
  5825. Ast *value = fv->value;
  5826. Type *type_hint = nullptr;
  5827. if (pt) {
  5828. isize param_index = lookup_procedure_parameter(pt, key);
  5829. if (param_index < 0) {
  5830. if (show_error) {
  5831. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5832. }
  5833. success = false;
  5834. continue;
  5835. }
  5836. Entity *e = pt->params->Tuple.variables[param_index];
  5837. if (!is_type_polymorphic(e->type)) {
  5838. type_hint = e->type;
  5839. }
  5840. }
  5841. Operand o = {};
  5842. check_expr_with_type_hint(c, &o, value, type_hint);
  5843. if (o.mode == Addressing_Invalid) {
  5844. success = false;
  5845. }
  5846. array_add(named_operands, o);
  5847. }
  5848. }
  5849. return success;
  5850. }
  5851. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5852. Entity *e, Type *proc_type,
  5853. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5854. CallArgumentErrorMode show_error_mode,
  5855. CallArgumentData *data) {
  5856. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5857. Ast *ident = operand->expr;
  5858. while (ident->kind == Ast_SelectorExpr) {
  5859. Ast *s = ident->SelectorExpr.selector;
  5860. ident = s;
  5861. }
  5862. if (e == nullptr) {
  5863. e = entity_of_node(ident);
  5864. if (e != nullptr) {
  5865. proc_type = e->type;
  5866. }
  5867. }
  5868. GB_ASSERT(proc_type != nullptr);
  5869. proc_type = base_type(proc_type);
  5870. GB_ASSERT(proc_type->kind == Type_Proc);
  5871. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5872. if (return_on_failure && err != CallArgumentError_None) {
  5873. return false;
  5874. }
  5875. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5876. if (!return_on_failure && entity_to_use != nullptr) {
  5877. add_entity_use(c, ident, entity_to_use);
  5878. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5879. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5880. }
  5881. if (data->gen_entity != nullptr) {
  5882. Entity *e = data->gen_entity;
  5883. DeclInfo *decl = data->gen_entity->decl_info;
  5884. CheckerContext ctx = *c;
  5885. ctx.scope = decl->scope;
  5886. ctx.decl = decl;
  5887. ctx.proc_name = e->token.string;
  5888. ctx.curr_proc_decl = decl;
  5889. ctx.curr_proc_sig = e->type;
  5890. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5891. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5892. if (return_on_failure) {
  5893. if (!ok) {
  5894. return false;
  5895. }
  5896. } else {
  5897. decl->where_clauses_evaluated = true;
  5898. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5899. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5900. }
  5901. if (is_type_proc(data->gen_entity->type)) {
  5902. Type *t = base_type(entity_to_use->type);
  5903. data->result_type = t->Proc.results;
  5904. }
  5905. }
  5906. }
  5907. return true;
  5908. }
  5909. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5910. ast_node(ce, CallExpr, call);
  5911. GB_ASSERT(ce->split_args != nullptr);
  5912. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5913. Slice<Ast *> const &named_args = ce->split_args->named;
  5914. CallArgumentData data = {};
  5915. data.result_type = t_invalid;
  5916. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5917. auto procs = proc_group_entities_cloned(c, *operand);
  5918. if (procs.count > 1) {
  5919. isize max_arg_count = positional_args.count + named_args.count;
  5920. for (Ast *arg : positional_args) {
  5921. // NOTE(bill): The only thing that may have multiple values
  5922. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5923. arg = strip_or_return_expr(arg);
  5924. if (arg && arg->kind == Ast_CallExpr) {
  5925. max_arg_count = ISIZE_MAX;
  5926. break;
  5927. }
  5928. }
  5929. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5930. // NOTE(bill): The only thing that may have multiple values
  5931. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5932. if (arg->kind == Ast_FieldValue) {
  5933. arg = strip_or_return_expr(arg->FieldValue.value);
  5934. if (arg && arg->kind == Ast_CallExpr) {
  5935. max_arg_count = ISIZE_MAX;
  5936. break;
  5937. }
  5938. }
  5939. }
  5940. // ignore named arguments first
  5941. for (Ast *arg : named_args) {
  5942. if (arg->kind != Ast_FieldValue) {
  5943. continue;
  5944. }
  5945. ast_node(fv, FieldValue, arg);
  5946. if (fv->field->kind != Ast_Ident) {
  5947. continue;
  5948. }
  5949. String key = fv->field->Ident.token.string;
  5950. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5951. Type *t = procs[proc_index]->type;
  5952. if (is_type_proc(t)) {
  5953. isize param_index = lookup_procedure_parameter(t, key);
  5954. if (param_index < 0) {
  5955. array_unordered_remove(&procs, proc_index);
  5956. }
  5957. }
  5958. }
  5959. }
  5960. if (procs.count == 0) {
  5961. // if any of the named arguments are wrong, the `procs` will be empty
  5962. // just start from scratch
  5963. array_free(&procs);
  5964. procs = proc_group_entities_cloned(c, *operand);
  5965. }
  5966. // filter by positional argument length
  5967. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5968. Entity *proc = procs[proc_index];
  5969. Type *pt = base_type(proc->type);
  5970. if (!(pt != nullptr && is_type_proc(pt))) {
  5971. proc_index++;
  5972. continue;
  5973. }
  5974. isize param_count = 0;
  5975. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5976. if (param_count_excluding_defaults > max_arg_count) {
  5977. array_unordered_remove(&procs, proc_index);
  5978. continue;
  5979. }
  5980. proc_index++;
  5981. }
  5982. }
  5983. Entity **lhs = nullptr;
  5984. isize lhs_count = -1;
  5985. bool is_variadic = false;
  5986. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5987. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5988. defer (array_free(&positional_operands));
  5989. defer (array_free(&named_operands));
  5990. if (procs.count == 1) {
  5991. Entity *e = procs[0];
  5992. lhs = populate_proc_parameter_list(c, e->type, &lhs_count, &is_variadic);
  5993. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  5994. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5995. check_call_arguments_single(c, call, operand,
  5996. e, e->type,
  5997. positional_operands, named_operands,
  5998. CallArgumentErrorMode::ShowErrors,
  5999. &data);
  6000. }
  6001. return data;
  6002. }
  6003. {
  6004. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  6005. // where the same positional parameter has the same type value (and ellipsis)
  6006. isize proc_arg_count = -1;
  6007. for (Entity *p : procs) {
  6008. Type *pt = base_type(p->type);
  6009. if (pt != nullptr && is_type_proc(pt)) {
  6010. if (proc_arg_count < 0) {
  6011. proc_arg_count = pt->Proc.param_count;
  6012. } else {
  6013. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  6014. }
  6015. }
  6016. }
  6017. if (proc_arg_count >= 0) {
  6018. lhs_count = proc_arg_count;
  6019. if (lhs_count > 0) {
  6020. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  6021. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  6022. Entity *e = nullptr;
  6023. for (Entity *p : procs) {
  6024. Type *pt = base_type(p->type);
  6025. if (!(pt != nullptr && is_type_proc(pt))) {
  6026. continue;
  6027. }
  6028. if (e == nullptr) {
  6029. e = pt->Proc.params->Tuple.variables[param_index];
  6030. } else {
  6031. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  6032. if (e == f) {
  6033. continue;
  6034. }
  6035. if (are_types_identical(e->type, f->type)) {
  6036. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  6037. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  6038. if (ee == fe) {
  6039. continue;
  6040. }
  6041. }
  6042. // NOTE(bill): Entities are not close enough to be used
  6043. e = nullptr;
  6044. break;
  6045. }
  6046. }
  6047. lhs[param_index] = e;
  6048. }
  6049. }
  6050. }
  6051. }
  6052. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  6053. for_array(i, named_args) {
  6054. Ast *arg = named_args[i];
  6055. if (arg->kind != Ast_FieldValue) {
  6056. error(arg, "Expected a 'field = value'");
  6057. return data;
  6058. }
  6059. ast_node(fv, FieldValue, arg);
  6060. if (fv->field->kind != Ast_Ident) {
  6061. gbString expr_str = expr_to_string(fv->field);
  6062. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6063. gb_string_free(expr_str);
  6064. return data;
  6065. }
  6066. String key = fv->field->Ident.token.string;
  6067. Ast *value = fv->value;
  6068. Type *type_hint = nullptr;
  6069. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  6070. Entity *e = lhs[lhs_idx];
  6071. if (e != nullptr && e->token.string == key &&
  6072. !is_type_polymorphic(e->type)) {
  6073. type_hint = e->type;
  6074. break;
  6075. }
  6076. }
  6077. Operand o = {};
  6078. check_expr_with_type_hint(c, &o, value, type_hint);
  6079. array_add(&named_operands, o);
  6080. }
  6081. gb_free(heap_allocator(), lhs);
  6082. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  6083. defer (array_free(&valids));
  6084. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  6085. defer (array_free(&proc_entities));
  6086. for (Entity *proc : procs) {
  6087. array_add(&proc_entities, proc);
  6088. }
  6089. int max_matched_features = 0;
  6090. gbString expr_name = expr_to_string(operand->expr);
  6091. defer (gb_string_free(expr_name));
  6092. for_array(i, procs) {
  6093. Entity *p = procs[i];
  6094. if (p->flags & EntityFlag_Disabled) {
  6095. continue;
  6096. }
  6097. Type *pt = base_type(p->type);
  6098. if (pt != nullptr && is_type_proc(pt)) {
  6099. CallArgumentData data = {};
  6100. CheckerContext ctx = *c;
  6101. ctx.no_polymorphic_errors = true;
  6102. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  6103. ctx.hide_polymorphic_errors = true;
  6104. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  6105. p, pt,
  6106. positional_operands, named_operands,
  6107. CallArgumentErrorMode::NoErrors,
  6108. &data);
  6109. if (!is_a_candidate) {
  6110. continue;
  6111. }
  6112. isize index = i;
  6113. ValidIndexAndScore item = {};
  6114. item.score = data.score;
  6115. if (data.gen_entity != nullptr) {
  6116. array_add(&proc_entities, data.gen_entity);
  6117. index = proc_entities.count-1;
  6118. // prefer non-polymorphic procedures over polymorphic
  6119. item.score += assign_score_function(1);
  6120. }
  6121. max_matched_features = gb_max(max_matched_features, matched_target_features(&pt->Proc));
  6122. item.index = index;
  6123. array_add(&valids, item);
  6124. }
  6125. }
  6126. if (max_matched_features > 0) {
  6127. for_array(i, valids) {
  6128. Entity *p = procs[valids[i].index];
  6129. Type *t = base_type(p->type);
  6130. GB_ASSERT(t->kind == Type_Proc);
  6131. int matched = matched_target_features(&t->Proc);
  6132. valids[i].score += assign_score_function(max_matched_features-matched);
  6133. }
  6134. }
  6135. if (valids.count > 1) {
  6136. array_sort(valids, valid_index_and_score_cmp);
  6137. i64 best_score = valids[0].score;
  6138. Entity *best_entity = proc_entities[valids[0].index];
  6139. GB_ASSERT(best_entity != nullptr);
  6140. for (isize i = 1; i < valids.count; i++) {
  6141. if (best_score > valids[i].score) {
  6142. valids.count = i;
  6143. break;
  6144. }
  6145. if (best_entity == proc_entities[valids[i].index]) {
  6146. valids.count = i;
  6147. break;
  6148. }
  6149. }
  6150. }
  6151. auto print_argument_types = [&]() {
  6152. error_line("\tGiven argument types: (");
  6153. isize i = 0;
  6154. for (Operand const &o : positional_operands) {
  6155. if (i++ > 0) error_line(", ");
  6156. gbString type = type_to_string(o.type);
  6157. defer (gb_string_free(type));
  6158. error_line("%s", type);
  6159. }
  6160. for (Operand const &o : named_operands) {
  6161. if (i++ > 0) error_line(", ");
  6162. gbString type = type_to_string(o.type);
  6163. defer (gb_string_free(type));
  6164. if (i < ce->split_args->named.count) {
  6165. Ast *named_field = ce->split_args->named[i];
  6166. ast_node(fv, FieldValue, named_field);
  6167. gbString field = expr_to_string(fv->field);
  6168. defer (gb_string_free(field));
  6169. error_line("%s = %s", field, type);
  6170. } else {
  6171. error_line("%s", type);
  6172. }
  6173. }
  6174. error_line(")\n");
  6175. };
  6176. if (valids.count == 0) {
  6177. ERROR_BLOCK();
  6178. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  6179. if (positional_operands.count == 0 && named_operands.count == 0) {
  6180. error_line("\tNo given arguments\n");
  6181. } else {
  6182. print_argument_types();
  6183. }
  6184. if (procs.count == 0) {
  6185. procs = proc_group_entities_cloned(c, *operand);
  6186. }
  6187. if (procs.count > 0) {
  6188. error_line("Did you mean to use one of the following:\n");
  6189. }
  6190. // Try to reduce the list further for `$T: typeid` like parameters
  6191. bool *possibly_ignore = gb_alloc_array(temporary_allocator(), bool, procs.count);
  6192. isize possibly_ignore_set = 0;
  6193. if (true) {
  6194. // NOTE(bill): This currently only checks for #soa types
  6195. for_array(i, procs) {
  6196. Entity *proc = procs[i];
  6197. Type *t = base_type(proc->type);
  6198. if (t == nullptr || t->kind != Type_Proc) {
  6199. continue;
  6200. }
  6201. TypeProc *pt = &t->Proc;
  6202. if (pt->param_count == 0) {
  6203. continue;
  6204. }
  6205. for_array(j, pt->params->Tuple.variables) {
  6206. Entity *v = pt->params->Tuple.variables[j];
  6207. if (v->kind != Entity_TypeName) {
  6208. continue;
  6209. }
  6210. Type *dst_t = base_type(v->type);
  6211. while (dst_t->kind == Type_Generic && dst_t->Generic.specialized) {
  6212. dst_t = dst_t->Generic.specialized;
  6213. }
  6214. if (j >= positional_operands.count) {
  6215. continue;
  6216. }
  6217. Operand const &o = positional_operands[j];
  6218. if (o.mode != Addressing_Type) {
  6219. continue;
  6220. }
  6221. Type *t = base_type(o.type);
  6222. if (t->kind == dst_t->kind) {
  6223. continue;
  6224. }
  6225. Type *st = base_type(type_deref(o.type));
  6226. Type *dt = base_type(type_deref(dst_t));
  6227. if (st->kind == dt->kind) {
  6228. continue;
  6229. }
  6230. if (is_type_soa_struct(st)) {
  6231. possibly_ignore[i] = true;
  6232. possibly_ignore_set += 1;
  6233. continue;
  6234. }
  6235. }
  6236. }
  6237. }
  6238. if (possibly_ignore_set == procs.count) {
  6239. possibly_ignore_set = 0;
  6240. }
  6241. isize max_name_length = 0;
  6242. isize max_type_length = 0;
  6243. for_array(i, procs) {
  6244. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6245. continue;
  6246. }
  6247. Entity *proc = procs[i];
  6248. Type *t = base_type(proc->type);
  6249. if (t == t_invalid) continue;
  6250. String prefix = {};
  6251. String prefix_sep = {};
  6252. if (proc->pkg) {
  6253. prefix = proc->pkg->name;
  6254. prefix_sep = str_lit(".");
  6255. }
  6256. String name = proc->token.string;
  6257. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  6258. gbString pt;
  6259. if (t->Proc.node != nullptr) {
  6260. pt = expr_to_string(t->Proc.node);
  6261. } else {
  6262. pt = type_to_string(t);
  6263. }
  6264. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  6265. gb_string_free(pt);
  6266. }
  6267. isize max_spaces = gb_max(max_name_length, max_type_length);
  6268. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  6269. for (isize i = 0; i < max_spaces; i++) {
  6270. spaces[i] = ' ';
  6271. }
  6272. spaces[max_spaces] = 0;
  6273. for_array(i, procs) {
  6274. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6275. continue;
  6276. }
  6277. Entity *proc = procs[i];
  6278. TokenPos pos = proc->token.pos;
  6279. Type *t = base_type(proc->type);
  6280. if (t == t_invalid) continue;
  6281. GB_ASSERT(t->kind == Type_Proc);
  6282. gbString pt;
  6283. defer (gb_string_free(pt));
  6284. if (t->Proc.node != nullptr) {
  6285. pt = expr_to_string(t->Proc.node);
  6286. } else {
  6287. pt = type_to_string(t);
  6288. }
  6289. String prefix = {};
  6290. String prefix_sep = {};
  6291. if (proc->pkg) {
  6292. prefix = proc->pkg->name;
  6293. prefix_sep = str_lit(".");
  6294. }
  6295. String name = proc->token.string;
  6296. isize len = prefix.len + prefix_sep.len + name.len;
  6297. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  6298. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  6299. char const *sep = "::";
  6300. if (proc->kind == Entity_Variable) {
  6301. sep = ":=";
  6302. }
  6303. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  6304. LIT(prefix), LIT(prefix_sep), LIT(name),
  6305. name_padding, spaces,
  6306. sep,
  6307. pt,
  6308. type_padding, spaces,
  6309. token_pos_to_string(pos)
  6310. );
  6311. }
  6312. if (procs.count > 0) {
  6313. error_line("\n");
  6314. }
  6315. data.result_type = t_invalid;
  6316. } else if (valids.count > 1) {
  6317. ERROR_BLOCK();
  6318. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  6319. if (positional_operands.count == 0 && named_operands.count == 0) {
  6320. error_line("\tNo given arguments\n");
  6321. } else {
  6322. print_argument_types();
  6323. }
  6324. for (auto const &valid : valids) {
  6325. Entity *proc = proc_entities[valid.index];
  6326. GB_ASSERT(proc != nullptr);
  6327. TokenPos pos = proc->token.pos;
  6328. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  6329. gbString pt = nullptr;
  6330. defer (gb_string_free(pt));
  6331. if (t->Proc.node != nullptr) {
  6332. pt = expr_to_string(t->Proc.node);
  6333. } else {
  6334. pt = type_to_string(t);
  6335. }
  6336. String name = proc->token.string;
  6337. char const *sep = "::";
  6338. if (proc->kind == Entity_Variable) {
  6339. sep = ":=";
  6340. }
  6341. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  6342. if (proc->decl_info->proc_lit != nullptr) {
  6343. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  6344. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  6345. if (pl->where_token.kind != Token_Invalid) {
  6346. error_line("\n\t\twhere ");
  6347. for_array(j, pl->where_clauses) {
  6348. Ast *clause = pl->where_clauses[j];
  6349. if (j != 0) {
  6350. error_line("\t\t ");
  6351. }
  6352. gbString str = expr_to_string(clause);
  6353. error_line("%s", str);
  6354. gb_string_free(str);
  6355. if (j != pl->where_clauses.count-1) {
  6356. error_line(",");
  6357. }
  6358. }
  6359. error_line("\n\t");
  6360. }
  6361. }
  6362. error_line("at %s\n", token_pos_to_string(pos));
  6363. }
  6364. data.result_type = t_invalid;
  6365. } else {
  6366. GB_ASSERT(valids.count == 1);
  6367. Ast *ident = operand->expr;
  6368. while (ident->kind == Ast_SelectorExpr) {
  6369. Ast *s = ident->SelectorExpr.selector;
  6370. ident = s;
  6371. }
  6372. Entity *e = proc_entities[valids[0].index];
  6373. GB_ASSERT(e != nullptr);
  6374. Array<Operand> named_operands = {};
  6375. check_call_arguments_single(c, call, operand,
  6376. e, e->type,
  6377. positional_operands, named_operands,
  6378. CallArgumentErrorMode::ShowErrors,
  6379. &data);
  6380. return data;
  6381. }
  6382. return data;
  6383. }
  6384. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  6385. Type *proc_type = nullptr;
  6386. CallArgumentData data = {};
  6387. data.result_type = t_invalid;
  6388. proc_type = base_type(operand->type);
  6389. TypeProc *pt = nullptr;
  6390. if (proc_type) {
  6391. pt = &proc_type->Proc;
  6392. }
  6393. TEMPORARY_ALLOCATOR_GUARD();
  6394. ast_node(ce, CallExpr, call);
  6395. bool any_failure = false;
  6396. // Split positional and named args into separate arrays/slices
  6397. Slice<Ast *> positional_args = {};
  6398. Slice<Ast *> named_args = {};
  6399. if (ce->split_args == nullptr) {
  6400. positional_args = ce->args;
  6401. for (isize i = 0; i < ce->args.count; i++) {
  6402. Ast *arg = ce->args.data[i];
  6403. if (arg->kind == Ast_FieldValue) {
  6404. positional_args.count = i;
  6405. break;
  6406. }
  6407. }
  6408. named_args = slice(ce->args, positional_args.count, ce->args.count);
  6409. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  6410. split_args->positional = positional_args;
  6411. split_args->named = named_args;
  6412. ce->split_args = split_args;
  6413. } else {
  6414. positional_args = ce->split_args->positional;
  6415. named_args = ce->split_args->named;
  6416. }
  6417. if (operand->mode == Addressing_ProcGroup) {
  6418. return check_call_arguments_proc_group(c, operand, call);
  6419. }
  6420. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  6421. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6422. defer (array_free(&positional_operands));
  6423. defer (array_free(&named_operands));
  6424. if (positional_args.count > 0) {
  6425. isize lhs_count = -1;
  6426. bool is_variadic = false;
  6427. Entity **lhs = nullptr;
  6428. if (pt != nullptr) {
  6429. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count, &is_variadic);
  6430. }
  6431. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, is_variadic ? UnpackFlag_IsVariadic : UnpackFlag_None);
  6432. }
  6433. if (named_args.count > 0) {
  6434. for_array(i, named_args) {
  6435. Ast *arg = named_args[i];
  6436. if (arg->kind != Ast_FieldValue) {
  6437. error(arg, "Expected a 'field = value'");
  6438. return data;
  6439. }
  6440. ast_node(fv, FieldValue, arg);
  6441. if (fv->field->kind != Ast_Ident) {
  6442. gbString expr_str = expr_to_string(fv->field);
  6443. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6444. any_failure = true;
  6445. gb_string_free(expr_str);
  6446. continue;
  6447. }
  6448. String key = fv->field->Ident.token.string;
  6449. Ast *value = fv->value;
  6450. isize param_index = lookup_procedure_parameter(pt, key);
  6451. Type *type_hint = nullptr;
  6452. if (param_index >= 0) {
  6453. Entity *e = pt->params->Tuple.variables[param_index];
  6454. type_hint = e->type;
  6455. }
  6456. Operand o = {};
  6457. check_expr_with_type_hint(c, &o, value, type_hint);
  6458. if (o.mode == Addressing_Invalid) {
  6459. any_failure = true;
  6460. }
  6461. array_add(&named_operands, o);
  6462. }
  6463. }
  6464. if (!any_failure) {
  6465. check_call_arguments_single(c, call, operand,
  6466. nullptr, proc_type,
  6467. positional_operands, named_operands,
  6468. CallArgumentErrorMode::ShowErrors,
  6469. &data);
  6470. } else if (pt) {
  6471. data.result_type = pt->results;
  6472. }
  6473. return data;
  6474. }
  6475. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6476. if (!is_type_polymorphic_record(t)) {
  6477. return -1;
  6478. }
  6479. TypeTuple *params = get_record_polymorphic_params(t);
  6480. if (params == nullptr) {
  6481. return -1;
  6482. }
  6483. for_array(i, params->variables) {
  6484. Entity *e = params->variables[i];
  6485. String name = e->token.string;
  6486. if (is_blank_ident(name)) {
  6487. continue;
  6488. }
  6489. if (name == parameter_name) {
  6490. return i;
  6491. }
  6492. }
  6493. return -1;
  6494. }
  6495. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6496. ast_node(ce, CallExpr, call);
  6497. Type *original_type = operand->type;
  6498. GB_ASSERT(is_type_polymorphic_record(original_type));
  6499. bool show_error = true;
  6500. Array<Operand> operands = {};
  6501. defer (array_free(&operands));
  6502. CallArgumentError err = CallArgumentError_None;
  6503. bool named_fields = false;
  6504. {
  6505. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6506. auto prev_type_path = c->type_path;
  6507. c->type_path = new_checker_type_path();
  6508. defer ({
  6509. destroy_checker_type_path(c->type_path);
  6510. c->type_path = prev_type_path;
  6511. });
  6512. if (is_call_expr_field_value(ce)) {
  6513. named_fields = true;
  6514. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6515. for_array(i, ce->args) {
  6516. Ast *arg = ce->args[i];
  6517. ast_node(fv, FieldValue, arg);
  6518. if (fv->value == nullptr) {
  6519. error(fv->eq, "Expected a value");
  6520. err = CallArgumentError_InvalidFieldValue;
  6521. continue;
  6522. }
  6523. if (fv->field->kind == Ast_Ident) {
  6524. String name = fv->field->Ident.token.string;
  6525. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6526. if (index >= 0) {
  6527. TypeTuple *params = get_record_polymorphic_params(original_type);
  6528. Entity *e = params->variables[index];
  6529. if (e->kind == Entity_Constant) {
  6530. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6531. continue;
  6532. }
  6533. }
  6534. }
  6535. check_expr_or_type(c, &operands[i], fv->value);
  6536. }
  6537. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6538. if (vari_expand) {
  6539. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6540. }
  6541. } else {
  6542. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6543. Entity **lhs = nullptr;
  6544. isize lhs_count = -1;
  6545. TypeTuple *params = get_record_polymorphic_params(original_type);
  6546. if (params != nullptr) {
  6547. lhs = params->variables.data;
  6548. lhs_count = params->variables.count;
  6549. }
  6550. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6551. }
  6552. }
  6553. if (err != 0) {
  6554. operand->mode = Addressing_Invalid;
  6555. return err;
  6556. }
  6557. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6558. isize param_count = tuple->variables.count;
  6559. isize minimum_param_count = param_count;
  6560. for (; minimum_param_count > 0; minimum_param_count--) {
  6561. Entity *e = tuple->variables[minimum_param_count-1];
  6562. if (e->kind != Entity_Constant) {
  6563. break;
  6564. }
  6565. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6566. break;
  6567. }
  6568. }
  6569. Array<Operand> ordered_operands = operands;
  6570. if (!named_fields) {
  6571. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6572. array_copy(&ordered_operands, operands, 0);
  6573. } else {
  6574. TEMPORARY_ALLOCATOR_GUARD();
  6575. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6576. // LEAK(bill)
  6577. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6578. for_array(i, ce->args) {
  6579. Ast *arg = ce->args[i];
  6580. ast_node(fv, FieldValue, arg);
  6581. if (fv->field->kind != Ast_Ident) {
  6582. if (show_error) {
  6583. gbString expr_str = expr_to_string(fv->field);
  6584. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6585. gb_string_free(expr_str);
  6586. }
  6587. err = CallArgumentError_InvalidFieldValue;
  6588. continue;
  6589. }
  6590. String name = fv->field->Ident.token.string;
  6591. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6592. if (index < 0) {
  6593. if (show_error) {
  6594. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6595. }
  6596. err = CallArgumentError_ParameterNotFound;
  6597. continue;
  6598. }
  6599. if (visited[index]) {
  6600. if (show_error) {
  6601. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6602. }
  6603. err = CallArgumentError_DuplicateParameter;
  6604. continue;
  6605. }
  6606. visited[index] = true;
  6607. ordered_operands[index] = operands[i];
  6608. }
  6609. for (isize i = 0; i < param_count; i++) {
  6610. if (!visited[i]) {
  6611. Entity *e = tuple->variables[i];
  6612. if (is_blank_ident(e->token)) {
  6613. continue;
  6614. }
  6615. if (show_error) {
  6616. if (e->kind == Entity_TypeName) {
  6617. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6618. LIT(e->token.string));
  6619. } else {
  6620. gbString str = type_to_string(e->type);
  6621. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6622. LIT(e->token.string), str);
  6623. gb_string_free(str);
  6624. }
  6625. }
  6626. err = CallArgumentError_ParameterMissing;
  6627. }
  6628. }
  6629. }
  6630. if (err != 0) {
  6631. operand->mode = Addressing_Invalid;
  6632. return err;
  6633. }
  6634. while (ordered_operands.count > 0) {
  6635. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6636. break;
  6637. }
  6638. array_pop(&ordered_operands);
  6639. }
  6640. if (minimum_param_count != param_count) {
  6641. if (param_count < ordered_operands.count) {
  6642. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6643. err = CallArgumentError_TooManyArguments;
  6644. } else if (minimum_param_count > ordered_operands.count) {
  6645. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6646. err = CallArgumentError_TooFewArguments;
  6647. }
  6648. } else {
  6649. if (param_count < ordered_operands.count) {
  6650. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6651. err = CallArgumentError_TooManyArguments;
  6652. } else if (param_count > ordered_operands.count) {
  6653. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6654. err = CallArgumentError_TooFewArguments;
  6655. }
  6656. }
  6657. if (err != 0) {
  6658. return err;
  6659. }
  6660. if (minimum_param_count != param_count) {
  6661. array_resize(&ordered_operands, param_count);
  6662. isize missing_count = 0;
  6663. // NOTE(bill): Replace missing operands with the default values (if possible)
  6664. for_array(i, ordered_operands) {
  6665. Operand *o = &ordered_operands[i];
  6666. if (o->expr == nullptr) {
  6667. Entity *e = tuple->variables[i];
  6668. if (e->kind == Entity_Constant) {
  6669. missing_count += 1;
  6670. o->mode = Addressing_Constant;
  6671. o->type = default_type(e->type);
  6672. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6673. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6674. o->value = e->Constant.param_value.value;
  6675. }
  6676. } else if (e->kind == Entity_TypeName) {
  6677. missing_count += 1;
  6678. o->mode = Addressing_Type;
  6679. o->type = e->type;
  6680. o->expr = e->identifier;
  6681. }
  6682. }
  6683. }
  6684. }
  6685. isize oo_count = gb_min(param_count, ordered_operands.count);
  6686. i64 score = 0;
  6687. for (isize i = 0; i < oo_count; i++) {
  6688. Entity *e = tuple->variables[i];
  6689. Operand *o = &ordered_operands[i];
  6690. if (o->mode == Addressing_Invalid) {
  6691. continue;
  6692. }
  6693. if (e->kind == Entity_TypeName) {
  6694. if (o->mode != Addressing_Type) {
  6695. if (show_error) {
  6696. gbString expr = expr_to_string(o->expr);
  6697. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6698. gb_string_free(expr);
  6699. }
  6700. err = CallArgumentError_WrongTypes;
  6701. }
  6702. if (are_types_identical(e->type, o->type)) {
  6703. score += assign_score_function(1);
  6704. } else {
  6705. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6706. }
  6707. } else {
  6708. i64 s = 0;
  6709. if (o->type->kind == Type_Generic) {
  6710. // Polymorphic name!
  6711. score += assign_score_function(1);
  6712. continue;
  6713. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6714. if (show_error) {
  6715. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6716. }
  6717. err = CallArgumentError_WrongTypes;
  6718. }
  6719. o->type = e->type;
  6720. if (o->mode != Addressing_Constant) {
  6721. bool valid = false;
  6722. if (is_type_proc(o->type)) {
  6723. Entity *proc_entity = entity_from_expr(o->expr);
  6724. valid = proc_entity != nullptr;
  6725. }
  6726. if (!valid) {
  6727. if (show_error) {
  6728. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6729. }
  6730. err = CallArgumentError_NoneConstantParameter;
  6731. }
  6732. }
  6733. score += s;
  6734. }
  6735. // NOTE(bill): Add type info the parameters
  6736. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6737. // add_type_info_type(c, o->type);
  6738. }
  6739. if (show_error && err) {
  6740. return err;
  6741. }
  6742. {
  6743. GenTypesData *found_gen_types = ensure_polymorphic_record_entity_has_gen_types(c, original_type);
  6744. mutex_lock(&found_gen_types->mutex);
  6745. defer (mutex_unlock(&found_gen_types->mutex));
  6746. Entity *found_entity = find_polymorphic_record_entity(found_gen_types, param_count, ordered_operands);
  6747. if (found_entity) {
  6748. operand->mode = Addressing_Type;
  6749. operand->type = found_entity->type;
  6750. return err;
  6751. }
  6752. CheckerContext ctx = *c;
  6753. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6754. ctx.scope = polymorphic_record_parent_scope(original_type);
  6755. GB_ASSERT(ctx.scope != nullptr);
  6756. Type *bt = base_type(original_type);
  6757. String generated_name = make_string_c(expr_to_string(call));
  6758. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6759. if (bt->kind == Type_Struct) {
  6760. Ast *node = clone_ast(bt->Struct.node);
  6761. Type *struct_type = alloc_type_struct();
  6762. struct_type->Struct.node = node;
  6763. struct_type->Struct.polymorphic_parent = original_type;
  6764. set_base_type(named_type, struct_type);
  6765. check_open_scope(&ctx, node);
  6766. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6767. check_close_scope(&ctx);
  6768. } else if (bt->kind == Type_Union) {
  6769. Ast *node = clone_ast(bt->Union.node);
  6770. Type *union_type = alloc_type_union();
  6771. union_type->Union.node = node;
  6772. union_type->Union.polymorphic_parent = original_type;
  6773. set_base_type(named_type, union_type);
  6774. check_open_scope(&ctx, node);
  6775. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6776. check_close_scope(&ctx);
  6777. } else {
  6778. GB_PANIC("Unsupported parametric polymorphic record type");
  6779. }
  6780. bt = base_type(named_type);
  6781. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6782. GB_ASSERT(original_type->kind == Type_Named);
  6783. Entity *e = original_type->Named.type_name;
  6784. GB_ASSERT(e->kind == Entity_TypeName);
  6785. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6786. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6787. TypeTuple *tuple = get_record_polymorphic_params(bt);
  6788. if (tuple != nullptr) for_array(i, tuple->variables) {
  6789. Entity *v = tuple->variables[i];
  6790. String name = v->token.string;
  6791. if (i > 0) {
  6792. s = gb_string_append_fmt(s, ", ");
  6793. }
  6794. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6795. if (v->kind == Entity_TypeName) {
  6796. if (v->type->kind != Type_Generic) {
  6797. s = gb_string_append_fmt(s, "=");
  6798. s = write_type_to_string(s, v->type, false);
  6799. }
  6800. } else if (v->kind == Entity_Constant) {
  6801. if (v->Constant.value.kind != ExactValue_Invalid) {
  6802. s = gb_string_append_fmt(s, "=");
  6803. s = write_exact_value_to_string(s, v->Constant.value);
  6804. }
  6805. }
  6806. }
  6807. s = gb_string_append_fmt(s, ")");
  6808. String new_name = make_string_c(s);
  6809. named_type->Named.name = new_name;
  6810. if (named_type->Named.type_name) {
  6811. named_type->Named.type_name->token.string = new_name;
  6812. }
  6813. }
  6814. operand->mode = Addressing_Type;
  6815. operand->type = named_type;
  6816. }
  6817. return err;
  6818. }
  6819. // returns true on success
  6820. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6821. bool success = true;
  6822. if (args.count > 0) {
  6823. if (allow_mixed) {
  6824. bool was_named = false;
  6825. for (Ast *arg : args) {
  6826. if (was_named && arg->kind != Ast_FieldValue) {
  6827. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6828. success = false;
  6829. break;
  6830. }
  6831. was_named = was_named || arg->kind == Ast_FieldValue;
  6832. }
  6833. } else {
  6834. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6835. for (Ast *arg : args) {
  6836. bool mix = false;
  6837. if (first_is_field_value) {
  6838. mix = arg->kind != Ast_FieldValue;
  6839. } else {
  6840. mix = arg->kind == Ast_FieldValue;
  6841. }
  6842. if (mix) {
  6843. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6844. success = false;
  6845. }
  6846. }
  6847. }
  6848. }
  6849. return success;
  6850. }
  6851. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6852. operand->mode = Addressing_Invalid; \
  6853. operand->expr = call; \
  6854. return Expr_Stmt; \
  6855. }
  6856. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6857. if (proc != nullptr &&
  6858. proc->kind == Ast_BasicDirective) {
  6859. ast_node(bd, BasicDirective, proc);
  6860. String name = bd->name.string;
  6861. if (
  6862. name == "location" ||
  6863. name == "exists" ||
  6864. name == "assert" ||
  6865. name == "panic" ||
  6866. name == "defined" ||
  6867. name == "config" ||
  6868. name == "load" ||
  6869. name == "load_directory" ||
  6870. name == "load_hash" ||
  6871. name == "hash" ||
  6872. name == "caller_expression"
  6873. ) {
  6874. operand->mode = Addressing_Builtin;
  6875. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6876. operand->expr = proc;
  6877. operand->type = t_invalid;
  6878. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6879. } else {
  6880. error(proc, "Unknown directive: #%.*s", LIT(name));
  6881. operand->expr = proc;
  6882. operand->type = t_invalid;
  6883. operand->mode = Addressing_Invalid;
  6884. return Expr_Expr;
  6885. }
  6886. if (inlining != ProcInlining_none) {
  6887. error(call, "Inlining operators are not allowed on built-in procedures");
  6888. }
  6889. } else {
  6890. if (proc != nullptr) {
  6891. check_expr_or_type(c, operand, proc);
  6892. } else {
  6893. GB_ASSERT(operand->expr != nullptr);
  6894. }
  6895. }
  6896. if (operand->mode == Addressing_Invalid) {
  6897. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6898. for (Ast *arg : args) {
  6899. if (arg->kind == Ast_FieldValue) {
  6900. arg = arg->FieldValue.value;
  6901. }
  6902. check_expr_base(c, operand, arg, nullptr);
  6903. }
  6904. operand->mode = Addressing_Invalid;
  6905. operand->expr = call;
  6906. return Expr_Stmt;
  6907. }
  6908. if (operand->mode == Addressing_Type) {
  6909. Type *t = operand->type;
  6910. if (is_type_polymorphic_record(t)) {
  6911. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6912. if (!is_type_named(t)) {
  6913. gbString s = expr_to_string(operand->expr);
  6914. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6915. gb_string_free(s);
  6916. operand->mode = Addressing_Invalid;
  6917. operand->type = t_invalid;;
  6918. return Expr_Expr;
  6919. }
  6920. auto err = check_polymorphic_record_type(c, operand, call);
  6921. if (err == 0) {
  6922. Ast *ident = operand->expr;
  6923. while (ident->kind == Ast_SelectorExpr) {
  6924. Ast *s = ident->SelectorExpr.selector;
  6925. ident = s;
  6926. }
  6927. Type *ot = operand->type;
  6928. GB_ASSERT(ot->kind == Type_Named);
  6929. Entity *e = ot->Named.type_name;
  6930. add_entity_use(c, ident, e);
  6931. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6932. } else {
  6933. operand->mode = Addressing_Invalid;
  6934. operand->type = t_invalid;
  6935. }
  6936. } else {
  6937. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6938. operand->mode = Addressing_Invalid;
  6939. isize arg_count = args.count;
  6940. switch (arg_count) {
  6941. case 0:
  6942. {
  6943. gbString str = type_to_string(t);
  6944. error(call, "Missing argument in conversion to '%s'", str);
  6945. gb_string_free(str);
  6946. } break;
  6947. default:
  6948. {
  6949. gbString str = type_to_string(t);
  6950. error(call, "Too many arguments in conversion to '%s'", str);
  6951. gb_string_free(str);
  6952. } break;
  6953. case 1: {
  6954. Ast *arg = args[0];
  6955. if (arg->kind == Ast_FieldValue) {
  6956. error(call, "'field = value' cannot be used in a type conversion");
  6957. arg = arg->FieldValue.value;
  6958. // NOTE(bill): Carry on the cast regardless
  6959. }
  6960. check_expr_with_type_hint(c, operand, arg, t);
  6961. if (operand->mode != Addressing_Invalid) {
  6962. if (is_type_polymorphic(t)) {
  6963. error(call, "A polymorphic type cannot be used in a type conversion");
  6964. } else {
  6965. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  6966. // as it assumes it is determining the type
  6967. check_cast(c, operand, t);
  6968. }
  6969. }
  6970. operand->type = t;
  6971. operand->expr = call;
  6972. if (operand->mode != Addressing_Invalid) {
  6973. update_untyped_expr_type(c, arg, t, false);
  6974. }
  6975. break;
  6976. }
  6977. }
  6978. }
  6979. return Expr_Expr;
  6980. }
  6981. if (operand->mode == Addressing_Builtin) {
  6982. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  6983. i32 id = operand->builtin_id;
  6984. Entity *e = entity_of_node(operand->expr);
  6985. if (e != nullptr && e->token.string == "expand_to_tuple") {
  6986. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  6987. }
  6988. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  6989. operand->mode = Addressing_Invalid;
  6990. operand->type = t_invalid;
  6991. }
  6992. operand->expr = call;
  6993. return builtin_procs[id].kind;
  6994. }
  6995. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  6996. Entity *initial_entity = entity_of_node(operand->expr);
  6997. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  6998. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  6999. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  7000. if (c->decl) {
  7001. c->decl->defer_used += 1;
  7002. }
  7003. }
  7004. add_entity_use(c, operand->expr, initial_entity);
  7005. if (initial_entity->Procedure.entry_point_only) {
  7006. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  7007. // Okay
  7008. } else {
  7009. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  7010. }
  7011. }
  7012. }
  7013. if (operand->mode != Addressing_ProcGroup) {
  7014. Type *proc_type = base_type(operand->type);
  7015. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  7016. bool valid_mode = is_operand_value(*operand);
  7017. if (!valid_type || !valid_mode) {
  7018. Ast *e = operand->expr;
  7019. gbString str = expr_to_string(e);
  7020. gbString type_str = type_to_string(operand->type);
  7021. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  7022. gb_string_free(type_str);
  7023. gb_string_free(str);
  7024. operand->mode = Addressing_Invalid;
  7025. operand->expr = call;
  7026. return Expr_Stmt;
  7027. }
  7028. }
  7029. CallArgumentData data = check_call_arguments(c, operand, call);
  7030. Type *result_type = data.result_type;
  7031. gb_zero_item(operand);
  7032. operand->expr = call;
  7033. if (result_type == t_invalid) {
  7034. operand->mode = Addressing_Invalid;
  7035. operand->type = t_invalid;
  7036. return Expr_Stmt;
  7037. }
  7038. Type *pt = base_type(operand->type);
  7039. if (pt == nullptr) {
  7040. pt = t_invalid;
  7041. }
  7042. if (pt == t_invalid) {
  7043. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7044. pt = type_of_expr(operand->expr->CallExpr.proc);
  7045. }
  7046. if (pt == t_invalid && data.gen_entity) {
  7047. pt = data.gen_entity->type;
  7048. }
  7049. }
  7050. pt = base_type(pt);
  7051. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  7052. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  7053. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  7054. }
  7055. }
  7056. if (result_type == nullptr) {
  7057. operand->mode = Addressing_NoValue;
  7058. } else {
  7059. GB_ASSERT(is_type_tuple(result_type));
  7060. isize count = result_type->Tuple.variables.count;
  7061. switch (count) {
  7062. case 0:
  7063. operand->mode = Addressing_NoValue;
  7064. break;
  7065. case 1:
  7066. operand->mode = Addressing_Value;
  7067. operand->type = result_type->Tuple.variables[0]->type;
  7068. break;
  7069. default:
  7070. operand->mode = Addressing_Value;
  7071. operand->type = result_type;
  7072. break;
  7073. }
  7074. }
  7075. bool is_call_inlined = false;
  7076. switch (inlining) {
  7077. case ProcInlining_inline:
  7078. is_call_inlined = true;
  7079. if (proc != nullptr) {
  7080. Entity *e = entity_from_expr(proc);
  7081. if (e != nullptr && e->kind == Entity_Procedure) {
  7082. DeclInfo *decl = e->decl_info;
  7083. if (decl->proc_lit) {
  7084. ast_node(pl, ProcLit, decl->proc_lit);
  7085. if (pl->inlining == ProcInlining_no_inline) {
  7086. error(call, "'#force_inline' cannot be applied to a procedure that has been marked as '#force_no_inline'");
  7087. }
  7088. }
  7089. }
  7090. }
  7091. break;
  7092. case ProcInlining_no_inline:
  7093. break;
  7094. case ProcInlining_none:
  7095. if (proc != nullptr) {
  7096. Entity *e = entity_from_expr(proc);
  7097. if (e != nullptr && e->kind == Entity_Procedure) {
  7098. DeclInfo *decl = e->decl_info;
  7099. if (decl->proc_lit) {
  7100. ast_node(pl, ProcLit, decl->proc_lit);
  7101. if (pl->inlining == ProcInlining_inline) {
  7102. is_call_inlined = true;
  7103. }
  7104. }
  7105. }
  7106. }
  7107. }
  7108. {
  7109. String invalid;
  7110. if (pt->kind == Type_Proc && pt->Proc.require_target_feature.len != 0) {
  7111. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.require_target_feature, &invalid)) {
  7112. error(call, "Called procedure requires target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7113. } else if (!check_target_feature_is_enabled(pt->Proc.require_target_feature, &invalid)) {
  7114. error(call, "Calling this procedure requires target feature '%.*s' to be enabled", LIT(invalid));
  7115. }
  7116. }
  7117. if (pt->kind == Type_Proc && pt->Proc.enable_target_feature.len != 0) {
  7118. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.enable_target_feature, &invalid)) {
  7119. error(call, "Called procedure enables target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7120. }
  7121. // NOTE: Due to restrictions in LLVM you can not inline calls with a superset of features.
  7122. if (is_call_inlined) {
  7123. if (c->curr_proc_decl == nullptr) {
  7124. error(call, "Calling a '#force_inline' procedure that enables target features is not allowed at file scope");
  7125. } else {
  7126. GB_ASSERT(c->curr_proc_decl->entity);
  7127. GB_ASSERT(c->curr_proc_decl->entity->type->kind == Type_Proc);
  7128. String scope_features = c->curr_proc_decl->entity->type->Proc.enable_target_feature;
  7129. if (!check_target_feature_is_superset_of(scope_features, pt->Proc.enable_target_feature, &invalid)) {
  7130. ERROR_BLOCK();
  7131. error(call, "Inlined procedure enables target feature '%.*s', this requires the calling procedure to at least enable the same feature", LIT(invalid));
  7132. error_line("\tSuggested Example: @(enable_target_feature=\"%.*s\")\n", LIT(invalid));
  7133. }
  7134. }
  7135. }
  7136. }
  7137. }
  7138. operand->expr = call;
  7139. {
  7140. Type *type = nullptr;
  7141. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7142. type = type_of_expr(operand->expr->CallExpr.proc);
  7143. }
  7144. if (type == nullptr) {
  7145. type = pt;
  7146. }
  7147. type = base_type(type);
  7148. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  7149. operand->mode = Addressing_OptionalOk;
  7150. operand->type = type->Proc.results->Tuple.variables[0]->type;
  7151. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7152. operand->expr->CallExpr.optional_ok_one = true;
  7153. }
  7154. }
  7155. }
  7156. return Expr_Expr;
  7157. }
  7158. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  7159. check_expr_base(c, o, e, t);
  7160. check_not_tuple(c, o);
  7161. char const *err_str = nullptr;
  7162. switch (o->mode) {
  7163. case Addressing_NoValue:
  7164. err_str = "used as a value";
  7165. break;
  7166. case Addressing_Type:
  7167. if (t == nullptr || !is_type_typeid(t)) {
  7168. err_str = "is not an expression but a type, in this context it is ambiguous";
  7169. }
  7170. break;
  7171. case Addressing_Builtin:
  7172. err_str = "must be called";
  7173. break;
  7174. }
  7175. if (err_str != nullptr) {
  7176. gbString str = expr_to_string(e);
  7177. error(e, "'%s' %s", str, err_str);
  7178. gb_string_free(str);
  7179. o->mode = Addressing_Invalid;
  7180. }
  7181. }
  7182. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  7183. switch (t->kind) {
  7184. case Type_Basic:
  7185. if (t->Basic.kind == Basic_string) {
  7186. if (o->mode == Addressing_Constant) {
  7187. *max_count = o->value.value_string.len;
  7188. }
  7189. if (o->mode != Addressing_Constant) {
  7190. o->mode = Addressing_Value;
  7191. }
  7192. o->type = t_u8;
  7193. return true;
  7194. } else if (t->Basic.kind == Basic_UntypedString) {
  7195. if (o->mode == Addressing_Constant) {
  7196. *max_count = o->value.value_string.len;
  7197. o->type = t_u8;
  7198. return true;
  7199. }
  7200. return false;
  7201. }
  7202. break;
  7203. case Type_MultiPointer:
  7204. o->type = t->MultiPointer.elem;
  7205. if (o->mode != Addressing_Constant) {
  7206. o->mode = Addressing_Variable;
  7207. }
  7208. return true;
  7209. case Type_Array:
  7210. *max_count = t->Array.count;
  7211. if (indirection) {
  7212. o->mode = Addressing_Variable;
  7213. } else if (o->mode != Addressing_Variable &&
  7214. o->mode != Addressing_Constant) {
  7215. o->mode = Addressing_Value;
  7216. }
  7217. o->type = t->Array.elem;
  7218. return true;
  7219. case Type_EnumeratedArray:
  7220. *max_count = t->EnumeratedArray.count;
  7221. if (indirection) {
  7222. o->mode = Addressing_Variable;
  7223. } else if (o->mode != Addressing_Variable &&
  7224. o->mode != Addressing_Constant) {
  7225. o->mode = Addressing_Value;
  7226. }
  7227. o->type = t->EnumeratedArray.elem;
  7228. return true;
  7229. case Type_Matrix:
  7230. if (indirection) {
  7231. o->mode = Addressing_Variable;
  7232. } else if (o->mode != Addressing_Variable) {
  7233. o->mode = Addressing_Value;
  7234. }
  7235. if (t->Matrix.is_row_major) {
  7236. *max_count = t->Matrix.row_count;
  7237. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.column_count);
  7238. } else {
  7239. *max_count = t->Matrix.column_count;
  7240. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  7241. }
  7242. return true;
  7243. case Type_Slice:
  7244. o->type = t->Slice.elem;
  7245. if (o->mode != Addressing_Constant) {
  7246. o->mode = Addressing_Variable;
  7247. }
  7248. return true;
  7249. case Type_DynamicArray:
  7250. o->type = t->DynamicArray.elem;
  7251. if (o->mode != Addressing_Constant) {
  7252. o->mode = Addressing_Variable;
  7253. }
  7254. return true;
  7255. case Type_Struct:
  7256. if (t->Struct.soa_kind != StructSoa_None) {
  7257. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7258. *max_count = t->Struct.soa_count;
  7259. }
  7260. o->type = t->Struct.soa_elem;
  7261. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  7262. o->mode = Addressing_SoaVariable;
  7263. } else {
  7264. o->mode = Addressing_Value;
  7265. }
  7266. return true;
  7267. }
  7268. return false;
  7269. }
  7270. if (is_type_pointer(original_type) && indirection) {
  7271. Type *ptr = base_type(original_type);
  7272. if (ptr->kind == Type_MultiPointer && o->mode == Addressing_SoaVariable) {
  7273. o->type = ptr->MultiPointer.elem;
  7274. o->mode = Addressing_Value;
  7275. return true;
  7276. }
  7277. }
  7278. return false;
  7279. }
  7280. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  7281. if (is_type_untyped_uninit(x)) {
  7282. return true;
  7283. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  7284. return true;
  7285. } else if (is_type_untyped_uninit(y)) {
  7286. return true;
  7287. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  7288. return true;
  7289. }
  7290. return are_types_identical(x, y);
  7291. }
  7292. 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) {
  7293. if (!is_ast_range(node)) {
  7294. return false;
  7295. }
  7296. ast_node(ie, BinaryExpr, node);
  7297. check_expr_with_type_hint(c, x, ie->left, type_hint);
  7298. if (x->mode == Addressing_Invalid) {
  7299. return false;
  7300. }
  7301. check_expr_with_type_hint(c, y, ie->right, type_hint);
  7302. if (y->mode == Addressing_Invalid) {
  7303. return false;
  7304. }
  7305. convert_to_typed(c, x, y->type);
  7306. if (x->mode == Addressing_Invalid) {
  7307. return false;
  7308. }
  7309. convert_to_typed(c, y, x->type);
  7310. if (y->mode == Addressing_Invalid) {
  7311. return false;
  7312. }
  7313. convert_to_typed(c, x, default_type(y->type));
  7314. if (x->mode == Addressing_Invalid) {
  7315. return false;
  7316. }
  7317. convert_to_typed(c, y, default_type(x->type));
  7318. if (y->mode == Addressing_Invalid) {
  7319. return false;
  7320. }
  7321. if (!are_types_identical(x->type, y->type)) {
  7322. if (x->type != t_invalid &&
  7323. y->type != t_invalid) {
  7324. gbString xt = type_to_string(x->type);
  7325. gbString yt = type_to_string(y->type);
  7326. gbString expr_str = expr_to_string(x->expr);
  7327. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  7328. gb_string_free(expr_str);
  7329. gb_string_free(yt);
  7330. gb_string_free(xt);
  7331. }
  7332. return false;
  7333. }
  7334. Type *type = x->type;
  7335. if (is_for_loop) {
  7336. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  7337. error(ie->op, "Only numerical types are allowed within interval expressions");
  7338. return false;
  7339. }
  7340. } else {
  7341. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  7342. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  7343. return false;
  7344. }
  7345. }
  7346. if (x->mode == Addressing_Constant &&
  7347. y->mode == Addressing_Constant) {
  7348. ExactValue a = x->value;
  7349. ExactValue b = y->value;
  7350. GB_ASSERT(are_types_identical(x->type, y->type));
  7351. TokenKind op = Token_Lt;
  7352. switch (ie->op.kind) {
  7353. case Token_Ellipsis: op = Token_LtEq; break; // ..
  7354. case Token_RangeFull: op = Token_LtEq; break; // ..=
  7355. case Token_RangeHalf: op = Token_Lt; break; // ..<
  7356. default: error(ie->op, "Invalid range operator"); break;
  7357. }
  7358. bool ok = compare_exact_values(op, a, b);
  7359. if (!ok) {
  7360. // TODO(bill): Better error message
  7361. error(ie->op, "Invalid interval range");
  7362. return false;
  7363. }
  7364. ExactValue inline_for_depth = exact_value_sub(b, a);
  7365. if (ie->op.kind != Token_RangeHalf) {
  7366. inline_for_depth = exact_value_increment_one(inline_for_depth);
  7367. }
  7368. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  7369. } else if (inline_for_depth_ != nullptr) {
  7370. error(ie->op, "Interval expressions must be constant");
  7371. return false;
  7372. }
  7373. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  7374. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  7375. return true;
  7376. }
  7377. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  7378. if (is_operand_nil(*o)) {
  7379. return true;
  7380. }
  7381. Ast *expr = unparen_expr(o->expr);
  7382. if (expr != nullptr) {
  7383. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  7384. if (e != nullptr && e->kind == Entity_Procedure) {
  7385. return true;
  7386. }
  7387. if (expr->kind == Ast_ProcLit) {
  7388. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  7389. return true;
  7390. }
  7391. }
  7392. return o->mode == Addressing_Constant;
  7393. }
  7394. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  7395. if (is_type_enum(th)) {
  7396. Type *enum_type = base_type(th);
  7397. GB_ASSERT(enum_type->kind == Type_Enum);
  7398. String name = ise->selector->Ident.token.string;
  7399. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  7400. if (e == nullptr) {
  7401. return false;
  7402. }
  7403. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  7404. GB_ASSERT(e->kind == Entity_Constant);
  7405. o->value = e->Constant.value;
  7406. o->mode = Addressing_Constant;
  7407. o->type = e->type;
  7408. return true;
  7409. }
  7410. if (is_type_union(th)) {
  7411. TEMPORARY_ALLOCATOR_GUARD();
  7412. Type *union_type = base_type(th);
  7413. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  7414. for (Type *vt : union_type->Union.variants) {
  7415. Operand x = {};
  7416. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  7417. array_add(&operands, x);
  7418. }
  7419. }
  7420. if (operands.count == 1) {
  7421. *o = operands[0];
  7422. return true;
  7423. }
  7424. }
  7425. return false;
  7426. }
  7427. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7428. ast_node(ise, ImplicitSelectorExpr, node);
  7429. o->type = t_invalid;
  7430. o->expr = node;
  7431. o->mode = Addressing_Invalid;
  7432. Type *th = type_hint;
  7433. if (th == nullptr) {
  7434. gbString str = expr_to_string(node);
  7435. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  7436. gb_string_free(str);
  7437. return Expr_Expr;
  7438. }
  7439. o->type = th;
  7440. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  7441. if (!ok) {
  7442. String name = ise->selector->Ident.token.string;
  7443. if (is_type_enum(th)) {
  7444. ERROR_BLOCK();
  7445. Type *bt = base_type(th);
  7446. GB_ASSERT(bt->kind == Type_Enum);
  7447. gbString typ = type_to_string(th);
  7448. defer (gb_string_free(typ));
  7449. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  7450. check_did_you_mean_type(name, bt->Enum.fields);
  7451. } else if (is_type_bit_set(th) && is_type_enum(th->BitSet.elem)) {
  7452. ERROR_BLOCK();
  7453. gbString typ = type_to_string(th);
  7454. gbString str = expr_to_string(node);
  7455. error(node, "Cannot convert enum value to '%s'", typ);
  7456. error_line("\tSuggestion: Did you mean '{ %s }'?\n", str);
  7457. gb_string_free(typ);
  7458. gb_string_free(str);
  7459. } else {
  7460. gbString typ = type_to_string(th);
  7461. gbString str = expr_to_string(node);
  7462. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  7463. gb_string_free(str);
  7464. gb_string_free(typ);
  7465. }
  7466. }
  7467. o->expr = node;
  7468. return Expr_Expr;
  7469. }
  7470. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  7471. switch (x->mode) {
  7472. case Addressing_MapIndex:
  7473. case Addressing_OptionalOk:
  7474. case Addressing_OptionalOkPtr:
  7475. if (val_type_) *val_type_ = x->type;
  7476. break;
  7477. default:
  7478. if (ok_type_) *ok_type_ = x->type;
  7479. return;
  7480. }
  7481. Ast *expr = unparen_expr(x->expr);
  7482. if (expr->kind == Ast_CallExpr) {
  7483. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  7484. if (is_type_proc(pt)) {
  7485. Type *tuple = pt->Proc.results;
  7486. if (pt->Proc.result_count >= 2) {
  7487. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7488. }
  7489. if (change_operand) {
  7490. expr->CallExpr.optional_ok_one = false;
  7491. x->type = tuple;
  7492. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7493. }
  7494. return;
  7495. }
  7496. }
  7497. Type *tuple = make_optional_ok_type(x->type);
  7498. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7499. if (change_operand) {
  7500. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7501. x->type = tuple;
  7502. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  7503. }
  7504. }
  7505. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7506. ast_node(ie, MatrixIndexExpr, node);
  7507. check_expr(c, o, ie->expr);
  7508. node->viral_state_flags |= ie->expr->viral_state_flags;
  7509. if (o->mode == Addressing_Invalid) {
  7510. o->expr = node;
  7511. return;
  7512. }
  7513. Type *t = base_type(type_deref(o->type));
  7514. bool is_ptr = is_type_pointer(o->type);
  7515. bool is_const = o->mode == Addressing_Constant;
  7516. if (t->kind != Type_Matrix) {
  7517. gbString str = expr_to_string(o->expr);
  7518. gbString type_str = type_to_string(o->type);
  7519. defer (gb_string_free(str));
  7520. defer (gb_string_free(type_str));
  7521. if (is_const) {
  7522. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  7523. } else {
  7524. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  7525. }
  7526. o->mode = Addressing_Invalid;
  7527. o->expr = node;
  7528. return;
  7529. }
  7530. o->type = t->Matrix.elem;
  7531. if (is_ptr) {
  7532. o->mode = Addressing_Variable;
  7533. } else if (o->mode != Addressing_Variable) {
  7534. o->mode = Addressing_Value;
  7535. }
  7536. if (ie->row_index == nullptr) {
  7537. gbString str = expr_to_string(o->expr);
  7538. error(o->expr, "Missing row index for '%s'", str);
  7539. gb_string_free(str);
  7540. o->mode = Addressing_Invalid;
  7541. o->expr = node;
  7542. return;
  7543. }
  7544. if (ie->column_index == nullptr) {
  7545. gbString str = expr_to_string(o->expr);
  7546. error(o->expr, "Missing column index for '%s'", str);
  7547. gb_string_free(str);
  7548. o->mode = Addressing_Invalid;
  7549. o->expr = node;
  7550. return;
  7551. }
  7552. i64 row_count = t->Matrix.row_count;
  7553. i64 column_count = t->Matrix.column_count;
  7554. i64 row_index = 0;
  7555. i64 column_index = 0;
  7556. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7557. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7558. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7559. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7560. }
  7561. gb_unused(row_ok);
  7562. gb_unused(column_ok);
  7563. }
  7564. struct TypeAndToken {
  7565. Type *type;
  7566. Token token;
  7567. };
  7568. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7569. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7570. if (operand.mode != Addressing_Constant) {
  7571. return;
  7572. }
  7573. if (operand.value.kind == ExactValue_Invalid) {
  7574. return;
  7575. }
  7576. uintptr key = hash_exact_value(operand.value);
  7577. GB_ASSERT(key != 0);
  7578. isize count = multi_map_count(seen, key);
  7579. if (count) {
  7580. TEMPORARY_ALLOCATOR_GUARD();
  7581. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  7582. multi_map_get_all(seen, key, taps);
  7583. for (isize i = 0; i < count; i++) {
  7584. TypeAndToken tap = taps[i];
  7585. Operand to = {};
  7586. to.mode = Addressing_Value;
  7587. to.type = tap.type;
  7588. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7589. continue;
  7590. }
  7591. TokenPos pos = tap.token.pos;
  7592. if (use_expr) {
  7593. gbString expr_str = expr_to_string(operand.expr);
  7594. error(operand.expr,
  7595. "Duplicate case '%s'\n"
  7596. "\tprevious case at %s",
  7597. expr_str,
  7598. token_pos_to_string(pos));
  7599. gb_string_free(expr_str);
  7600. } else {
  7601. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7602. }
  7603. return;
  7604. }
  7605. }
  7606. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7607. multi_map_insert(seen, key, tap);
  7608. }
  7609. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7610. if (is_type_enum(x.type)) {
  7611. // TODO(bill): Fix this logic so it's fast!!!
  7612. i64 v0 = exact_value_to_i64(lhs.value);
  7613. i64 v1 = exact_value_to_i64(rhs.value);
  7614. Operand v = {};
  7615. v.mode = Addressing_Constant;
  7616. v.type = x.type;
  7617. v.expr = x.expr;
  7618. Type *bt = base_type(x.type);
  7619. GB_ASSERT(bt->kind == Type_Enum);
  7620. for (i64 vi = v0; vi <= v1; vi++) {
  7621. if (upper_op != Token_LtEq && vi == v1) {
  7622. break;
  7623. }
  7624. v.value = exact_value_i64(vi);
  7625. add_constant_switch_case(ctx, seen, v);
  7626. }
  7627. } else {
  7628. add_constant_switch_case(ctx, seen, lhs);
  7629. if (upper_op == Token_LtEq) {
  7630. add_constant_switch_case(ctx, seen, rhs);
  7631. }
  7632. }
  7633. }
  7634. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7635. add_constant_switch_case(ctx, seen, x);
  7636. }
  7637. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7638. ast_node(bd, BasicDirective, node);
  7639. ExprKind kind = Expr_Expr;
  7640. o->mode = Addressing_Constant;
  7641. String name = bd->name.string;
  7642. if (name == "file") {
  7643. String file = get_file_path_string(bd->token.pos.file_id);
  7644. if (build_context.obfuscate_source_code_locations) {
  7645. file = obfuscate_string(file, "F");
  7646. }
  7647. o->type = t_untyped_string;
  7648. o->value = exact_value_string(file);
  7649. } else if (name == "directory") {
  7650. String file = get_file_path_string(bd->token.pos.file_id);
  7651. String path = dir_from_path(file);
  7652. if (build_context.obfuscate_source_code_locations) {
  7653. path = obfuscate_string(path, "D");
  7654. }
  7655. o->type = t_untyped_string;
  7656. o->value = exact_value_string(path);
  7657. } else if (name == "line") {
  7658. i32 line = bd->token.pos.line;
  7659. if (build_context.obfuscate_source_code_locations) {
  7660. line = obfuscate_i32(line);
  7661. }
  7662. o->type = t_untyped_integer;
  7663. o->value = exact_value_i64(line);
  7664. } else if (name == "procedure") {
  7665. if (c->curr_proc_decl == nullptr) {
  7666. error(node, "#procedure may only be used within procedures");
  7667. o->type = t_untyped_string;
  7668. o->value = exact_value_string(str_lit(""));
  7669. } else {
  7670. String p = c->proc_name;
  7671. if (build_context.obfuscate_source_code_locations) {
  7672. p = obfuscate_string(p, "P");
  7673. }
  7674. o->type = t_untyped_string;
  7675. o->value = exact_value_string(p);
  7676. }
  7677. } else if (name == "caller_location") {
  7678. init_core_source_code_location(c->checker);
  7679. error(node, "#caller_location may only be used as a default argument parameter");
  7680. o->type = t_source_code_location;
  7681. o->mode = Addressing_Value;
  7682. } else if (name == "caller_expression") {
  7683. error(node, "#caller_expression may only be used as a default argument parameter");
  7684. o->type = t_string;
  7685. o->mode = Addressing_Value;
  7686. } else if (name == "branch_location") {
  7687. if (!c->in_defer) {
  7688. error(node, "#branch_location may only be used within a 'defer' statement");
  7689. } else if (c->curr_proc_decl) {
  7690. Entity *e = c->curr_proc_decl->entity;
  7691. if (e != nullptr) {
  7692. GB_ASSERT(e->kind == Entity_Procedure);
  7693. e->Procedure.uses_branch_location = true;
  7694. }
  7695. }
  7696. o->type = t_source_code_location;
  7697. o->mode = Addressing_Value;
  7698. } else {
  7699. if (name == "location") {
  7700. init_core_source_code_location(c->checker);
  7701. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  7702. o->type = t_source_code_location;
  7703. o->mode = Addressing_Value;
  7704. } else if (
  7705. name == "assert" ||
  7706. name == "defined" ||
  7707. name == "config" ||
  7708. name == "exists" ||
  7709. name == "load" ||
  7710. name == "load_hash" ||
  7711. name == "load_directory" ||
  7712. name == "load_or"
  7713. ) {
  7714. error(node, "'#%.*s' must be used as a call", LIT(name));
  7715. o->type = t_invalid;
  7716. o->mode = Addressing_Invalid;
  7717. } else {
  7718. error(node, "Unknown directive: #%.*s", LIT(name));
  7719. o->type = t_invalid;
  7720. o->mode = Addressing_Invalid;
  7721. }
  7722. }
  7723. return kind;
  7724. }
  7725. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7726. ExprKind kind = Expr_Expr;
  7727. Operand cond = {Addressing_Invalid};
  7728. ast_node(te, TernaryIfExpr, node);
  7729. check_expr(c, &cond, te->cond);
  7730. node->viral_state_flags |= te->cond->viral_state_flags;
  7731. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7732. error(te->cond, "Non-boolean condition in ternary if expression");
  7733. }
  7734. Operand x = {Addressing_Invalid};
  7735. Operand y = {Addressing_Invalid};
  7736. check_expr_or_type(c, &x, te->x, type_hint);
  7737. node->viral_state_flags |= te->x->viral_state_flags;
  7738. if (te->y != nullptr) {
  7739. Type *th = type_hint;
  7740. if (type_hint == nullptr && is_type_typed(x.type)) {
  7741. th = x.type;
  7742. }
  7743. check_expr_or_type(c, &y, te->y, th);
  7744. node->viral_state_flags |= te->y->viral_state_flags;
  7745. } else {
  7746. error(node, "A ternary expression must have an else clause");
  7747. return kind;
  7748. }
  7749. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7750. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7751. gbString type_string = expr_to_string(type_expr);
  7752. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7753. gb_string_free(type_string);
  7754. return kind;
  7755. }
  7756. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7757. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7758. if (x.mode == Addressing_Invalid) {
  7759. return kind;
  7760. }
  7761. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7762. if (y.mode == Addressing_Invalid) {
  7763. x.mode = Addressing_Invalid;
  7764. return kind;
  7765. }
  7766. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7767. // x: union{f32} = f32(123) if cond else nil
  7768. if (type_hint && !is_type_any(type_hint)) {
  7769. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7770. check_cast(c, &x, type_hint);
  7771. check_cast(c, &y, type_hint);
  7772. }
  7773. }
  7774. if (!ternary_compare_types(x.type, y.type)) {
  7775. gbString its = type_to_string(x.type);
  7776. gbString ets = type_to_string(y.type);
  7777. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7778. gb_string_free(ets);
  7779. gb_string_free(its);
  7780. return kind;
  7781. }
  7782. o->type = x.type;
  7783. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  7784. o->type = y.type;
  7785. }
  7786. o->mode = Addressing_Value;
  7787. o->expr = node;
  7788. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7789. if (check_cast_internal(c, &x, type_hint) &&
  7790. check_cast_internal(c, &y, type_hint)) {
  7791. convert_to_typed(c, o, type_hint);
  7792. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7793. o->type = type_hint;
  7794. }
  7795. }
  7796. return kind;
  7797. }
  7798. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7799. ExprKind kind = Expr_Expr;
  7800. Operand cond = {};
  7801. ast_node(te, TernaryWhenExpr, node);
  7802. check_expr(c, &cond, te->cond);
  7803. node->viral_state_flags |= te->cond->viral_state_flags;
  7804. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7805. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7806. return kind;
  7807. }
  7808. if (cond.value.value_bool) {
  7809. check_expr_or_type(c, o, te->x, type_hint);
  7810. node->viral_state_flags |= te->x->viral_state_flags;
  7811. } else {
  7812. if (te->y != nullptr) {
  7813. check_expr_or_type(c, o, te->y, type_hint);
  7814. node->viral_state_flags |= te->y->viral_state_flags;
  7815. } else {
  7816. error(node, "A ternary when expression must have an else clause");
  7817. return kind;
  7818. }
  7819. }
  7820. return kind;
  7821. }
  7822. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7823. ast_node(oe, OrElseExpr, node);
  7824. String name = oe->token.string;
  7825. Ast *arg = oe->x;
  7826. Ast *default_value = oe->y;
  7827. Operand x = {};
  7828. Operand y = {};
  7829. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7830. if (is_load_directive_call(arg)) {
  7831. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7832. // Allow for chaining of '#load(path) or_else #load(path)'
  7833. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  7834. bool y_is_diverging = false;
  7835. check_expr_base(c, &y, default_value, x.type);
  7836. switch (y.mode) {
  7837. case Addressing_NoValue:
  7838. if (is_diverging_expr(y.expr)) {
  7839. // Allow
  7840. y.mode = Addressing_Value;
  7841. y_is_diverging = true;
  7842. } else {
  7843. error_operand_no_value(&y);
  7844. y.mode = Addressing_Invalid;
  7845. }
  7846. break;
  7847. case Addressing_Type:
  7848. error_operand_not_expression(&y);
  7849. y.mode = Addressing_Invalid;
  7850. break;
  7851. }
  7852. if (y.mode == Addressing_Invalid) {
  7853. o->mode = Addressing_Value;
  7854. o->type = t_invalid;
  7855. o->expr = node;
  7856. return Expr_Expr;
  7857. }
  7858. if (!y_is_diverging) {
  7859. check_assignment(c, &y, x.type, name);
  7860. if (y.mode != Addressing_Constant) {
  7861. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7862. }
  7863. }
  7864. }
  7865. if (res == LoadDirective_Success) {
  7866. *o = x;
  7867. } else {
  7868. *o = y;
  7869. }
  7870. o->expr = node;
  7871. return Expr_Expr;
  7872. }
  7873. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7874. if (x.mode == Addressing_Invalid) {
  7875. o->mode = Addressing_Value;
  7876. o->type = t_invalid;
  7877. o->expr = node;
  7878. return Expr_Expr;
  7879. }
  7880. bool y_is_diverging = false;
  7881. check_expr_base(c, &y, default_value, x.type);
  7882. switch (y.mode) {
  7883. case Addressing_NoValue:
  7884. if (is_diverging_expr(y.expr)) {
  7885. // Allow
  7886. y.mode = Addressing_Value;
  7887. y_is_diverging = true;
  7888. } else {
  7889. error_operand_no_value(&y);
  7890. y.mode = Addressing_Invalid;
  7891. }
  7892. break;
  7893. case Addressing_Type:
  7894. error_operand_not_expression(&y);
  7895. y.mode = Addressing_Invalid;
  7896. break;
  7897. }
  7898. if (y.mode == Addressing_Invalid) {
  7899. o->mode = Addressing_Value;
  7900. o->type = t_invalid;
  7901. o->expr = node;
  7902. return Expr_Expr;
  7903. }
  7904. Type *left_type = nullptr;
  7905. Type *right_type = nullptr;
  7906. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7907. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7908. if (left_type != nullptr) {
  7909. if (!y_is_diverging) {
  7910. check_assignment(c, &y, left_type, name);
  7911. }
  7912. } else {
  7913. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7914. }
  7915. if (left_type == nullptr) {
  7916. left_type = t_invalid;
  7917. }
  7918. o->mode = Addressing_Value;
  7919. o->type = left_type;
  7920. o->expr = node;
  7921. return Expr_Expr;
  7922. }
  7923. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7924. ast_node(re, OrReturnExpr, node);
  7925. String name = re->token.string;
  7926. Operand x = {};
  7927. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  7928. if (x.mode == Addressing_Invalid) {
  7929. o->mode = Addressing_Value;
  7930. o->type = t_invalid;
  7931. o->expr = node;
  7932. return Expr_Expr;
  7933. }
  7934. Type *left_type = nullptr;
  7935. Type *right_type = nullptr;
  7936. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7937. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  7938. if (right_type == nullptr) {
  7939. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7940. } else {
  7941. Type *proc_type = base_type(c->curr_proc_sig);
  7942. GB_ASSERT(proc_type->kind == Type_Proc);
  7943. Type *result_type = proc_type->Proc.results;
  7944. if (result_type == nullptr) {
  7945. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  7946. } else {
  7947. GB_ASSERT(result_type->kind == Type_Tuple);
  7948. auto const &vars = result_type->Tuple.variables;
  7949. Type *end_type = vars[vars.count-1]->type;
  7950. if (vars.count > 1) {
  7951. if (!proc_type->Proc.has_named_results) {
  7952. 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));
  7953. }
  7954. }
  7955. Operand rhs = {};
  7956. rhs.type = right_type;
  7957. rhs.mode = Addressing_Value;
  7958. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  7959. // NOTE(bill): allow implicit conversion between boolean types
  7960. // within 'or_return' to improve the experience using third-party code
  7961. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  7962. ERROR_BLOCK();
  7963. // TODO(bill): better error message
  7964. gbString a = type_to_string(right_type);
  7965. gbString b = type_to_string(end_type);
  7966. gbString ret_type = type_to_string(result_type);
  7967. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  7968. if (vars.count == 1) {
  7969. error_line("\tProcedure return value type: %s\n", ret_type);
  7970. } else {
  7971. error_line("\tProcedure return value types: (%s)\n", ret_type);
  7972. }
  7973. gb_string_free(ret_type);
  7974. gb_string_free(b);
  7975. gb_string_free(a);
  7976. }
  7977. }
  7978. }
  7979. o->expr = node;
  7980. o->type = left_type;
  7981. if (left_type != nullptr) {
  7982. o->mode = Addressing_Value;
  7983. } else {
  7984. o->mode = Addressing_NoValue;
  7985. }
  7986. if (c->curr_proc_sig == nullptr) {
  7987. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  7988. }
  7989. if (c->in_defer) {
  7990. error(node, "'or_return' cannot be used within a defer statement");
  7991. }
  7992. return Expr_Expr;
  7993. }
  7994. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7995. ast_node(be, OrBranchExpr, node);
  7996. String name = be->token.string;
  7997. Operand x = {};
  7998. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  7999. if (x.mode == Addressing_Invalid) {
  8000. o->mode = Addressing_Value;
  8001. o->type = t_invalid;
  8002. o->expr = node;
  8003. return Expr_Expr;
  8004. }
  8005. Type *left_type = nullptr;
  8006. Type *right_type = nullptr;
  8007. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8008. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  8009. if (right_type == nullptr) {
  8010. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8011. } else {
  8012. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  8013. // okay
  8014. } else {
  8015. gbString s = type_to_string(right_type);
  8016. error(node, "'%.*s' requires a boolean or nil-able type, got %s", LIT(name), s);
  8017. gb_string_free(s);
  8018. }
  8019. }
  8020. o->expr = node;
  8021. o->type = left_type;
  8022. if (left_type != nullptr) {
  8023. o->mode = Addressing_Value;
  8024. } else {
  8025. o->mode = Addressing_NoValue;
  8026. }
  8027. if (c->curr_proc_sig == nullptr) {
  8028. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8029. }
  8030. Ast *label = be->label;
  8031. switch (be->token.kind) {
  8032. case Token_or_break:
  8033. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  8034. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  8035. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  8036. }
  8037. break;
  8038. case Token_or_continue:
  8039. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  8040. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  8041. }
  8042. break;
  8043. }
  8044. if (label != nullptr) {
  8045. if (c->in_defer) {
  8046. error(label, "A labelled '%.*s' cannot be used within a 'defer'", LIT(name));
  8047. return Expr_Expr;
  8048. }
  8049. if (label->kind != Ast_Ident) {
  8050. error(label, "A branch statement's label name must be an identifier");
  8051. return Expr_Expr;
  8052. }
  8053. Ast *ident = label;
  8054. String name = ident->Ident.token.string;
  8055. Operand o = {};
  8056. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  8057. if (e == nullptr) {
  8058. error(ident, "Undeclared label name: %.*s", LIT(name));
  8059. return Expr_Expr;
  8060. }
  8061. add_entity_use(c, ident, e);
  8062. if (e->kind != Entity_Label) {
  8063. error(ident, "'%.*s' is not a label", LIT(name));
  8064. return Expr_Expr;
  8065. }
  8066. Ast *parent = e->Label.parent;
  8067. GB_ASSERT(parent != nullptr);
  8068. switch (parent->kind) {
  8069. case Ast_BlockStmt:
  8070. case Ast_IfStmt:
  8071. case Ast_SwitchStmt:
  8072. if (be->token.kind != Token_or_break) {
  8073. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  8074. }
  8075. break;
  8076. case Ast_RangeStmt:
  8077. case Ast_ForStmt:
  8078. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  8079. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  8080. }
  8081. break;
  8082. }
  8083. }
  8084. return Expr_Expr;
  8085. }
  8086. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  8087. Type *bt = base_type(type);
  8088. StringSet fields_visited = {};
  8089. defer (string_set_destroy(&fields_visited));
  8090. StringMap<String> fields_visited_through_raw_union = {};
  8091. defer (string_map_destroy(&fields_visited_through_raw_union));
  8092. String assignment_str = str_lit("structure literal");
  8093. if (bt->kind == Type_BitField) {
  8094. assignment_str = str_lit("bit_field literal");
  8095. }
  8096. for (Ast *elem : elems) {
  8097. if (elem->kind != Ast_FieldValue) {
  8098. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8099. continue;
  8100. }
  8101. ast_node(fv, FieldValue, elem);
  8102. Ast *ident = fv->field;
  8103. if (ident->kind == Ast_ImplicitSelectorExpr) {
  8104. gbString expr_str = expr_to_string(ident);
  8105. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  8106. gb_string_free(expr_str);
  8107. ident = ident->ImplicitSelectorExpr.selector;
  8108. }
  8109. if (ident->kind != Ast_Ident) {
  8110. gbString expr_str = expr_to_string(ident);
  8111. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  8112. gb_string_free(expr_str);
  8113. continue;
  8114. }
  8115. String name = ident->Ident.token.string;
  8116. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8117. bool is_unknown = sel.entity == nullptr;
  8118. if (is_unknown) {
  8119. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  8120. continue;
  8121. }
  8122. Entity *field = nullptr;
  8123. if (bt->kind == Type_Struct) {
  8124. field = bt->Struct.fields[sel.index[0]];
  8125. } else if (bt->kind == Type_BitField) {
  8126. field = bt->BitField.fields[sel.index[0]];
  8127. } else {
  8128. GB_PANIC("Unknown type");
  8129. }
  8130. add_entity_use(c, ident, field);
  8131. if (string_set_update(&fields_visited, name)) {
  8132. if (sel.index.count > 1) {
  8133. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8134. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8135. } else {
  8136. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  8137. }
  8138. } else {
  8139. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  8140. }
  8141. continue;
  8142. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8143. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8144. continue;
  8145. }
  8146. if (sel.indirect) {
  8147. 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));
  8148. continue;
  8149. }
  8150. if (sel.index.count > 1) {
  8151. GB_ASSERT(bt->kind == Type_Struct);
  8152. if (is_constant) {
  8153. Type *ft = type;
  8154. for (i32 index : sel.index) {
  8155. Type *bt = base_type(ft);
  8156. switch (bt->kind) {
  8157. case Type_Struct:
  8158. if (bt->Struct.is_raw_union) {
  8159. is_constant = false;
  8160. break;
  8161. }
  8162. ft = bt->Struct.fields[index]->type;
  8163. break;
  8164. case Type_Array:
  8165. ft = bt->Array.elem;
  8166. break;
  8167. case Type_BitField:
  8168. is_constant = false;
  8169. ft = bt->BitField.fields[index]->type;
  8170. break;
  8171. default:
  8172. GB_PANIC("invalid type: %s", type_to_string(ft));
  8173. break;
  8174. }
  8175. }
  8176. if (is_constant &&
  8177. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  8178. is_constant = false;
  8179. }
  8180. }
  8181. Type *nested_ft = bt;
  8182. for (i32 index : sel.index) {
  8183. Type *bt = base_type(nested_ft);
  8184. switch (bt->kind) {
  8185. case Type_Struct:
  8186. if (bt->Struct.is_raw_union) {
  8187. for (Entity *re : bt->Struct.fields) {
  8188. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  8189. }
  8190. }
  8191. nested_ft = bt->Struct.fields[index]->type;
  8192. break;
  8193. case Type_Array:
  8194. nested_ft = bt->Array.elem;
  8195. break;
  8196. case Type_BitField:
  8197. nested_ft = bt->BitField.fields[index]->type;
  8198. break;
  8199. default:
  8200. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  8201. break;
  8202. }
  8203. }
  8204. field = sel.entity;
  8205. }
  8206. Operand o = {};
  8207. check_expr_or_type(c, &o, fv->value, field->type);
  8208. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8209. is_constant = false;
  8210. }
  8211. if (is_constant) {
  8212. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8213. }
  8214. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  8215. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  8216. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  8217. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  8218. }
  8219. check_assignment(c, &o, field->type, assignment_str);
  8220. c->bit_field_bit_size = prev_bit_field_bit_size;
  8221. }
  8222. }
  8223. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  8224. type_expr = unparen_expr(type_expr);
  8225. if (type_expr == nullptr) {
  8226. return false;
  8227. }
  8228. // [?]Type
  8229. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  8230. Ast *count = type_expr->ArrayType.count;
  8231. if (count->kind == Ast_UnaryExpr &&
  8232. count->UnaryExpr.op.kind == Token_Question) {
  8233. return true;
  8234. }
  8235. }
  8236. return false;
  8237. }
  8238. gb_internal bool check_for_dynamic_literals(CheckerContext *c, Ast *node, AstCompoundLit *cl) {
  8239. if (cl->elems.count > 0 && (check_feature_flags(c, node) & OptInFeatureFlag_DynamicLiterals) == 0) {
  8240. ERROR_BLOCK();
  8241. error(node, "Compound literals of dynamic types are disabled by default");
  8242. error_line("\tSuggestion: If you want to enable them for this specific file, add '#+feature dynamic-literals' at the top of the file\n");
  8243. error_line("\tWarning: Please understand that dynamic literals will implicitly allocate using the current 'context.allocator' in that scope\n");
  8244. if (build_context.ODIN_DEFAULT_TO_NIL_ALLOCATOR) {
  8245. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8246. } else if (build_context.ODIN_DEFAULT_TO_PANIC_ALLOCATOR) {
  8247. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8248. }
  8249. return false;
  8250. }
  8251. return cl->elems.count > 0;
  8252. }
  8253. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8254. ExprKind kind = Expr_Expr;
  8255. ast_node(cl, CompoundLit, node);
  8256. Type *type = type_hint;
  8257. if (type != nullptr && is_type_untyped(type)) {
  8258. type = nullptr;
  8259. }
  8260. bool is_to_be_determined_array_count = false;
  8261. bool is_constant = true;
  8262. Ast *type_expr = cl->type;
  8263. bool used_type_hint_expr = false;
  8264. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  8265. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  8266. type_expr = clone_ast(c->type_hint_expr);
  8267. used_type_hint_expr = true;
  8268. }
  8269. }
  8270. if (type_expr != nullptr) {
  8271. type = nullptr;
  8272. // [?]Type
  8273. if (type_expr->kind == Ast_ArrayType) {
  8274. Ast *count = type_expr->ArrayType.count;
  8275. if (count != nullptr) {
  8276. if (count->kind == Ast_UnaryExpr &&
  8277. count->UnaryExpr.op.kind == Token_Question) {
  8278. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  8279. is_to_be_determined_array_count = true;
  8280. }
  8281. } else {
  8282. type = alloc_type_slice(check_type(c, type_expr->ArrayType.elem));
  8283. }
  8284. if (cl->elems.count > 0) {
  8285. if (type_expr->ArrayType.tag != nullptr) {
  8286. Ast *tag = type_expr->ArrayType.tag;
  8287. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8288. String name = tag->BasicDirective.name.string;
  8289. if (name == "soa") {
  8290. error(node, "#soa arrays are not supported for compound literals");
  8291. return kind;
  8292. }
  8293. }
  8294. }
  8295. } else if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  8296. if (cl->elems.count > 0) {
  8297. Ast *tag = type_expr->DynamicArrayType.tag;
  8298. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8299. String name = tag->BasicDirective.name.string;
  8300. if (name == "soa") {
  8301. error(node, "#soa arrays are not supported for compound literals");
  8302. return kind;
  8303. }
  8304. }
  8305. }
  8306. if (type == nullptr) {
  8307. type = check_type(c, type_expr);
  8308. }
  8309. }
  8310. if (type == nullptr) {
  8311. error(node, "Missing type in compound literal");
  8312. return kind;
  8313. }
  8314. Type *t = base_type(type);
  8315. if (is_type_polymorphic(t)) {
  8316. gbString str = type_to_string(type);
  8317. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  8318. o->expr = node;
  8319. o->type = type;
  8320. gb_string_free(str);
  8321. return kind;
  8322. }
  8323. switch (t->kind) {
  8324. case Type_Struct: {
  8325. if (cl->elems.count == 0) {
  8326. break; // NOTE(bill): No need to init
  8327. }
  8328. if (t->Struct.soa_kind != StructSoa_None) {
  8329. error(node, "#soa arrays are not supported for compound literals");
  8330. break;
  8331. }
  8332. if (t->Struct.is_raw_union) {
  8333. if (cl->elems.count > 0) {
  8334. // NOTE: unions cannot be constant
  8335. is_constant = false;
  8336. if (cl->elems[0]->kind != Ast_FieldValue) {
  8337. gbString type_str = type_to_string(type);
  8338. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  8339. gb_string_free(type_str);
  8340. } else {
  8341. if (cl->elems.count != 1) {
  8342. gbString type_str = type_to_string(type);
  8343. 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);
  8344. gb_string_free(type_str);
  8345. } else {
  8346. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8347. }
  8348. }
  8349. }
  8350. break;
  8351. }
  8352. wait_signal_until_available(&t->Struct.fields_wait_signal);
  8353. isize field_count = t->Struct.fields.count;
  8354. isize min_field_count = t->Struct.fields.count;
  8355. for (isize i = min_field_count-1; i >= 0; i--) {
  8356. Entity *e = t->Struct.fields[i];
  8357. GB_ASSERT(e->kind == Entity_Variable);
  8358. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  8359. min_field_count--;
  8360. } else {
  8361. break;
  8362. }
  8363. }
  8364. if (cl->elems[0]->kind == Ast_FieldValue) {
  8365. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8366. } else {
  8367. bool seen_field_value = false;
  8368. for_array(index, cl->elems) {
  8369. Entity *field = nullptr;
  8370. Ast *elem = cl->elems[index];
  8371. if (elem->kind == Ast_FieldValue) {
  8372. seen_field_value = true;
  8373. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8374. continue;
  8375. } else if (seen_field_value) {
  8376. error(elem, "Value elements cannot be used after a 'field = value'");
  8377. continue;
  8378. }
  8379. if (index >= field_count) {
  8380. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8381. break;
  8382. }
  8383. if (field == nullptr) {
  8384. field = t->Struct.fields[index];
  8385. }
  8386. Operand o = {};
  8387. check_expr_or_type(c, &o, elem, field->type);
  8388. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8389. is_constant = false;
  8390. }
  8391. if (is_constant) {
  8392. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8393. }
  8394. check_assignment(c, &o, field->type, str_lit("structure literal"));
  8395. }
  8396. if (cl->elems.count < field_count) {
  8397. if (min_field_count < field_count) {
  8398. if (cl->elems.count < min_field_count) {
  8399. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  8400. }
  8401. } else {
  8402. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8403. }
  8404. }
  8405. }
  8406. break;
  8407. }
  8408. case Type_Slice:
  8409. case Type_Array:
  8410. case Type_DynamicArray:
  8411. case Type_SimdVector:
  8412. case Type_Matrix:
  8413. {
  8414. Type *elem_type = nullptr;
  8415. String context_name = {};
  8416. i64 max_type_count = -1;
  8417. if (t->kind == Type_Slice) {
  8418. elem_type = t->Slice.elem;
  8419. context_name = str_lit("slice literal");
  8420. } else if (t->kind == Type_Array) {
  8421. elem_type = t->Array.elem;
  8422. context_name = str_lit("array literal");
  8423. if (!is_to_be_determined_array_count) {
  8424. max_type_count = t->Array.count;
  8425. }
  8426. } else if (t->kind == Type_DynamicArray) {
  8427. elem_type = t->DynamicArray.elem;
  8428. context_name = str_lit("dynamic array literal");
  8429. is_constant = false;
  8430. } else if (t->kind == Type_SimdVector) {
  8431. elem_type = t->SimdVector.elem;
  8432. context_name = str_lit("simd vector literal");
  8433. max_type_count = t->SimdVector.count;
  8434. } else if (t->kind == Type_Matrix) {
  8435. elem_type = t->Matrix.elem;
  8436. context_name = str_lit("matrix literal");
  8437. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  8438. } else {
  8439. GB_PANIC("unreachable");
  8440. }
  8441. i64 max = 0;
  8442. Type *bet = base_type(elem_type);
  8443. if (!elem_type_can_be_constant(bet)) {
  8444. is_constant = false;
  8445. }
  8446. if (bet == t_invalid) {
  8447. break;
  8448. }
  8449. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8450. RangeCache rc = range_cache_make(heap_allocator());
  8451. defer (range_cache_destroy(&rc));
  8452. for (Ast *elem : cl->elems) {
  8453. if (elem->kind != Ast_FieldValue) {
  8454. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8455. continue;
  8456. }
  8457. ast_node(fv, FieldValue, elem);
  8458. if (is_ast_range(fv->field)) {
  8459. Token op = fv->field->BinaryExpr.op;
  8460. Operand x = {};
  8461. Operand y = {};
  8462. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  8463. if (!ok) {
  8464. continue;
  8465. }
  8466. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  8467. error(x.expr, "Expected a constant integer as an array field");
  8468. continue;
  8469. }
  8470. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  8471. error(y.expr, "Expected a constant integer as an array field");
  8472. continue;
  8473. }
  8474. i64 lo = exact_value_to_i64(x.value);
  8475. i64 hi = exact_value_to_i64(y.value);
  8476. i64 max_index = hi;
  8477. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  8478. hi -= 1;
  8479. } else { // .. (inclusive)
  8480. max_index += 1;
  8481. }
  8482. bool new_range = range_cache_add_range(&rc, lo, hi);
  8483. if (!new_range) {
  8484. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  8485. continue;
  8486. }
  8487. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  8488. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  8489. continue;
  8490. }
  8491. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  8492. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  8493. continue;
  8494. }
  8495. if (max < hi) {
  8496. max = max_index;
  8497. }
  8498. Operand operand = {};
  8499. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8500. check_assignment(c, &operand, elem_type, context_name);
  8501. is_constant = is_constant && operand.mode == Addressing_Constant;
  8502. } else {
  8503. Operand op_index = {};
  8504. check_expr(c, &op_index, fv->field);
  8505. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  8506. error(elem, "Expected a constant integer as an array field");
  8507. continue;
  8508. }
  8509. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  8510. i64 index = exact_value_to_i64(op_index.value);
  8511. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  8512. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  8513. continue;
  8514. }
  8515. bool new_index = range_cache_add_index(&rc, index);
  8516. if (!new_index) {
  8517. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  8518. continue;
  8519. }
  8520. if (max < index+1) {
  8521. max = index+1;
  8522. }
  8523. Operand operand = {};
  8524. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8525. check_assignment(c, &operand, elem_type, context_name);
  8526. is_constant = is_constant && operand.mode == Addressing_Constant;
  8527. }
  8528. }
  8529. cl->max_count = max;
  8530. } else {
  8531. isize index = 0;
  8532. for (; index < cl->elems.count; index++) {
  8533. Ast *e = cl->elems[index];
  8534. if (e == nullptr) {
  8535. error(node, "Invalid literal element");
  8536. continue;
  8537. }
  8538. if (e->kind == Ast_FieldValue) {
  8539. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8540. continue;
  8541. }
  8542. if (0 <= max_type_count && max_type_count <= index) {
  8543. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8544. }
  8545. Operand operand = {};
  8546. check_expr_with_type_hint(c, &operand, e, elem_type);
  8547. check_assignment(c, &operand, elem_type, context_name);
  8548. is_constant = is_constant && operand.mode == Addressing_Constant;
  8549. }
  8550. if (max < index) {
  8551. max = index;
  8552. }
  8553. }
  8554. if (t->kind == Type_Array) {
  8555. if (is_to_be_determined_array_count) {
  8556. t->Array.count = max;
  8557. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8558. if (0 < max && max < t->Array.count) {
  8559. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8560. }
  8561. }
  8562. }
  8563. if (t->kind == Type_SimdVector) {
  8564. if (!is_constant) {
  8565. // error(node, "Expected all constant elements for a simd vector");
  8566. }
  8567. }
  8568. if (t->kind == Type_DynamicArray) {
  8569. if (check_for_dynamic_literals(c, node, cl)) {
  8570. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  8571. add_package_dependency(c, "runtime", "__dynamic_array_append");
  8572. }
  8573. }
  8574. if (t->kind == Type_Matrix) {
  8575. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8576. if (0 < max && max < max_type_count) {
  8577. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  8578. }
  8579. }
  8580. }
  8581. break;
  8582. }
  8583. case Type_EnumeratedArray:
  8584. {
  8585. Type *elem_type = t->EnumeratedArray.elem;
  8586. Type *index_type = t->EnumeratedArray.index;
  8587. String context_name = str_lit("enumerated array literal");
  8588. i64 max_type_count = t->EnumeratedArray.count;
  8589. gbString index_type_str = type_to_string(index_type);
  8590. defer (gb_string_free(index_type_str));
  8591. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  8592. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  8593. String total_lo_string = {};
  8594. String total_hi_string = {};
  8595. GB_ASSERT(is_type_enum(index_type));
  8596. {
  8597. Type *bt = base_type(index_type);
  8598. GB_ASSERT(bt->kind == Type_Enum);
  8599. for (Entity *f : bt->Enum.fields) {
  8600. if (f->kind != Entity_Constant) {
  8601. continue;
  8602. }
  8603. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  8604. total_lo_string = f->token.string;
  8605. }
  8606. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  8607. total_hi_string = f->token.string;
  8608. }
  8609. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8610. break;
  8611. }
  8612. }
  8613. }
  8614. i64 max = 0;
  8615. Type *bet = base_type(elem_type);
  8616. if (!elem_type_can_be_constant(bet)) {
  8617. is_constant = false;
  8618. }
  8619. if (bet == t_invalid) {
  8620. break;
  8621. }
  8622. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8623. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8624. defer (map_destroy(&seen));
  8625. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8626. RangeCache rc = range_cache_make(heap_allocator());
  8627. defer (range_cache_destroy(&rc));
  8628. for (Ast *elem : cl->elems) {
  8629. if (elem->kind != Ast_FieldValue) {
  8630. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8631. continue;
  8632. }
  8633. ast_node(fv, FieldValue, elem);
  8634. if (is_ast_range(fv->field)) {
  8635. Token op = fv->field->BinaryExpr.op;
  8636. Operand x = {};
  8637. Operand y = {};
  8638. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8639. if (!ok) {
  8640. continue;
  8641. }
  8642. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8643. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8644. continue;
  8645. }
  8646. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8647. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8648. continue;
  8649. }
  8650. i64 lo = exact_value_to_i64(x.value);
  8651. i64 hi = exact_value_to_i64(y.value);
  8652. i64 max_index = hi;
  8653. if (op.kind == Token_RangeHalf) {
  8654. hi -= 1;
  8655. }
  8656. bool new_range = range_cache_add_range(&rc, lo, hi);
  8657. if (!new_range) {
  8658. gbString lo_str = expr_to_string(x.expr);
  8659. gbString hi_str = expr_to_string(y.expr);
  8660. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8661. gb_string_free(hi_str);
  8662. gb_string_free(lo_str);
  8663. continue;
  8664. }
  8665. // NOTE(bill): These are sanity checks for invalid enum values
  8666. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8667. gbString lo_str = expr_to_string(x.expr);
  8668. 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));
  8669. gb_string_free(lo_str);
  8670. continue;
  8671. }
  8672. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8673. gbString hi_str = expr_to_string(y.expr);
  8674. 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));
  8675. gb_string_free(hi_str);
  8676. continue;
  8677. }
  8678. if (max < hi) {
  8679. max = max_index;
  8680. }
  8681. Operand operand = {};
  8682. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8683. check_assignment(c, &operand, elem_type, context_name);
  8684. is_constant = is_constant && operand.mode == Addressing_Constant;
  8685. TokenKind upper_op = Token_LtEq;
  8686. if (op.kind == Token_RangeHalf) {
  8687. upper_op = Token_Lt;
  8688. }
  8689. add_to_seen_map(c, &seen, upper_op, x, x, y);
  8690. } else {
  8691. Operand op_index = {};
  8692. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8693. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8694. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8695. continue;
  8696. }
  8697. i64 index = exact_value_to_i64(op_index.value);
  8698. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8699. gbString idx_str = expr_to_string(op_index.expr);
  8700. 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));
  8701. gb_string_free(idx_str);
  8702. continue;
  8703. }
  8704. bool new_index = range_cache_add_index(&rc, index);
  8705. if (!new_index) {
  8706. gbString idx_str = expr_to_string(op_index.expr);
  8707. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8708. gb_string_free(idx_str);
  8709. continue;
  8710. }
  8711. if (max < index+1) {
  8712. max = index+1;
  8713. }
  8714. Operand operand = {};
  8715. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8716. check_assignment(c, &operand, elem_type, context_name);
  8717. is_constant = is_constant && operand.mode == Addressing_Constant;
  8718. add_to_seen_map(c, &seen, op_index);
  8719. }
  8720. }
  8721. cl->max_count = max;
  8722. } else {
  8723. isize index = 0;
  8724. for (; index < cl->elems.count; index++) {
  8725. Ast *e = cl->elems[index];
  8726. if (e == nullptr) {
  8727. error(node, "Invalid literal element");
  8728. continue;
  8729. }
  8730. if (e->kind == Ast_FieldValue) {
  8731. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8732. continue;
  8733. }
  8734. if (0 <= max_type_count && max_type_count <= index) {
  8735. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8736. }
  8737. Operand operand = {};
  8738. check_expr_with_type_hint(c, &operand, e, elem_type);
  8739. check_assignment(c, &operand, elem_type, context_name);
  8740. is_constant = is_constant && operand.mode == Addressing_Constant;
  8741. }
  8742. if (max < index) {
  8743. max = index;
  8744. }
  8745. }
  8746. bool was_error = false;
  8747. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8748. if (0 < max && max < t->EnumeratedArray.count) {
  8749. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  8750. was_error = true;
  8751. } else {
  8752. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  8753. was_error = true;
  8754. }
  8755. }
  8756. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  8757. if (cl->elems.count > 0 && !was_error && !is_partial) {
  8758. TEMPORARY_ALLOCATOR_GUARD();
  8759. Type *et = base_type(index_type);
  8760. GB_ASSERT(et->kind == Type_Enum);
  8761. auto fields = et->Enum.fields;
  8762. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  8763. for (Entity *f : fields) {
  8764. if (f->kind != Entity_Constant) {
  8765. continue;
  8766. }
  8767. ExactValue v = f->Constant.value;
  8768. uintptr hash = hash_exact_value(v);
  8769. auto found = map_get(&seen, hash);
  8770. if (!found) {
  8771. array_add(&unhandled, f);
  8772. }
  8773. }
  8774. if (unhandled.count > 0) {
  8775. ERROR_BLOCK();
  8776. if (unhandled.count == 1) {
  8777. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  8778. } else {
  8779. error(node, "Unhandled enumerated array cases:");
  8780. for_array(i, unhandled) {
  8781. Entity *f = unhandled[i];
  8782. error_line("\t%.*s\n", LIT(f->token.string));
  8783. }
  8784. }
  8785. if (!build_context.terse_errors) {
  8786. error_line("\n");
  8787. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  8788. }
  8789. }
  8790. }
  8791. break;
  8792. }
  8793. case Type_Basic: {
  8794. if (!is_type_any(t)) {
  8795. if (cl->elems.count != 0) {
  8796. gbString s = type_to_string(t);
  8797. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  8798. gb_string_free(s);
  8799. is_constant = false;
  8800. }
  8801. break;
  8802. }
  8803. if (cl->elems.count == 0) {
  8804. break; // NOTE(bill): No need to init
  8805. }
  8806. { // Checker values
  8807. Type *field_types[2] = {t_rawptr, t_typeid};
  8808. isize field_count = 2;
  8809. if (cl->elems[0]->kind == Ast_FieldValue) {
  8810. bool fields_visited[2] = {};
  8811. for_array(i, cl->elems) {
  8812. Ast *elem = cl->elems[i];
  8813. if (elem->kind != Ast_FieldValue) {
  8814. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8815. continue;
  8816. }
  8817. ast_node(fv, FieldValue, elem);
  8818. if (fv->field->kind != Ast_Ident) {
  8819. gbString expr_str = expr_to_string(fv->field);
  8820. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  8821. gb_string_free(expr_str);
  8822. continue;
  8823. }
  8824. String name = fv->field->Ident.token.string;
  8825. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8826. if (sel.entity == nullptr) {
  8827. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  8828. continue;
  8829. }
  8830. isize index = sel.index[0];
  8831. if (fields_visited[index]) {
  8832. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  8833. continue;
  8834. }
  8835. fields_visited[index] = true;
  8836. check_expr(c, o, fv->value);
  8837. // NOTE(bill): 'any' literals can never be constant
  8838. is_constant = false;
  8839. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8840. }
  8841. } else {
  8842. for_array(index, cl->elems) {
  8843. Ast *elem = cl->elems[index];
  8844. if (elem->kind == Ast_FieldValue) {
  8845. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8846. continue;
  8847. }
  8848. check_expr(c, o, elem);
  8849. if (index >= field_count) {
  8850. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  8851. break;
  8852. }
  8853. // NOTE(bill): 'any' literals can never be constant
  8854. is_constant = false;
  8855. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8856. }
  8857. if (cl->elems.count < field_count) {
  8858. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  8859. }
  8860. }
  8861. }
  8862. break;
  8863. }
  8864. case Type_Map: {
  8865. if (cl->elems.count == 0) {
  8866. break;
  8867. }
  8868. is_constant = false;
  8869. { // Checker values
  8870. bool key_is_typeid = is_type_typeid(t->Map.key);
  8871. bool value_is_typeid = is_type_typeid(t->Map.value);
  8872. for (Ast *elem : cl->elems) {
  8873. if (elem->kind != Ast_FieldValue) {
  8874. error(elem, "Only 'field = value' elements are allowed in a map literal");
  8875. continue;
  8876. }
  8877. ast_node(fv, FieldValue, elem);
  8878. if (key_is_typeid) {
  8879. check_expr_or_type(c, o, fv->field, t->Map.key);
  8880. } else {
  8881. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  8882. }
  8883. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  8884. if (o->mode == Addressing_Invalid) {
  8885. continue;
  8886. }
  8887. if (value_is_typeid) {
  8888. check_expr_or_type(c, o, fv->value, t->Map.value);
  8889. } else {
  8890. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  8891. }
  8892. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  8893. }
  8894. }
  8895. if (check_for_dynamic_literals(c, node, cl)) {
  8896. add_map_reserve_dependencies(c);
  8897. add_map_set_dependencies(c);
  8898. }
  8899. break;
  8900. }
  8901. case Type_BitSet: {
  8902. if (cl->elems.count == 0) {
  8903. break; // NOTE(bill): No need to init
  8904. }
  8905. Type *et = base_type(t->BitSet.elem);
  8906. isize field_count = 0;
  8907. if (et != nullptr && et->kind == Type_Enum) {
  8908. field_count = et->Enum.fields.count;
  8909. }
  8910. if (is_type_array(bit_set_to_int(t))) {
  8911. is_constant = false;
  8912. }
  8913. if (cl->elems[0]->kind == Ast_FieldValue) {
  8914. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  8915. is_constant = false;
  8916. } else {
  8917. for (Ast *elem : cl->elems) {
  8918. if (elem->kind == Ast_FieldValue) {
  8919. error(elem, "'field = value' in a bit_set a literal is not allowed");
  8920. continue;
  8921. }
  8922. check_expr_with_type_hint(c, o, elem, et);
  8923. if (is_constant) {
  8924. is_constant = o->mode == Addressing_Constant;
  8925. }
  8926. if (elem->kind == Ast_BinaryExpr) {
  8927. switch (elem->BinaryExpr.op.kind) {
  8928. case Token_Or:
  8929. {
  8930. gbString x = expr_to_string(elem->BinaryExpr.left);
  8931. gbString y = expr_to_string(elem->BinaryExpr.right);
  8932. gbString e = expr_to_string(elem);
  8933. error(elem, "Was the following intended? '%s, %s'; if not, surround the expression with parentheses '(%s)'", x, y, e);
  8934. gb_string_free(e);
  8935. gb_string_free(y);
  8936. gb_string_free(x);
  8937. }
  8938. break;
  8939. }
  8940. }
  8941. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  8942. if (o->mode == Addressing_Constant) {
  8943. i64 lower = t->BitSet.lower;
  8944. i64 upper = t->BitSet.upper;
  8945. i64 v = exact_value_to_i64(o->value);
  8946. if (lower <= v && v <= upper) {
  8947. // okay
  8948. } else {
  8949. gbString s = expr_to_string(o->expr);
  8950. error(elem, "Bit field value out of bounds, %s (%lld) not in the range %lld .. %lld", s, v, lower, upper);
  8951. gb_string_free(s);
  8952. continue;
  8953. }
  8954. }
  8955. }
  8956. }
  8957. break;
  8958. }
  8959. case Type_BitField: {
  8960. if (cl->elems.count == 0) {
  8961. break; // NOTE(bill): No need to init
  8962. }
  8963. is_constant = false;
  8964. if (cl->elems[0]->kind != Ast_FieldValue) {
  8965. gbString type_str = type_to_string(type);
  8966. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  8967. gb_string_free(type_str);
  8968. } else {
  8969. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8970. }
  8971. break;
  8972. }
  8973. default: {
  8974. if (cl->elems.count == 0) {
  8975. break; // NOTE(bill): No need to init
  8976. }
  8977. gbString str = type_to_string(type);
  8978. error(node, "Invalid compound literal type '%s'", str);
  8979. gb_string_free(str);
  8980. return kind;
  8981. }
  8982. }
  8983. if (is_constant) {
  8984. o->mode = Addressing_Constant;
  8985. if (is_type_bit_set(type)) {
  8986. // NOTE(bill): Encode as an integer
  8987. Type *bt = base_type(type);
  8988. BigInt bits = {};
  8989. BigInt one = {};
  8990. big_int_from_u64(&one, 1);
  8991. for (Ast *e : cl->elems) {
  8992. GB_ASSERT(e->kind != Ast_FieldValue);
  8993. TypeAndValue tav = e->tav;
  8994. if (tav.mode != Addressing_Constant) {
  8995. continue;
  8996. }
  8997. if (tav.value.kind != ExactValue_Integer) {
  8998. continue;
  8999. }
  9000. i64 v = big_int_to_i64(&tav.value.value_integer);
  9001. i64 lower = bt->BitSet.lower;
  9002. u64 index = cast(u64)(v-lower);
  9003. BigInt bit = {};
  9004. big_int_from_u64(&bit, index);
  9005. big_int_shl(&bit, &one, &bit);
  9006. big_int_or(&bits, &bits, &bit);
  9007. }
  9008. o->value.kind = ExactValue_Integer;
  9009. o->value.value_integer = bits;
  9010. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  9011. ExactValue value = exact_value_compound(node);
  9012. Type *bt = core_type(type);
  9013. if (bt->kind == Type_Basic) {
  9014. if (bt->Basic.flags & BasicFlag_Boolean) {
  9015. value = exact_value_bool(false);
  9016. } else if (bt->Basic.flags & BasicFlag_Integer) {
  9017. value = exact_value_i64(0);
  9018. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  9019. value = exact_value_i64(0);
  9020. } else if (bt->Basic.flags & BasicFlag_Float) {
  9021. value = exact_value_float(0);
  9022. } else if (bt->Basic.flags & BasicFlag_Complex) {
  9023. value = exact_value_complex(0, 0);
  9024. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  9025. value = exact_value_quaternion(0, 0, 0, 0);
  9026. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  9027. value = exact_value_pointer(0);
  9028. } else if (bt->Basic.flags & BasicFlag_String) {
  9029. String empty_string = {};
  9030. value = exact_value_string(empty_string);
  9031. } else if (bt->Basic.flags & BasicFlag_Rune) {
  9032. value = exact_value_i64(0);
  9033. }
  9034. }
  9035. o->value = value;
  9036. } else {
  9037. o->value = exact_value_compound(node);
  9038. }
  9039. } else {
  9040. o->mode = Addressing_Value;
  9041. }
  9042. o->type = type;
  9043. return kind;
  9044. }
  9045. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9046. ExprKind kind = Expr_Expr;
  9047. ast_node(ta, TypeAssertion, node);
  9048. check_expr(c, o, ta->expr);
  9049. node->viral_state_flags |= ta->expr->viral_state_flags;
  9050. if (o->mode == Addressing_Invalid) {
  9051. o->expr = node;
  9052. return kind;
  9053. }
  9054. if (o->mode == Addressing_Constant) {
  9055. gbString expr_str = expr_to_string(o->expr);
  9056. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  9057. gb_string_free(expr_str);
  9058. o->mode = Addressing_Invalid;
  9059. o->expr = node;
  9060. return kind;
  9061. }
  9062. if (is_type_untyped(o->type)) {
  9063. gbString expr_str = expr_to_string(o->expr);
  9064. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  9065. gb_string_free(expr_str);
  9066. o->mode = Addressing_Invalid;
  9067. o->expr = node;
  9068. return kind;
  9069. }
  9070. Type *src = type_deref(o->type);
  9071. Type *bsrc = base_type(src);
  9072. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  9073. if (!is_type_union(src)) {
  9074. gbString str = type_to_string(o->type);
  9075. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  9076. gb_string_free(str);
  9077. o->mode = Addressing_Invalid;
  9078. o->expr = node;
  9079. return kind;
  9080. }
  9081. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  9082. bool allowed = false;
  9083. for (Type *vt : bsrc->Union.variants) {
  9084. if (are_types_identical(vt, type_hint)) {
  9085. allowed = true;
  9086. add_type_info_type(c, vt);
  9087. break;
  9088. }
  9089. }
  9090. if (allowed) {
  9091. add_type_info_type(c, o->type);
  9092. o->type = type_hint;
  9093. o->mode = Addressing_OptionalOk;
  9094. goto end;
  9095. }
  9096. }
  9097. if (bsrc->Union.variants.count != 1) {
  9098. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  9099. o->mode = Addressing_Invalid;
  9100. o->expr = node;
  9101. return kind;
  9102. }
  9103. add_type_info_type(c, o->type);
  9104. add_type_info_type(c, bsrc->Union.variants[0]);
  9105. o->type = bsrc->Union.variants[0];
  9106. o->mode = Addressing_OptionalOk;
  9107. } else {
  9108. Type *t = check_type(c, ta->type);
  9109. Type *dst = t;
  9110. if (is_type_union(src)) {
  9111. bool ok = false;
  9112. for (Type *vt : bsrc->Union.variants) {
  9113. if (are_types_identical(vt, dst)) {
  9114. ok = true;
  9115. break;
  9116. }
  9117. }
  9118. if (!ok) {
  9119. gbString expr_str = expr_to_string(o->expr);
  9120. gbString dst_type_str = type_to_string(t);
  9121. defer (gb_string_free(expr_str));
  9122. defer (gb_string_free(dst_type_str));
  9123. if (bsrc->Union.variants.count == 0) {
  9124. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  9125. } else {
  9126. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  9127. }
  9128. o->mode = Addressing_Invalid;
  9129. o->expr = node;
  9130. return kind;
  9131. }
  9132. add_type_info_type(c, o->type);
  9133. add_type_info_type(c, t);
  9134. o->type = t;
  9135. o->mode = Addressing_OptionalOk;
  9136. } else if (is_type_any(src)) {
  9137. o->type = t;
  9138. o->mode = Addressing_OptionalOk;
  9139. add_type_info_type(c, o->type);
  9140. add_type_info_type(c, t);
  9141. } else {
  9142. gbString str = type_to_string(o->type);
  9143. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  9144. gb_string_free(str);
  9145. o->mode = Addressing_Invalid;
  9146. o->expr = node;
  9147. return kind;
  9148. }
  9149. }
  9150. end:;
  9151. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  9152. add_package_dependency(c, "runtime", "type_assertion_check");
  9153. add_package_dependency(c, "runtime", "type_assertion_check2");
  9154. }
  9155. return kind;
  9156. }
  9157. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9158. ast_node(se, SelectorCallExpr, node);
  9159. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  9160. // COM APIs is a great example of where this kind of thing is extremely useful
  9161. // General idea:
  9162. //
  9163. // x->y(123) == x.y(x, 123)
  9164. //
  9165. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  9166. // Just regenerating a new AST aids things
  9167. //
  9168. // TODO(bill): Is this a good hack or not?
  9169. //
  9170. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  9171. if (se->modified_call) {
  9172. // Prevent double evaluation
  9173. o->expr = node;
  9174. o->type = node->tav.type;
  9175. o->value = node->tav.value;
  9176. o->mode = node->tav.mode;
  9177. return Expr_Expr;
  9178. }
  9179. bool allow_arrow_right_selector_expr;
  9180. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9181. c->allow_arrow_right_selector_expr = true;
  9182. Operand x = {};
  9183. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  9184. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9185. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  9186. o->mode = Addressing_Invalid;
  9187. o->type = t_invalid;
  9188. o->expr = node;
  9189. return kind;
  9190. }
  9191. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  9192. gbString type_str = type_to_string(x.type);
  9193. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  9194. gb_string_free(type_str);
  9195. o->mode = Addressing_Invalid;
  9196. o->type = t_invalid;
  9197. o->expr = node;
  9198. return Expr_Stmt;
  9199. }
  9200. ast_node(ce, CallExpr, se->call);
  9201. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  9202. Ast *first_arg = x.expr->SelectorExpr.expr;
  9203. GB_ASSERT(first_arg != nullptr);
  9204. Entity *e = entity_of_node(se->expr);
  9205. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  9206. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  9207. }
  9208. if (e->kind != Entity_ProcGroup) {
  9209. Type *pt = base_type(x.type);
  9210. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  9211. Type *first_type = nullptr;
  9212. String first_arg_name = {};
  9213. if (pt->Proc.param_count > 0) {
  9214. Entity *f = pt->Proc.params->Tuple.variables[0];
  9215. first_type = f->type;
  9216. first_arg_name = f->token.string;
  9217. }
  9218. if (first_arg_name.len == 0) {
  9219. first_arg_name = str_lit("_");
  9220. }
  9221. if (first_type == nullptr) {
  9222. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  9223. o->mode = Addressing_Invalid;
  9224. o->type = t_invalid;
  9225. o->expr = node;
  9226. return Expr_Stmt;
  9227. }
  9228. Operand y = {};
  9229. y.mode = first_arg->tav.mode;
  9230. y.type = first_arg->tav.type;
  9231. y.value = first_arg->tav.value;
  9232. if (check_is_assignable_to(c, &y, first_type)) {
  9233. // Do nothing, it's valid
  9234. } else {
  9235. Operand z = y;
  9236. z.type = type_deref(y.type);
  9237. if (check_is_assignable_to(c, &z, first_type)) {
  9238. // NOTE(bill): AST GENERATION HACK!
  9239. Token op = {Token_Pointer};
  9240. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  9241. } else if (y.mode == Addressing_Variable) {
  9242. Operand w = y;
  9243. w.type = alloc_type_pointer(y.type);
  9244. if (check_is_assignable_to(c, &w, first_type)) {
  9245. // NOTE(bill): AST GENERATION HACK!
  9246. Token op = {Token_And};
  9247. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  9248. }
  9249. }
  9250. }
  9251. if (ce->args.count > 0) {
  9252. bool fail = false;
  9253. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  9254. for (Ast *arg : ce->args) {
  9255. bool mix = false;
  9256. if (first_is_field_value) {
  9257. mix = arg->kind != Ast_FieldValue;
  9258. } else {
  9259. mix = arg->kind == Ast_FieldValue;
  9260. }
  9261. if (mix) {
  9262. fail = true;
  9263. break;
  9264. }
  9265. }
  9266. if (!fail && first_is_field_value) {
  9267. Token op = {Token_Eq};
  9268. AstFile *f = first_arg->file();
  9269. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  9270. }
  9271. }
  9272. }
  9273. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  9274. modified_args[0] = first_arg;
  9275. slice_copy(&modified_args, ce->args, 1);
  9276. ce->args = modified_args;
  9277. se->modified_call = true;
  9278. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9279. c->allow_arrow_right_selector_expr = true;
  9280. check_expr_base(c, o, se->call, type_hint);
  9281. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9282. o->expr = node;
  9283. return Expr_Expr;
  9284. }
  9285. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9286. ExprKind kind = Expr_Expr;
  9287. ast_node(ie, IndexExpr, node);
  9288. check_expr(c, o, ie->expr);
  9289. node->viral_state_flags |= ie->expr->viral_state_flags;
  9290. if (o->mode == Addressing_Invalid) {
  9291. o->expr = node;
  9292. return kind;
  9293. }
  9294. Type *t = base_type(type_deref(o->type));
  9295. bool is_ptr = is_type_pointer(o->type);
  9296. bool is_const = o->mode == Addressing_Constant;
  9297. if (is_type_map(t)) {
  9298. Operand key = {};
  9299. if (is_type_typeid(t->Map.key)) {
  9300. check_expr_or_type(c, &key, ie->index, t->Map.key);
  9301. } else {
  9302. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  9303. }
  9304. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  9305. if (key.mode == Addressing_Invalid) {
  9306. o->mode = Addressing_Invalid;
  9307. o->expr = node;
  9308. return kind;
  9309. }
  9310. o->mode = Addressing_MapIndex;
  9311. o->type = t->Map.value;
  9312. o->expr = node;
  9313. add_map_get_dependencies(c);
  9314. add_map_set_dependencies(c);
  9315. return Expr_Expr;
  9316. }
  9317. i64 max_count = -1;
  9318. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  9319. if (is_const) {
  9320. if (is_type_array(t)) {
  9321. // Okay
  9322. } else if (is_type_slice(t)) {
  9323. // Okay
  9324. } else if (is_type_enumerated_array(t)) {
  9325. // Okay
  9326. } else if (is_type_string(t)) {
  9327. // Okay
  9328. } else if (is_type_matrix(t)) {
  9329. // Okay
  9330. } else {
  9331. valid = false;
  9332. }
  9333. }
  9334. if (!valid) {
  9335. gbString str = expr_to_string(o->expr);
  9336. gbString type_str = type_to_string(o->type);
  9337. defer (gb_string_free(str));
  9338. defer (gb_string_free(type_str));
  9339. if (is_const) {
  9340. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  9341. } else {
  9342. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  9343. }
  9344. o->mode = Addressing_Invalid;
  9345. o->expr = node;
  9346. return kind;
  9347. }
  9348. if (ie->index == nullptr) {
  9349. gbString str = expr_to_string(o->expr);
  9350. error(o->expr, "Missing index for '%s'", str);
  9351. gb_string_free(str);
  9352. o->mode = Addressing_Invalid;
  9353. o->expr = node;
  9354. return kind;
  9355. }
  9356. Type *index_type_hint = nullptr;
  9357. if (is_type_enumerated_array(t)) {
  9358. Type *bt = base_type(t);
  9359. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  9360. index_type_hint = bt->EnumeratedArray.index;
  9361. }
  9362. i64 index = 0;
  9363. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  9364. if (is_const) {
  9365. if (index < 0) {
  9366. ERROR_BLOCK();
  9367. gbString str = expr_to_string(o->expr);
  9368. error(o->expr, "Cannot index a constant '%s'", str);
  9369. if (!build_context.terse_errors) {
  9370. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9371. }
  9372. gb_string_free(str);
  9373. o->mode = Addressing_Invalid;
  9374. o->expr = node;
  9375. return kind;
  9376. } else if (ok && !is_type_matrix(t)) {
  9377. TypeAndValue tav = type_and_value_of_expr(ie->expr);
  9378. ExactValue value = tav.value;
  9379. o->mode = Addressing_Constant;
  9380. bool success = false;
  9381. bool finish = false;
  9382. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  9383. if (!success) {
  9384. ERROR_BLOCK();
  9385. gbString str = expr_to_string(o->expr);
  9386. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  9387. if (!build_context.terse_errors) {
  9388. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9389. }
  9390. gb_string_free(str);
  9391. o->mode = Addressing_Invalid;
  9392. o->expr = node;
  9393. return kind;
  9394. }
  9395. }
  9396. }
  9397. if (type_hint != nullptr && is_type_matrix(t)) {
  9398. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  9399. // if a type hint exists
  9400. }
  9401. return kind;
  9402. }
  9403. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9404. ExprKind kind = Expr_Stmt;
  9405. ast_node(se, SliceExpr, node);
  9406. check_expr(c, o, se->expr);
  9407. node->viral_state_flags |= se->expr->viral_state_flags;
  9408. if (o->mode == Addressing_Invalid) {
  9409. o->mode = Addressing_Invalid;
  9410. o->expr = node;
  9411. return kind;
  9412. }
  9413. bool valid = false;
  9414. i64 max_count = -1;
  9415. Type *t = base_type(type_deref(o->type));
  9416. switch (t->kind) {
  9417. case Type_Basic:
  9418. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  9419. valid = true;
  9420. if (o->mode == Addressing_Constant) {
  9421. max_count = o->value.value_string.len;
  9422. }
  9423. o->type = type_deref(o->type);
  9424. }
  9425. break;
  9426. case Type_Array:
  9427. valid = true;
  9428. max_count = t->Array.count;
  9429. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9430. gbString str = expr_to_string(node);
  9431. error(node, "Cannot slice array '%s', value is not addressable", str);
  9432. gb_string_free(str);
  9433. o->mode = Addressing_Invalid;
  9434. o->expr = node;
  9435. return kind;
  9436. }
  9437. o->type = alloc_type_slice(t->Array.elem);
  9438. break;
  9439. case Type_MultiPointer:
  9440. valid = true;
  9441. o->type = type_deref(o->type);
  9442. break;
  9443. case Type_Slice:
  9444. valid = true;
  9445. o->type = type_deref(o->type);
  9446. break;
  9447. case Type_DynamicArray:
  9448. valid = true;
  9449. o->type = alloc_type_slice(t->DynamicArray.elem);
  9450. break;
  9451. case Type_Struct:
  9452. if (is_type_soa_struct(t)) {
  9453. valid = true;
  9454. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9455. max_count = t->Struct.soa_count;
  9456. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9457. gbString str = expr_to_string(node);
  9458. error(node, "Cannot slice #soa array '%s', value is not addressable", str);
  9459. gb_string_free(str);
  9460. o->mode = Addressing_Invalid;
  9461. o->expr = node;
  9462. return kind;
  9463. }
  9464. }
  9465. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  9466. }
  9467. break;
  9468. case Type_EnumeratedArray:
  9469. {
  9470. gbString str = expr_to_string(o->expr);
  9471. gbString type_str = type_to_string(o->type);
  9472. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  9473. gb_string_free(type_str);
  9474. gb_string_free(str);
  9475. o->mode = Addressing_Invalid;
  9476. o->expr = node;
  9477. return kind;
  9478. }
  9479. break;
  9480. }
  9481. if (!valid) {
  9482. gbString str = expr_to_string(o->expr);
  9483. gbString type_str = type_to_string(o->type);
  9484. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  9485. gb_string_free(type_str);
  9486. gb_string_free(str);
  9487. o->mode = Addressing_Invalid;
  9488. o->expr = node;
  9489. return kind;
  9490. }
  9491. if (se->low == nullptr && se->high != nullptr) {
  9492. // It is okay to continue as it will assume the 1st index is zero
  9493. }
  9494. i64 indices[2] = {};
  9495. Ast *nodes[2] = {se->low, se->high};
  9496. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9497. i64 index = max_count;
  9498. if (nodes[i] != nullptr) {
  9499. i64 capacity = -1;
  9500. if (max_count >= 0) {
  9501. capacity = max_count;
  9502. }
  9503. i64 j = 0;
  9504. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  9505. index = j;
  9506. }
  9507. node->viral_state_flags |= nodes[i]->viral_state_flags;
  9508. } else if (i == 0) {
  9509. index = 0;
  9510. }
  9511. indices[i] = index;
  9512. }
  9513. for (isize i = 0; i < gb_count_of(indices); i++) {
  9514. i64 a = indices[i];
  9515. for (isize j = i+1; j < gb_count_of(indices); j++) {
  9516. i64 b = indices[j];
  9517. if (a > b && b >= 0) {
  9518. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  9519. }
  9520. }
  9521. }
  9522. if (max_count < 0) {
  9523. if (o->mode == Addressing_Constant) {
  9524. gbString s = expr_to_string(se->expr);
  9525. error(se->expr, "Cannot slice constant value '%s'", s);
  9526. gb_string_free(s);
  9527. }
  9528. }
  9529. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  9530. /*
  9531. x[:] -> [^]T
  9532. x[i:] -> [^]T
  9533. x[:n] -> []T
  9534. x[i:n] -> []T
  9535. */
  9536. o->type = alloc_type_slice(t->MultiPointer.elem);
  9537. }
  9538. o->mode = Addressing_Value;
  9539. if (is_type_string(t) && max_count >= 0) {
  9540. bool all_constant = true;
  9541. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9542. if (nodes[i] != nullptr) {
  9543. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  9544. if (tav.mode != Addressing_Constant) {
  9545. all_constant = false;
  9546. break;
  9547. }
  9548. }
  9549. }
  9550. if (!all_constant) {
  9551. ERROR_BLOCK();
  9552. gbString str = expr_to_string(o->expr);
  9553. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  9554. if (!build_context.terse_errors) {
  9555. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9556. }
  9557. gb_string_free(str);
  9558. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  9559. o->expr = node;
  9560. return kind;
  9561. }
  9562. String s = {};
  9563. if (o->value.kind == ExactValue_String) {
  9564. s = o->value.value_string;
  9565. }
  9566. o->mode = Addressing_Constant;
  9567. o->type = t;
  9568. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9569. }
  9570. return kind;
  9571. }
  9572. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9573. u32 prev_state_flags = c->state_flags;
  9574. defer (c->state_flags = prev_state_flags);
  9575. if (node->state_flags != 0) {
  9576. u32 in = node->state_flags;
  9577. u32 out = c->state_flags;
  9578. if (in & StateFlag_no_bounds_check) {
  9579. out |= StateFlag_no_bounds_check;
  9580. out &= ~StateFlag_bounds_check;
  9581. } else if (in & StateFlag_bounds_check) {
  9582. out |= StateFlag_bounds_check;
  9583. out &= ~StateFlag_no_bounds_check;
  9584. }
  9585. if (in & StateFlag_no_type_assert) {
  9586. out |= StateFlag_no_type_assert;
  9587. out &= ~StateFlag_type_assert;
  9588. } else if (in & StateFlag_type_assert) {
  9589. out |= StateFlag_type_assert;
  9590. out &= ~StateFlag_no_type_assert;
  9591. }
  9592. c->state_flags = out;
  9593. }
  9594. ExprKind kind = Expr_Stmt;
  9595. o->mode = Addressing_Invalid;
  9596. o->type = t_invalid;
  9597. o->value = {ExactValue_Invalid};
  9598. switch (node->kind) {
  9599. default:
  9600. return kind;
  9601. case_ast_node(be, BadExpr, node)
  9602. return kind;
  9603. case_end;
  9604. case_ast_node(i, Implicit, node)
  9605. switch (i->kind) {
  9606. case Token_context:
  9607. {
  9608. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  9609. error(node, "'context' is only allowed within procedures");
  9610. return kind;
  9611. }
  9612. if (unparen_expr(c->assignment_lhs_hint) == node) {
  9613. c->scope->flags |= ScopeFlag_ContextDefined;
  9614. }
  9615. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  9616. error(node, "'context' has not been defined within this scope");
  9617. // Continue with value
  9618. }
  9619. init_core_context(c->checker);
  9620. o->mode = Addressing_Context;
  9621. o->type = t_context;
  9622. }
  9623. break;
  9624. default:
  9625. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  9626. return kind;
  9627. }
  9628. case_end;
  9629. case_ast_node(i, Ident, node);
  9630. check_ident(c, o, node, nullptr, type_hint, false);
  9631. case_end;
  9632. case_ast_node(u, Uninit, node);
  9633. o->mode = Addressing_Value;
  9634. o->type = t_untyped_uninit;
  9635. error(node, "Use of --- outside of variable declaration");
  9636. case_end;
  9637. case_ast_node(bl, BasicLit, node);
  9638. Type *t = t_invalid;
  9639. switch (node->tav.value.kind) {
  9640. case ExactValue_String: t = t_untyped_string; break;
  9641. case ExactValue_Float: t = t_untyped_float; break;
  9642. case ExactValue_Complex: t = t_untyped_complex; break;
  9643. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  9644. case ExactValue_Integer:
  9645. t = t_untyped_integer;
  9646. if (bl->token.kind == Token_Rune) {
  9647. t = t_untyped_rune;
  9648. }
  9649. break;
  9650. default:
  9651. GB_PANIC("Unhandled value type for basic literal");
  9652. break;
  9653. }
  9654. o->mode = Addressing_Constant;
  9655. o->type = t;
  9656. o->value = node->tav.value;
  9657. case_end;
  9658. case_ast_node(bd, BasicDirective, node);
  9659. kind = check_basic_directive_expr(c, o, node, type_hint);
  9660. case_end;
  9661. case_ast_node(pg, ProcGroup, node);
  9662. error(node, "Illegal use of a procedure group");
  9663. o->mode = Addressing_Invalid;
  9664. case_end;
  9665. case_ast_node(pl, ProcLit, node);
  9666. CheckerContext ctx = *c;
  9667. DeclInfo *decl = nullptr;
  9668. Type *type = alloc_type(Type_Proc);
  9669. check_open_scope(&ctx, pl->type);
  9670. {
  9671. decl = make_decl_info(ctx.scope, ctx.decl);
  9672. decl->proc_lit = node;
  9673. ctx.decl = decl;
  9674. defer (ctx.decl = ctx.decl->parent);
  9675. if (pl->tags != 0) {
  9676. error(node, "A procedure literal cannot have tags");
  9677. pl->tags = 0; // TODO(bill): Should I zero this?!
  9678. }
  9679. check_procedure_type(&ctx, type, pl->type);
  9680. if (!is_type_proc(type)) {
  9681. gbString str = expr_to_string(node);
  9682. error(node, "Invalid procedure literal '%s'", str);
  9683. gb_string_free(str);
  9684. check_close_scope(&ctx);
  9685. return kind;
  9686. }
  9687. if (pl->body == nullptr) {
  9688. error(node, "A procedure literal must have a body");
  9689. return kind;
  9690. }
  9691. pl->decl = decl;
  9692. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  9693. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  9694. array_add(&ctx.checker->nested_proc_lits, decl);
  9695. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  9696. }
  9697. check_close_scope(&ctx);
  9698. o->mode = Addressing_Value;
  9699. o->type = type;
  9700. case_end;
  9701. case_ast_node(te, TernaryIfExpr, node);
  9702. kind = check_ternary_if_expr(c, o, node, type_hint);
  9703. case_end;
  9704. case_ast_node(te, TernaryWhenExpr, node);
  9705. kind = check_ternary_when_expr(c, o, node, type_hint);
  9706. case_end;
  9707. case_ast_node(oe, OrElseExpr, node);
  9708. return check_or_else_expr(c, o, node, type_hint);
  9709. case_end;
  9710. case_ast_node(re, OrReturnExpr, node);
  9711. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  9712. return check_or_return_expr(c, o, node, type_hint);
  9713. case_end;
  9714. case_ast_node(re, OrBranchExpr, node);
  9715. return check_or_branch_expr(c, o, node, type_hint);
  9716. case_end;
  9717. case_ast_node(cl, CompoundLit, node);
  9718. kind = check_compound_literal(c, o, node, type_hint);
  9719. case_end;
  9720. case_ast_node(pe, ParenExpr, node);
  9721. kind = check_expr_base(c, o, pe->expr, type_hint);
  9722. node->viral_state_flags |= pe->expr->viral_state_flags;
  9723. o->expr = node;
  9724. case_end;
  9725. case_ast_node(te, TagExpr, node);
  9726. String name = te->name.string;
  9727. error(node, "Unknown tag expression, #%.*s", LIT(name));
  9728. if (te->expr) {
  9729. kind = check_expr_base(c, o, te->expr, type_hint);
  9730. node->viral_state_flags |= te->expr->viral_state_flags;
  9731. }
  9732. o->expr = node;
  9733. case_end;
  9734. case_ast_node(ta, TypeAssertion, node);
  9735. kind = check_type_assertion(c, o, node, type_hint);
  9736. case_end;
  9737. case_ast_node(tc, TypeCast, node);
  9738. check_expr_or_type(c, o, tc->type);
  9739. if (o->mode != Addressing_Type) {
  9740. gbString str = expr_to_string(tc->type);
  9741. error(tc->type, "Expected a type, got %s", str);
  9742. gb_string_free(str);
  9743. o->mode = Addressing_Invalid;
  9744. }
  9745. if (o->mode == Addressing_Invalid) {
  9746. o->expr = node;
  9747. return kind;
  9748. }
  9749. Type *type = o->type;
  9750. check_expr_base(c, o, tc->expr, type);
  9751. node->viral_state_flags |= tc->expr->viral_state_flags;
  9752. if (o->mode != Addressing_Invalid) {
  9753. switch (tc->token.kind) {
  9754. case Token_transmute:
  9755. check_transmute(c, node, o, type, true);
  9756. break;
  9757. case Token_cast:
  9758. check_cast(c, o, type, true);
  9759. break;
  9760. default:
  9761. error(node, "Invalid AST: Invalid casting expression");
  9762. o->mode = Addressing_Invalid;
  9763. break;
  9764. }
  9765. }
  9766. return Expr_Expr;
  9767. case_end;
  9768. case_ast_node(ac, AutoCast, node);
  9769. check_expr_base(c, o, ac->expr, type_hint);
  9770. node->viral_state_flags |= ac->expr->viral_state_flags;
  9771. if (o->mode == Addressing_Invalid) {
  9772. o->expr = node;
  9773. return kind;
  9774. }
  9775. if (type_hint) {
  9776. check_cast(c, o, type_hint);
  9777. }
  9778. o->expr = node;
  9779. return Expr_Expr;
  9780. case_end;
  9781. case_ast_node(ue, UnaryExpr, node);
  9782. Type *th = type_hint;
  9783. if (ue->op.kind == Token_And) {
  9784. th = type_deref(th);
  9785. }
  9786. check_expr_base(c, o, ue->expr, th);
  9787. node->viral_state_flags |= ue->expr->viral_state_flags;
  9788. if (o->mode != Addressing_Invalid) {
  9789. check_unary_expr(c, o, ue->op, node);
  9790. }
  9791. o->expr = node;
  9792. return Expr_Expr;
  9793. case_end;
  9794. case_ast_node(be, BinaryExpr, node);
  9795. check_binary_expr(c, o, node, type_hint, true);
  9796. if (o->mode == Addressing_Invalid) {
  9797. o->expr = node;
  9798. return kind;
  9799. }
  9800. case_end;
  9801. case_ast_node(se, SelectorExpr, node);
  9802. check_selector(c, o, node, type_hint);
  9803. node->viral_state_flags |= se->expr->viral_state_flags;
  9804. case_end;
  9805. case_ast_node(se, SelectorCallExpr, node);
  9806. return check_selector_call_expr(c, o, node, type_hint);
  9807. case_end;
  9808. case_ast_node(ise, ImplicitSelectorExpr, node);
  9809. return check_implicit_selector_expr(c, o, node, type_hint);
  9810. case_end;
  9811. case_ast_node(ie, IndexExpr, node);
  9812. kind = check_index_expr(c, o, node, type_hint);
  9813. case_end;
  9814. case_ast_node(se, SliceExpr, node);
  9815. kind = check_slice_expr(c, o, node, type_hint);
  9816. case_end;
  9817. case_ast_node(mie, MatrixIndexExpr, node);
  9818. check_matrix_index_expr(c, o, node, type_hint);
  9819. o->expr = node;
  9820. return Expr_Expr;
  9821. case_end;
  9822. case_ast_node(ce, CallExpr, node);
  9823. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  9824. case_end;
  9825. case_ast_node(de, DerefExpr, node);
  9826. check_expr_or_type(c, o, de->expr);
  9827. node->viral_state_flags |= de->expr->viral_state_flags;
  9828. if (o->mode == Addressing_Invalid) {
  9829. o->mode = Addressing_Invalid;
  9830. o->expr = node;
  9831. return kind;
  9832. } else {
  9833. Type *t = base_type(o->type);
  9834. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  9835. o->mode = Addressing_Variable;
  9836. o->type = t->Pointer.elem;
  9837. } else if (t->kind == Type_SoaPointer) {
  9838. o->mode = Addressing_SoaVariable;
  9839. o->type = type_deref(t);
  9840. } else {
  9841. gbString str = expr_to_string(o->expr);
  9842. gbString typ = type_to_string(o->type);
  9843. ERROR_BLOCK();
  9844. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  9845. if (o->type && is_type_multi_pointer(o->type)) {
  9846. if (!build_context.terse_errors) {
  9847. error_line("\tDid you mean '%s[0]'?\n", str);
  9848. }
  9849. }
  9850. gb_string_free(typ);
  9851. gb_string_free(str);
  9852. o->mode = Addressing_Invalid;
  9853. o->expr = node;
  9854. return kind;
  9855. }
  9856. }
  9857. case_end;
  9858. case_ast_node(ia, InlineAsmExpr, node);
  9859. if (c->curr_proc_decl == nullptr) {
  9860. error(node, "Inline asm expressions are only allowed within a procedure body");
  9861. }
  9862. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  9863. Type *return_type = nullptr;
  9864. for_array(i, ia->param_types) {
  9865. param_types[i] = check_type(c, ia->param_types[i]);
  9866. }
  9867. if (ia->return_type != nullptr) {
  9868. return_type = check_type(c, ia->return_type);
  9869. }
  9870. Operand x = {};
  9871. check_expr(c, &x, ia->asm_string);
  9872. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9873. error(x.expr, "Expected a constant string for the inline asm main parameter");
  9874. }
  9875. check_expr(c, &x, ia->constraints_string);
  9876. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9877. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  9878. }
  9879. Scope *scope = create_scope(c->info, c->scope);
  9880. scope->flags |= ScopeFlag_Proc;
  9881. Type *params = alloc_type_tuple();
  9882. Type *results = alloc_type_tuple();
  9883. if (param_types.count != 0) {
  9884. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  9885. for_array(i, param_types) {
  9886. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  9887. }
  9888. }
  9889. if (return_type != nullptr) {
  9890. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  9891. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  9892. }
  9893. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  9894. o->type = pt;
  9895. o->mode = Addressing_Value;
  9896. o->expr = node;
  9897. return Expr_Expr;
  9898. case_end;
  9899. case Ast_DistinctType:
  9900. case Ast_TypeidType:
  9901. case Ast_PolyType:
  9902. case Ast_ProcType:
  9903. case Ast_PointerType:
  9904. case Ast_MultiPointerType:
  9905. case Ast_ArrayType:
  9906. case Ast_DynamicArrayType:
  9907. case Ast_StructType:
  9908. case Ast_UnionType:
  9909. case Ast_EnumType:
  9910. case Ast_MapType:
  9911. case Ast_BitSetType:
  9912. case Ast_MatrixType:
  9913. case Ast_RelativeType:
  9914. o->mode = Addressing_Type;
  9915. o->type = check_type(c, node);
  9916. break;
  9917. }
  9918. kind = Expr_Expr;
  9919. o->expr = node;
  9920. return kind;
  9921. }
  9922. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9923. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  9924. if (o->type != nullptr && core_type(o->type) == nullptr) {
  9925. o->type = t_invalid;
  9926. gbString xs = expr_to_string(o->expr);
  9927. if (o->mode == Addressing_Type) {
  9928. error(o->expr, "Invalid type usage '%s'", xs);
  9929. } else {
  9930. error(o->expr, "Invalid expression '%s'", xs);
  9931. }
  9932. gb_string_free(xs);
  9933. }
  9934. if (o->type != nullptr && is_type_untyped(o->type)) {
  9935. add_untyped(c, node, o->mode, o->type, o->value);
  9936. }
  9937. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  9938. add_type_and_value(c, node, o->mode, o->type, o->value);
  9939. return kind;
  9940. }
  9941. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  9942. check_expr_base(c, o, e, nullptr);
  9943. switch (o->mode) {
  9944. default:
  9945. return; // NOTE(bill): Valid
  9946. case Addressing_NoValue:
  9947. error_operand_no_value(o);
  9948. break;
  9949. }
  9950. o->mode = Addressing_Invalid;
  9951. }
  9952. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  9953. check_expr_base(c, o, e, nullptr);
  9954. switch (o->mode) {
  9955. default:
  9956. return; // NOTE(bill): Valid
  9957. case Addressing_NoValue:
  9958. error_operand_no_value(o);
  9959. break;
  9960. case Addressing_Type:
  9961. error_operand_not_expression(o);
  9962. break;
  9963. }
  9964. o->mode = Addressing_Invalid;
  9965. }
  9966. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9967. check_expr_base(c, o, e, type_hint);
  9968. switch (o->mode) {
  9969. default:
  9970. return; // NOTE(bill): Valid
  9971. case Addressing_NoValue:
  9972. error_operand_no_value(o);
  9973. break;
  9974. case Addressing_Type:
  9975. error_operand_not_expression(o);
  9976. break;
  9977. }
  9978. o->mode = Addressing_Invalid;
  9979. }
  9980. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  9981. if (o->mode == Addressing_Value) {
  9982. // NOTE(bill): Tuples are not first class thus never named
  9983. if (o->type->kind == Type_Tuple) {
  9984. isize count = o->type->Tuple.variables.count;
  9985. error(o->expr,
  9986. "%td-valued expression found where single value expected", count);
  9987. o->mode = Addressing_Invalid;
  9988. GB_ASSERT(count != 1);
  9989. }
  9990. }
  9991. }
  9992. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  9993. check_multi_expr(c, o, e);
  9994. check_not_tuple(c, o);
  9995. }
  9996. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  9997. check_expr_base(c, o, e, type_hint);
  9998. check_not_tuple(c, o);
  9999. error_operand_no_value(o);
  10000. }
  10001. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  10002. switch (v.kind) {
  10003. case ExactValue_Invalid:
  10004. return true;
  10005. case ExactValue_Bool:
  10006. return !v.value_bool;
  10007. case ExactValue_String:
  10008. return v.value_string.len == 0;
  10009. case ExactValue_Integer:
  10010. return big_int_is_zero(&v.value_integer);
  10011. case ExactValue_Float:
  10012. return v.value_float == 0.0;
  10013. case ExactValue_Complex:
  10014. if (v.value_complex) {
  10015. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  10016. }
  10017. return true;
  10018. case ExactValue_Quaternion:
  10019. if (v.value_quaternion) {
  10020. return v.value_quaternion->real == 0.0 &&
  10021. v.value_quaternion->imag == 0.0 &&
  10022. v.value_quaternion->jmag == 0.0 &&
  10023. v.value_quaternion->kmag == 0.0;
  10024. }
  10025. return true;
  10026. case ExactValue_Pointer:
  10027. return v.value_pointer == 0;
  10028. case ExactValue_Compound:
  10029. if (v.value_compound == nullptr) {
  10030. return true;
  10031. } else {
  10032. ast_node(cl, CompoundLit, v.value_compound);
  10033. if (cl->elems.count == 0) {
  10034. return true;
  10035. } else {
  10036. for (Ast *elem : cl->elems) {
  10037. if (elem->tav.mode != Addressing_Constant) {
  10038. return false;
  10039. }
  10040. if (!is_exact_value_zero(elem->tav.value)) {
  10041. return false;
  10042. }
  10043. }
  10044. return true;
  10045. }
  10046. }
  10047. case ExactValue_Procedure:
  10048. return v.value_procedure == nullptr;
  10049. case ExactValue_Typeid:
  10050. return v.value_typeid == nullptr;
  10051. }
  10052. return true;
  10053. }
  10054. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  10055. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  10056. for_array(i, params) {
  10057. if (i > 0) {
  10058. str = gb_string_appendc(str, ", ");
  10059. }
  10060. str = write_expr_to_string(str, params[i], false);
  10061. }
  10062. return str;
  10063. }
  10064. gb_internal gbString string_append_string(gbString str, String string) {
  10065. if (string.len > 0) {
  10066. return gb_string_append_length(str, &string[0], string.len);
  10067. }
  10068. return str;
  10069. }
  10070. gb_internal gbString string_append_token(gbString str, Token token) {
  10071. str = string_append_string(str, token.string);
  10072. return str;
  10073. }
  10074. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  10075. if (node == nullptr)
  10076. return str;
  10077. if (is_ast_stmt(node)) {
  10078. GB_ASSERT("stmt passed to write_expr_to_string");
  10079. }
  10080. switch (node->kind) {
  10081. default:
  10082. str = gb_string_appendc(str, "(BadExpr)");
  10083. break;
  10084. case_ast_node(i, Ident, node);
  10085. str = string_append_token(str, i->token);
  10086. case_end;
  10087. case_ast_node(i, Implicit, node);
  10088. str = string_append_token(str, *i);
  10089. case_end;
  10090. case_ast_node(bl, BasicLit, node);
  10091. str = string_append_token(str, bl->token);
  10092. case_end;
  10093. case_ast_node(bd, BasicDirective, node);
  10094. str = gb_string_append_rune(str, '#');
  10095. str = string_append_string(str, bd->name.string);
  10096. case_end;
  10097. case_ast_node(ud, Uninit, node);
  10098. str = gb_string_appendc(str, "---");
  10099. case_end;
  10100. case_ast_node(pg, ProcGroup, node);
  10101. str = gb_string_appendc(str, "proc{");
  10102. for_array(i, pg->args) {
  10103. if (i > 0) str = gb_string_appendc(str, ", ");
  10104. str = write_expr_to_string(str, pg->args[i], shorthand);
  10105. }
  10106. str = gb_string_append_rune(str, '}');
  10107. case_end;
  10108. case_ast_node(pl, ProcLit, node);
  10109. str = write_expr_to_string(str, pl->type, shorthand);
  10110. if (pl->body) {
  10111. str = gb_string_appendc(str, " {...}");
  10112. } else {
  10113. str = gb_string_appendc(str, " ---");
  10114. }
  10115. case_end;
  10116. case_ast_node(cl, CompoundLit, node);
  10117. str = write_expr_to_string(str, cl->type, shorthand);
  10118. str = gb_string_append_rune(str, '{');
  10119. if (shorthand) {
  10120. str = gb_string_appendc(str, "...");
  10121. } else {
  10122. for_array(i, cl->elems) {
  10123. if (i > 0) str = gb_string_appendc(str, ", ");
  10124. str = write_expr_to_string(str, cl->elems[i], shorthand);
  10125. }
  10126. }
  10127. str = gb_string_append_rune(str, '}');
  10128. case_end;
  10129. case_ast_node(te, TagExpr, node);
  10130. str = gb_string_append_rune(str, '#');
  10131. str = string_append_token(str, te->name);
  10132. str = write_expr_to_string(str, te->expr, shorthand);
  10133. case_end;
  10134. case_ast_node(ue, UnaryExpr, node);
  10135. str = string_append_token(str, ue->op);
  10136. str = write_expr_to_string(str, ue->expr, shorthand);
  10137. case_end;
  10138. case_ast_node(de, DerefExpr, node);
  10139. str = write_expr_to_string(str, de->expr, shorthand);
  10140. str = gb_string_append_rune(str, '^');
  10141. case_end;
  10142. case_ast_node(be, BinaryExpr, node);
  10143. str = write_expr_to_string(str, be->left, shorthand);
  10144. str = gb_string_append_rune(str, ' ');
  10145. str = string_append_token(str, be->op);
  10146. str = gb_string_append_rune(str, ' ');
  10147. str = write_expr_to_string(str, be->right, shorthand);
  10148. case_end;
  10149. case_ast_node(te, TernaryIfExpr, node);
  10150. TokenPos x = ast_token(te->x).pos;
  10151. TokenPos cond = ast_token(te->cond).pos;
  10152. if (x < cond) {
  10153. str = write_expr_to_string(str, te->x, shorthand);
  10154. str = gb_string_appendc(str, " if ");
  10155. str = write_expr_to_string(str, te->cond, shorthand);
  10156. str = gb_string_appendc(str, " else ");
  10157. str = write_expr_to_string(str, te->y, shorthand);
  10158. } else {
  10159. str = write_expr_to_string(str, te->cond, shorthand);
  10160. str = gb_string_appendc(str, " ? ");
  10161. str = write_expr_to_string(str, te->x, shorthand);
  10162. str = gb_string_appendc(str, " : ");
  10163. str = write_expr_to_string(str, te->y, shorthand);
  10164. }
  10165. case_end;
  10166. case_ast_node(te, TernaryWhenExpr, node);
  10167. str = write_expr_to_string(str, te->x, shorthand);
  10168. str = gb_string_appendc(str, " when ");
  10169. str = write_expr_to_string(str, te->cond, shorthand);
  10170. str = gb_string_appendc(str, " else ");
  10171. str = write_expr_to_string(str, te->y, shorthand);
  10172. case_end;
  10173. case_ast_node(oe, OrElseExpr, node);
  10174. str = write_expr_to_string(str, oe->x, shorthand);
  10175. str = gb_string_appendc(str, " or_else ");
  10176. str = write_expr_to_string(str, oe->y, shorthand);
  10177. case_end;
  10178. case_ast_node(oe, OrReturnExpr, node);
  10179. str = write_expr_to_string(str, oe->expr, shorthand);
  10180. str = gb_string_appendc(str, " or_return");
  10181. case_end;
  10182. case_ast_node(oe, OrBranchExpr, node);
  10183. str = write_expr_to_string(str, oe->expr, shorthand);
  10184. str = gb_string_append_rune(str, ' ');
  10185. str = string_append_token(str, oe->token);
  10186. if (oe->label) {
  10187. str = gb_string_append_rune(str, ' ');
  10188. str = write_expr_to_string(str, oe->label, shorthand);
  10189. }
  10190. case_end;
  10191. case_ast_node(pe, ParenExpr, node);
  10192. str = gb_string_append_rune(str, '(');
  10193. str = write_expr_to_string(str, pe->expr, shorthand);
  10194. str = gb_string_append_rune(str, ')');
  10195. case_end;
  10196. case_ast_node(se, SelectorExpr, node);
  10197. str = write_expr_to_string(str, se->expr, shorthand);
  10198. str = string_append_token(str, se->token);
  10199. str = write_expr_to_string(str, se->selector, shorthand);
  10200. case_end;
  10201. case_ast_node(se, ImplicitSelectorExpr, node);
  10202. str = gb_string_append_rune(str, '.');
  10203. str = write_expr_to_string(str, se->selector, shorthand);
  10204. case_end;
  10205. case_ast_node(se, SelectorCallExpr, node);
  10206. str = write_expr_to_string(str, se->expr, shorthand);
  10207. str = gb_string_appendc(str, "(");
  10208. ast_node(ce, CallExpr, se->call);
  10209. isize start = se->modified_call ? 1 : 0;
  10210. for (isize i = start; i < ce->args.count; i++) {
  10211. Ast *arg = ce->args[i];
  10212. if (i > start) {
  10213. str = gb_string_appendc(str, ", ");
  10214. }
  10215. str = write_expr_to_string(str, arg, shorthand);
  10216. }
  10217. str = gb_string_appendc(str, ")");
  10218. case_end;
  10219. case_ast_node(ta, TypeAssertion, node);
  10220. str = write_expr_to_string(str, ta->expr, shorthand);
  10221. if (ta->type != nullptr &&
  10222. ta->type->kind == Ast_UnaryExpr &&
  10223. ta->type->UnaryExpr.op.kind == Token_Question) {
  10224. str = gb_string_appendc(str, ".?");
  10225. } else {
  10226. str = gb_string_appendc(str, ".(");
  10227. str = write_expr_to_string(str, ta->type, shorthand);
  10228. str = gb_string_append_rune(str, ')');
  10229. }
  10230. case_end;
  10231. case_ast_node(tc, TypeCast, node);
  10232. str = string_append_token(str, tc->token);
  10233. str = gb_string_append_rune(str, '(');
  10234. str = write_expr_to_string(str, tc->type, shorthand);
  10235. str = gb_string_append_rune(str, ')');
  10236. str = write_expr_to_string(str, tc->expr, shorthand);
  10237. case_end;
  10238. case_ast_node(ac, AutoCast, node);
  10239. str = string_append_token(str, ac->token);
  10240. str = gb_string_append_rune(str, ' ');
  10241. str = write_expr_to_string(str, ac->expr, shorthand);
  10242. case_end;
  10243. case_ast_node(ie, IndexExpr, node);
  10244. str = write_expr_to_string(str, ie->expr, shorthand);
  10245. str = gb_string_append_rune(str, '[');
  10246. str = write_expr_to_string(str, ie->index, shorthand);
  10247. str = gb_string_append_rune(str, ']');
  10248. case_end;
  10249. case_ast_node(se, SliceExpr, node);
  10250. str = write_expr_to_string(str, se->expr, shorthand);
  10251. str = gb_string_append_rune(str, '[');
  10252. str = write_expr_to_string(str, se->low, shorthand);
  10253. str = string_append_token(str, se->interval);
  10254. str = write_expr_to_string(str, se->high, shorthand);
  10255. str = gb_string_append_rune(str, ']');
  10256. case_end;
  10257. case_ast_node(mie, MatrixIndexExpr, node);
  10258. str = write_expr_to_string(str, mie->expr, shorthand);
  10259. str = gb_string_append_rune(str, '[');
  10260. str = write_expr_to_string(str, mie->row_index, shorthand);
  10261. str = gb_string_appendc(str, ", ");
  10262. str = write_expr_to_string(str, mie->column_index, shorthand);
  10263. str = gb_string_append_rune(str, ']');
  10264. case_end;
  10265. case_ast_node(e, Ellipsis, node);
  10266. str = gb_string_appendc(str, "..");
  10267. str = write_expr_to_string(str, e->expr, shorthand);
  10268. case_end;
  10269. case_ast_node(fv, FieldValue, node);
  10270. str = write_expr_to_string(str, fv->field, shorthand);
  10271. str = gb_string_appendc(str, " = ");
  10272. str = write_expr_to_string(str, fv->value, shorthand);
  10273. case_end;
  10274. case_ast_node(fv, EnumFieldValue, node);
  10275. str = write_expr_to_string(str, fv->name, shorthand);
  10276. if (fv->value) {
  10277. str = gb_string_appendc(str, " = ");
  10278. str = write_expr_to_string(str, fv->value, shorthand);
  10279. }
  10280. case_end;
  10281. case_ast_node(ht, HelperType, node);
  10282. str = gb_string_appendc(str, "#type ");
  10283. str = write_expr_to_string(str, ht->type, shorthand);
  10284. case_end;
  10285. case_ast_node(ht, DistinctType, node);
  10286. str = gb_string_appendc(str, "distinct ");
  10287. str = write_expr_to_string(str, ht->type, shorthand);
  10288. case_end;
  10289. case_ast_node(pt, PolyType, node);
  10290. str = gb_string_append_rune(str, '$');
  10291. str = write_expr_to_string(str, pt->type, shorthand);
  10292. if (pt->specialization != nullptr) {
  10293. str = gb_string_append_rune(str, '/');
  10294. str = write_expr_to_string(str, pt->specialization, shorthand);
  10295. }
  10296. case_end;
  10297. case_ast_node(pt, PointerType, node);
  10298. if (pt->tag) {
  10299. str = write_expr_to_string(str, pt->tag, false);
  10300. }
  10301. str = gb_string_append_rune(str, '^');
  10302. str = write_expr_to_string(str, pt->type, shorthand);
  10303. case_end;
  10304. case_ast_node(pt, MultiPointerType, node);
  10305. str = gb_string_appendc(str, "[^]");
  10306. str = write_expr_to_string(str, pt->type, shorthand);
  10307. case_end;
  10308. case_ast_node(at, ArrayType, node);
  10309. if (at->tag) {
  10310. str = write_expr_to_string(str, at->tag, false);
  10311. }
  10312. str = gb_string_append_rune(str, '[');
  10313. if (at->count != nullptr &&
  10314. at->count->kind == Ast_UnaryExpr &&
  10315. at->count->UnaryExpr.op.kind == Token_Question) {
  10316. str = gb_string_appendc(str, "?");
  10317. } else {
  10318. str = write_expr_to_string(str, at->count, shorthand);
  10319. }
  10320. str = gb_string_append_rune(str, ']');
  10321. str = write_expr_to_string(str, at->elem, shorthand);
  10322. case_end;
  10323. case_ast_node(at, DynamicArrayType, node);
  10324. if (at->tag) {
  10325. str = write_expr_to_string(str, at->tag, false);
  10326. }
  10327. str = gb_string_appendc(str, "[dynamic]");
  10328. str = write_expr_to_string(str, at->elem, shorthand);
  10329. case_end;
  10330. case_ast_node(bs, BitSetType, node);
  10331. str = gb_string_appendc(str, "bit_set[");
  10332. str = write_expr_to_string(str, bs->elem, shorthand);
  10333. str = gb_string_appendc(str, "]");
  10334. case_end;
  10335. case_ast_node(mt, MapType, node);
  10336. str = gb_string_appendc(str, "map[");
  10337. str = write_expr_to_string(str, mt->key, shorthand);
  10338. str = gb_string_append_rune(str, ']');
  10339. str = write_expr_to_string(str, mt->value, shorthand);
  10340. case_end;
  10341. case_ast_node(mt, MatrixType, node);
  10342. str = gb_string_appendc(str, "matrix[");
  10343. str = write_expr_to_string(str, mt->row_count, shorthand);
  10344. str = gb_string_appendc(str, ", ");
  10345. str = write_expr_to_string(str, mt->column_count, shorthand);
  10346. str = gb_string_append_rune(str, ']');
  10347. str = write_expr_to_string(str, mt->elem, shorthand);
  10348. case_end;
  10349. case_ast_node(f, Field, node);
  10350. if (f->flags&FieldFlag_using) {
  10351. str = gb_string_appendc(str, "using ");
  10352. }
  10353. if (f->flags&FieldFlag_no_alias) {
  10354. str = gb_string_appendc(str, "#no_alias ");
  10355. }
  10356. if (f->flags&FieldFlag_c_vararg) {
  10357. str = gb_string_appendc(str, "#c_vararg ");
  10358. }
  10359. if (f->flags&FieldFlag_any_int) {
  10360. str = gb_string_appendc(str, "#any_int ");
  10361. }
  10362. if (f->flags&FieldFlag_no_broadcast) {
  10363. str = gb_string_appendc(str, "#no_broadcast ");
  10364. }
  10365. if (f->flags&FieldFlag_const) {
  10366. str = gb_string_appendc(str, "#const ");
  10367. }
  10368. if (f->flags&FieldFlag_subtype) {
  10369. str = gb_string_appendc(str, "#subtype ");
  10370. }
  10371. for_array(i, f->names) {
  10372. Ast *name = f->names[i];
  10373. if (i > 0) str = gb_string_appendc(str, ", ");
  10374. str = write_expr_to_string(str, name, shorthand);
  10375. }
  10376. if (f->names.count > 0) {
  10377. if (f->type == nullptr && f->default_value != nullptr) {
  10378. str = gb_string_append_rune(str, ' ');
  10379. }
  10380. str = gb_string_appendc(str, ":");
  10381. }
  10382. if (f->type != nullptr) {
  10383. str = gb_string_append_rune(str, ' ');
  10384. str = write_expr_to_string(str, f->type, shorthand);
  10385. }
  10386. if (f->default_value != nullptr) {
  10387. if (f->type != nullptr) {
  10388. str = gb_string_append_rune(str, ' ');
  10389. }
  10390. str = gb_string_appendc(str, "= ");
  10391. str = write_expr_to_string(str, f->default_value, shorthand);
  10392. }
  10393. case_end;
  10394. case_ast_node(f, FieldList, node);
  10395. bool has_name = false;
  10396. for_array(i, f->list) {
  10397. ast_node(field, Field, f->list[i]);
  10398. if (field->names.count > 1) {
  10399. has_name = true;
  10400. break;
  10401. }
  10402. if (field->names.count == 0) {
  10403. continue;
  10404. }
  10405. if (!is_blank_ident(field->names[0])) {
  10406. has_name = true;
  10407. break;
  10408. }
  10409. }
  10410. for_array(i, f->list) {
  10411. if (i > 0) str = gb_string_appendc(str, ", ");
  10412. if (has_name) {
  10413. str = write_expr_to_string(str, f->list[i], shorthand);
  10414. } else {
  10415. ast_node(field, Field, f->list[i]);
  10416. if (field->flags&FieldFlag_using) {
  10417. str = gb_string_appendc(str, "using ");
  10418. }
  10419. if (field->flags&FieldFlag_no_alias) {
  10420. str = gb_string_appendc(str, "#no_alias ");
  10421. }
  10422. if (field->flags&FieldFlag_c_vararg) {
  10423. str = gb_string_appendc(str, "#c_vararg ");
  10424. }
  10425. if (field->flags&FieldFlag_any_int) {
  10426. str = gb_string_appendc(str, "#any_int ");
  10427. }
  10428. if (field->flags&FieldFlag_no_broadcast) {
  10429. str = gb_string_appendc(str, "#no_broadcast ");
  10430. }
  10431. if (field->flags&FieldFlag_const) {
  10432. str = gb_string_appendc(str, "#const ");
  10433. }
  10434. if (field->flags&FieldFlag_subtype) {
  10435. str = gb_string_appendc(str, "#subtype ");
  10436. }
  10437. str = write_expr_to_string(str, field->type, shorthand);
  10438. }
  10439. }
  10440. case_end;
  10441. case_ast_node(ce, CallExpr, node);
  10442. switch (ce->inlining) {
  10443. case ProcInlining_inline:
  10444. str = gb_string_appendc(str, "#force_inline ");
  10445. break;
  10446. case ProcInlining_no_inline:
  10447. str = gb_string_appendc(str, "#force_no_inline ");
  10448. break;
  10449. }
  10450. str = write_expr_to_string(str, ce->proc, shorthand);
  10451. str = gb_string_appendc(str, "(");
  10452. isize idx0 = cast(isize)ce->was_selector;
  10453. for (isize i = idx0; i < ce->args.count; i++) {
  10454. Ast *arg = ce->args[i];
  10455. if (i > idx0) {
  10456. str = gb_string_appendc(str, ", ");
  10457. }
  10458. str = write_expr_to_string(str, arg, shorthand);
  10459. }
  10460. str = gb_string_appendc(str, ")");
  10461. case_end;
  10462. case_ast_node(tt, TypeidType, node);
  10463. str = gb_string_appendc(str, "typeid");
  10464. if (tt->specialization) {
  10465. str = gb_string_appendc(str, "/");
  10466. str = write_expr_to_string(str, tt->specialization, shorthand);
  10467. }
  10468. case_end;
  10469. case_ast_node(pt, ProcType, node);
  10470. str = gb_string_appendc(str, "proc(");
  10471. str = write_expr_to_string(str, pt->params, shorthand);
  10472. str = gb_string_appendc(str, ")");
  10473. if (pt->results != nullptr) {
  10474. str = gb_string_appendc(str, " -> ");
  10475. bool parens_needed = false;
  10476. if (pt->results && pt->results->kind == Ast_FieldList) {
  10477. for (Ast *field : pt->results->FieldList.list) {
  10478. ast_node(f, Field, field);
  10479. if (f->names.count != 0) {
  10480. parens_needed = true;
  10481. break;
  10482. }
  10483. }
  10484. }
  10485. if (parens_needed) {
  10486. str = gb_string_append_rune(str, '(');
  10487. }
  10488. str = write_expr_to_string(str, pt->results, shorthand);
  10489. if (parens_needed) {
  10490. str = gb_string_append_rune(str, ')');
  10491. }
  10492. }
  10493. case_end;
  10494. case_ast_node(st, StructType, node);
  10495. str = gb_string_appendc(str, "struct ");
  10496. if (st->polymorphic_params) {
  10497. str = gb_string_append_rune(str, '(');
  10498. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10499. str = gb_string_appendc(str, ") ");
  10500. }
  10501. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  10502. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  10503. if (st->align) {
  10504. str = gb_string_appendc(str, "#align ");
  10505. str = write_expr_to_string(str, st->align, shorthand);
  10506. str = gb_string_append_rune(str, ' ');
  10507. }
  10508. str = gb_string_append_rune(str, '{');
  10509. if (shorthand) {
  10510. str = gb_string_appendc(str, "...");
  10511. } else {
  10512. str = write_struct_fields_to_string(str, st->fields);
  10513. }
  10514. str = gb_string_append_rune(str, '}');
  10515. case_end;
  10516. case_ast_node(st, UnionType, node);
  10517. str = gb_string_appendc(str, "union ");
  10518. if (st->polymorphic_params) {
  10519. str = gb_string_append_rune(str, '(');
  10520. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10521. str = gb_string_appendc(str, ") ");
  10522. }
  10523. switch (st->kind) {
  10524. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  10525. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  10526. }
  10527. if (st->align) {
  10528. str = gb_string_appendc(str, "#align ");
  10529. str = write_expr_to_string(str, st->align, shorthand);
  10530. str = gb_string_append_rune(str, ' ');
  10531. }
  10532. str = gb_string_append_rune(str, '{');
  10533. if (shorthand) {
  10534. str = gb_string_appendc(str, "...");
  10535. } else {
  10536. str = write_struct_fields_to_string(str, st->variants);
  10537. }
  10538. str = gb_string_append_rune(str, '}');
  10539. case_end;
  10540. case_ast_node(et, EnumType, node);
  10541. str = gb_string_appendc(str, "enum ");
  10542. if (et->base_type != nullptr) {
  10543. str = write_expr_to_string(str, et->base_type, shorthand);
  10544. str = gb_string_append_rune(str, ' ');
  10545. }
  10546. str = gb_string_append_rune(str, '{');
  10547. if (shorthand) {
  10548. str = gb_string_appendc(str, "...");
  10549. } else {
  10550. for_array(i, et->fields) {
  10551. if (i > 0) {
  10552. str = gb_string_appendc(str, ", ");
  10553. }
  10554. str = write_expr_to_string(str, et->fields[i], shorthand);
  10555. }
  10556. }
  10557. str = gb_string_append_rune(str, '}');
  10558. case_end;
  10559. case_ast_node(rt, RelativeType, node);
  10560. str = write_expr_to_string(str, rt->tag, shorthand);
  10561. str = gb_string_appendc(str, "" );
  10562. str = write_expr_to_string(str, rt->type, shorthand);
  10563. case_end;
  10564. case_ast_node(f, BitFieldField, node);
  10565. str = write_expr_to_string(str, f->name, shorthand);
  10566. str = gb_string_appendc(str, ": ");
  10567. str = write_expr_to_string(str, f->type, shorthand);
  10568. str = gb_string_appendc(str, " | ");
  10569. str = write_expr_to_string(str, f->bit_size, shorthand);
  10570. case_end;
  10571. case_ast_node(bf, BitFieldType, node);
  10572. str = gb_string_appendc(str, "bit_field ");
  10573. if (!shorthand) {
  10574. str = write_expr_to_string(str, bf->backing_type, shorthand);
  10575. }
  10576. str = gb_string_appendc(str, " {");
  10577. if (shorthand) {
  10578. str = gb_string_appendc(str, "...");
  10579. } else {
  10580. for_array(i, bf->fields) {
  10581. if (i > 0) {
  10582. str = gb_string_appendc(str, ", ");
  10583. }
  10584. str = write_expr_to_string(str, bf->fields[i], false);
  10585. }
  10586. }
  10587. str = gb_string_appendc(str, "}");
  10588. case_end;
  10589. case_ast_node(ia, InlineAsmExpr, node);
  10590. str = gb_string_appendc(str, "asm(");
  10591. for_array(i, ia->param_types) {
  10592. if (i > 0) {
  10593. str = gb_string_appendc(str, ", ");
  10594. }
  10595. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  10596. }
  10597. str = gb_string_appendc(str, ")");
  10598. if (ia->return_type != nullptr) {
  10599. str = gb_string_appendc(str, " -> ");
  10600. str = write_expr_to_string(str, ia->return_type, shorthand);
  10601. }
  10602. if (ia->has_side_effects) {
  10603. str = gb_string_appendc(str, " #side_effects");
  10604. }
  10605. if (ia->is_align_stack) {
  10606. str = gb_string_appendc(str, " #stack_align");
  10607. }
  10608. if (ia->dialect) {
  10609. str = gb_string_appendc(str, " #");
  10610. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  10611. }
  10612. str = gb_string_appendc(str, " {");
  10613. if (shorthand) {
  10614. str = gb_string_appendc(str, "...");
  10615. } else {
  10616. str = write_expr_to_string(str, ia->asm_string, shorthand);
  10617. str = gb_string_appendc(str, ", ");
  10618. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  10619. }
  10620. str = gb_string_appendc(str, "}");
  10621. case_end;
  10622. }
  10623. return str;
  10624. }
  10625. gb_internal gbString expr_to_string(Ast *expression) {
  10626. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  10627. }
  10628. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  10629. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  10630. }
  10631. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  10632. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  10633. }