check_expr.cpp 358 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246
  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. if (expr == nullptr) {
  217. return nullptr;
  218. }
  219. switch (expr->kind) {
  220. case Ast_Ident:
  221. return expr->Ident.entity;
  222. case Ast_SelectorExpr:
  223. return entity_from_expr(expr->SelectorExpr.selector);
  224. }
  225. return nullptr;
  226. }
  227. gb_internal void error_operand_not_expression(Operand *o) {
  228. if (o->mode == Addressing_Type) {
  229. gbString err = expr_to_string(o->expr);
  230. error(o->expr, "'%s' is not an expression but a type", err);
  231. gb_string_free(err);
  232. o->mode = Addressing_Invalid;
  233. }
  234. }
  235. gb_internal void error_operand_no_value(Operand *o) {
  236. if (o->mode == Addressing_NoValue) {
  237. Ast *x = unparen_expr(o->expr);
  238. if (x != nullptr && x->kind == Ast_CallExpr) {
  239. Ast *p = unparen_expr(x->CallExpr.proc);
  240. if (p->kind == Ast_BasicDirective) {
  241. String tag = p->BasicDirective.name.string;
  242. if (tag == "panic" ||
  243. tag == "assert") {
  244. return;
  245. }
  246. }
  247. }
  248. gbString err = expr_to_string(o->expr);
  249. if (x != nullptr && x->kind == Ast_CallExpr) {
  250. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  251. } else {
  252. error(o->expr, "'%s' used as a value", err);
  253. }
  254. gb_string_free(err);
  255. o->mode = Addressing_Invalid;
  256. }
  257. }
  258. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  259. if (build_context.dynamic_map_calls) {
  260. add_package_dependency(c, "runtime", "__dynamic_map_get");
  261. } else {
  262. add_package_dependency(c, "runtime", "map_desired_position");
  263. add_package_dependency(c, "runtime", "map_probe_distance");
  264. }
  265. }
  266. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  267. init_core_source_code_location(c->checker);
  268. if (t_map_set_proc == nullptr) {
  269. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  270. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  271. }
  272. if (build_context.dynamic_map_calls) {
  273. add_package_dependency(c, "runtime", "__dynamic_map_set");
  274. } else {
  275. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  276. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  277. }
  278. }
  279. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  280. init_core_source_code_location(c->checker);
  281. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  282. }
  283. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  284. Scope *s = c->scope;
  285. check_collect_entities(c, nodes);
  286. for (auto const &entry : s->elements) {
  287. Entity *e = entry.value;\
  288. switch (e->kind) {
  289. case Entity_Constant:
  290. case Entity_TypeName:
  291. case Entity_Procedure:
  292. break;
  293. default:
  294. continue;
  295. }
  296. DeclInfo *d = decl_info_of_entity(e);
  297. if (d != nullptr) {
  298. check_entity_decl(c, e, d, nullptr);
  299. }
  300. }
  301. }
  302. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  303. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  304. ///////////////////////////////////////////////////////////////////////////////
  305. // //
  306. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  307. // //
  308. ///////////////////////////////////////////////////////////////////////////////
  309. CheckerInfo *info = old_c->info;
  310. if (base_entity == nullptr) {
  311. return false;
  312. }
  313. if (!is_type_proc(base_entity->type)) {
  314. return false;
  315. }
  316. if (base_entity->flags & EntityFlag_Disabled) {
  317. return false;
  318. }
  319. String name = base_entity->token.string;
  320. Type *src = base_type(base_entity->type);
  321. Type *dst = nullptr;
  322. if (type != nullptr) {
  323. dst = base_type(type);
  324. }
  325. if (param_operands == nullptr) {
  326. GB_ASSERT(dst != nullptr);
  327. }
  328. if (param_operands != nullptr) {
  329. GB_ASSERT(dst == nullptr);
  330. }
  331. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  332. return false;
  333. }
  334. if (dst != nullptr) {
  335. if (dst->Proc.is_polymorphic) {
  336. return false;
  337. }
  338. if (dst->Proc.param_count != src->Proc.param_count ||
  339. dst->Proc.result_count != src->Proc.result_count) {
  340. return false;
  341. }
  342. }
  343. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  344. if (old_decl == nullptr) {
  345. return false;
  346. }
  347. gbAllocator a = heap_allocator();
  348. Array<Operand> operands = {};
  349. if (param_operands) {
  350. operands = *param_operands;
  351. } else {
  352. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  353. for (isize i = 0; i < dst->Proc.param_count; i++) {
  354. Entity *param = dst->Proc.params->Tuple.variables[i];
  355. Operand o = {Addressing_Value};
  356. o.type = param->type;
  357. array_add(&operands, o);
  358. }
  359. }
  360. defer (if (param_operands == nullptr) {
  361. array_free(&operands);
  362. });
  363. CheckerContext nctx = *old_c;
  364. Scope *scope = create_scope(info, base_entity->scope);
  365. scope->flags |= ScopeFlag_Proc;
  366. nctx.scope = scope;
  367. nctx.allow_polymorphic_types = true;
  368. if (nctx.polymorphic_scope == nullptr) {
  369. nctx.polymorphic_scope = scope;
  370. }
  371. auto *pt = &src->Proc;
  372. // NOTE(bill): This is slightly memory leaking if the type already exists
  373. // Maybe it's better to check with the previous types first?
  374. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  375. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  376. if (!success) {
  377. return false;
  378. }
  379. GenProcsData *gen_procs = nullptr;
  380. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  381. GB_ASSERT(base_entity->kind == Entity_Procedure);
  382. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  383. gen_procs = base_entity->Procedure.gen_procs;
  384. if (gen_procs) {
  385. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  386. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  387. for (Entity *other : gen_procs->procs) {
  388. Type *pt = base_type(other->type);
  389. if (are_types_identical(pt, final_proc_type)) {
  390. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  391. if (poly_proc_data) {
  392. poly_proc_data->gen_entity = other;
  393. }
  394. return true;
  395. }
  396. }
  397. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  398. } else {
  399. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  400. gen_procs->procs.allocator = heap_allocator();
  401. base_entity->Procedure.gen_procs = gen_procs;
  402. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  403. }
  404. {
  405. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  406. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  407. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  408. nctx.no_polymorphic_errors = false;
  409. // NOTE(bill): Reset scope from the failed procedure type
  410. scope->head_child.store(nullptr, std::memory_order_relaxed);
  411. string_map_clear(&scope->elements);
  412. ptr_set_clear(&scope->imported);
  413. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  414. Ast *cloned_proc_type_node = clone_ast(pt->node);
  415. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  416. if (!success) {
  417. return false;
  418. }
  419. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  420. for (Entity *other : gen_procs->procs) {
  421. Type *pt = base_type(other->type);
  422. if (are_types_identical(pt, final_proc_type)) {
  423. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  424. if (poly_proc_data) {
  425. poly_proc_data->gen_entity = other;
  426. }
  427. DeclInfo *decl = other->decl_info;
  428. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  429. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  430. proc_info->file = other->file;
  431. proc_info->token = other->token;
  432. proc_info->decl = decl;
  433. proc_info->type = other->type;
  434. proc_info->body = decl->proc_lit->ProcLit.body;
  435. proc_info->tags = other->Procedure.tags;;
  436. proc_info->generated_from_polymorphic = true;
  437. proc_info->poly_def_node = poly_def_node;
  438. check_procedure_later(nctx.checker, proc_info);
  439. }
  440. return true;
  441. }
  442. }
  443. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  444. }
  445. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  446. ast_node(pl, ProcLit, proc_lit);
  447. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  448. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  449. final_proc_type->Proc.is_poly_specialized = true;
  450. final_proc_type->Proc.is_polymorphic = true;
  451. final_proc_type->Proc.variadic = src->Proc.variadic;
  452. final_proc_type->Proc.require_results = src->Proc.require_results;
  453. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  454. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  455. final_proc_type->Proc.diverging = src->Proc.diverging;
  456. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  457. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  458. final_proc_type->Proc.enable_target_feature = src->Proc.enable_target_feature;
  459. final_proc_type->Proc.require_target_feature = src->Proc.require_target_feature;
  460. for (isize i = 0; i < operands.count; i++) {
  461. Operand o = operands[i];
  462. if (final_proc_type == o.type ||
  463. base_entity->type == o.type) {
  464. // NOTE(bill): Cycle
  465. final_proc_type->Proc.is_poly_specialized = false;
  466. break;
  467. }
  468. }
  469. u64 tags = base_entity->Procedure.tags;
  470. Ast *ident = clone_ast(base_entity->identifier);
  471. Token token = ident->Ident.token;
  472. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  473. d->gen_proc_type = final_proc_type;
  474. d->type_expr = pl->type;
  475. d->proc_lit = proc_lit;
  476. d->proc_checked_state = ProcCheckedState_Unchecked;
  477. d->defer_use_checked = false;
  478. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  479. entity->state.store(EntityState_Resolved);
  480. entity->identifier = ident;
  481. add_entity_and_decl_info(&nctx, ident, entity, d);
  482. // NOTE(bill): Set the scope afterwards as this is not real overloading
  483. entity->scope = scope->parent;
  484. entity->file = base_entity->file;
  485. entity->pkg = base_entity->pkg;
  486. entity->flags = 0;
  487. entity->Procedure.optimization_mode = base_entity->Procedure.optimization_mode;
  488. if (base_entity->flags & EntityFlag_Cold) {
  489. entity->flags |= EntityFlag_Cold;
  490. }
  491. if (base_entity->flags & EntityFlag_Disabled) {
  492. entity->flags |= EntityFlag_Disabled;
  493. }
  494. d->entity = entity;
  495. AstFile *file = nullptr;
  496. {
  497. Scope *s = entity->scope;
  498. while (s != nullptr && s->file == nullptr) {
  499. file = s->file;
  500. s = s->parent;
  501. }
  502. }
  503. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  504. array_add(&gen_procs->procs, entity);
  505. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  506. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  507. proc_info->file = file;
  508. proc_info->token = token;
  509. proc_info->decl = d;
  510. proc_info->type = final_proc_type;
  511. proc_info->body = pl->body;
  512. proc_info->tags = tags;
  513. proc_info->generated_from_polymorphic = true;
  514. proc_info->poly_def_node = poly_def_node;
  515. if (poly_proc_data) {
  516. poly_proc_data->gen_entity = entity;
  517. poly_proc_data->proc_info = proc_info;
  518. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  519. }
  520. // NOTE(bill): Check the newly generated procedure body
  521. check_procedure_later(nctx.checker, proc_info);
  522. return true;
  523. }
  524. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  525. if (operand->expr == nullptr) return false;
  526. Entity *base_entity = entity_from_expr(operand->expr);
  527. if (base_entity == nullptr) return false;
  528. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  529. }
  530. 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) {
  531. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  532. }
  533. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  534. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  535. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  536. #define MAXIMUM_TYPE_DISTANCE 10
  537. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming) {
  538. if (c == nullptr) {
  539. GB_ASSERT(operand->mode == Addressing_Value);
  540. GB_ASSERT(is_type_typed(operand->type));
  541. }
  542. if (operand->mode == Addressing_Invalid ||
  543. type == t_invalid) {
  544. return -1;
  545. }
  546. if (operand->mode == Addressing_Builtin) {
  547. return -1;
  548. }
  549. if (operand->mode == Addressing_Type) {
  550. if (is_type_typeid(type)) {
  551. if (is_type_polymorphic(operand->type)) {
  552. return -1;
  553. }
  554. add_type_info_type(c, operand->type);
  555. return 4;
  556. }
  557. return -1;
  558. }
  559. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  560. return -1;
  561. }
  562. Type *s = operand->type;
  563. if (are_types_identical(s, type)) {
  564. return 0;
  565. }
  566. Type *src = base_type(s);
  567. Type *dst = base_type(type);
  568. if (is_type_untyped_uninit(src)) {
  569. return 1;
  570. }
  571. if (is_type_untyped_nil(src)) {
  572. if (type_has_nil(dst)) {
  573. return 1;
  574. }
  575. return -1;
  576. }
  577. if (is_type_untyped(src)) {
  578. if (is_type_any(dst)) {
  579. // NOTE(bill): Anything can cast to 'Any'
  580. add_type_info_type(c, s);
  581. return MAXIMUM_TYPE_DISTANCE;
  582. }
  583. if (dst->kind == Type_Basic) {
  584. if (operand->mode == Addressing_Constant) {
  585. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  586. if (is_type_typed(dst) && src->kind == Type_Basic) {
  587. switch (src->Basic.kind) {
  588. case Basic_UntypedBool:
  589. if (is_type_boolean(dst)) {
  590. return 1;
  591. }
  592. break;
  593. case Basic_UntypedRune:
  594. if (is_type_integer(dst) || is_type_rune(dst)) {
  595. return 1;
  596. }
  597. break;
  598. case Basic_UntypedInteger:
  599. if (is_type_integer(dst) || is_type_rune(dst)) {
  600. return 1;
  601. }
  602. break;
  603. case Basic_UntypedString:
  604. if (is_type_string(dst)) {
  605. return 1;
  606. }
  607. break;
  608. case Basic_UntypedFloat:
  609. if (is_type_float(dst)) {
  610. return 1;
  611. }
  612. break;
  613. case Basic_UntypedComplex:
  614. if (is_type_complex(dst)) {
  615. return 1;
  616. }
  617. if (is_type_quaternion(dst)) {
  618. return 2;
  619. }
  620. break;
  621. case Basic_UntypedQuaternion:
  622. if (is_type_quaternion(dst)) {
  623. return 1;
  624. }
  625. break;
  626. }
  627. }
  628. return 2;
  629. }
  630. return -1;
  631. }
  632. if (src->kind == Type_Basic) {
  633. Type *d = base_array_type(dst);
  634. i64 score = -1;
  635. switch (src->Basic.kind) {
  636. case Basic_UntypedBool:
  637. if (is_type_boolean(d)) {
  638. score = 1;
  639. }
  640. break;
  641. case Basic_UntypedRune:
  642. if (is_type_integer(d) || is_type_rune(d)) {
  643. score = 1;
  644. }
  645. break;
  646. case Basic_UntypedInteger:
  647. if (is_type_integer(d) || is_type_rune(d)) {
  648. score = 1;
  649. }
  650. break;
  651. case Basic_UntypedString:
  652. if (is_type_string(d)) {
  653. score = 1;
  654. }
  655. break;
  656. case Basic_UntypedFloat:
  657. if (is_type_float(d)) {
  658. score = 1;
  659. }
  660. break;
  661. case Basic_UntypedComplex:
  662. if (is_type_complex(d)) {
  663. score = 1;
  664. }
  665. if (is_type_quaternion(d)) {
  666. score = 2;
  667. }
  668. break;
  669. case Basic_UntypedQuaternion:
  670. if (is_type_quaternion(d)) {
  671. score = 1;
  672. }
  673. break;
  674. }
  675. if (score > 0) {
  676. if (is_type_typed(d)) {
  677. score += 1;
  678. }
  679. if (d != dst) {
  680. score += 6;
  681. }
  682. }
  683. return score;
  684. }
  685. }
  686. }
  687. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  688. if (c->in_enum_type) {
  689. return 3;
  690. }
  691. }
  692. {
  693. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  694. if (subtype_level > 0) {
  695. return 4 + subtype_level;
  696. }
  697. }
  698. // rawptr <- ^T
  699. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  700. return 5;
  701. }
  702. // rawptr <- [^]T
  703. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  704. return 5;
  705. }
  706. // ^T <- [^]T
  707. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  708. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  709. return 4;
  710. }
  711. }
  712. // [^]T <- ^T
  713. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  714. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  715. return 4;
  716. }
  717. }
  718. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  719. bool modify_type = !c->no_polymorphic_errors;
  720. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  721. return 2;
  722. }
  723. }
  724. if (is_type_union(dst)) {
  725. for (Type *vt : dst->Union.variants) {
  726. if (are_types_identical(vt, s)) {
  727. return 1;
  728. }
  729. if (is_type_proc(vt)) {
  730. if (are_types_identical(base_type(vt), src)) {
  731. return 1;
  732. }
  733. }
  734. }
  735. if (dst->Union.variants.count == 1) {
  736. Type *vt = dst->Union.variants[0];
  737. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  738. if (score >= 0) {
  739. return score+2;
  740. }
  741. } else if (is_type_untyped(src)) {
  742. i64 prev_lowest_score = -1;
  743. i64 lowest_score = -1;
  744. for (Type *vt : dst->Union.variants) {
  745. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  746. if (score >= 0) {
  747. if (lowest_score < 0) {
  748. lowest_score = score;
  749. } else {
  750. if (prev_lowest_score < 0) {
  751. prev_lowest_score = lowest_score;
  752. } else {
  753. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  754. }
  755. lowest_score = gb_min(lowest_score, score);
  756. }
  757. }
  758. }
  759. if (lowest_score >= 0) {
  760. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  761. return lowest_score+2;
  762. }
  763. }
  764. }
  765. }
  766. if (is_type_proc(dst)) {
  767. if (are_types_identical(src, dst)) {
  768. return 3;
  769. }
  770. PolyProcData poly_proc_data = {};
  771. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  772. Entity *e = poly_proc_data.gen_entity;
  773. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  774. add_entity_use(c, operand->expr, e);
  775. return 4;
  776. }
  777. }
  778. if (is_type_complex_or_quaternion(dst)) {
  779. Type *elem = base_complex_elem_type(dst);
  780. if (are_types_identical(elem, base_type(src))) {
  781. return 5;
  782. }
  783. }
  784. if (allow_array_programming) {
  785. if (is_type_array(dst)) {
  786. Type *elem = base_array_type(dst);
  787. i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
  788. if (distance >= 0) {
  789. return distance + 6;
  790. }
  791. }
  792. if (is_type_simd_vector(dst)) {
  793. Type *dst_elem = base_array_type(dst);
  794. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  795. if (distance >= 0) {
  796. return distance + 6;
  797. }
  798. }
  799. }
  800. if (is_type_matrix(dst)) {
  801. if (are_types_identical(src, dst)) {
  802. return 5;
  803. }
  804. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  805. Type *dst_elem = base_array_type(dst);
  806. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  807. if (distance >= 0) {
  808. return distance + 7;
  809. }
  810. }
  811. }
  812. if (is_type_any(dst)) {
  813. if (!is_type_polymorphic(src)) {
  814. if (operand->mode == Addressing_Context && operand->type == t_context) {
  815. return -1;
  816. } else {
  817. // NOTE(bill): Anything can cast to 'Any'
  818. add_type_info_type(c, s);
  819. return MAXIMUM_TYPE_DISTANCE;
  820. }
  821. }
  822. }
  823. Ast *expr = unparen_expr(operand->expr);
  824. if (expr != nullptr) {
  825. if (expr->kind == Ast_AutoCast) {
  826. Operand x = *operand;
  827. x.expr = expr->AutoCast.expr;
  828. if (check_cast_internal(c, &x, type)) {
  829. return MAXIMUM_TYPE_DISTANCE;
  830. }
  831. }
  832. }
  833. return -1;
  834. }
  835. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  836. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  837. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  838. // TODO(bill): A decent score function
  839. i64 d = distance*distance; // x^2
  840. if (is_variadic && d >= 0) {
  841. d += distance + 1; // x^2 + x + 1
  842. }
  843. return gb_max(c - d, 0);
  844. }
  845. 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) {
  846. if (c == nullptr) {
  847. GB_ASSERT(operand->mode == Addressing_Value);
  848. GB_ASSERT(is_type_typed(operand->type));
  849. }
  850. if (operand->mode == Addressing_Invalid || type == t_invalid) {
  851. if (score_) *score_ = 0;
  852. return false;
  853. }
  854. // Handle polymorphic procedure used as default parameter
  855. if (operand->mode == Addressing_Value && is_type_proc(type) && is_type_proc(operand->type)) {
  856. Entity *e = entity_from_expr(operand->expr);
  857. if (e != nullptr && e->kind == Entity_Procedure && is_type_polymorphic(e->type) && !is_type_polymorphic(type)) {
  858. // Special case: Allow a polymorphic procedure to be used as default value for concrete proc type
  859. // during the initial check. It will be properly instantiated when actually used.
  860. if (score_) *score_ = assign_score_function(1);
  861. return true;
  862. }
  863. }
  864. i64 score = check_distance_between_types(c, operand, type, allow_array_programming);
  865. if (score >= 0) {
  866. if (score_) *score_ = assign_score_function(score, is_variadic);
  867. return true;
  868. }
  869. if (score_) *score_ = 0;
  870. return false;
  871. }
  872. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming=true) {
  873. i64 score = 0;
  874. return check_is_assignable_to_with_score(c, operand, type, &score, /*is_variadic*/false, allow_array_programming);
  875. }
  876. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  877. Operand x = {};
  878. x.type = src;
  879. x.mode = Addressing_Value;
  880. return check_is_assignable_to(nullptr, &x, dst);
  881. }
  882. gb_internal AstPackage *get_package_of_type(Type *type) {
  883. for (;;) {
  884. if (type == nullptr) {
  885. return nullptr;
  886. }
  887. switch (type->kind) {
  888. case Type_Basic:
  889. return builtin_pkg;
  890. case Type_Named:
  891. if (type->Named.type_name != nullptr) {
  892. return type->Named.type_name->pkg;
  893. }
  894. return nullptr;
  895. case Type_Pointer:
  896. type = type->Pointer.elem;
  897. continue;
  898. case Type_Array:
  899. type = type->Array.elem;
  900. continue;
  901. case Type_Slice:
  902. type = type->Slice.elem;
  903. continue;
  904. case Type_DynamicArray:
  905. type = type->DynamicArray.elem;
  906. continue;
  907. }
  908. return nullptr;
  909. }
  910. }
  911. // NOTE(bill): 'context_name' is for debugging and error messages
  912. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  913. check_not_tuple(c, operand);
  914. if (operand->mode == Addressing_Invalid) {
  915. return;
  916. }
  917. // Grab definite or indefinite article matching `context_name`, or "" if not found.
  918. String article = error_article(context_name);
  919. if (is_type_untyped(operand->type)) {
  920. Type *target_type = type;
  921. if (type == nullptr || is_type_any(type)) {
  922. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  923. error(operand->expr, "Use of --- in %.*s%.*s", LIT(article), LIT(context_name));
  924. operand->mode = Addressing_Invalid;
  925. return;
  926. }
  927. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  928. error(operand->expr, "Use of untyped nil in %.*s%.*s", LIT(article), LIT(context_name));
  929. operand->mode = Addressing_Invalid;
  930. return;
  931. }
  932. target_type = default_type(operand->type);
  933. if (type != nullptr && !is_type_any(type)) {
  934. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  935. }
  936. add_type_info_type(c, type);
  937. add_type_info_type(c, target_type);
  938. }
  939. convert_to_typed(c, operand, target_type);
  940. if (operand->mode == Addressing_Invalid) {
  941. return;
  942. }
  943. }
  944. if (type == nullptr) {
  945. return;
  946. }
  947. if (operand->mode == Addressing_ProcGroup) {
  948. bool good = false;
  949. if (type != nullptr && is_type_proc(type)) {
  950. Array<Entity *> procs = proc_group_entities(c, *operand);
  951. // NOTE(bill): These should be done
  952. for (Entity *e : procs) {
  953. Type *t = base_type(e->type);
  954. if (t == t_invalid) {
  955. continue;
  956. }
  957. Operand x = {};
  958. x.mode = Addressing_Value;
  959. x.type = t;
  960. if (check_is_assignable_to(c, &x, type)) {
  961. add_entity_use(c, operand->expr, e);
  962. good = true;
  963. break;
  964. }
  965. }
  966. }
  967. if (!good) {
  968. gbString expr_str = expr_to_string(operand->expr);
  969. gbString op_type_str = type_to_string(operand->type);
  970. gbString type_str = type_to_string(type);
  971. defer (gb_string_free(type_str));
  972. defer (gb_string_free(op_type_str));
  973. defer (gb_string_free(expr_str));
  974. // TODO(bill): is this a good enough error message?
  975. error(operand->expr,
  976. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s%.*s",
  977. expr_str,
  978. op_type_str,
  979. LIT(article),
  980. LIT(context_name));
  981. operand->mode = Addressing_Invalid;
  982. }
  983. convert_to_typed(c, operand, type);
  984. return;
  985. }
  986. if (check_is_assignable_to(c, operand, type)) {
  987. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  988. add_type_info_type(c, operand->type);
  989. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  990. }
  991. } else {
  992. gbString expr_str = expr_to_string(operand->expr);
  993. gbString op_type_str = type_to_string(operand->type);
  994. gbString type_str = type_to_string(type);
  995. defer (gb_string_free(type_str));
  996. defer (gb_string_free(op_type_str));
  997. defer (gb_string_free(expr_str));
  998. switch (operand->mode) {
  999. case Addressing_Builtin:
  1000. error(operand->expr,
  1001. "Cannot assign built-in procedure '%s' to %.*s%.*s",
  1002. expr_str,
  1003. LIT(article),
  1004. LIT(context_name));
  1005. break;
  1006. case Addressing_Type:
  1007. if (is_type_polymorphic(operand->type)) {
  1008. error(operand->expr,
  1009. "Cannot assign '%s', a polymorphic type, to %.*s%.*s",
  1010. op_type_str,
  1011. LIT(article),
  1012. LIT(context_name));
  1013. } else {
  1014. ERROR_BLOCK();
  1015. error(operand->expr,
  1016. "Cannot assign '%s', a type, to %.*s%.*s",
  1017. op_type_str,
  1018. LIT(article),
  1019. LIT(context_name));
  1020. if (type && are_types_identical(type, t_any)) {
  1021. error_line("\tSuggestion: 'typeid_of(%s)'", expr_str);
  1022. }
  1023. }
  1024. break;
  1025. default:
  1026. // TODO(bill): is this a good enough error message?
  1027. {
  1028. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  1029. gbString type_extra = gb_string_make(heap_allocator(), "");
  1030. defer (gb_string_free(op_type_extra));
  1031. defer (gb_string_free(type_extra));
  1032. isize on = gb_string_length(op_type_str);
  1033. isize tn = gb_string_length(type_str);
  1034. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  1035. AstPackage *op_pkg = get_package_of_type(operand->type);
  1036. AstPackage *type_pkg = get_package_of_type(type);
  1037. if (op_pkg != nullptr) {
  1038. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  1039. }
  1040. if (type_pkg != nullptr) {
  1041. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  1042. }
  1043. }
  1044. ERROR_BLOCK();
  1045. error(operand->expr,
  1046. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s%.*s",
  1047. expr_str,
  1048. op_type_str, op_type_extra,
  1049. type_str, type_extra,
  1050. LIT(article),
  1051. LIT(context_name));
  1052. check_assignment_error_suggestion(c, operand, type);
  1053. Type *src = base_type(operand->type);
  1054. Type *dst = base_type(type);
  1055. if (context_name == "procedure argument") {
  1056. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  1057. gbString a = expr_to_string(operand->expr);
  1058. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  1059. gb_string_free(a);
  1060. }
  1061. }
  1062. if (src->kind == dst->kind && src->kind == Type_Proc) {
  1063. Type *x = src;
  1064. Type *y = dst;
  1065. bool same_inputs = are_types_identical_internal(x->Proc.params, y->Proc.params, false);
  1066. bool same_outputs = are_types_identical_internal(x->Proc.results, y->Proc.results, false);
  1067. if (same_inputs && same_outputs &&
  1068. x->Proc.calling_convention != y->Proc.calling_convention) {
  1069. gbString s_expected = type_to_string(y);
  1070. gbString s_got = type_to_string(x);
  1071. error_line("\tNote: The calling conventions differ between the procedure signature types\n");
  1072. error_line("\t Expected \"%s\", got \"%s\"\n",
  1073. proc_calling_convention_strings[y->Proc.calling_convention],
  1074. proc_calling_convention_strings[x->Proc.calling_convention]);
  1075. error_line("\t Expected: %s\n", s_expected);
  1076. error_line("\t Got: %s\n", s_got);
  1077. gb_string_free(s_got);
  1078. gb_string_free(s_expected);
  1079. } else if (same_inputs && same_outputs &&
  1080. x->Proc.diverging != y->Proc.diverging) {
  1081. gbString s_expected = type_to_string(y);
  1082. if (y->Proc.diverging) {
  1083. s_expected = gb_string_appendc(s_expected, " -> !");
  1084. }
  1085. gbString s_got = type_to_string(x);
  1086. if (x->Proc.diverging) {
  1087. s_got = gb_string_appendc(s_got, " -> !");
  1088. }
  1089. error_line("\tNote: One of the procedures is diverging while the other isn't\n");
  1090. error_line("\t Expected: %s\n", s_expected);
  1091. error_line("\t Got: %s\n", s_got);
  1092. gb_string_free(s_got);
  1093. gb_string_free(s_expected);
  1094. } else if (same_inputs && !same_outputs) {
  1095. gbString s_expected = type_to_string(y->Proc.results);
  1096. gbString s_got = type_to_string(x->Proc.results);
  1097. error_line("\tNote: The return types differ between the procedure signature types\n");
  1098. error_line("\t Expected: %s\n", s_expected);
  1099. error_line("\t Got: %s\n", s_got);
  1100. gb_string_free(s_got);
  1101. gb_string_free(s_expected);
  1102. } else if (!same_inputs && same_outputs) {
  1103. gbString s_expected = type_to_string(y->Proc.params);
  1104. gbString s_got = type_to_string(x->Proc.params);
  1105. error_line("\tNote: The input parameter types differ between the procedure signature types\n");
  1106. error_line("\t Expected: %s\n", s_expected);
  1107. error_line("\t Got: %s\n", s_got);
  1108. gb_string_free(s_got);
  1109. gb_string_free(s_expected);
  1110. } else {
  1111. gbString s_expected = type_to_string(y);
  1112. gbString s_got = type_to_string(x);
  1113. error_line("\tNote: The signature type do not match whatsoever\n");
  1114. error_line("\t Expected: %s\n", s_expected);
  1115. error_line("\t Got: %s\n", s_got);
  1116. gb_string_free(s_got);
  1117. gb_string_free(s_expected);
  1118. }
  1119. }
  1120. }
  1121. break;
  1122. }
  1123. operand->mode = Addressing_Invalid;
  1124. return;
  1125. }
  1126. }
  1127. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1128. Type *gt = *gt_;
  1129. GB_ASSERT(gt->kind == Type_Generic);
  1130. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1131. GB_ASSERT(e != nullptr);
  1132. if (e->kind == Entity_TypeName) {
  1133. *gt_ = nullptr;
  1134. *dst_count = source_count;
  1135. e->kind = Entity_Constant;
  1136. e->Constant.value = exact_value_i64(source_count);
  1137. e->type = t_untyped_integer;
  1138. return true;
  1139. } else if (e->kind == Entity_Constant) {
  1140. *gt_ = nullptr;
  1141. if (e->Constant.value.kind != ExactValue_Integer) {
  1142. return false;
  1143. }
  1144. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1145. if (count != source_count) {
  1146. return false;
  1147. }
  1148. *dst_count = source_count;
  1149. return true;
  1150. }
  1151. return false;
  1152. }
  1153. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1154. Operand o = {Addressing_Value};
  1155. o.type = source;
  1156. switch (poly->kind) {
  1157. case Type_Basic:
  1158. if (compound) return are_types_identical(poly, source);
  1159. return check_is_assignable_to(c, &o, poly);
  1160. case Type_Named: {
  1161. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1162. return true;
  1163. }
  1164. if (compound || !is_type_generic(poly)) {
  1165. return are_types_identical(poly, source);
  1166. }
  1167. return check_is_assignable_to(c, &o, poly);
  1168. }
  1169. case Type_Generic: {
  1170. if (poly->Generic.specialized != nullptr) {
  1171. Type *s = poly->Generic.specialized;
  1172. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1173. return false;
  1174. }
  1175. }
  1176. if (modify_type) {
  1177. Type *ds = default_type(source);
  1178. gb_memmove(poly, ds, gb_size_of(Type));
  1179. }
  1180. return true;
  1181. }
  1182. case Type_Pointer:
  1183. if (source->kind == Type_Pointer) {
  1184. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1185. if (level > 0) {
  1186. return true;
  1187. }
  1188. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1189. } else if (source->kind == Type_MultiPointer) {
  1190. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1191. if (level > 0) {
  1192. return true;
  1193. }
  1194. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1195. }
  1196. return false;
  1197. case Type_MultiPointer:
  1198. if (source->kind == Type_MultiPointer) {
  1199. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1200. if (level > 0) {
  1201. return true;
  1202. }
  1203. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1204. } else if (source->kind == Type_Pointer) {
  1205. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1206. if (level > 0) {
  1207. return true;
  1208. }
  1209. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1210. }
  1211. return false;
  1212. case Type_Array:
  1213. if (source->kind == Type_Array) {
  1214. if (poly->Array.generic_count != nullptr) {
  1215. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1216. return false;
  1217. }
  1218. }
  1219. if (poly->Array.count == source->Array.count) {
  1220. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1221. }
  1222. } else if (source->kind == Type_EnumeratedArray) {
  1223. if (poly->Array.generic_count != nullptr) {
  1224. Type *gt = poly->Array.generic_count;
  1225. GB_ASSERT(gt->kind == Type_Generic);
  1226. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1227. GB_ASSERT(e != nullptr);
  1228. if (e->kind == Entity_TypeName) {
  1229. Type *index = source->EnumeratedArray.index;
  1230. Type *it = base_type(index);
  1231. if (it->kind != Type_Enum) {
  1232. return false;
  1233. }
  1234. poly->kind = Type_EnumeratedArray;
  1235. poly->cached_size = -1;
  1236. poly->cached_align = -1;
  1237. poly->flags.exchange(source->flags);
  1238. poly->failure = false;
  1239. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1240. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1241. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1242. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1243. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1244. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1245. e->kind = Entity_TypeName;
  1246. e->TypeName.is_type_alias = true;
  1247. e->type = index;
  1248. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1249. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1250. }
  1251. }
  1252. }
  1253. }
  1254. return false;
  1255. case Type_EnumeratedArray:
  1256. if (source->kind == Type_EnumeratedArray) {
  1257. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1258. return false;
  1259. }
  1260. if (poly->EnumeratedArray.op) {
  1261. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1262. return false;
  1263. }
  1264. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1265. return false;
  1266. }
  1267. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1268. return false;
  1269. }
  1270. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1271. }
  1272. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1273. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1274. return index || elem;
  1275. }
  1276. return false;
  1277. case Type_DynamicArray:
  1278. if (source->kind == Type_DynamicArray) {
  1279. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1280. }
  1281. return false;
  1282. case Type_Slice:
  1283. if (source->kind == Type_Slice) {
  1284. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1285. }
  1286. return false;
  1287. case Type_Enum:
  1288. return false;
  1289. case Type_BitSet:
  1290. if (source->kind == Type_BitSet) {
  1291. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1292. return false;
  1293. }
  1294. // For generic types like bit_set[$T] the upper and lower of the poly type will be zeroes since
  1295. // it could not figure that stuff out when the poly type was created.
  1296. if (poly->BitSet.upper == 0 && modify_type) {
  1297. poly->BitSet.upper = source->BitSet.upper;
  1298. }
  1299. if (poly->BitSet.lower == 0 && modify_type) {
  1300. poly->BitSet.lower = source->BitSet.lower;
  1301. }
  1302. if (poly->BitSet.underlying == nullptr) {
  1303. if (modify_type) {
  1304. poly->BitSet.underlying = source->BitSet.underlying;
  1305. }
  1306. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1307. return false;
  1308. }
  1309. return true;
  1310. }
  1311. return false;
  1312. case Type_Union:
  1313. if (source->kind == Type_Union) {
  1314. TypeUnion *x = &poly->Union;
  1315. TypeUnion *y = &source->Union;
  1316. if (x->variants.count != y->variants.count) {
  1317. return false;
  1318. }
  1319. for_array(i, x->variants) {
  1320. Type *a = x->variants[i];
  1321. Type *b = y->variants[i];
  1322. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1323. if (!ok) return false;
  1324. }
  1325. return true;
  1326. }
  1327. return false;
  1328. case Type_Struct:
  1329. if (source->kind == Type_Struct) {
  1330. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1331. poly->Struct.soa_kind != StructSoa_None) {
  1332. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1333. if (ok) switch (source->Struct.soa_kind) {
  1334. case StructSoa_None:
  1335. default:
  1336. GB_PANIC("Unhandled SOA Kind");
  1337. break;
  1338. case StructSoa_Fixed:
  1339. if (modify_type) {
  1340. Type *type = make_soa_struct_fixed(c, nullptr, poly->Struct.node, poly->Struct.soa_elem, poly->Struct.soa_count, nullptr);
  1341. gb_memmove(poly, type, gb_size_of(*type));
  1342. }
  1343. break;
  1344. case StructSoa_Slice:
  1345. if (modify_type) {
  1346. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1347. gb_memmove(poly, type, gb_size_of(*type));
  1348. }
  1349. break;
  1350. case StructSoa_Dynamic:
  1351. if (modify_type) {
  1352. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1353. gb_memmove(poly, type, gb_size_of(*type));
  1354. }
  1355. break;
  1356. }
  1357. return ok;
  1358. }
  1359. // NOTE(bill): Check for subtypes of
  1360. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1361. }
  1362. return false;
  1363. case Type_BitField:
  1364. if (source->kind == Type_BitField) {
  1365. return is_polymorphic_type_assignable(c, poly->BitField.backing_type, source->BitField.backing_type, true, modify_type);
  1366. }
  1367. return false;
  1368. case Type_Tuple:
  1369. GB_PANIC("This should never happen");
  1370. return false;
  1371. case Type_Proc:
  1372. if (source->kind == Type_Proc) {
  1373. TypeProc *x = &poly->Proc;
  1374. TypeProc *y = &source->Proc;
  1375. if (x->calling_convention != y->calling_convention) {
  1376. return false;
  1377. }
  1378. if (x->c_vararg != y->c_vararg) {
  1379. return false;
  1380. }
  1381. if (x->variadic != y->variadic) {
  1382. return false;
  1383. }
  1384. if (x->param_count != y->param_count) {
  1385. return false;
  1386. }
  1387. if (x->result_count != y->result_count) {
  1388. return false;
  1389. }
  1390. for (isize i = 0; i < x->param_count; i++) {
  1391. Entity *a = x->params->Tuple.variables[i];
  1392. Entity *b = y->params->Tuple.variables[i];
  1393. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1394. if (!ok) return false;
  1395. }
  1396. for (isize i = 0; i < x->result_count; i++) {
  1397. Entity *a = x->results->Tuple.variables[i];
  1398. Entity *b = y->results->Tuple.variables[i];
  1399. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1400. if (!ok) return false;
  1401. }
  1402. return true;
  1403. }
  1404. return false;
  1405. case Type_Map:
  1406. if (source->kind == Type_Map) {
  1407. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1408. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1409. if (key || value) {
  1410. poly->Map.lookup_result_type = nullptr;
  1411. init_map_internal_types(poly);
  1412. return true;
  1413. }
  1414. }
  1415. return false;
  1416. case Type_Matrix:
  1417. if (source->kind == Type_Matrix) {
  1418. if (poly->Matrix.generic_row_count != nullptr) {
  1419. poly->Matrix.stride_in_bytes = 0;
  1420. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1421. return false;
  1422. }
  1423. }
  1424. if (poly->Matrix.generic_column_count != nullptr) {
  1425. poly->Matrix.stride_in_bytes = 0;
  1426. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1427. return false;
  1428. }
  1429. }
  1430. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1431. poly->Matrix.column_count == source->Matrix.column_count) {
  1432. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1433. }
  1434. }
  1435. return false;
  1436. case Type_SimdVector:
  1437. if (source->kind == Type_SimdVector) {
  1438. if (poly->SimdVector.generic_count != nullptr) {
  1439. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1440. return false;
  1441. }
  1442. }
  1443. if (poly->SimdVector.count == source->SimdVector.count) {
  1444. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1445. }
  1446. }
  1447. return false;
  1448. }
  1449. return false;
  1450. }
  1451. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1452. if (curr->state != EntityState_InProgress) {
  1453. return false;
  1454. }
  1455. for_array(i, *c->type_path) {
  1456. Entity *prev = c->type_path->data[i];
  1457. if (prev == curr) {
  1458. if (report) {
  1459. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1460. for (isize j = i; j < c->type_path->count; j++) {
  1461. Entity *curr = (*c->type_path)[j];
  1462. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1463. }
  1464. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1465. curr->type = t_invalid;
  1466. }
  1467. return true;
  1468. }
  1469. }
  1470. return false;
  1471. }
  1472. struct CIdentSuggestion {
  1473. String name;
  1474. String msg;
  1475. };
  1476. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1477. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1478. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1479. {str_lit("sizeof"), str_lit("'size_of'?")},
  1480. {str_lit("alignof"), str_lit("'align_of'?")},
  1481. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1482. {str_lit("_Bool"), str_lit("'bool'?")},
  1483. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1484. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1485. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1486. {str_lit("float"), str_lit("'f32'?")},
  1487. {str_lit("double"), str_lit("'f64'?")},
  1488. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1489. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1490. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1491. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1492. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1493. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1494. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1495. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1496. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1497. {str_lit("uint8_t"), str_lit("'u8'?")},
  1498. {str_lit("int8_t"), str_lit("'i8'?")},
  1499. {str_lit("uint16_t"), str_lit("'u16'?")},
  1500. {str_lit("int16_t"), str_lit("'i16'?")},
  1501. {str_lit("uint32_t"), str_lit("'u32'?")},
  1502. {str_lit("int32_t"), str_lit("'i32'?")},
  1503. {str_lit("uint64_t"), str_lit("'u64'?")},
  1504. {str_lit("int64_t"), str_lit("'i64'?")},
  1505. {str_lit("uint128_t"), str_lit("'u128'?")},
  1506. {str_lit("int128_t"), str_lit("'i128'?")},
  1507. {str_lit("float32"), str_lit("'f32'?")},
  1508. {str_lit("float64"), str_lit("'f64'?")},
  1509. {str_lit("float32_t"), str_lit("'f32'?")},
  1510. {str_lit("float64_t"), str_lit("'f64'?")},
  1511. };
  1512. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1513. GB_ASSERT(n->kind == Ast_Ident);
  1514. o->mode = Addressing_Invalid;
  1515. o->expr = n;
  1516. String name = n->Ident.token.string;
  1517. Entity *e = scope_lookup(c->scope, name);
  1518. if (e == nullptr) {
  1519. if (is_blank_ident(name)) {
  1520. error(n, "'_' cannot be used as a value");
  1521. } else {
  1522. ERROR_BLOCK();
  1523. error(n, "Undeclared name: %.*s", LIT(name));
  1524. // NOTE(bill): Loads of checks for C programmers
  1525. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1526. if (name == suggestion.name) {
  1527. error_line("\tSuggestion: Did you mean %.*s\n", LIT(suggestion.msg));
  1528. }
  1529. }
  1530. }
  1531. o->type = t_invalid;
  1532. o->mode = Addressing_Invalid;
  1533. if (named_type != nullptr) {
  1534. set_base_type(named_type, t_invalid);
  1535. }
  1536. return nullptr;
  1537. }
  1538. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1539. if (e->parent_proc_decl != nullptr &&
  1540. e->parent_proc_decl != c->curr_proc_decl) {
  1541. if (e->kind == Entity_Variable) {
  1542. if ((e->flags & EntityFlag_Static) == 0) {
  1543. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1544. return nullptr;
  1545. }
  1546. } else if (e->kind == Entity_Label) {
  1547. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1548. return nullptr;
  1549. }
  1550. }
  1551. if (e->kind == Entity_ProcGroup) {
  1552. auto *pge = &e->ProcGroup;
  1553. DeclInfo *d = decl_info_of_entity(e);
  1554. check_entity_decl(c, e, d, nullptr);
  1555. Array<Entity *> procs = pge->entities;
  1556. bool skip = false;
  1557. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1558. // NOTE(bill): These should be done
  1559. for (Entity *proc : procs) {
  1560. Type *t = base_type(proc->type);
  1561. if (t == t_invalid) {
  1562. continue;
  1563. }
  1564. Operand x = {};
  1565. x.mode = Addressing_Value;
  1566. x.type = t;
  1567. if (check_is_assignable_to(c, &x, type_hint)) {
  1568. e = proc;
  1569. add_entity_use(c, n, e);
  1570. skip = true;
  1571. break;
  1572. }
  1573. }
  1574. }
  1575. if (!skip) {
  1576. o->mode = Addressing_ProcGroup;
  1577. o->type = t_invalid;
  1578. o->proc_group = e;
  1579. return nullptr;
  1580. }
  1581. }
  1582. add_entity_use(c, n, e);
  1583. if (e->state == EntityState_Unresolved) {
  1584. check_entity_decl(c, e, nullptr, named_type);
  1585. }
  1586. if (e->type == nullptr) {
  1587. // TODO(bill): Which is correct? return or compiler_error?
  1588. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1589. return nullptr;
  1590. }
  1591. e->flags |= EntityFlag_Used;
  1592. Type *type = e->type;
  1593. o->type = type;
  1594. switch (e->kind) {
  1595. case Entity_Constant:
  1596. if (type == t_invalid) {
  1597. o->type = t_invalid;
  1598. return e;
  1599. }
  1600. o->value = e->Constant.value;
  1601. if (o->value.kind == ExactValue_Invalid) {
  1602. return e;
  1603. }
  1604. if (o->value.kind == ExactValue_Procedure) {
  1605. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1606. if (proc != nullptr) {
  1607. o->mode = Addressing_Value;
  1608. o->type = proc->type;
  1609. return proc;
  1610. }
  1611. }
  1612. o->mode = Addressing_Constant;
  1613. break;
  1614. case Entity_Variable:
  1615. e->flags |= EntityFlag_Used;
  1616. if (type == t_invalid) {
  1617. o->type = t_invalid;
  1618. return e;
  1619. }
  1620. o->mode = Addressing_Variable;
  1621. if (e->flags & EntityFlag_Value) {
  1622. o->mode = Addressing_Value;
  1623. }
  1624. break;
  1625. case Entity_Procedure:
  1626. o->mode = Addressing_Value;
  1627. o->value = exact_value_procedure(n);
  1628. break;
  1629. case Entity_Builtin:
  1630. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1631. o->mode = Addressing_Builtin;
  1632. break;
  1633. case Entity_TypeName:
  1634. o->mode = Addressing_Type;
  1635. if (check_cycle(c, e, true)) {
  1636. o->type = t_invalid;
  1637. }
  1638. if (o->type != nullptr && o->type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1639. Type *bt = base_type(o->type);
  1640. if (bt != nullptr) {
  1641. o->type = bt;
  1642. }
  1643. }
  1644. break;
  1645. case Entity_ImportName:
  1646. if (!allow_import_name) {
  1647. error(n, "Use of import name '%.*s' not in the form of 'x.y'", LIT(name));
  1648. }
  1649. return e;
  1650. case Entity_LibraryName:
  1651. if (!allow_import_name) {
  1652. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1653. }
  1654. return e;
  1655. case Entity_Label:
  1656. o->mode = Addressing_NoValue;
  1657. break;
  1658. case Entity_Nil:
  1659. o->mode = Addressing_Value;
  1660. break;
  1661. default:
  1662. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1663. break;
  1664. }
  1665. return e;
  1666. }
  1667. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1668. if (o->type == nullptr) {
  1669. gbString str = expr_to_string(o->expr);
  1670. error(o->expr, "Expression has no value '%s'", str);
  1671. gb_string_free(str);
  1672. return false;
  1673. }
  1674. if (o->mode == Addressing_Type) {
  1675. gbString str = type_to_string(o->type);
  1676. error(o->expr, "Expected an expression for operator '%.*s', got type '%s'", LIT(op.string), str);
  1677. gb_string_free(str);
  1678. return false;
  1679. }
  1680. Type *type = base_type(core_array_type(o->type));
  1681. gbString str = nullptr;
  1682. switch (op.kind) {
  1683. case Token_Add:
  1684. case Token_Sub:
  1685. if (!is_type_numeric(type)) {
  1686. str = expr_to_string(o->expr);
  1687. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1688. gb_string_free(str);
  1689. }
  1690. break;
  1691. case Token_Xor:
  1692. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1693. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1694. }
  1695. break;
  1696. case Token_Not:
  1697. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1698. ERROR_BLOCK();
  1699. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1700. if (is_type_integer(type)) {
  1701. str = expr_to_string(o->expr);
  1702. error_line("\tSuggestion: Did you mean to do one of the following?\n");
  1703. error_line("\t\t'%s == 0'?\n", str);
  1704. error_line("\t\tUse of the bitwise not operator '~'?\n");
  1705. gb_string_free(str);
  1706. }
  1707. } else {
  1708. o->type = t_untyped_bool;
  1709. }
  1710. break;
  1711. case Token_Mul:
  1712. {
  1713. ERROR_BLOCK();
  1714. error(op, "Operator '%.*s' is not a valid unary operator in Odin", LIT(op.string));
  1715. if (is_type_pointer(o->type)) {
  1716. str = expr_to_string(o->expr);
  1717. error_line("\tSuggestion: Did you mean '%s^'?\n", str);
  1718. o->type = type_deref(o->type);
  1719. } else if (is_type_multi_pointer(o->type)) {
  1720. str = expr_to_string(o->expr);
  1721. error_line("\tSuggestion: The value is a multi-pointer, did you mean '%s[0]'?\n", str);
  1722. o->type = type_deref(o->type, true);
  1723. }
  1724. }
  1725. break;
  1726. default:
  1727. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1728. return false;
  1729. }
  1730. return true;
  1731. }
  1732. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1733. Type *main_type = o->type;
  1734. Type *type = base_type(core_array_type(main_type));
  1735. Type *ct = core_type(type);
  1736. switch (op.kind) {
  1737. case Token_Sub:
  1738. case Token_SubEq:
  1739. if (is_type_bit_set(type)) {
  1740. return true;
  1741. } else if (!is_type_numeric(type)) {
  1742. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1743. return false;
  1744. }
  1745. break;
  1746. case Token_Quo:
  1747. case Token_QuoEq:
  1748. if (is_type_matrix(main_type)) {
  1749. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1750. return false;
  1751. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1752. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1753. return false;
  1754. }
  1755. /*fallthrough*/
  1756. case Token_Mul:
  1757. case Token_MulEq:
  1758. case Token_AddEq:
  1759. if (is_type_bit_set(type)) {
  1760. return true;
  1761. } else if (!is_type_numeric(type)) {
  1762. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1763. return false;
  1764. }
  1765. break;
  1766. case Token_Add:
  1767. if (is_type_string(type)) {
  1768. if (o->mode == Addressing_Constant) {
  1769. return true;
  1770. }
  1771. error(op, "String concatenation is only allowed with constant strings");
  1772. return false;
  1773. } else if (is_type_bit_set(type)) {
  1774. return true;
  1775. } else if (!is_type_numeric(type)) {
  1776. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1777. return false;
  1778. }
  1779. break;
  1780. case Token_And:
  1781. case Token_Or:
  1782. case Token_AndEq:
  1783. case Token_OrEq:
  1784. case Token_Xor:
  1785. case Token_XorEq:
  1786. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1787. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1788. return false;
  1789. }
  1790. break;
  1791. case Token_Mod:
  1792. case Token_ModMod:
  1793. case Token_ModEq:
  1794. case Token_ModModEq:
  1795. if (is_type_matrix(main_type)) {
  1796. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1797. return false;
  1798. }
  1799. if (!is_type_integer(type)) {
  1800. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1801. return false;
  1802. } else if (is_type_simd_vector(main_type)) {
  1803. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1804. return false;
  1805. }
  1806. break;
  1807. case Token_AndNot:
  1808. case Token_AndNotEq:
  1809. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1810. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1811. return false;
  1812. }
  1813. break;
  1814. case Token_CmpAnd:
  1815. case Token_CmpOr:
  1816. case Token_CmpAndEq:
  1817. case Token_CmpOrEq:
  1818. if (!is_type_boolean(type)) {
  1819. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1820. return false;
  1821. }
  1822. break;
  1823. default:
  1824. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1825. return false;
  1826. }
  1827. return true;
  1828. }
  1829. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1830. if (in_value.kind == ExactValue_Invalid) {
  1831. // NOTE(bill): There's already been an error
  1832. return true;
  1833. }
  1834. type = core_type(type);
  1835. if (type == t_invalid) {
  1836. return false;
  1837. } else if (is_type_boolean(type)) {
  1838. return in_value.kind == ExactValue_Bool;
  1839. } else if (is_type_string(type)) {
  1840. return in_value.kind == ExactValue_String;
  1841. } else if (is_type_integer(type) || is_type_rune(type)) {
  1842. if (in_value.kind == ExactValue_Bool) {
  1843. return false;
  1844. }
  1845. ExactValue v = exact_value_to_integer(in_value);
  1846. if (v.kind != ExactValue_Integer) {
  1847. return false;
  1848. }
  1849. if (out_value) *out_value = v;
  1850. if (is_type_untyped(type)) {
  1851. return true;
  1852. }
  1853. BigInt i = v.value_integer;
  1854. i64 byte_size = type_size_of(type);
  1855. BigInt umax = {};
  1856. BigInt imin = {};
  1857. BigInt imax = {};
  1858. if (c->bit_field_bit_size > 0) {
  1859. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1860. big_int_from_u64(&umax, 1);
  1861. big_int_from_i64(&imin, 1);
  1862. big_int_from_i64(&imax, 1);
  1863. BigInt bu = {};
  1864. BigInt bi = {};
  1865. big_int_from_i64(&bu, bit_size);
  1866. big_int_from_i64(&bi, bit_size-1);
  1867. big_int_shl_eq(&umax, &bu);
  1868. mp_decr(&umax);
  1869. big_int_shl_eq(&imin, &bi);
  1870. big_int_neg(&imin, &imin);
  1871. big_int_shl_eq(&imax, &bi);
  1872. mp_decr(&imax);
  1873. } else {
  1874. if (byte_size < 16) {
  1875. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1876. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1877. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1878. } else {
  1879. big_int_from_u64(&umax, 1);
  1880. big_int_from_i64(&imin, 1);
  1881. big_int_from_i64(&imax, 1);
  1882. BigInt bi128 = {};
  1883. BigInt bi127 = {};
  1884. big_int_from_i64(&bi128, 128);
  1885. big_int_from_i64(&bi127, 127);
  1886. big_int_shl_eq(&umax, &bi128);
  1887. mp_decr(&umax);
  1888. big_int_shl_eq(&imin, &bi127);
  1889. big_int_neg(&imin, &imin);
  1890. big_int_shl_eq(&imax, &bi127);
  1891. mp_decr(&imax);
  1892. }
  1893. }
  1894. switch (type->Basic.kind) {
  1895. case Basic_rune:
  1896. case Basic_i8:
  1897. case Basic_i16:
  1898. case Basic_i32:
  1899. case Basic_i64:
  1900. case Basic_i128:
  1901. case Basic_int:
  1902. case Basic_i16le:
  1903. case Basic_i32le:
  1904. case Basic_i64le:
  1905. case Basic_i128le:
  1906. case Basic_i16be:
  1907. case Basic_i32be:
  1908. case Basic_i64be:
  1909. case Basic_i128be:
  1910. {
  1911. // return imin <= i && i <= imax;
  1912. int a = big_int_cmp(&imin, &i);
  1913. int b = big_int_cmp(&i, &imax);
  1914. return (a <= 0) && (b <= 0);
  1915. }
  1916. case Basic_u8:
  1917. case Basic_u16:
  1918. case Basic_u32:
  1919. case Basic_u64:
  1920. case Basic_u128:
  1921. case Basic_uint:
  1922. case Basic_uintptr:
  1923. case Basic_u16le:
  1924. case Basic_u32le:
  1925. case Basic_u64le:
  1926. case Basic_u128le:
  1927. case Basic_u16be:
  1928. case Basic_u32be:
  1929. case Basic_u64be:
  1930. case Basic_u128be:
  1931. {
  1932. // return 0ull <= i && i <= umax;
  1933. int b = big_int_cmp(&i, &umax);
  1934. return !i.sign && (b <= 0);
  1935. }
  1936. case Basic_UntypedInteger:
  1937. return true;
  1938. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1939. }
  1940. } else if (is_type_float(type)) {
  1941. ExactValue v = exact_value_to_float(in_value);
  1942. if (v.kind != ExactValue_Float) {
  1943. return false;
  1944. }
  1945. if (out_value) *out_value = v;
  1946. switch (type->Basic.kind) {
  1947. case Basic_f16:
  1948. case Basic_f32:
  1949. case Basic_f64:
  1950. return true;
  1951. case Basic_f16le:
  1952. case Basic_f16be:
  1953. case Basic_f32le:
  1954. case Basic_f32be:
  1955. case Basic_f64le:
  1956. case Basic_f64be:
  1957. return true;
  1958. case Basic_UntypedFloat:
  1959. return true;
  1960. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1961. }
  1962. } else if (is_type_complex(type)) {
  1963. ExactValue v = exact_value_to_complex(in_value);
  1964. if (v.kind != ExactValue_Complex) {
  1965. return false;
  1966. }
  1967. switch (type->Basic.kind) {
  1968. case Basic_complex32:
  1969. case Basic_complex64:
  1970. case Basic_complex128: {
  1971. ExactValue real = exact_value_real(v);
  1972. ExactValue imag = exact_value_imag(v);
  1973. if (real.kind != ExactValue_Invalid &&
  1974. imag.kind != ExactValue_Invalid) {
  1975. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1976. return true;
  1977. }
  1978. break;
  1979. }
  1980. case Basic_UntypedComplex:
  1981. return true;
  1982. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1983. }
  1984. return false;
  1985. } else if (is_type_quaternion(type)) {
  1986. ExactValue v = exact_value_to_quaternion(in_value);
  1987. if (v.kind != ExactValue_Quaternion) {
  1988. return false;
  1989. }
  1990. switch (type->Basic.kind) {
  1991. case Basic_quaternion64:
  1992. case Basic_quaternion128:
  1993. case Basic_quaternion256: {
  1994. ExactValue real = exact_value_real(v);
  1995. ExactValue imag = exact_value_imag(v);
  1996. ExactValue jmag = exact_value_jmag(v);
  1997. ExactValue kmag = exact_value_kmag(v);
  1998. if (real.kind != ExactValue_Invalid &&
  1999. imag.kind != ExactValue_Invalid) {
  2000. 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));
  2001. return true;
  2002. }
  2003. break;
  2004. }
  2005. case Basic_UntypedComplex:
  2006. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  2007. return true;
  2008. case Basic_UntypedQuaternion:
  2009. return true;
  2010. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  2011. }
  2012. return false;
  2013. } else if (is_type_pointer(type)) {
  2014. if (in_value.kind == ExactValue_Pointer) {
  2015. return true;
  2016. }
  2017. if (in_value.kind == ExactValue_Integer) {
  2018. return false;
  2019. // return true;
  2020. }
  2021. if (in_value.kind == ExactValue_String) {
  2022. return false;
  2023. }
  2024. if (out_value) *out_value = in_value;
  2025. } else if (is_type_bit_set(type)) {
  2026. if (in_value.kind == ExactValue_Integer) {
  2027. return true;
  2028. }
  2029. }
  2030. return false;
  2031. }
  2032. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  2033. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  2034. gbString b = type_to_string(type);
  2035. defer (gb_string_free(b));
  2036. if (is_type_enum(o->type)) {
  2037. if (check_is_castable_to(c, o, type)) {
  2038. gbString ot = type_to_string(o->type);
  2039. error_line("\tSuggestion: Try casting the '%s' expression to '%s'", ot, b);
  2040. gb_string_free(ot);
  2041. }
  2042. return true;
  2043. }
  2044. i64 sz = type_size_of(type);
  2045. i64 bit_size = 8*sz;
  2046. bool size_changed = false;
  2047. if (max_bit_size > 0) {
  2048. size_changed = (bit_size != max_bit_size);
  2049. bit_size = gb_min(bit_size, max_bit_size);
  2050. }
  2051. BigInt *bi = &o->value.value_integer;
  2052. if (is_type_unsigned(type)) {
  2053. BigInt one = big_int_make_u64(1);
  2054. BigInt max_size = big_int_make_u64(1);
  2055. BigInt bits = big_int_make_i64(bit_size);
  2056. big_int_shl_eq(&max_size, &bits);
  2057. big_int_sub_eq(&max_size, &one);
  2058. if (big_int_is_neg(bi)) {
  2059. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  2060. BigInt dst = {};
  2061. big_int_neg(&dst, bi);
  2062. if (big_int_cmp(&dst, &max_size) < 0) {
  2063. big_int_sub_eq(&dst, &one);
  2064. String dst_str = big_int_to_string(temporary_allocator(), &dst);
  2065. gbString t = type_to_string(type);
  2066. error_line("\tSuggestion: ~%s(%.*s)\n", t, LIT(dst_str));
  2067. gb_string_free(t);
  2068. }
  2069. } else {
  2070. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2071. if (size_changed) {
  2072. 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));
  2073. } else {
  2074. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2075. }
  2076. }
  2077. } else {
  2078. BigInt zero = big_int_make_u64(0);
  2079. BigInt one = big_int_make_u64(1);
  2080. BigInt max_size = big_int_make_u64(1);
  2081. BigInt bits = big_int_make_i64(bit_size - 1);
  2082. big_int_shl_eq(&max_size, &bits);
  2083. String max_size_str = {};
  2084. if (big_int_is_neg(bi)) {
  2085. big_int_neg(&max_size, &max_size);
  2086. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2087. } else {
  2088. big_int_sub_eq(&max_size, &one);
  2089. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2090. }
  2091. if (size_changed) {
  2092. 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));
  2093. } else {
  2094. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2095. }
  2096. }
  2097. return true;
  2098. }
  2099. return false;
  2100. }
  2101. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  2102. gbString a = expr_to_string(o->expr);
  2103. gbString b = type_to_string(type);
  2104. defer(
  2105. gb_string_free(b);
  2106. gb_string_free(a);
  2107. );
  2108. Type *src = base_type(o->type);
  2109. Type *dst = base_type(type);
  2110. if (is_type_array(src) && is_type_slice(dst)) {
  2111. Type *s = src->Array.elem;
  2112. Type *d = dst->Slice.elem;
  2113. if (are_types_identical(s, d)) {
  2114. error_line("\tSuggestion: The array expression may be sliced with %s[:]\n", a);
  2115. }
  2116. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  2117. Type *s = src->DynamicArray.elem;
  2118. Type *d = dst->Slice.elem;
  2119. if (are_types_identical(s, d)) {
  2120. error_line("\tSuggestion: The dynamic array expression may be sliced with %s[:]\n", a);
  2121. }
  2122. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  2123. error_line("\tSuggestion: The expression may be directly casted to type %s\n", b);
  2124. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2125. error_line("\tSuggestion: A string may be transmuted to %s\n", b);
  2126. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable,\n");
  2127. error_line("\t whereas slices in general are assumed to be mutable.\n");
  2128. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  2129. error_line("\tSuggestion: The expression may be casted to %s\n", b);
  2130. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  2131. return;
  2132. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  2133. gbString s = expr_to_string(c->type_hint_expr);
  2134. error_line("\tSuggestion: Make sure that `%s` is attached to the compound literal directly\n", s);
  2135. gb_string_free(s);
  2136. } else if (is_type_pointer(type) &&
  2137. o->mode == Addressing_Variable &&
  2138. are_types_identical(type_deref(type), o->type)) {
  2139. gbString s = expr_to_string(o->expr);
  2140. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  2141. gb_string_free(s);
  2142. } else if (is_type_pointer(o->type) &&
  2143. are_types_identical(type_deref(o->type), type)) {
  2144. gbString s = expr_to_string(o->expr);
  2145. error_line("\tSuggestion: Did you mean `%s^`\n", s);
  2146. gb_string_free(s);
  2147. }
  2148. }
  2149. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  2150. gbString a = expr_to_string(o->expr);
  2151. gbString b = type_to_string(type);
  2152. defer(
  2153. gb_string_free(b);
  2154. gb_string_free(a);
  2155. );
  2156. Type *src = base_type(o->type);
  2157. Type *dst = base_type(type);
  2158. if (is_type_array(src) && is_type_slice(dst)) {
  2159. Type *s = src->Array.elem;
  2160. Type *d = dst->Slice.elem;
  2161. if (are_types_identical(s, d)) {
  2162. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2163. }
  2164. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  2165. if (is_type_uintptr(type)) {
  2166. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  2167. } else {
  2168. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  2169. i64 x = type_size_of(o->type);
  2170. i64 y = type_size_of(type);
  2171. if (x != y) {
  2172. 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);
  2173. }
  2174. }
  2175. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2176. if (is_type_uintptr(o->type)) {
  2177. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2178. } else {
  2179. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2180. }
  2181. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2182. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2183. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2184. return;
  2185. }
  2186. }
  2187. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2188. GB_ASSERT(o->mode == Addressing_Constant);
  2189. ExactValue out_value = o->value;
  2190. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2191. o->value = out_value;
  2192. return true;
  2193. } else {
  2194. o->value = out_value;
  2195. gbString a = expr_to_string(o->expr);
  2196. gbString b = type_to_string(type);
  2197. gbString c = type_to_string(o->type);
  2198. gbString s = exact_value_to_string(o->value);
  2199. defer(
  2200. gb_string_free(s);
  2201. gb_string_free(c);
  2202. gb_string_free(b);
  2203. gb_string_free(a);
  2204. o->mode = Addressing_Invalid;
  2205. );
  2206. ERROR_BLOCK();
  2207. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2208. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2209. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2210. } else {
  2211. i64 max_bit_size = 0;
  2212. if (ctx->bit_field_bit_size) {
  2213. max_bit_size = ctx->bit_field_bit_size;
  2214. }
  2215. if (are_types_identical(o->type, type)) {
  2216. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2217. } else {
  2218. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2219. }
  2220. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2221. }
  2222. } else {
  2223. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2224. check_assignment_error_suggestion(ctx, o, type);
  2225. }
  2226. return false;
  2227. }
  2228. }
  2229. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2230. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2231. if (o->expr->SelectorExpr.is_bit_field) {
  2232. return true;
  2233. }
  2234. }
  2235. if (o->mode == Addressing_OptionalOk) {
  2236. Ast *expr = unselector_expr(o->expr);
  2237. if (expr->kind != Ast_TypeAssertion) {
  2238. return true;
  2239. }
  2240. ast_node(ta, TypeAssertion, expr);
  2241. TypeAndValue tv = ta->expr->tav;
  2242. if (is_type_pointer(tv.type)) {
  2243. return false;
  2244. }
  2245. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2246. return false;
  2247. }
  2248. if (is_type_any(tv.type)) {
  2249. return false;
  2250. }
  2251. return true;
  2252. }
  2253. if (o->mode == Addressing_MapIndex) {
  2254. return false;
  2255. }
  2256. Ast *expr = unparen_expr(o->expr);
  2257. if (expr->kind == Ast_CompoundLit) {
  2258. return false;
  2259. }
  2260. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2261. }
  2262. gb_internal ExactValue exact_bit_set_all_set_mask(Type *type) {
  2263. type = base_type(type);
  2264. GB_ASSERT(type->kind == Type_BitSet);
  2265. i64 lower = type->BitSet.lower;
  2266. i64 upper = type->BitSet.upper;
  2267. Type *elem = type->BitSet.elem;
  2268. Type *underlying = type->BitSet.underlying;
  2269. bool is_backed = underlying != nullptr;
  2270. gb_unused(is_backed);
  2271. BigInt b_lower = {};
  2272. BigInt b_upper = {};
  2273. big_int_from_i64(&b_lower, lower);
  2274. big_int_from_i64(&b_upper, upper);
  2275. BigInt one = {};
  2276. big_int_from_u64(&one, 1);
  2277. BigInt mask = {};
  2278. if (elem == nullptr) {
  2279. big_int_from_i64(&mask, -1);
  2280. } else if (is_type_enum(elem)) {
  2281. Type *e = base_type(elem);
  2282. GB_ASSERT(e->kind == Type_Enum);
  2283. gb_unused(e);
  2284. if ((big_int_cmp(&e->Enum.min_value->value_integer, &b_lower) == 0 || is_backed) &&
  2285. big_int_cmp(&e->Enum.max_value->value_integer, &b_upper) == 0) {
  2286. i64 lower_base = is_backed ? gb_min(0, lower) : lower;
  2287. BigInt b_lower_base = {};
  2288. big_int_from_i64(&b_lower_base, lower_base);
  2289. for (Entity *f : e->Enum.fields) {
  2290. if (f->kind != Entity_Constant) {
  2291. continue;
  2292. }
  2293. if (f->Constant.value.kind != ExactValue_Integer) {
  2294. continue;
  2295. }
  2296. BigInt shift_amount = {};
  2297. big_int_sub(&shift_amount, &f->Constant.value.value_integer, &b_lower_base);
  2298. BigInt value = {};
  2299. big_int_shl(&value, &one, &shift_amount);
  2300. big_int_or(&mask, &mask, &value);
  2301. }
  2302. } else {
  2303. // TODO(bill): enum range based");
  2304. big_int_from_i64(&mask, -1);
  2305. }
  2306. } else {
  2307. i64 lower_base = lower;
  2308. for (i64 x = lower; x <= upper; x++) {
  2309. BigInt shift_amount = {};
  2310. big_int_from_i64(&shift_amount, x - lower_base);
  2311. BigInt value = {};
  2312. big_int_shl(&value, &one, &shift_amount);
  2313. big_int_or(&mask, &mask, &value);
  2314. }
  2315. }
  2316. ExactValue res = {};
  2317. res.kind = ExactValue_Integer;
  2318. res.value_integer = mask;
  2319. return res;
  2320. }
  2321. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2322. switch (op.kind) {
  2323. case Token_And: { // Pointer address
  2324. if (check_is_not_addressable(c, o)) {
  2325. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2326. ast_node(ue, UnaryExpr, node);
  2327. gbString str = expr_to_string(ue->expr);
  2328. defer (gb_string_free(str));
  2329. Entity *e = entity_of_node(ue->expr);
  2330. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2331. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2332. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2333. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2334. } else {
  2335. switch (o->mode) {
  2336. case Addressing_Constant:
  2337. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2338. break;
  2339. case Addressing_SwizzleValue:
  2340. case Addressing_SwizzleVariable:
  2341. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2342. break;
  2343. default:
  2344. {
  2345. ERROR_BLOCK();
  2346. error(op, "Cannot take the pointer address of '%s'", str);
  2347. if (e == nullptr) {
  2348. break;
  2349. }
  2350. if ((e->flags & EntityFlag_ForValue) != 0) {
  2351. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2352. if (parent_type != nullptr && is_type_string(parent_type)) {
  2353. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2354. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2355. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2356. } else {
  2357. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2358. }
  2359. if (parent_type != nullptr && is_type_map(parent_type)) {
  2360. error_line("\t Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2361. } else {
  2362. error_line("\t Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2363. }
  2364. }
  2365. if ((e->flags & EntityFlag_SwitchValue) != 0) {
  2366. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2367. error_line("\t Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2368. }
  2369. }
  2370. break;
  2371. }
  2372. }
  2373. }
  2374. o->mode = Addressing_Invalid;
  2375. return;
  2376. }
  2377. if (o->mode == Addressing_SoaVariable) {
  2378. ast_node(ue, UnaryExpr, node);
  2379. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2380. ast_node(ie, IndexExpr, ue->expr);
  2381. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2382. GB_ASSERT(is_type_soa_struct(soa_type));
  2383. o->type = alloc_type_soa_pointer(soa_type);
  2384. } else {
  2385. o->type = alloc_type_pointer(o->type);
  2386. }
  2387. } else {
  2388. o->type = alloc_type_pointer(o->type);
  2389. }
  2390. switch (o->mode) {
  2391. case Addressing_OptionalOk:
  2392. case Addressing_MapIndex:
  2393. o->mode = Addressing_OptionalOkPtr;
  2394. break;
  2395. default:
  2396. o->mode = Addressing_Value;
  2397. break;
  2398. }
  2399. return;
  2400. }
  2401. }
  2402. if (!check_unary_op(c, o, op)) {
  2403. o->mode = Addressing_Invalid;
  2404. return;
  2405. }
  2406. if (o->mode == Addressing_Constant) {
  2407. Type *type = base_type(o->type);
  2408. if (!is_type_constant_type(o->type)) {
  2409. if (is_type_array_like(o->type)) {
  2410. o->mode = Addressing_Value;
  2411. return;
  2412. }
  2413. gbString xt = type_to_string(o->type);
  2414. gbString err_str = expr_to_string(node);
  2415. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2416. gb_string_free(err_str);
  2417. gb_string_free(xt);
  2418. o->mode = Addressing_Invalid;
  2419. return;
  2420. }
  2421. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2422. gbString err_str = expr_to_string(node);
  2423. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2424. gb_string_free(err_str);
  2425. o->mode = Addressing_Invalid;
  2426. return;
  2427. }
  2428. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2429. gbString err_str = expr_to_string(node);
  2430. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2431. gb_string_free(err_str);
  2432. o->mode = Addressing_Invalid;
  2433. return;
  2434. }
  2435. i32 precision = 0;
  2436. if (is_type_typed(type)) {
  2437. precision = cast(i32)(8 * type_size_of(type));
  2438. }
  2439. bool is_unsigned = is_type_unsigned(type);
  2440. if (is_type_rune(type)) {
  2441. GB_ASSERT(!is_unsigned);
  2442. }
  2443. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2444. if (op.kind == Token_Xor && is_type_bit_set(type)) {
  2445. ExactValue mask = exact_bit_set_all_set_mask(type);
  2446. o->value = exact_binary_operator_value(Token_And, o->value, mask);
  2447. }
  2448. if (is_type_typed(type)) {
  2449. if (node != nullptr) {
  2450. o->expr = node;
  2451. }
  2452. check_is_expressible(c, o, type);
  2453. }
  2454. return;
  2455. }
  2456. o->mode = Addressing_Value;
  2457. }
  2458. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2459. if (t == nullptr) {
  2460. return;
  2461. }
  2462. t = base_type(t);
  2463. if (!is_type_comparable(t)) {
  2464. return;
  2465. }
  2466. switch (t->kind) {
  2467. case Type_Basic:
  2468. switch (t->Basic.kind) {
  2469. case Basic_complex32:
  2470. add_package_dependency(c, "runtime", "complex32_eq");
  2471. add_package_dependency(c, "runtime", "complex32_ne");
  2472. break;
  2473. case Basic_complex64:
  2474. add_package_dependency(c, "runtime", "complex64_eq");
  2475. add_package_dependency(c, "runtime", "complex64_ne");
  2476. break;
  2477. case Basic_complex128:
  2478. add_package_dependency(c, "runtime", "complex128_eq");
  2479. add_package_dependency(c, "runtime", "complex128_ne");
  2480. break;
  2481. case Basic_quaternion64:
  2482. add_package_dependency(c, "runtime", "quaternion64_eq");
  2483. add_package_dependency(c, "runtime", "quaternion64_ne");
  2484. break;
  2485. case Basic_quaternion128:
  2486. add_package_dependency(c, "runtime", "quaternion128_eq");
  2487. add_package_dependency(c, "runtime", "quaternion128_ne");
  2488. break;
  2489. case Basic_quaternion256:
  2490. add_package_dependency(c, "runtime", "quaternion256_eq");
  2491. add_package_dependency(c, "runtime", "quaternion256_ne");
  2492. break;
  2493. case Basic_cstring:
  2494. add_package_dependency(c, "runtime", "cstring_eq");
  2495. add_package_dependency(c, "runtime", "cstring_ne");
  2496. break;
  2497. case Basic_string:
  2498. add_package_dependency(c, "runtime", "string_eq");
  2499. add_package_dependency(c, "runtime", "string_ne");
  2500. break;
  2501. }
  2502. break;
  2503. case Type_Struct:
  2504. for (Entity *field : t->Struct.fields) {
  2505. add_comparison_procedures_for_fields(c, field->type);
  2506. }
  2507. break;
  2508. }
  2509. }
  2510. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2511. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2512. bool comp = are_types_identical(x->type, y->type);
  2513. switch (op) {
  2514. case Token_CmpEq: /* comp = comp; */ break;
  2515. case Token_NotEq: comp = !comp; break;
  2516. }
  2517. x->mode = Addressing_Constant;
  2518. x->type = t_untyped_bool;
  2519. x->value = exact_value_bool(comp);
  2520. return;
  2521. }
  2522. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2523. add_type_info_type(c, x->type);
  2524. add_type_info_type(c, y->type);
  2525. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2526. x->mode = Addressing_Value;
  2527. x->type = t_untyped_bool;
  2528. return;
  2529. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2530. add_type_info_type(c, x->type);
  2531. add_type_info_type(c, y->type);
  2532. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2533. x->mode = Addressing_Value;
  2534. x->type = t_untyped_bool;
  2535. return;
  2536. }
  2537. TEMPORARY_ALLOCATOR_GUARD();
  2538. gbString err_str = nullptr;
  2539. if (check_is_assignable_to(c, x, y->type) ||
  2540. check_is_assignable_to(c, y, x->type)) {
  2541. Type *err_type = x->type;
  2542. bool defined = false;
  2543. switch (op) {
  2544. case Token_CmpEq:
  2545. case Token_NotEq:
  2546. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2547. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2548. (is_operand_nil(*y) && type_has_nil(x->type));
  2549. break;
  2550. case Token_Lt:
  2551. case Token_Gt:
  2552. case Token_LtEq:
  2553. case Token_GtEq:
  2554. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2555. defined = true;
  2556. } else {
  2557. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2558. }
  2559. break;
  2560. }
  2561. if (!defined) {
  2562. gbString xs = type_to_string(x->type, temporary_allocator());
  2563. gbString ys = type_to_string(y->type, temporary_allocator());
  2564. if (!is_type_comparable(x->type)) {
  2565. err_str = gb_string_make(temporary_allocator(),
  2566. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", xs, LIT(token_strings[op]))
  2567. );
  2568. } else if (!is_type_comparable(y->type)) {
  2569. err_str = gb_string_make(temporary_allocator(),
  2570. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", ys, LIT(token_strings[op]))
  2571. );
  2572. } else {
  2573. err_str = gb_string_make(temporary_allocator(),
  2574. gb_bprintf("Operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2575. );
  2576. }
  2577. } else {
  2578. Type *comparison_type = x->type;
  2579. if (x->type == err_type && is_operand_nil(*x)) {
  2580. comparison_type = y->type;
  2581. }
  2582. add_comparison_procedures_for_fields(c, comparison_type);
  2583. }
  2584. } else {
  2585. gbString xt, yt;
  2586. if (x->mode == Addressing_ProcGroup) {
  2587. xt = gb_string_make(temporary_allocator(), "procedure group");
  2588. } else {
  2589. xt = type_to_string(x->type);
  2590. }
  2591. if (y->mode == Addressing_ProcGroup) {
  2592. yt = gb_string_make(temporary_allocator(), "procedure group");
  2593. } else {
  2594. yt = type_to_string(y->type);
  2595. }
  2596. err_str = gb_string_make(temporary_allocator(), gb_bprintf("Mismatched types '%s' and '%s'", xt, yt));
  2597. }
  2598. if (err_str != nullptr) {
  2599. error(node, "Cannot compare expression. %s.", err_str);
  2600. x->type = t_untyped_bool;
  2601. } else {
  2602. if (x->mode == Addressing_Constant &&
  2603. y->mode == Addressing_Constant) {
  2604. if (is_type_constant_type(x->type)) {
  2605. if (is_type_bit_set(x->type)) {
  2606. switch (op) {
  2607. case Token_CmpEq:
  2608. case Token_NotEq:
  2609. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2610. break;
  2611. case Token_Lt:
  2612. case Token_LtEq:
  2613. {
  2614. ExactValue lhs = x->value;
  2615. ExactValue rhs = y->value;
  2616. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2617. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2618. if (op == Token_Lt) {
  2619. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2620. }
  2621. x->value = res;
  2622. break;
  2623. }
  2624. case Token_Gt:
  2625. case Token_GtEq:
  2626. {
  2627. ExactValue lhs = x->value;
  2628. ExactValue rhs = y->value;
  2629. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2630. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2631. if (op == Token_Gt) {
  2632. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2633. }
  2634. x->value = res;
  2635. break;
  2636. }
  2637. }
  2638. } else {
  2639. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2640. }
  2641. } else {
  2642. x->mode = Addressing_Value;
  2643. }
  2644. } else {
  2645. x->mode = Addressing_Value;
  2646. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2647. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2648. i64 size = 0;
  2649. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2650. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2651. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2652. switch (op) {
  2653. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2654. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2655. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2656. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2657. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2658. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2659. }
  2660. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2661. switch (op) {
  2662. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2663. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2664. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2665. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2666. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2667. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2668. }
  2669. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2670. switch (op) {
  2671. case Token_CmpEq:
  2672. switch (8*size) {
  2673. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2674. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2675. }
  2676. break;
  2677. case Token_NotEq:
  2678. switch (8*size) {
  2679. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2680. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2681. }
  2682. break;
  2683. }
  2684. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2685. switch (op) {
  2686. case Token_CmpEq:
  2687. switch (8*size) {
  2688. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2689. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2690. }
  2691. break;
  2692. case Token_NotEq:
  2693. switch (8*size) {
  2694. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2695. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2696. }
  2697. break;
  2698. }
  2699. }
  2700. }
  2701. x->type = t_untyped_bool;
  2702. }
  2703. }
  2704. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2705. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2706. ast_node(be, BinaryExpr, node);
  2707. bool y_is_untyped = is_type_untyped(y->type);
  2708. if (y_is_untyped) {
  2709. convert_to_typed(c, y, t_untyped_integer);
  2710. if (y->mode == Addressing_Invalid) {
  2711. x->mode = Addressing_Invalid;
  2712. return;
  2713. }
  2714. } else if (!is_type_unsigned(y->type)) {
  2715. gbString y_str = expr_to_string(y->expr);
  2716. error(y->expr, "Shift amount '%s' must be an unsigned integer", y_str);
  2717. gb_string_free(y_str);
  2718. x->mode = Addressing_Invalid;
  2719. return;
  2720. }
  2721. bool x_is_untyped = is_type_untyped(x->type);
  2722. if (!(x_is_untyped || is_type_integer(x->type))) {
  2723. gbString x_str = expr_to_string(x->expr);
  2724. error(x->expr, "Shifted operand '%s' must be an integer", x_str);
  2725. gb_string_free(x_str);
  2726. x->mode = Addressing_Invalid;
  2727. return;
  2728. }
  2729. if (y->mode == Addressing_Constant) {
  2730. if (big_int_is_neg(&y->value.value_integer)) {
  2731. gbString y_str = expr_to_string(y->expr);
  2732. error(y->expr, "Shift amount '%s' cannot be negative", y_str);
  2733. gb_string_free(y_str);
  2734. x->mode = Addressing_Invalid;
  2735. return;
  2736. }
  2737. BigInt max_shift = {};
  2738. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2739. if (big_int_cmp(&y->value.value_integer, &max_shift) > 0) {
  2740. gbString y_str = expr_to_string(y->expr);
  2741. error(y->expr, "Shift amount '%s' must be <= %u", y_str, MAX_BIG_INT_SHIFT);
  2742. gb_string_free(y_str);
  2743. x->mode = Addressing_Invalid;
  2744. return;
  2745. }
  2746. if (x->mode == Addressing_Constant) {
  2747. if (x_is_untyped) {
  2748. convert_to_typed(c, x, t_untyped_integer);
  2749. if (x->mode == Addressing_Invalid) {
  2750. return;
  2751. }
  2752. x->expr = node;
  2753. x->value = exact_value_shift(be->op.kind, exact_value_to_integer(x->value), exact_value_to_integer(y->value));
  2754. return;
  2755. }
  2756. x->expr = node;
  2757. x->value = exact_value_shift(be->op.kind, x->value, y->value);
  2758. check_is_expressible(c, x, x->type);
  2759. return;
  2760. }
  2761. if (y_is_untyped) {
  2762. convert_to_typed(c, y, t_uint);
  2763. }
  2764. return;
  2765. }
  2766. if (x->mode == Addressing_Constant) {
  2767. if (x_is_untyped) {
  2768. if (type_hint) {
  2769. if (is_type_integer(type_hint)) {
  2770. convert_to_typed(c, x, type_hint);
  2771. } else if (is_type_any(type_hint)) {
  2772. convert_to_typed(c, x, default_type(t_untyped_integer));
  2773. } else {
  2774. gbString x_str = expr_to_string(x->expr);
  2775. gbString type_str = type_to_string(type_hint);
  2776. error(x->expr, "Shifted operand '%s' cannot convert to non-integer type '%s'", x_str, type_str);
  2777. gb_string_free(x_str);
  2778. gb_string_free(type_str);
  2779. x->mode = Addressing_Invalid;
  2780. return;
  2781. }
  2782. } else {
  2783. check_is_expressible(c, x, default_type(t_untyped_integer));
  2784. }
  2785. if (x->mode == Addressing_Invalid) {
  2786. return;
  2787. }
  2788. }
  2789. x->mode = Addressing_Value;
  2790. }
  2791. }
  2792. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2793. if (check_is_assignable_to(c, operand, y)) {
  2794. return true;
  2795. }
  2796. bool is_constant = operand->mode == Addressing_Constant;
  2797. Type *x = operand->type;
  2798. Type *src = core_type(x);
  2799. Type *dst = core_type(y);
  2800. if (are_types_identical(src, dst)) {
  2801. return true;
  2802. }
  2803. // if (is_type_tuple(src)) {
  2804. // Ast *expr = unparen_expr(operand->expr);
  2805. // if (expr && expr->kind == Ast_CallExpr) {
  2806. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2807. // ast_node(ce, CallExpr, expr);
  2808. // Type *pt = base_type(type_of_expr(ce->proc));
  2809. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2810. // if (pt->Proc.result_count > 0) {
  2811. // Operand op = *operand;
  2812. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2813. // bool ok = check_is_castable_to(c, &op, y);
  2814. // if (ok) {
  2815. // ce->optional_ok_one = true;
  2816. // }
  2817. // return ok;
  2818. // }
  2819. // }
  2820. // }
  2821. // }
  2822. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2823. if (is_type_u8_array(dst)) {
  2824. String s = operand->value.value_string;
  2825. return s.len == dst->Array.count;
  2826. }
  2827. if (is_type_rune_array(dst)) {
  2828. String s = operand->value.value_string;
  2829. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2830. }
  2831. }
  2832. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2833. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2834. return dst->Array.count == src->Array.count;
  2835. }
  2836. }
  2837. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2838. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2839. }
  2840. // Cast between booleans and integers
  2841. if (is_type_boolean(src) || is_type_integer(src)) {
  2842. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2843. return true;
  2844. }
  2845. }
  2846. // Cast between numbers
  2847. if (is_type_integer(src) || is_type_float(src)) {
  2848. if (is_type_integer(dst) || is_type_float(dst)) {
  2849. return true;
  2850. }
  2851. }
  2852. if (is_type_bit_field(src)) {
  2853. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2854. }
  2855. if (is_type_bit_field(dst)) {
  2856. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2857. }
  2858. if (is_type_integer(src) && is_type_rune(dst)) {
  2859. return true;
  2860. }
  2861. if (is_type_rune(src) && is_type_integer(dst)) {
  2862. return true;
  2863. }
  2864. if (is_type_complex(src) && is_type_complex(dst)) {
  2865. return true;
  2866. }
  2867. if (is_type_float(src) && is_type_complex(dst)) {
  2868. return true;
  2869. }
  2870. if (is_type_float(src) && is_type_quaternion(dst)) {
  2871. return true;
  2872. }
  2873. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2874. return true;
  2875. }
  2876. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2877. return true;
  2878. }
  2879. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2880. GB_ASSERT(src->kind == Type_Matrix);
  2881. GB_ASSERT(dst->kind == Type_Matrix);
  2882. Operand op = *operand;
  2883. op.type = src->Matrix.elem;
  2884. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2885. return false;
  2886. }
  2887. if (src->Matrix.row_count != src->Matrix.column_count) {
  2888. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2889. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2890. return src_count == dst_count;
  2891. }
  2892. return is_matrix_square(dst) && is_matrix_square(src);
  2893. }
  2894. // Cast between pointers
  2895. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2896. return true;
  2897. }
  2898. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2899. return true;
  2900. }
  2901. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2902. return true;
  2903. }
  2904. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2905. return true;
  2906. }
  2907. // uintptr <-> pointer
  2908. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2909. return true;
  2910. }
  2911. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2912. return true;
  2913. }
  2914. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2915. return true;
  2916. }
  2917. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2918. return true;
  2919. }
  2920. // []byte/[]u8 <-> string (not cstring)
  2921. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2922. return true;
  2923. }
  2924. // cstring -> string
  2925. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2926. if (operand->mode != Addressing_Constant) {
  2927. add_package_dependency(c, "runtime", "cstring_to_string");
  2928. }
  2929. return true;
  2930. }
  2931. // cstring -> ^u8
  2932. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2933. return !is_constant;
  2934. }
  2935. // cstring -> [^]u8
  2936. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2937. return !is_constant;
  2938. }
  2939. // cstring -> rawptr
  2940. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2941. return !is_constant;
  2942. }
  2943. // ^u8 -> cstring
  2944. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2945. return !is_constant;
  2946. }
  2947. // [^]u8 -> cstring
  2948. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2949. return !is_constant;
  2950. }
  2951. // rawptr -> cstring
  2952. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2953. return !is_constant;
  2954. }
  2955. // proc <-> proc
  2956. if (is_type_proc(src) && is_type_proc(dst)) {
  2957. if (is_type_polymorphic(dst)) {
  2958. if (is_type_polymorphic(src) &&
  2959. operand->mode == Addressing_Variable) {
  2960. return true;
  2961. }
  2962. return false;
  2963. }
  2964. return true;
  2965. }
  2966. // proc -> rawptr
  2967. if (is_type_proc(src) && is_type_rawptr(dst)) {
  2968. return true;
  2969. }
  2970. // rawptr -> proc
  2971. if (is_type_rawptr(src) && is_type_proc(dst)) {
  2972. return true;
  2973. }
  2974. if (is_type_array(dst)) {
  2975. Type *elem = base_array_type(dst);
  2976. if (check_is_castable_to(c, operand, elem)) {
  2977. return true;
  2978. }
  2979. }
  2980. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  2981. if (src->SimdVector.count != dst->SimdVector.count) {
  2982. return false;
  2983. }
  2984. Type *elem_src = base_array_type(src);
  2985. Type *elem_dst = base_array_type(dst);
  2986. Operand x = {};
  2987. x.type = elem_src;
  2988. x.mode = Addressing_Value;
  2989. return check_is_castable_to(c, &x, elem_dst);
  2990. }
  2991. if (is_type_simd_vector(dst)) {
  2992. Type *elem = base_array_type(dst);
  2993. if (check_is_castable_to(c, operand, elem)) {
  2994. return true;
  2995. }
  2996. }
  2997. return false;
  2998. }
  2999. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  3000. bool is_const_expr = x->mode == Addressing_Constant;
  3001. Type *bt = base_type(type);
  3002. if (is_const_expr && is_type_constant_type(bt)) {
  3003. if (core_type(bt)->kind == Type_Basic) {
  3004. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  3005. return true;
  3006. } else if (check_is_castable_to(c, x, type)) {
  3007. if (is_type_pointer(type)) {
  3008. return true;
  3009. }
  3010. }
  3011. } else if (check_is_castable_to(c, x, type)) {
  3012. x->value = {};
  3013. x->mode = Addressing_Value;
  3014. return true;
  3015. }
  3016. } else if (check_is_castable_to(c, x, type)) {
  3017. if (x->mode != Addressing_Constant) {
  3018. x->mode = Addressing_Value;
  3019. } else if (is_type_slice(type) && is_type_string(x->type)) {
  3020. x->mode = Addressing_Value;
  3021. } else if (is_type_union(type)) {
  3022. x->mode = Addressing_Value;
  3023. }
  3024. if (x->mode == Addressing_Value) {
  3025. x->value = {};
  3026. }
  3027. return true;
  3028. }
  3029. return false;
  3030. }
  3031. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type, bool forbid_identical = false) {
  3032. if (!is_operand_value(*x)) {
  3033. error(x->expr, "Only values can be casted");
  3034. x->mode = Addressing_Invalid;
  3035. return;
  3036. }
  3037. bool is_const_expr = x->mode == Addressing_Constant;
  3038. bool can_convert = check_cast_internal(c, x, type);
  3039. if (!can_convert) {
  3040. TEMPORARY_ALLOCATOR_GUARD();
  3041. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  3042. gbString to_type = type_to_string(type, temporary_allocator());
  3043. gbString from_type = type_to_string(x->type, temporary_allocator());
  3044. x->mode = Addressing_Invalid;
  3045. ERROR_BLOCK();
  3046. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  3047. if (is_const_expr) {
  3048. gbString val_str = exact_value_to_string(x->value);
  3049. if (is_type_float(x->type) && is_type_integer(type)) {
  3050. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  3051. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3052. x->mode = Addressing_Constant;
  3053. x->type = type;
  3054. } else {
  3055. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  3056. if (is_type_numeric(type)) {
  3057. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3058. x->mode = Addressing_Constant;
  3059. x->type = type;
  3060. }
  3061. }
  3062. gb_string_free(val_str);
  3063. }
  3064. check_cast_error_suggestion(c, x, type);
  3065. return;
  3066. }
  3067. if (is_type_untyped(x->type)) {
  3068. Type *final_type = type;
  3069. if (is_const_expr && !is_type_constant_type(type)) {
  3070. if (is_type_union(type)) {
  3071. convert_to_typed(c, x, type);
  3072. }
  3073. final_type = default_type(x->type);
  3074. }
  3075. update_untyped_expr_type(c, x->expr, final_type, true);
  3076. } else {
  3077. Type *src = core_type(x->type);
  3078. Type *dst = core_type(type);
  3079. if (src != dst) {
  3080. bool const REQUIRE = true;
  3081. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  3082. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  3083. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  3084. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  3085. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  3086. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  3087. } else if (src == t_f16 && is_type_float(dst)) {
  3088. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  3089. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  3090. } else if (is_type_float(dst) && dst == t_f16) {
  3091. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  3092. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  3093. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  3094. }
  3095. }
  3096. // If we check polymorphic procedures, we risk erring on
  3097. // identical casts that cannot be foreseen or otherwise
  3098. // forbidden, so just skip them.
  3099. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3100. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig))) {
  3101. Type *src_exact = x->type;
  3102. Type *dst_exact = type;
  3103. if (src_exact != nullptr &&
  3104. dst_exact != nullptr &&
  3105. are_types_identical(src_exact, dst_exact)
  3106. ) {
  3107. gbString oper_str = expr_to_string(x->expr);
  3108. gbString to_type = type_to_string(dst_exact);
  3109. error(x->expr, "Unneeded cast of '%s' to identical type '%s'", oper_str, to_type);
  3110. gb_string_free(oper_str);
  3111. gb_string_free(to_type);
  3112. }
  3113. }
  3114. }
  3115. x->type = type;
  3116. }
  3117. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t, bool forbid_identical = false) {
  3118. if (!is_operand_value(*o)) {
  3119. error(o->expr, "'transmute' can only be applied to values");
  3120. o->mode = Addressing_Invalid;
  3121. return false;
  3122. }
  3123. Operand src = *o;
  3124. Type *src_t = o->type;
  3125. Type *dst_t = t;
  3126. Type *src_bt = base_type(src_t);
  3127. Type *dst_bt = base_type(dst_t);
  3128. if (is_type_untyped(src_t)) {
  3129. gbString expr_str = expr_to_string(o->expr);
  3130. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  3131. gb_string_free(expr_str);
  3132. o->mode = Addressing_Invalid;
  3133. o->expr = node;
  3134. return false;
  3135. }
  3136. if (dst_bt == nullptr || dst_bt == t_invalid) {
  3137. GB_ASSERT(global_error_collector.count != 0);
  3138. o->mode = Addressing_Invalid;
  3139. o->expr = node;
  3140. return false;
  3141. }
  3142. if (src_bt == nullptr || src_bt == t_invalid) {
  3143. // NOTE(bill): this should be an error
  3144. GB_ASSERT(global_error_collector.count != 0);
  3145. o->mode = Addressing_Value;
  3146. o->expr = node;
  3147. o->type = dst_t;
  3148. return true;
  3149. }
  3150. i64 srcz = type_size_of(src_t);
  3151. i64 dstz = type_size_of(dst_t);
  3152. if (srcz != dstz) {
  3153. gbString expr_str = expr_to_string(o->expr);
  3154. gbString type_str = type_to_string(dst_t);
  3155. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  3156. gb_string_free(type_str);
  3157. gb_string_free(expr_str);
  3158. o->mode = Addressing_Invalid;
  3159. o->expr = node;
  3160. return false;
  3161. }
  3162. o->expr = node;
  3163. o->type = dst_t;
  3164. if (o->mode == Addressing_Constant) {
  3165. if (are_types_identical(src_bt, dst_bt)) {
  3166. return true;
  3167. }
  3168. if ((is_type_integer(src_t) && is_type_integer(dst_t)) ||
  3169. is_type_integer(src_t) && is_type_bit_set(dst_t)) {
  3170. if (types_have_same_internal_endian(src_t, dst_t)) {
  3171. ExactValue src_v = exact_value_to_integer(o->value);
  3172. GB_ASSERT(src_v.kind == ExactValue_Integer || src_v.kind == ExactValue_Invalid);
  3173. BigInt v = src_v.value_integer;
  3174. BigInt smax = {};
  3175. BigInt umax = {};
  3176. big_int_from_u64(&smax, 0);
  3177. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  3178. big_int_from_u64(&umax, 1);
  3179. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  3180. big_int_shl_eq(&umax, &sz_in_bits);
  3181. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  3182. if (big_int_cmp(&v, &smax) >= 0) {
  3183. big_int_sub_eq(&v, &umax);
  3184. }
  3185. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  3186. if (big_int_is_neg(&v)) {
  3187. big_int_add_eq(&v, &umax);
  3188. }
  3189. }
  3190. o->value.kind = ExactValue_Integer;
  3191. o->value.value_integer = v;
  3192. return true;
  3193. }
  3194. }
  3195. } else {
  3196. // If we check polymorphic procedures, we risk erring on
  3197. // identical casts that cannot be foreseen or otherwise
  3198. // forbidden, so just skip them.
  3199. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3200. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig)) &&
  3201. check_is_castable_to(c, &src, dst_t)) {
  3202. if (are_types_identical(src_t, dst_t)) {
  3203. gbString oper_str = expr_to_string(o->expr);
  3204. gbString to_type = type_to_string(dst_t);
  3205. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3206. gb_string_free(oper_str);
  3207. gb_string_free(to_type);
  3208. } else if (is_type_internally_pointer_like(src_t) &&
  3209. is_type_internally_pointer_like(dst_t)) {
  3210. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since the types are pointer-like");
  3211. } else if (are_types_identical(src_bt, dst_bt)) {
  3212. gbString oper_str = expr_to_string(o->expr);
  3213. gbString to_type = type_to_string(dst_t);
  3214. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3215. gb_string_free(oper_str);
  3216. gb_string_free(to_type);
  3217. } else if (is_type_integer(src_t) && is_type_integer(dst_t) &&
  3218. types_have_same_internal_endian(src_t, dst_t) &&
  3219. type_endian_kind_of(src_t) == type_endian_kind_of(dst_t)) {
  3220. gbString oper_type = type_to_string(src_t);
  3221. gbString to_type = type_to_string(dst_t);
  3222. 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);
  3223. gb_string_free(to_type);
  3224. gb_string_free(oper_type);
  3225. }
  3226. }
  3227. }
  3228. o->mode = Addressing_Value;
  3229. o->value = {};
  3230. return true;
  3231. }
  3232. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  3233. if (is_type_array_like(x->type) || is_type_array_like(y->type)) {
  3234. if (op.kind == Token_CmpAnd || op.kind == Token_CmpOr) {
  3235. error(op, "Array programming is not allowed with the operator '%.*s'", LIT(op.string));
  3236. }
  3237. }
  3238. if (is_type_array(x->type) && !is_type_array(y->type)) {
  3239. if (check_is_assignable_to(c, y, x->type)) {
  3240. if (check_binary_op(c, x, op)) {
  3241. return true;
  3242. }
  3243. }
  3244. }
  3245. if (is_type_simd_vector(x->type) && !is_type_simd_vector(y->type)) {
  3246. if (check_is_assignable_to(c, y, x->type)) {
  3247. if (check_binary_op(c, x, op)) {
  3248. return true;
  3249. }
  3250. }
  3251. }
  3252. return false;
  3253. }
  3254. gb_internal bool is_ise_expr(Ast *node) {
  3255. node = unparen_expr(node);
  3256. return node->kind == Ast_ImplicitSelectorExpr;
  3257. }
  3258. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  3259. if (use_lhs_as_type_hint) { // RHS in this case
  3260. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  3261. }
  3262. return false;
  3263. }
  3264. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  3265. Type *xt = base_type(matrix);
  3266. if (type_hint != nullptr) {
  3267. Type *th = base_type(type_hint);
  3268. if (are_types_identical(th, xt)) {
  3269. return type_hint;
  3270. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  3271. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  3272. // ignore
  3273. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  3274. xt->Matrix.column_count == th->Matrix.column_count) {
  3275. return type_hint;
  3276. }
  3277. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  3278. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  3279. // ignore
  3280. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  3281. return type_hint;
  3282. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3283. return type_hint;
  3284. }
  3285. }
  3286. }
  3287. return matrix;
  3288. }
  3289. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3290. if (!check_binary_op(c, x, op)) {
  3291. x->mode = Addressing_Invalid;
  3292. return;
  3293. }
  3294. Type *xt = base_type(x->type);
  3295. Type *yt = base_type(y->type);
  3296. if (is_type_matrix(x->type)) {
  3297. GB_ASSERT(xt->kind == Type_Matrix);
  3298. if (op.kind == Token_Mul) {
  3299. if (yt->kind == Type_Matrix) {
  3300. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3301. goto matrix_error;
  3302. }
  3303. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3304. goto matrix_error;
  3305. }
  3306. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3307. goto matrix_error;
  3308. }
  3309. x->mode = Addressing_Value;
  3310. if (are_types_identical(xt, yt)) {
  3311. if (are_types_identical(x->type, y->type)) {
  3312. return;
  3313. }
  3314. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3315. // prefer the named type
  3316. x->type = y->type;
  3317. }
  3318. } else {
  3319. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3320. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3321. }
  3322. goto matrix_success;
  3323. } else if (yt->kind == Type_Array) {
  3324. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3325. goto matrix_error;
  3326. }
  3327. if (xt->Matrix.column_count != yt->Array.count) {
  3328. goto matrix_error;
  3329. }
  3330. // Treat arrays as column vectors
  3331. x->mode = Addressing_Value;
  3332. if (xt->Matrix.row_count == yt->Array.count) {
  3333. x->type = y->type;
  3334. } else {
  3335. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3336. }
  3337. goto matrix_success;
  3338. }
  3339. }
  3340. if (!are_types_identical(xt, yt)) {
  3341. goto matrix_error;
  3342. }
  3343. x->mode = Addressing_Value;
  3344. x->type = xt;
  3345. goto matrix_success;
  3346. } else {
  3347. GB_ASSERT(!is_type_matrix(xt));
  3348. GB_ASSERT(is_type_matrix(yt));
  3349. if (op.kind == Token_Mul) {
  3350. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3351. if (xt->kind == Type_Array) {
  3352. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3353. goto matrix_error;
  3354. }
  3355. if (xt->Array.count != yt->Matrix.row_count) {
  3356. goto matrix_error;
  3357. }
  3358. // Treat arrays as row vectors
  3359. x->mode = Addressing_Value;
  3360. if (yt->Matrix.column_count == xt->Array.count) {
  3361. x->type = x->type;
  3362. } else {
  3363. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3364. }
  3365. goto matrix_success;
  3366. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3367. x->type = check_matrix_type_hint(y->type, type_hint);
  3368. return;
  3369. }
  3370. }
  3371. if (!are_types_identical(xt, yt)) {
  3372. goto matrix_error;
  3373. }
  3374. x->mode = Addressing_Value;
  3375. x->type = xt;
  3376. goto matrix_success;
  3377. }
  3378. matrix_success:
  3379. x->type = check_matrix_type_hint(x->type, type_hint);
  3380. return;
  3381. matrix_error:
  3382. gbString xts = type_to_string(x->type);
  3383. gbString yts = type_to_string(y->type);
  3384. gbString expr_str = expr_to_string(x->expr);
  3385. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3386. gb_string_free(expr_str);
  3387. gb_string_free(yts);
  3388. gb_string_free(xts);
  3389. x->type = t_invalid;
  3390. x->mode = Addressing_Invalid;
  3391. return;
  3392. }
  3393. gb_internal void check_binary_expr_dependency(CheckerContext *c, Token op, Type *bt, bool REQUIRE) {
  3394. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3395. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3396. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3397. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3398. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3399. }
  3400. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3401. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3402. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3403. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3404. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3405. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3406. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3407. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3408. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3409. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3410. }
  3411. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3412. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3413. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3414. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3415. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3416. case Basic_u128:
  3417. case Basic_i128:
  3418. if (is_arch_wasm()) {
  3419. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3420. }
  3421. break;
  3422. }
  3423. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3424. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3425. case Basic_u128:
  3426. case Basic_i128:
  3427. if (is_arch_wasm()) {
  3428. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3429. }
  3430. break;
  3431. }
  3432. } else if (op.kind == Token_Shr || op.kind == Token_ShrEq) {
  3433. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3434. case Basic_u128:
  3435. case Basic_i128:
  3436. if (is_arch_wasm()) {
  3437. add_package_dependency(c, "runtime", "__lshrti3", REQUIRE);
  3438. }
  3439. break;
  3440. }
  3441. }
  3442. }
  3443. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3444. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3445. Operand y_ = {}, *y = &y_;
  3446. ast_node(be, BinaryExpr, node);
  3447. defer({
  3448. node->viral_state_flags |= be->left->viral_state_flags;
  3449. node->viral_state_flags |= be->right->viral_state_flags;
  3450. });
  3451. Token op = be->op;
  3452. switch (op.kind) {
  3453. case Token_CmpEq:
  3454. case Token_NotEq: {
  3455. // NOTE(bill): Allow comparisons between types
  3456. if (is_ise_expr(be->left)) {
  3457. // Evalute the right before the left for an '.X' expression
  3458. check_expr_or_type(c, y, be->right, nullptr /* ignore type hint */);
  3459. check_expr_or_type(c, x, be->left, y->type);
  3460. } else {
  3461. check_expr_or_type(c, x, be->left, nullptr /* ignore type hint */);
  3462. check_expr_or_type(c, y, be->right, x->type);
  3463. }
  3464. bool xt = x->mode == Addressing_Type;
  3465. bool yt = y->mode == Addressing_Type;
  3466. // If only one is a type, this is an error
  3467. if (xt ^ yt) {
  3468. GB_ASSERT(xt != yt);
  3469. if (xt) {
  3470. if (!is_type_typeid(y->type)) {
  3471. error_operand_not_expression(x);
  3472. }
  3473. }
  3474. if (yt) {
  3475. if (!is_type_typeid(x->type)) {
  3476. error_operand_not_expression(y);
  3477. }
  3478. }
  3479. }
  3480. break;
  3481. }
  3482. case Token_in:
  3483. case Token_not_in:
  3484. {
  3485. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3486. check_expr(c, y, be->right);
  3487. Type *rhs_type = type_deref(y->type);
  3488. if (rhs_type == nullptr) {
  3489. error(y->expr, "Cannot use '%.*s' on an expression with no value", LIT(op.string));
  3490. x->mode = Addressing_Invalid;
  3491. x->expr = node;
  3492. return;
  3493. }
  3494. if (is_type_bit_set(rhs_type)) {
  3495. Type *elem = base_type(rhs_type)->BitSet.elem;
  3496. check_expr_with_type_hint(c, x, be->left, elem);
  3497. } else if (is_type_map(rhs_type)) {
  3498. Type *key = base_type(rhs_type)->Map.key;
  3499. check_expr_with_type_hint(c, x, be->left, key);
  3500. } else {
  3501. check_expr(c, x, be->left);
  3502. }
  3503. if (x->mode == Addressing_Invalid) {
  3504. return;
  3505. }
  3506. if (y->mode == Addressing_Invalid) {
  3507. x->mode = Addressing_Invalid;
  3508. x->expr = y->expr;
  3509. return;
  3510. }
  3511. if (is_type_map(rhs_type)) {
  3512. Type *yt = base_type(rhs_type);
  3513. if (op.kind == Token_in) {
  3514. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3515. } else {
  3516. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3517. }
  3518. add_map_get_dependencies(c);
  3519. } else if (is_type_bit_set(rhs_type)) {
  3520. Type *yt = base_type(rhs_type);
  3521. if (op.kind == Token_in) {
  3522. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3523. } else {
  3524. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3525. }
  3526. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3527. ExactValue k = exact_value_to_integer(x->value);
  3528. ExactValue v = exact_value_to_integer(y->value);
  3529. GB_ASSERT(k.kind == ExactValue_Integer);
  3530. GB_ASSERT(v.kind == ExactValue_Integer);
  3531. i64 key = big_int_to_i64(&k.value_integer);
  3532. i64 lower = yt->BitSet.lower;
  3533. i64 upper = yt->BitSet.upper;
  3534. if (lower <= key && key <= upper) {
  3535. i64 bit = 1ll<<key;
  3536. i64 bits = big_int_to_i64(&v.value_integer);
  3537. x->mode = Addressing_Constant;
  3538. x->type = t_untyped_bool;
  3539. if (op.kind == Token_in) {
  3540. x->value = exact_value_bool((bit & bits) != 0);
  3541. } else {
  3542. x->value = exact_value_bool((bit & bits) == 0);
  3543. }
  3544. x->expr = node;
  3545. return;
  3546. } else {
  3547. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3548. x->mode = Addressing_Invalid;
  3549. }
  3550. }
  3551. } else {
  3552. gbString t = type_to_string(y->type);
  3553. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3554. gb_string_free(t);
  3555. x->expr = node;
  3556. x->mode = Addressing_Invalid;
  3557. return;
  3558. }
  3559. if (x->mode != Addressing_Invalid) {
  3560. x->mode = Addressing_Value;
  3561. x->type = t_untyped_bool;
  3562. }
  3563. x->expr = node;
  3564. return;
  3565. }
  3566. default:
  3567. if (is_ise_expr(be->left)) {
  3568. // Evalute the right before the left for an '.X' expression
  3569. check_expr_or_type(c, y, be->right, type_hint);
  3570. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3571. check_expr_or_type(c, x, be->left, y->type);
  3572. } else {
  3573. check_expr_with_type_hint(c, x, be->left, type_hint);
  3574. }
  3575. } else {
  3576. check_expr_with_type_hint(c, x, be->left, type_hint);
  3577. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3578. check_expr_with_type_hint(c, y, be->right, x->type);
  3579. } else {
  3580. check_expr_with_type_hint(c, y, be->right, type_hint);
  3581. }
  3582. }
  3583. break;
  3584. }
  3585. if (x->mode == Addressing_Invalid) {
  3586. return;
  3587. }
  3588. if (y->mode == Addressing_Invalid) {
  3589. x->mode = Addressing_Invalid;
  3590. x->expr = y->expr;
  3591. return;
  3592. }
  3593. if (x->mode == Addressing_Builtin) {
  3594. x->mode = Addressing_Invalid;
  3595. error(x->expr, "built-in expression in binary expression");
  3596. return;
  3597. }
  3598. if (y->mode == Addressing_Builtin) {
  3599. x->mode = Addressing_Invalid;
  3600. error(y->expr, "built-in expression in binary expression");
  3601. return;
  3602. }
  3603. if (x->mode == Addressing_ProcGroup) {
  3604. x->mode = Addressing_Invalid;
  3605. if (x->proc_group != nullptr) {
  3606. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3607. } else {
  3608. error(x->expr, "procedure group used in binary expression");
  3609. }
  3610. return;
  3611. }
  3612. if (y->mode == Addressing_ProcGroup) {
  3613. x->mode = Addressing_Invalid;
  3614. if (x->proc_group != nullptr) {
  3615. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3616. } else {
  3617. error(y->expr, "procedure group used in binary expression");
  3618. }
  3619. return;
  3620. }
  3621. bool REQUIRE = true;
  3622. Type *btx = base_type(x->type);
  3623. Type *bty = base_type(y->type);
  3624. check_binary_expr_dependency(c, op, btx, REQUIRE);
  3625. check_binary_expr_dependency(c, op, bty, REQUIRE);
  3626. if (token_is_shift(op.kind)) {
  3627. check_shift(c, x, y, node, type_hint);
  3628. return;
  3629. }
  3630. switch (op.kind) {
  3631. case Token_Quo:
  3632. case Token_Mod:
  3633. case Token_ModMod:
  3634. case Token_QuoEq:
  3635. case Token_ModEq:
  3636. case Token_ModModEq:
  3637. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3638. is_type_float(x->type) && is_type_untyped(x->type)) {
  3639. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3640. gbString t = type_to_string(y->type);
  3641. if (x->value.kind != ExactValue_Invalid) {
  3642. gbString s = exact_value_to_string(x->value);
  3643. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3644. gb_string_free(s);
  3645. } else {
  3646. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3647. }
  3648. gb_string_free(t);
  3649. }
  3650. break;
  3651. }
  3652. convert_to_typed(c, x, y->type);
  3653. if (x->mode == Addressing_Invalid) {
  3654. return;
  3655. }
  3656. convert_to_typed(c, y, x->type);
  3657. if (y->mode == Addressing_Invalid) {
  3658. x->mode = Addressing_Invalid;
  3659. return;
  3660. }
  3661. if (token_is_comparison(op.kind)) {
  3662. check_comparison(c, node, x, y, op.kind);
  3663. return;
  3664. }
  3665. if (check_binary_array_expr(c, op, x, y)) {
  3666. x->mode = Addressing_Value;
  3667. x->type = x->type;
  3668. return;
  3669. }
  3670. if (check_binary_array_expr(c, op, y, x)) {
  3671. x->mode = Addressing_Value;
  3672. x->type = y->type;
  3673. return;
  3674. }
  3675. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3676. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3677. x->expr = node;
  3678. return;
  3679. }
  3680. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3681. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3682. // NOTE(bill, 2022-06-26)
  3683. // Allow any boolean types within `&&` and `||`
  3684. // This is an exception to all other binary expressions since the result
  3685. // of a comparison will always be an untyped boolean, and allowing
  3686. // any boolean between these two simplifies a lot of expressions
  3687. } else if (!are_types_identical(x->type, y->type)) {
  3688. if (x->type != t_invalid &&
  3689. y->type != t_invalid) {
  3690. gbString xt = type_to_string(x->type);
  3691. gbString yt = type_to_string(y->type);
  3692. gbString expr_str = expr_to_string(node);
  3693. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3694. gb_string_free(expr_str);
  3695. gb_string_free(yt);
  3696. gb_string_free(xt);
  3697. }
  3698. x->mode = Addressing_Invalid;
  3699. return;
  3700. }
  3701. if (!check_binary_op(c, x, op)) {
  3702. x->mode = Addressing_Invalid;
  3703. return;
  3704. }
  3705. switch (op.kind) {
  3706. case Token_Quo:
  3707. case Token_Mod:
  3708. case Token_ModMod:
  3709. case Token_QuoEq:
  3710. case Token_ModEq:
  3711. case Token_ModModEq:
  3712. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3713. y->mode == Addressing_Constant) {
  3714. bool fail = false;
  3715. switch (y->value.kind) {
  3716. case ExactValue_Integer:
  3717. if (big_int_is_zero(&y->value.value_integer)) {
  3718. fail = true;
  3719. }
  3720. break;
  3721. case ExactValue_Float:
  3722. if (y->value.value_float == 0.0) {
  3723. fail = true;
  3724. }
  3725. break;
  3726. }
  3727. if (fail) {
  3728. error(y->expr, "Division by zero not allowed");
  3729. x->mode = Addressing_Invalid;
  3730. return;
  3731. }
  3732. }
  3733. break;
  3734. case Token_CmpAnd:
  3735. case Token_CmpOr:
  3736. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3737. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3738. }
  3739. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3740. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3741. }
  3742. break;
  3743. }
  3744. if (x->mode == Addressing_Constant &&
  3745. y->mode == Addressing_Constant) {
  3746. ExactValue a = x->value;
  3747. ExactValue b = y->value;
  3748. if (!is_type_constant_type(x->type)) {
  3749. x->mode = Addressing_Value;
  3750. return;
  3751. }
  3752. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3753. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3754. }
  3755. if (is_type_bit_set(x->type)) {
  3756. switch (op.kind) {
  3757. case Token_Add: op.kind = Token_Or; break;
  3758. case Token_Sub: op.kind = Token_AndNot; break;
  3759. }
  3760. }
  3761. x->value = exact_binary_operator_value(op.kind, a, b);
  3762. if (is_type_typed(x->type)) {
  3763. if (node != nullptr) {
  3764. x->expr = node;
  3765. }
  3766. check_is_expressible(c, x, x->type);
  3767. }
  3768. return;
  3769. } else if (is_type_string(x->type)) {
  3770. error(node, "String concatenation is only allowed with constant strings");
  3771. x->mode = Addressing_Invalid;
  3772. return;
  3773. }
  3774. x->mode = Addressing_Value;
  3775. }
  3776. gb_internal Operand make_operand_from_node(Ast *node) {
  3777. GB_ASSERT(node != nullptr);
  3778. Operand x = {};
  3779. x.expr = node;
  3780. x.mode = node->tav.mode;
  3781. x.type = node->tav.type;
  3782. x.value = node->tav.value;
  3783. return x;
  3784. }
  3785. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3786. GB_ASSERT(e != nullptr);
  3787. ExprInfo *old = check_get_expr_info(c, e);
  3788. if (old == nullptr) {
  3789. if (type != nullptr && type != t_invalid) {
  3790. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3791. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3792. if (e->kind == Ast_TernaryIfExpr) {
  3793. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3794. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3795. }
  3796. }
  3797. }
  3798. return;
  3799. }
  3800. switch (e->kind) {
  3801. case_ast_node(ue, UnaryExpr, e);
  3802. if (old->value.kind != ExactValue_Invalid) {
  3803. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3804. // They don't need to be updated as they will be updated later and
  3805. // checked at the end of general checking stage.
  3806. break;
  3807. }
  3808. update_untyped_expr_type(c, ue->expr, type, final);
  3809. case_end;
  3810. case_ast_node(be, BinaryExpr, e);
  3811. if (old->value.kind != ExactValue_Invalid) {
  3812. // See above note in UnaryExpr case
  3813. break;
  3814. }
  3815. if (token_is_comparison(be->op.kind)) {
  3816. // NOTE(bill): Do nothing as the types are fine
  3817. } else if (token_is_shift(be->op.kind)) {
  3818. update_untyped_expr_type(c, be->left, type, final);
  3819. } else {
  3820. update_untyped_expr_type(c, be->left, type, final);
  3821. update_untyped_expr_type(c, be->right, type, final);
  3822. }
  3823. case_end;
  3824. case_ast_node(te, TernaryIfExpr, e);
  3825. if (old->value.kind != ExactValue_Invalid) {
  3826. // See above note in UnaryExpr case
  3827. break;
  3828. }
  3829. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3830. // having an untyped value
  3831. Operand x = make_operand_from_node(te->x);
  3832. Operand y = make_operand_from_node(te->y);
  3833. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3834. update_untyped_expr_type(c, te->x, type, final);
  3835. }
  3836. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3837. update_untyped_expr_type(c, te->y, type, final);
  3838. }
  3839. case_end;
  3840. case_ast_node(te, TernaryWhenExpr, e);
  3841. if (old->value.kind != ExactValue_Invalid) {
  3842. // See above note in UnaryExpr case
  3843. break;
  3844. }
  3845. update_untyped_expr_type(c, te->x, type, final);
  3846. update_untyped_expr_type(c, te->y, type, final);
  3847. case_end;
  3848. case_ast_node(ore, OrReturnExpr, e);
  3849. if (old->value.kind != ExactValue_Invalid) {
  3850. // See above note in UnaryExpr case
  3851. break;
  3852. }
  3853. update_untyped_expr_type(c, ore->expr, type, final);
  3854. case_end;
  3855. case_ast_node(obe, OrBranchExpr, e);
  3856. if (old->value.kind != ExactValue_Invalid) {
  3857. // See above note in UnaryExpr case
  3858. break;
  3859. }
  3860. update_untyped_expr_type(c, obe->expr, type, final);
  3861. case_end;
  3862. case_ast_node(oee, OrElseExpr, e);
  3863. if (old->value.kind != ExactValue_Invalid) {
  3864. // See above note in UnaryExpr case
  3865. break;
  3866. }
  3867. update_untyped_expr_type(c, oee->x, type, final);
  3868. update_untyped_expr_type(c, oee->y, type, final);
  3869. case_end;
  3870. case_ast_node(pe, ParenExpr, e);
  3871. update_untyped_expr_type(c, pe->expr, type, final);
  3872. case_end;
  3873. }
  3874. if (!final && is_type_untyped(type)) {
  3875. old->type = base_type(type);
  3876. return;
  3877. }
  3878. // We need to remove it and then give it a new one
  3879. check_remove_expr_info(c, e);
  3880. if (old->is_lhs && !is_type_integer(type)) {
  3881. gbString expr_str = expr_to_string(e);
  3882. gbString type_str = type_to_string(type);
  3883. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3884. gb_string_free(type_str);
  3885. gb_string_free(expr_str);
  3886. return;
  3887. }
  3888. add_type_and_value(c, e, old->mode, type, old->value);
  3889. }
  3890. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3891. GB_ASSERT(e != nullptr);
  3892. ExprInfo *found = check_get_expr_info(c, e);
  3893. if (found) {
  3894. found->value = value;
  3895. }
  3896. }
  3897. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type, bool ignore_error_block=false) {
  3898. gbString expr_str = expr_to_string(operand->expr);
  3899. gbString type_str = type_to_string(target_type);
  3900. gbString from_type_str = type_to_string(operand->type);
  3901. char const *extra_text = "";
  3902. if (operand->mode == Addressing_Constant) {
  3903. if (big_int_is_zero(&operand->value.value_integer)) {
  3904. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  3905. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  3906. extra_text = " - Did you want 'nil'?";
  3907. }
  3908. }
  3909. }
  3910. if (!ignore_error_block) {
  3911. begin_error_block();
  3912. }
  3913. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  3914. if (operand->value.kind == ExactValue_String) {
  3915. String key = operand->value.value_string;
  3916. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  3917. Type *et = base_type(target_type);
  3918. check_did_you_mean_type(key, et->Enum.fields, ".");
  3919. }
  3920. }
  3921. gb_string_free(from_type_str);
  3922. gb_string_free(type_str);
  3923. gb_string_free(expr_str);
  3924. operand->mode = Addressing_Invalid;
  3925. if (!ignore_error_block) {
  3926. end_error_block();
  3927. }
  3928. }
  3929. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  3930. Type *t = core_type(type);
  3931. if (is_type_boolean(t)) {
  3932. // v = exact_value_to_boolean(v);
  3933. } else if (is_type_float(t)) {
  3934. v = exact_value_to_float(v);
  3935. } else if (is_type_integer(t)) {
  3936. v = exact_value_to_integer(v);
  3937. } else if (is_type_pointer(t)) {
  3938. v = exact_value_to_integer(v);
  3939. } else if (is_type_complex(t)) {
  3940. v = exact_value_to_complex(v);
  3941. } else if (is_type_quaternion(t)) {
  3942. v = exact_value_to_quaternion(v);
  3943. }
  3944. return v;
  3945. }
  3946. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  3947. // GB_ASSERT_NOT_NULL(target_type);
  3948. if (target_type == nullptr || operand->mode == Addressing_Invalid ||
  3949. operand->mode == Addressing_Type ||
  3950. is_type_typed(operand->type) ||
  3951. target_type == t_invalid) {
  3952. return;
  3953. }
  3954. if (is_type_untyped(target_type)) {
  3955. GB_ASSERT(operand->type->kind == Type_Basic);
  3956. GB_ASSERT(target_type->kind == Type_Basic);
  3957. BasicKind x_kind = operand->type->Basic.kind;
  3958. BasicKind y_kind = target_type->Basic.kind;
  3959. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  3960. if (x_kind < y_kind) {
  3961. operand->type = target_type;
  3962. update_untyped_expr_type(c, operand->expr, target_type, false);
  3963. }
  3964. } else if (x_kind != y_kind) {
  3965. operand->mode = Addressing_Invalid;
  3966. convert_untyped_error(c, operand, target_type);
  3967. return;
  3968. }
  3969. return;
  3970. }
  3971. Type *t = base_type(target_type);
  3972. if (c->in_enum_type) {
  3973. t = core_type(target_type);
  3974. }
  3975. switch (t->kind) {
  3976. case Type_Basic:
  3977. if (operand->mode == Addressing_Constant) {
  3978. check_is_expressible(c, operand, t);
  3979. if (operand->mode == Addressing_Invalid) {
  3980. return;
  3981. }
  3982. update_untyped_expr_value(c, operand->expr, operand->value);
  3983. } else {
  3984. switch (operand->type->Basic.kind) {
  3985. case Basic_UntypedBool:
  3986. if (!is_type_boolean(target_type)) {
  3987. operand->mode = Addressing_Invalid;
  3988. convert_untyped_error(c, operand, target_type);
  3989. return;
  3990. }
  3991. break;
  3992. case Basic_UntypedInteger:
  3993. case Basic_UntypedFloat:
  3994. case Basic_UntypedComplex:
  3995. case Basic_UntypedQuaternion:
  3996. case Basic_UntypedRune:
  3997. if (!is_type_numeric(target_type)) {
  3998. operand->mode = Addressing_Invalid;
  3999. convert_untyped_error(c, operand, target_type);
  4000. return;
  4001. }
  4002. break;
  4003. case Basic_UntypedNil:
  4004. if (is_type_any(target_type)) {
  4005. // target_type = t_untyped_nil;
  4006. } else if (is_type_cstring(target_type)) {
  4007. // target_type = t_untyped_nil;
  4008. } else if (!type_has_nil(target_type)) {
  4009. operand->mode = Addressing_Invalid;
  4010. convert_untyped_error(c, operand, target_type);
  4011. return;
  4012. }
  4013. break;
  4014. }
  4015. }
  4016. break;
  4017. case Type_Array: {
  4018. Type *elem = base_array_type(t);
  4019. if (check_is_assignable_to(c, operand, elem)) {
  4020. operand->mode = Addressing_Value;
  4021. } else {
  4022. if (operand->value.kind == ExactValue_String) {
  4023. String s = operand->value.value_string;
  4024. if (is_type_u8_array(t)) {
  4025. if (s.len == t->Array.count) {
  4026. break;
  4027. }
  4028. } else if (is_type_rune_array(t)) {
  4029. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  4030. if (rune_count == t->Array.count) {
  4031. break;
  4032. }
  4033. }
  4034. }
  4035. operand->mode = Addressing_Invalid;
  4036. convert_untyped_error(c, operand, target_type);
  4037. return;
  4038. }
  4039. break;
  4040. }
  4041. case Type_SimdVector: {
  4042. Type *elem = base_array_type(t);
  4043. if (check_is_assignable_to(c, operand, elem)) {
  4044. operand->mode = Addressing_Value;
  4045. } else {
  4046. operand->mode = Addressing_Invalid;
  4047. convert_untyped_error(c, operand, target_type);
  4048. return;
  4049. }
  4050. break;
  4051. }
  4052. case Type_Matrix: {
  4053. Type *elem = base_array_type(t);
  4054. if (check_is_assignable_to(c, operand, elem)) {
  4055. if (t->Matrix.row_count != t->Matrix.column_count) {
  4056. operand->mode = Addressing_Invalid;
  4057. ERROR_BLOCK();
  4058. convert_untyped_error(c, operand, target_type, true);
  4059. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  4060. return;
  4061. } else {
  4062. operand->mode = Addressing_Value;
  4063. }
  4064. } else {
  4065. operand->mode = Addressing_Invalid;
  4066. convert_untyped_error(c, operand, target_type);
  4067. return;
  4068. }
  4069. break;
  4070. }
  4071. case Type_Union:
  4072. // IMPORTANT NOTE HACK(bill): This is just to allow for comparisons against `0` with the `os.Error` type
  4073. // as a kind of transition period
  4074. if (!build_context.strict_style &&
  4075. operand->mode == Addressing_Constant &&
  4076. target_type->kind == Type_Named &&
  4077. (c->pkg == nullptr || c->pkg->name != "os") &&
  4078. target_type->Named.name == "Error") {
  4079. Entity *e = target_type->Named.type_name;
  4080. if (e->pkg && e->pkg->name == "os") {
  4081. if (is_exact_value_zero(operand->value) &&
  4082. (operand->value.kind == ExactValue_Integer ||
  4083. operand->value.kind == ExactValue_Float)) {
  4084. operand->mode = Addressing_Value;
  4085. // target_type = t_untyped_nil;
  4086. operand->value = empty_exact_value;
  4087. update_untyped_expr_value(c, operand->expr, operand->value);
  4088. break;
  4089. }
  4090. }
  4091. }
  4092. // "fallthrough"
  4093. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  4094. TEMPORARY_ALLOCATOR_GUARD();
  4095. isize count = t->Union.variants.count;
  4096. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  4097. isize valid_count = 0;
  4098. isize first_success_index = -1;
  4099. for_array(i, t->Union.variants) {
  4100. Type *vt = t->Union.variants[i];
  4101. i64 score = 0;
  4102. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  4103. valids[valid_count].index = i;
  4104. valids[valid_count].score = score;
  4105. valid_count += 1;
  4106. if (first_success_index < 0) {
  4107. first_success_index = i;
  4108. }
  4109. }
  4110. }
  4111. if (valid_count > 1) {
  4112. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  4113. i64 best_score = valids[0].score;
  4114. for (isize i = 1; i < valid_count; i++) {
  4115. auto v = valids[i];
  4116. if (best_score > v.score) {
  4117. valid_count = i;
  4118. break;
  4119. }
  4120. best_score = v.score;
  4121. }
  4122. first_success_index = valids[0].index;
  4123. }
  4124. gbString type_str = type_to_string(target_type);
  4125. defer (gb_string_free(type_str));
  4126. if (valid_count == 1) {
  4127. Type *new_type = t->Union.variants[first_success_index];
  4128. target_type = new_type;
  4129. if (is_type_union(new_type)) {
  4130. convert_to_typed(c, operand, new_type);
  4131. break;
  4132. }
  4133. operand->type = new_type;
  4134. operand->mode = Addressing_Value;
  4135. break;
  4136. } else if (valid_count > 1) {
  4137. ERROR_BLOCK();
  4138. GB_ASSERT(first_success_index >= 0);
  4139. operand->mode = Addressing_Invalid;
  4140. convert_untyped_error(c, operand, target_type, true);
  4141. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  4142. i32 j = 0;
  4143. for (i32 i = 0; i < valid_count; i++) {
  4144. ValidIndexAndScore valid = valids[i];
  4145. if (j > 0 && valid_count > 2) error_line(", ");
  4146. if (j == valid_count-1) {
  4147. if (valid_count == 2) error_line(" ");
  4148. error_line("or ");
  4149. }
  4150. gbString str = type_to_string(t->Union.variants[valid.index]);
  4151. error_line("'%s'", str);
  4152. gb_string_free(str);
  4153. j++;
  4154. }
  4155. error_line("\n\n");
  4156. return;
  4157. } else if (is_type_untyped_uninit(operand->type)) {
  4158. target_type = t_untyped_uninit;
  4159. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  4160. ERROR_BLOCK();
  4161. operand->mode = Addressing_Invalid;
  4162. convert_untyped_error(c, operand, target_type, true);
  4163. if (count > 0) {
  4164. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  4165. error_line("\t");
  4166. for (i32 i = 0; i < count; i++) {
  4167. Type *v = t->Union.variants[i];
  4168. if (i > 0 && count > 2) error_line(", ");
  4169. if (i == count-1) {
  4170. if (count == 2) error_line(" ");
  4171. if (count > 1) {
  4172. error_line("or ");
  4173. }
  4174. }
  4175. gbString str = type_to_string(v);
  4176. error_line("'%s'", str);
  4177. gb_string_free(str);
  4178. }
  4179. error_line("\n\n");
  4180. }
  4181. return;
  4182. }
  4183. }
  4184. /* fallthrough */
  4185. default:
  4186. if (is_type_untyped_uninit(operand->type)) {
  4187. target_type = t_untyped_uninit;
  4188. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  4189. target_type = t_untyped_nil;
  4190. } else {
  4191. operand->mode = Addressing_Invalid;
  4192. convert_untyped_error(c, operand, target_type);
  4193. return;
  4194. }
  4195. break;
  4196. }
  4197. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  4198. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  4199. } else {
  4200. target_type = default_type(operand->type);
  4201. }
  4202. }
  4203. update_untyped_expr_type(c, operand->expr, target_type, true);
  4204. operand->type = target_type;
  4205. }
  4206. 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) {
  4207. Operand operand = {Addressing_Invalid};
  4208. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  4209. if (operand.mode == Addressing_Invalid) {
  4210. if (value) *value = 0;
  4211. // NOTE(bill): return true here to propagate the errors better
  4212. return true;
  4213. }
  4214. Type *index_type = t_int;
  4215. if (type_hint != nullptr) {
  4216. index_type = type_hint;
  4217. }
  4218. convert_to_typed(c, &operand, index_type);
  4219. if (operand.mode == Addressing_Invalid) {
  4220. if (value) *value = 0;
  4221. return false;
  4222. }
  4223. if (type_hint != nullptr) {
  4224. if (!check_is_assignable_to(c, &operand, type_hint)) {
  4225. gbString expr_str = expr_to_string(operand.expr);
  4226. gbString index_type_str = type_to_string(type_hint);
  4227. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  4228. gb_string_free(index_type_str);
  4229. gb_string_free(expr_str);
  4230. if (value) *value = 0;
  4231. return false;
  4232. }
  4233. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  4234. gbString expr_str = expr_to_string(operand.expr);
  4235. gbString type_str = type_to_string(operand.type);
  4236. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  4237. gb_string_free(type_str);
  4238. gb_string_free(expr_str);
  4239. if (value) *value = 0;
  4240. return false;
  4241. }
  4242. if (operand.mode == Addressing_Constant &&
  4243. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  4244. BigInt i = exact_value_to_integer(operand.value).value_integer;
  4245. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  4246. TEMPORARY_ALLOCATOR_GUARD();
  4247. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4248. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4249. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  4250. if (value) *value = 0;
  4251. return false;
  4252. }
  4253. if (max_count >= 0) {
  4254. if (is_type_enum(index_type)) {
  4255. Type *bt = base_type(index_type);
  4256. GB_ASSERT(bt->kind == Type_Enum);
  4257. ExactValue const &lo = *bt->Enum.min_value;
  4258. ExactValue const &hi = *bt->Enum.max_value;
  4259. String lo_str = {};
  4260. String hi_str = {};
  4261. if (bt->Enum.fields.count > 0) {
  4262. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  4263. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  4264. lo_str = bt->Enum.fields[lo_idx]->token.string;
  4265. hi_str = bt->Enum.fields[hi_idx]->token.string;
  4266. }
  4267. bool out_of_bounds = false;
  4268. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  4269. out_of_bounds = true;
  4270. }
  4271. if (out_of_bounds) {
  4272. gbString expr_str = expr_to_string(operand.expr);
  4273. if (lo_str.len > 0) {
  4274. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  4275. } else {
  4276. gbString index_type_str = type_to_string(index_type);
  4277. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  4278. gb_string_free(index_type_str);
  4279. }
  4280. gb_string_free(expr_str);
  4281. return false;
  4282. }
  4283. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  4284. return true;
  4285. } else { // NOTE(bill): Do array bound checking
  4286. i64 v = -1;
  4287. if (i.used <= 1) {
  4288. v = big_int_to_i64(&i);
  4289. }
  4290. if (value) *value = v;
  4291. bool out_of_bounds = false;
  4292. if (v < 0) {
  4293. out_of_bounds = true;
  4294. } else if (open_range) {
  4295. out_of_bounds = v > max_count;
  4296. } else {
  4297. out_of_bounds = v >= max_count;
  4298. }
  4299. if (out_of_bounds) {
  4300. TEMPORARY_ALLOCATOR_GUARD();
  4301. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4302. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4303. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  4304. return false;
  4305. }
  4306. return true;
  4307. }
  4308. } else {
  4309. if (value) *value = exact_value_to_i64(operand.value);
  4310. return true;
  4311. }
  4312. }
  4313. // NOTE(bill): It's alright :D
  4314. if (value) *value = -1;
  4315. return true;
  4316. }
  4317. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  4318. if (value.kind == ExactValue_String) {
  4319. GB_ASSERT(0 <= index && index < value.value_string.len);
  4320. u8 val = value.value_string[index];
  4321. if (success_) *success_ = true;
  4322. if (finish_) *finish_ = true;
  4323. return exact_value_u64(val);
  4324. }
  4325. if (value.kind != ExactValue_Compound) {
  4326. if (success_) *success_ = true;
  4327. if (finish_) *finish_ = true;
  4328. return value;
  4329. }
  4330. Ast *node = value.value_compound;
  4331. switch (node->kind) {
  4332. case_ast_node(cl, CompoundLit, node);
  4333. if (cl->elems.count == 0) {
  4334. if (success_) *success_ = true;
  4335. if (finish_) *finish_ = true;
  4336. return empty_exact_value;
  4337. }
  4338. if (cl->elems[0]->kind == Ast_FieldValue) {
  4339. if (is_type_struct(node->tav.type)) {
  4340. bool found = false;
  4341. for (Ast *elem : cl->elems) {
  4342. if (elem->kind != Ast_FieldValue) {
  4343. continue;
  4344. }
  4345. ast_node(fv, FieldValue, elem);
  4346. String name = fv->field->Ident.token.string;
  4347. Selection sub_sel = lookup_field(node->tav.type, name, false);
  4348. defer (array_free(&sub_sel.index));
  4349. if (sub_sel.index.count > 0 &&
  4350. sub_sel.index[0] == index) {
  4351. value = fv->value->tav.value;
  4352. found = true;
  4353. break;
  4354. }
  4355. }
  4356. if (!found) {
  4357. // Use the zero value if it is not found
  4358. value = {};
  4359. }
  4360. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4361. for (Ast *elem : cl->elems) {
  4362. if (elem->kind != Ast_FieldValue) {
  4363. continue;
  4364. }
  4365. ast_node(fv, FieldValue, elem);
  4366. if (is_ast_range(fv->field)) {
  4367. ast_node(ie, BinaryExpr, fv->field);
  4368. TypeAndValue lo_tav = ie->left->tav;
  4369. TypeAndValue hi_tav = ie->right->tav;
  4370. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4371. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4372. TokenKind op = ie->op.kind;
  4373. i64 lo = exact_value_to_i64(lo_tav.value);
  4374. i64 hi = exact_value_to_i64(hi_tav.value);
  4375. i64 corrected_index = index;
  4376. if (is_type_enumerated_array(node->tav.type)) {
  4377. Type *bt = base_type(node->tav.type);
  4378. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4379. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4380. }
  4381. if (op != Token_RangeHalf) {
  4382. if (lo <= corrected_index && corrected_index <= hi) {
  4383. TypeAndValue tav = fv->value->tav;
  4384. if (success_) *success_ = true;
  4385. if (finish_) *finish_ = false;
  4386. return tav.value;
  4387. }
  4388. } else {
  4389. if (lo <= corrected_index && corrected_index < hi) {
  4390. TypeAndValue tav = fv->value->tav;
  4391. if (success_) *success_ = true;
  4392. if (finish_) *finish_ = false;
  4393. return tav.value;
  4394. }
  4395. }
  4396. } else {
  4397. TypeAndValue index_tav = fv->field->tav;
  4398. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4399. ExactValue index_value = index_tav.value;
  4400. if (is_type_enumerated_array(node->tav.type)) {
  4401. Type *bt = base_type(node->tav.type);
  4402. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4403. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4404. }
  4405. i64 field_index = exact_value_to_i64(index_value);
  4406. if (index == field_index) {
  4407. TypeAndValue tav = fv->value->tav;
  4408. if (success_) *success_ = true;
  4409. if (finish_) *finish_ = false;
  4410. return tav.value;
  4411. }
  4412. }
  4413. }
  4414. }
  4415. } else {
  4416. i32 count = (i32)cl->elems.count;
  4417. if (count < index) {
  4418. if (success_) *success_ = false;
  4419. if (finish_) *finish_ = true;
  4420. return empty_exact_value;
  4421. }
  4422. if (cl->elems.count <= index) {
  4423. if (success_) *success_ = false;
  4424. if (finish_) *finish_ = false;
  4425. return value;
  4426. }
  4427. TypeAndValue tav = cl->elems[index]->tav;
  4428. if (tav.mode == Addressing_Constant) {
  4429. if (success_) *success_ = true;
  4430. if (finish_) *finish_ = false;
  4431. return tav.value;
  4432. } else if (is_type_proc(tav.type)) {
  4433. if (success_) *success_ = true;
  4434. if (finish_) *finish_ = false;
  4435. return tav.value;
  4436. } else {
  4437. GB_ASSERT_MSG(is_type_untyped_nil(tav.type), "%s", type_to_string(tav.type));
  4438. if (success_) *success_ = true;
  4439. if (finish_) *finish_ = false;
  4440. return tav.value;
  4441. }
  4442. }
  4443. case_end;
  4444. default:
  4445. if (success_) *success_ = true;
  4446. if (finish_) *finish_ = true;
  4447. return empty_exact_value;
  4448. }
  4449. if (finish_) *finish_ = false;
  4450. return value;
  4451. }
  4452. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4453. if (operand->mode != Addressing_Constant) {
  4454. if (success_) *success_ = false;
  4455. return empty_exact_value;
  4456. }
  4457. if (sel.indirect) {
  4458. if (success_) *success_ = false;
  4459. return empty_exact_value;
  4460. }
  4461. if (sel.index.count == 0) {
  4462. if (success_) *success_ = false;
  4463. return empty_exact_value;
  4464. }
  4465. ExactValue value = operand->value;
  4466. if (value.kind == ExactValue_Compound) {
  4467. while (sel.index.count > 0) {
  4468. i32 index = sel.index[0];
  4469. sel = sub_selection(sel, 1);
  4470. bool finish = false;
  4471. value = get_constant_field_single(c, value, index, success_, &finish);
  4472. if (finish) {
  4473. return value;
  4474. }
  4475. }
  4476. if (success_) *success_ = true;
  4477. return value;
  4478. } else if (value.kind == ExactValue_Quaternion) {
  4479. // @QuaternionLayout
  4480. Quaternion256 q = *value.value_quaternion;
  4481. GB_ASSERT(sel.index.count == 1);
  4482. switch (sel.index[0]) {
  4483. case 3: // w
  4484. if (success_) *success_ = true;
  4485. return exact_value_float(q.real);
  4486. case 0: // x
  4487. if (success_) *success_ = true;
  4488. return exact_value_float(q.imag);
  4489. case 1: // y
  4490. if (success_) *success_ = true;
  4491. return exact_value_float(q.jmag);
  4492. case 2: // z
  4493. if (success_) *success_ = true;
  4494. return exact_value_float(q.kmag);
  4495. }
  4496. if (success_) *success_ = false;
  4497. return empty_exact_value;
  4498. } else if (value.kind == ExactValue_Complex) {
  4499. // @QuaternionLayout
  4500. Complex128 c = *value.value_complex;
  4501. GB_ASSERT(sel.index.count == 1);
  4502. switch (sel.index[0]) {
  4503. case 0: // real
  4504. if (success_) *success_ = true;
  4505. return exact_value_float(c.real);
  4506. case 1: // imag
  4507. if (success_) *success_ = true;
  4508. return exact_value_float(c.imag);
  4509. }
  4510. if (success_) *success_ = false;
  4511. return empty_exact_value;
  4512. }
  4513. if (success_) *success_ = true;
  4514. return empty_exact_value;
  4515. }
  4516. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4517. Type *array_type = base_type(type_deref(original_type));
  4518. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4519. if (array_type->kind == Type_SimdVector) {
  4520. Type *elem_type = array_type->SimdVector.elem;
  4521. return alloc_type_simd_vector(new_count, elem_type);
  4522. }
  4523. Type *elem_type = array_type->Array.elem;
  4524. Type *swizzle_array_type = nullptr;
  4525. Type *bth = base_type(type_deref(type_hint));
  4526. if (bth != nullptr && bth->kind == Type_Array &&
  4527. bth->Array.count == new_count &&
  4528. are_types_identical(bth->Array.elem, elem_type)) {
  4529. swizzle_array_type = type_hint;
  4530. } else {
  4531. i64 max_count = array_type->Array.count;
  4532. if (new_count == max_count) {
  4533. swizzle_array_type = original_type;
  4534. } else {
  4535. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4536. }
  4537. }
  4538. return swizzle_array_type;
  4539. }
  4540. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4541. bool is_declared = entity != nullptr;
  4542. if (is_declared) {
  4543. if (entity->kind == Entity_Builtin) {
  4544. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4545. // This means that we should just ignore the found result through it
  4546. *allow_builtin = entity->scope == import_scope ||
  4547. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4548. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4549. is_declared = false;
  4550. }
  4551. }
  4552. return is_declared;
  4553. }
  4554. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4555. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4556. if (node == nullptr) {
  4557. return nullptr;
  4558. }
  4559. /*if (node->kind == Ast_TernaryWhenExpr) {
  4560. ast_node(we, TernaryWhenExpr, node);
  4561. if (we->cond == nullptr) {
  4562. return nullptr;
  4563. }
  4564. if (we->cond->tav.mode != Addressing_Constant) {
  4565. return nullptr;
  4566. }
  4567. if (we->cond->tav.value.kind != ExactValue_Bool) {
  4568. return nullptr;
  4569. }
  4570. if (we->cond->tav.value.value_bool) {
  4571. return check_entity_from_ident_or_selector(c, we->x, ident_only);
  4572. } else {
  4573. Entity *e = check_entity_from_ident_or_selector(c, we->y, ident_only);
  4574. return e;
  4575. }
  4576. } else */if (node->kind == Ast_Ident) {
  4577. String name = node->Ident.token.string;
  4578. return scope_lookup(c->scope, name);
  4579. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4580. ast_node(se, SelectorExpr, node);
  4581. if (se->token.kind == Token_ArrowRight) {
  4582. return nullptr;
  4583. }
  4584. Ast *op_expr = se->expr;
  4585. Ast *selector = unparen_expr(se->selector);
  4586. if (selector == nullptr) {
  4587. return nullptr;
  4588. }
  4589. if (selector->kind != Ast_Ident) {
  4590. return nullptr;
  4591. }
  4592. Entity *entity = nullptr;
  4593. Entity *expr_entity = nullptr;
  4594. bool check_op_expr = true;
  4595. if (op_expr->kind == Ast_Ident) {
  4596. String op_name = op_expr->Ident.token.string;
  4597. Entity *e = scope_lookup(c->scope, op_name);
  4598. if (e == nullptr) {
  4599. return nullptr;
  4600. }
  4601. add_entity_use(c, op_expr, e);
  4602. expr_entity = e;
  4603. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4604. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4605. // It pretty much needs to be in this order and this way
  4606. // If you can clean this up, please do but be really careful
  4607. String import_name = op_name;
  4608. Scope *import_scope = e->ImportName.scope;
  4609. String entity_name = selector->Ident.token.string;
  4610. check_op_expr = false;
  4611. entity = scope_lookup_current(import_scope, entity_name);
  4612. bool allow_builtin = false;
  4613. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4614. return nullptr;
  4615. }
  4616. check_entity_decl(c, entity, nullptr, nullptr);
  4617. if (entity->kind == Entity_ProcGroup) {
  4618. return entity;
  4619. }
  4620. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4621. }
  4622. }
  4623. Operand operand = {};
  4624. if (check_op_expr) {
  4625. check_expr_base(c, &operand, op_expr, nullptr);
  4626. if (operand.mode == Addressing_Invalid) {
  4627. return nullptr;
  4628. }
  4629. }
  4630. if (entity == nullptr && selector->kind == Ast_Ident) {
  4631. String field_name = selector->Ident.token.string;
  4632. if (is_type_dynamic_array(type_deref(operand.type))) {
  4633. init_mem_allocator(c->checker);
  4634. }
  4635. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4636. entity = sel.entity;
  4637. }
  4638. if (entity != nullptr) {
  4639. return entity;
  4640. }
  4641. }
  4642. return nullptr;
  4643. }
  4644. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4645. ast_node(se, SelectorExpr, node);
  4646. bool check_op_expr = true;
  4647. Entity *expr_entity = nullptr;
  4648. Entity *entity = nullptr;
  4649. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4650. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4651. ERROR_BLOCK();
  4652. error(node, "Illegal use of -> selector shorthand outside of a call");
  4653. gbString x = expr_to_string(se->expr);
  4654. gbString y = expr_to_string(se->selector);
  4655. error_line("\tSuggestion: Did you mean '%s.%s'?\n", x, y);
  4656. gb_string_free(y);
  4657. gb_string_free(x);
  4658. // TODO(bill): Should this terminate here or propagate onwards?
  4659. // operand->mode = Addressing_Invalid;
  4660. // operand->expr = node;
  4661. // return nullptr;
  4662. }
  4663. operand->expr = node;
  4664. Ast *op_expr = se->expr;
  4665. Ast *selector = unparen_expr(se->selector);
  4666. if (selector == nullptr) {
  4667. operand->mode = Addressing_Invalid;
  4668. operand->expr = node;
  4669. return nullptr;
  4670. }
  4671. if (selector->kind != Ast_Ident) {
  4672. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4673. operand->mode = Addressing_Invalid;
  4674. operand->expr = node;
  4675. return nullptr;
  4676. }
  4677. if (op_expr->kind == Ast_Ident) {
  4678. String op_name = op_expr->Ident.token.string;
  4679. Entity *e = scope_lookup(c->scope, op_name);
  4680. add_entity_use(c, op_expr, e);
  4681. expr_entity = e;
  4682. if (e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup) && selector->kind == Ast_Ident) {
  4683. gbString sel_str = expr_to_string(selector);
  4684. error(node, "'%s' is not declared by by '%.*s'", sel_str, LIT(e->token.string));
  4685. gb_string_free(sel_str);
  4686. operand->mode = Addressing_Invalid;
  4687. operand->expr = node;
  4688. return nullptr;
  4689. } else if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4690. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4691. // It pretty much needs to be in this order and this way
  4692. // If you can clean this up, please do but be really careful
  4693. String import_name = op_name;
  4694. Scope *import_scope = e->ImportName.scope;
  4695. String entity_name = selector->Ident.token.string;
  4696. if (import_scope == nullptr) {
  4697. ERROR_BLOCK();
  4698. error(node, "'%.*s' is not imported in this file, '%.*s' is unavailable", LIT(import_name), LIT(entity_name));
  4699. operand->mode = Addressing_Invalid;
  4700. operand->expr = node;
  4701. return nullptr;
  4702. }
  4703. check_op_expr = false;
  4704. entity = scope_lookup_current(import_scope, entity_name);
  4705. bool allow_builtin = false;
  4706. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4707. ERROR_BLOCK();
  4708. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4709. operand->mode = Addressing_Invalid;
  4710. operand->expr = node;
  4711. check_did_you_mean_scope(entity_name, import_scope);
  4712. return nullptr;
  4713. }
  4714. if (!is_entity_exported(entity, allow_builtin)) {
  4715. gbString sel_str = expr_to_string(selector);
  4716. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4717. gb_string_free(sel_str);
  4718. // NOTE(bill): make the state valid still, even if it's "invalid"
  4719. // operand->mode = Addressing_Invalid;
  4720. // operand->expr = node;
  4721. // return nullptr;
  4722. }
  4723. check_entity_decl(c, entity, nullptr, nullptr);
  4724. if (entity->kind == Entity_ProcGroup) {
  4725. operand->mode = Addressing_ProcGroup;
  4726. operand->proc_group = entity;
  4727. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4728. return entity;
  4729. }
  4730. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4731. }
  4732. }
  4733. if (check_op_expr) {
  4734. check_expr_base(c, operand, op_expr, nullptr);
  4735. if (operand->mode == Addressing_Invalid) {
  4736. operand->mode = Addressing_Invalid;
  4737. operand->expr = node;
  4738. return nullptr;
  4739. }
  4740. }
  4741. if (operand->type && is_type_soa_struct(type_deref(operand->type))) {
  4742. complete_soa_type(c->checker, type_deref(operand->type), false);
  4743. }
  4744. if (entity == nullptr && selector->kind == Ast_Ident) {
  4745. String field_name = selector->Ident.token.string;
  4746. Type *t = type_deref(operand->type);
  4747. if (t == nullptr) {
  4748. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4749. } else {
  4750. if (is_type_dynamic_array(t)) {
  4751. init_mem_allocator(c->checker);
  4752. }
  4753. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4754. entity = sel.entity;
  4755. // NOTE(bill): Add type info needed for fields like 'names'
  4756. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4757. add_type_info_type(c, operand->type);
  4758. }
  4759. if (is_type_enum(operand->type)) {
  4760. add_type_info_type(c, operand->type);
  4761. }
  4762. }
  4763. }
  4764. if (operand->type && is_type_simd_vector(type_deref(operand->type))) {
  4765. String field_name = selector->Ident.token.string;
  4766. if (field_name.len == 1) {
  4767. error(op_expr, "Extracting an element from a #simd array using .%.*s syntax is disallowed, prefer `simd.extract`", LIT(field_name));
  4768. } else {
  4769. error(op_expr, "Extracting elements from a #simd array using .%.*s syntax is disallowed, prefer `swizzle`", LIT(field_name));
  4770. }
  4771. return nullptr;
  4772. }
  4773. if (entity == nullptr && selector->kind == Ast_Ident && operand->type != nullptr &&
  4774. (is_type_array(type_deref(operand->type)))) {
  4775. String field_name = selector->Ident.token.string;
  4776. if (1 < field_name.len && field_name.len <= 4) {
  4777. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4778. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4779. bool found_xyzw = false;
  4780. bool found_rgba = false;
  4781. for (isize i = 0; i < field_name.len; i++) {
  4782. bool valid = false;
  4783. for (isize j = 0; j < 4; j++) {
  4784. if (field_name.text[i] == swizzles_xyzw[j]) {
  4785. found_xyzw = true;
  4786. valid = true;
  4787. break;
  4788. }
  4789. if (field_name.text[i] == swizzles_rgba[j]) {
  4790. found_rgba = true;
  4791. valid = true;
  4792. break;
  4793. }
  4794. }
  4795. if (!valid) {
  4796. goto end_of_array_selector_swizzle;
  4797. }
  4798. }
  4799. u8 *swizzles = nullptr;
  4800. u8 index_count = cast(u8)field_name.len;
  4801. if (found_xyzw && found_rgba) {
  4802. gbString op_str = expr_to_string(op_expr);
  4803. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4804. gb_string_free(op_str);
  4805. operand->mode = Addressing_Invalid;
  4806. operand->expr = node;
  4807. return nullptr;
  4808. }
  4809. u8 indices = 0;
  4810. if (found_xyzw) {
  4811. swizzles = swizzles_xyzw;
  4812. } else if (found_rgba) {
  4813. swizzles = swizzles_rgba;
  4814. }
  4815. for (isize i = 0; i < field_name.len; i++) {
  4816. for (isize j = 0; j < 4; j++) {
  4817. if (field_name.text[i] == swizzles[j]) {
  4818. indices |= cast(u8)(j)<<(i*2);
  4819. break;
  4820. }
  4821. }
  4822. }
  4823. Type *original_type = operand->type;
  4824. Type *array_type = base_type(type_deref(original_type));
  4825. GB_ASSERT(array_type->kind == Type_Array);
  4826. i64 array_count = get_array_type_count(array_type);
  4827. for (u8 i = 0; i < index_count; i++) {
  4828. u8 idx = indices>>(i*2) & 3;
  4829. if (idx >= array_count) {
  4830. char c = 0;
  4831. if (found_xyzw) {
  4832. c = swizzles_xyzw[idx];
  4833. } else if (found_rgba) {
  4834. c = swizzles_rgba[idx];
  4835. } else {
  4836. GB_PANIC("unknown swizzle kind");
  4837. }
  4838. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4839. break;
  4840. }
  4841. }
  4842. se->swizzle_count = index_count;
  4843. se->swizzle_indices = indices;
  4844. AddressingMode prev_mode = operand->mode;
  4845. operand->mode = Addressing_SwizzleValue;
  4846. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4847. operand->expr = node;
  4848. switch (prev_mode) {
  4849. case Addressing_Variable:
  4850. case Addressing_SoaVariable:
  4851. case Addressing_SwizzleVariable:
  4852. operand->mode = Addressing_SwizzleVariable;
  4853. break;
  4854. case Addressing_Value:
  4855. if (is_type_pointer(original_type)) {
  4856. operand->mode = Addressing_SwizzleVariable;
  4857. }
  4858. break;
  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_AllowUndef = 1<<1,
  5163. };
  5164. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags,
  5165. isize variadic_index = -1) {
  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 allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  5191. bool is_variadic = variadic_index > -1;
  5192. if (!is_variadic) {
  5193. variadic_index = lhs_count;
  5194. }
  5195. bool optional_ok = false;
  5196. isize tuple_index = 0;
  5197. for (Ast *rhs : rhs_arguments) {
  5198. if (rhs->kind == Ast_FieldValue) {
  5199. error(rhs, "Invalid use of 'field = value'");
  5200. rhs = rhs->FieldValue.value;
  5201. }
  5202. CheckerContext c_ = *ctx;
  5203. CheckerContext *c = &c_;
  5204. Operand o = {};
  5205. Type *type_hint = nullptr;
  5206. if (lhs != nullptr) {
  5207. if (tuple_index < variadic_index) {
  5208. // NOTE(bill): override DeclInfo for dependency
  5209. Entity *e = lhs[tuple_index];
  5210. if (e != nullptr) {
  5211. type_hint = e->type;
  5212. }
  5213. } else if (is_variadic) {
  5214. Entity *e = lhs[variadic_index];
  5215. if (e != nullptr) {
  5216. GB_ASSERT(e->flags & EntityFlag_Ellipsis);
  5217. GB_ASSERT(is_type_slice(e->type));
  5218. type_hint = e->type->Slice.elem;
  5219. }
  5220. }
  5221. }
  5222. Ast *rhs_expr = unparen_expr(rhs);
  5223. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  5224. // NOTE(bill): Just handle this very specific logic here
  5225. o.type = t_untyped_uninit;
  5226. o.mode = Addressing_Value;
  5227. o.expr = rhs;
  5228. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  5229. } else {
  5230. check_expr_base(c, &o, rhs, type_hint);
  5231. }
  5232. if (o.mode == Addressing_NoValue) {
  5233. error_operand_no_value(&o);
  5234. o.mode = Addressing_Invalid;
  5235. }
  5236. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5237. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  5238. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5239. Ast *expr = unparen_expr(o.expr);
  5240. Operand val0 = o;
  5241. Operand val1 = o;
  5242. val0.mode = Addressing_Value;
  5243. val1.mode = Addressing_Value;
  5244. val1.type = t_untyped_bool;
  5245. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5246. if (expr->kind == Ast_TypeAssertion &&
  5247. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5248. // NOTE(bill): Used only for optimizations in the backend
  5249. if (is_blank_ident(lhs[0]->token)) {
  5250. expr->TypeAssertion.ignores[0] = true;
  5251. }
  5252. if (is_blank_ident(lhs[1]->token)) {
  5253. expr->TypeAssertion.ignores[1] = true;
  5254. }
  5255. }
  5256. array_add(operands, val0);
  5257. array_add(operands, val1);
  5258. optional_ok = true;
  5259. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  5260. } else {
  5261. array_add(operands, o);
  5262. tuple_index += 1;
  5263. }
  5264. } else {
  5265. TypeTuple *tuple = &o.type->Tuple;
  5266. for (Entity *e : tuple->variables) {
  5267. o.type = e->type;
  5268. array_add(operands, o);
  5269. }
  5270. isize count = tuple->variables.count;
  5271. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  5272. }
  5273. }
  5274. return optional_ok;
  5275. }
  5276. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  5277. GB_ASSERT(pt != nullptr);
  5278. GB_ASSERT(pt->kind == Type_Proc);
  5279. isize param_count = 0;
  5280. isize param_count_excluding_defaults = 0;
  5281. bool variadic = pt->Proc.variadic;
  5282. TypeTuple *param_tuple = nullptr;
  5283. if (pt->Proc.params != nullptr) {
  5284. param_tuple = &pt->Proc.params->Tuple;
  5285. param_count = param_tuple->variables.count;
  5286. if (variadic) {
  5287. for (isize i = param_count-1; i >= 0; i--) {
  5288. Entity *e = param_tuple->variables[i];
  5289. if (e->kind == Entity_TypeName) {
  5290. break;
  5291. }
  5292. if (e->kind == Entity_Variable) {
  5293. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5294. param_count--;
  5295. continue;
  5296. }
  5297. }
  5298. break;
  5299. }
  5300. param_count--;
  5301. }
  5302. }
  5303. param_count_excluding_defaults = param_count;
  5304. if (param_tuple != nullptr) {
  5305. for (isize i = param_count-1; i >= 0; i--) {
  5306. Entity *e = param_tuple->variables[i];
  5307. if (e->kind == Entity_TypeName) {
  5308. break;
  5309. }
  5310. if (e->kind == Entity_Variable) {
  5311. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5312. param_count_excluding_defaults--;
  5313. continue;
  5314. }
  5315. }
  5316. break;
  5317. }
  5318. }
  5319. if (param_count_) *param_count_ = param_count;
  5320. return param_count_excluding_defaults;
  5321. }
  5322. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  5323. isize param_count = pt->param_count;
  5324. for (isize i = 0; i < param_count; i++) {
  5325. Entity *e = pt->params->Tuple.variables[i];
  5326. String name = e->token.string;
  5327. if (is_blank_ident(name)) {
  5328. continue;
  5329. }
  5330. if (name == parameter_name) {
  5331. return i;
  5332. }
  5333. }
  5334. return -1;
  5335. }
  5336. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  5337. type = base_type(type);
  5338. GB_ASSERT(type->kind == Type_Proc);
  5339. return lookup_procedure_parameter(&type->Proc, parameter_name);
  5340. }
  5341. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  5342. Entity *entity, Type *proc_type,
  5343. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  5344. CallArgumentErrorMode show_error_mode,
  5345. CallArgumentData *data) {
  5346. TEMPORARY_ALLOCATOR_GUARD();
  5347. CallArgumentError err = CallArgumentError_None;
  5348. ast_node(ce, CallExpr, call);
  5349. GB_ASSERT(is_type_proc(proc_type));
  5350. proc_type = base_type(proc_type);
  5351. TypeProc *pt = &proc_type->Proc;
  5352. isize param_count = 0;
  5353. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  5354. bool variadic = pt->variadic;
  5355. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5356. i64 score = 0;
  5357. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  5358. Type *final_proc_type = proc_type;
  5359. Entity *gen_entity = nullptr;
  5360. if (vari_expand && !variadic) {
  5361. if (show_error) {
  5362. error(ce->ellipsis,
  5363. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  5364. LIT(ce->proc->Ident.token.string));
  5365. }
  5366. err = CallArgumentError_NonVariadicExpand;
  5367. } else if (vari_expand && pt->c_vararg) {
  5368. if (show_error) {
  5369. error(ce->ellipsis,
  5370. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  5371. LIT(ce->proc->Ident.token.string));
  5372. }
  5373. err = CallArgumentError_NonVariadicExpand;
  5374. }
  5375. GB_ASSERT(ce->split_args);
  5376. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  5377. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  5378. defer ({
  5379. for (Operand const &o : ordered_operands) {
  5380. if (o.expr != nullptr) {
  5381. call->viral_state_flags |= o.expr->viral_state_flags;
  5382. }
  5383. }
  5384. });
  5385. isize positional_operand_count = positional_operands.count;
  5386. if (variadic) {
  5387. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5388. } else if (positional_operand_count > pt->param_count) {
  5389. err = CallArgumentError_TooManyArguments;
  5390. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5391. if (show_error) {
  5392. gbString proc_str = expr_to_string(ce->proc);
  5393. defer (gb_string_free(proc_str));
  5394. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5395. }
  5396. return err;
  5397. }
  5398. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5399. for (isize i = 0; i < positional_operand_count; i++) {
  5400. ordered_operands[i] = positional_operands[i];
  5401. visited[i] = true;
  5402. }
  5403. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5404. bool named_variadic_param = false;
  5405. if (named_operands.count != 0) {
  5406. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5407. for_array(i, ce->split_args->named) {
  5408. Ast *arg = ce->split_args->named[i];
  5409. Operand operand = named_operands[i];
  5410. ast_node(fv, FieldValue, arg);
  5411. if (fv->field->kind != Ast_Ident) {
  5412. if (show_error) {
  5413. gbString expr_str = expr_to_string(fv->field);
  5414. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5415. gb_string_free(expr_str);
  5416. }
  5417. err = CallArgumentError_InvalidFieldValue;
  5418. continue;
  5419. }
  5420. String name = fv->field->Ident.token.string;
  5421. isize param_index = lookup_procedure_parameter(pt, name);
  5422. if (param_index < 0) {
  5423. if (show_error) {
  5424. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5425. }
  5426. err = CallArgumentError_ParameterNotFound;
  5427. continue;
  5428. }
  5429. if (pt->variadic && param_index == pt->variadic_index) {
  5430. named_variadic_param = true;
  5431. }
  5432. if (visited[param_index]) {
  5433. if (show_error) {
  5434. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5435. }
  5436. err = CallArgumentError_DuplicateParameter;
  5437. continue;
  5438. }
  5439. visited[param_index] = true;
  5440. ordered_operands[param_index] = operand;
  5441. }
  5442. }
  5443. isize dummy_argument_count = 0;
  5444. bool actually_variadic = false;
  5445. if (variadic) {
  5446. if (visited[pt->variadic_index] &&
  5447. positional_operand_count < positional_operands.count) {
  5448. if (show_error) {
  5449. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5450. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5451. }
  5452. err = CallArgumentError_DuplicateParameter;
  5453. } else if (!visited[pt->variadic_index]) {
  5454. visited[pt->variadic_index] = true;
  5455. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5456. if (vari_expand) {
  5457. if (variadic_operands.count == 0) {
  5458. error(call, "'..' in the wrong position");
  5459. } else {
  5460. GB_ASSERT(variadic_operands.count != 0);
  5461. *variadic_operand = variadic_operands[0];
  5462. variadic_operand->type = default_type(variadic_operand->type);
  5463. actually_variadic = true;
  5464. }
  5465. } else {
  5466. AstFile *f = call->file();
  5467. // HACK(bill): this is an awful hack
  5468. Operand o = {};
  5469. o.mode = Addressing_Value;
  5470. o.expr = ast_ident(f, make_token_ident("nil"));
  5471. o.expr->Ident.token.pos = ast_token(call).pos;
  5472. if (variadic_operands.count != 0) {
  5473. actually_variadic = true;
  5474. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5475. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5476. o.type = vt->type;
  5477. } else {
  5478. dummy_argument_count += 1;
  5479. o.type = t_untyped_nil;
  5480. }
  5481. *variadic_operand = o;
  5482. }
  5483. }
  5484. }
  5485. for (Operand const &o : ordered_operands) {
  5486. if (o.mode != Addressing_Invalid) {
  5487. check_no_copy_assignment(o, str_lit("procedure call expression"));
  5488. }
  5489. }
  5490. for (isize i = 0; i < pt->param_count; i++) {
  5491. if (!visited[i]) {
  5492. Entity *e = pt->params->Tuple.variables[i];
  5493. if (e->kind == Entity_Variable) {
  5494. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5495. ordered_operands[i].mode = Addressing_Value;
  5496. ordered_operands[i].type = e->type;
  5497. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5498. dummy_argument_count += 1;
  5499. score += assign_score_function(1);
  5500. continue;
  5501. }
  5502. }
  5503. if (show_error) {
  5504. if (e->kind == Entity_TypeName) {
  5505. error(call, "Type parameter '%.*s' is missing in procedure call",
  5506. LIT(e->token.string));
  5507. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5508. // Ignore
  5509. } else {
  5510. gbString str = type_to_string(e->type);
  5511. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5512. LIT(e->token.string), str);
  5513. gb_string_free(str);
  5514. }
  5515. }
  5516. err = CallArgumentError_ParameterMissing;
  5517. }
  5518. }
  5519. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5520. bool allow_array_programming = !(e && (e->flags & EntityFlag_NoBroadcast));
  5521. i64 s = 0;
  5522. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic, allow_array_programming)) {
  5523. bool ok = false;
  5524. if (e && (e->flags & EntityFlag_AnyInt)) {
  5525. if (is_type_integer(param_type)) {
  5526. ok = check_is_castable_to(c, o, param_type);
  5527. }
  5528. }
  5529. if (!allow_array_programming && check_is_assignable_to_with_score(c, o, param_type, nullptr, param_is_variadic, !allow_array_programming)) {
  5530. if (show_error) {
  5531. error(o->expr, "'#no_broadcast' disallows automatic broadcasting a value across all elements of an array-like type in a procedure argument");
  5532. }
  5533. }
  5534. if (ok) {
  5535. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5536. } else {
  5537. if (show_error) {
  5538. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5539. }
  5540. err = CallArgumentError_WrongTypes;
  5541. }
  5542. } else if (show_error) {
  5543. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5544. }
  5545. if (e && e->flags & EntityFlag_ConstInput) {
  5546. if (o->mode != Addressing_Constant) {
  5547. if (show_error) {
  5548. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5549. }
  5550. err = CallArgumentError_NoneConstantParameter;
  5551. }
  5552. }
  5553. if (!err && is_type_any(param_type)) {
  5554. add_type_info_type(c, o->type);
  5555. }
  5556. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5557. add_type_info_type(c, o->type);
  5558. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5559. } else if (show_error && is_type_untyped(o->type)) {
  5560. update_untyped_expr_type(c, o->expr, param_type, true);
  5561. }
  5562. return s;
  5563. };
  5564. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5565. err = CallArgumentError_None;
  5566. if (variadic) {
  5567. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5568. Type *t = pt->params->Tuple.variables[0]->type;
  5569. if (is_type_polymorphic(t)) {
  5570. if (show_error) {
  5571. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5572. }
  5573. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5574. }
  5575. }
  5576. } else {
  5577. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5578. PolyProcData poly_proc_data = {};
  5579. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5580. gen_entity = poly_proc_data.gen_entity;
  5581. Type *gept = base_type(gen_entity->type);
  5582. GB_ASSERT(is_type_proc(gept));
  5583. final_proc_type = gen_entity->type;
  5584. pt = &gept->Proc;
  5585. } else {
  5586. err = CallArgumentError_WrongTypes;
  5587. }
  5588. }
  5589. for (isize i = 0; i < pt->param_count; i++) {
  5590. Operand *o = &ordered_operands[i];
  5591. if (o->mode == Addressing_Invalid) {
  5592. continue;
  5593. }
  5594. Entity *e = pt->params->Tuple.variables[i];
  5595. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5596. if (e->kind == Entity_TypeName) {
  5597. GB_ASSERT(pt->is_polymorphic);
  5598. if (o->mode != Addressing_Type) {
  5599. if (show_error) {
  5600. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5601. }
  5602. err = CallArgumentError_WrongTypes;
  5603. }
  5604. if (are_types_identical(e->type, o->type)) {
  5605. score += assign_score_function(1);
  5606. } else {
  5607. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5608. }
  5609. continue;
  5610. }
  5611. if (param_is_variadic) {
  5612. if (!named_variadic_param) {
  5613. continue;
  5614. }
  5615. }
  5616. score += eval_param_and_score(c, o, e->type, err, false, e, show_error);
  5617. }
  5618. }
  5619. if (variadic) {
  5620. Entity *var_entity = pt->params->Tuple.variables[pt->variadic_index];
  5621. Type *slice = var_entity->type;
  5622. GB_ASSERT(is_type_slice(slice));
  5623. Type *elem = base_type(slice)->Slice.elem;
  5624. Type *t = elem;
  5625. if (is_type_polymorphic(t)) {
  5626. if (show_error) {
  5627. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5628. }
  5629. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5630. }
  5631. for_array(operand_index, variadic_operands) {
  5632. Operand *o = &variadic_operands[operand_index];
  5633. if (vari_expand) {
  5634. t = slice;
  5635. if (operand_index > 0) {
  5636. if (show_error) {
  5637. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5638. }
  5639. if (data) {
  5640. data->score = score;
  5641. data->result_type = final_proc_type->Proc.results;
  5642. data->gen_entity = gen_entity;
  5643. }
  5644. return CallArgumentError_MultipleVariadicExpand;
  5645. }
  5646. }
  5647. score += eval_param_and_score(c, o, t, err, true, var_entity, show_error);
  5648. }
  5649. if (!vari_expand && variadic_operands.count != 0) {
  5650. // NOTE(bill, 2024-07-14): minimize the stack usage for variadic parameters with the backing array
  5651. if (c->decl) {
  5652. bool found = false;
  5653. for (auto &vr : c->decl->variadic_reuses) {
  5654. if (are_types_identical(slice, vr.slice_type)) {
  5655. vr.max_count = gb_max(vr.max_count, variadic_operands.count);
  5656. found = true;
  5657. break;
  5658. }
  5659. }
  5660. if (!found) {
  5661. array_add(&c->decl->variadic_reuses, VariadicReuseData{slice, variadic_operands.count});
  5662. }
  5663. }
  5664. }
  5665. }
  5666. if (data) {
  5667. data->score = score;
  5668. data->result_type = final_proc_type->Proc.results;
  5669. data->gen_entity = gen_entity;
  5670. Ast *proc_lit = nullptr;
  5671. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5672. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5673. if (vp && vp->kind == Ast_ProcLit) {
  5674. proc_lit = vp;
  5675. }
  5676. }
  5677. if (proc_lit == nullptr) {
  5678. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5679. }
  5680. }
  5681. return err;
  5682. }
  5683. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5684. GB_ASSERT(ce != nullptr);
  5685. if (ce->args.count == 0) {
  5686. return false;
  5687. }
  5688. return ce->args[0]->kind == Ast_FieldValue;
  5689. }
  5690. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_) {
  5691. Entity **lhs = nullptr;
  5692. isize lhs_count = -1;
  5693. if (proc_type == nullptr || proc_type == t_invalid) {
  5694. return nullptr;
  5695. }
  5696. GB_ASSERT(is_type_proc(proc_type));
  5697. TypeProc *pt = &base_type(proc_type)->Proc;
  5698. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5699. if (pt->params != nullptr) {
  5700. lhs = pt->params->Tuple.variables.data;
  5701. lhs_count = pt->params->Tuple.variables.count;
  5702. }
  5703. } else {
  5704. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5705. if (pt->params == nullptr) {
  5706. lhs_count = 0;
  5707. } else {
  5708. lhs_count = pt->params->Tuple.variables.count;
  5709. }
  5710. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5711. for (isize i = 0; i < lhs_count; i++) {
  5712. Entity *e = pt->params->Tuple.variables[i];
  5713. if (!is_type_polymorphic(e->type)) {
  5714. lhs[i] = e;
  5715. }
  5716. }
  5717. }
  5718. if (lhs_count_) *lhs_count_ = lhs_count;
  5719. return lhs;
  5720. }
  5721. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5722. if (clauses != nullptr) {
  5723. for (Ast *clause : *clauses) {
  5724. Operand o = {};
  5725. check_expr(ctx, &o, clause);
  5726. if (o.mode != Addressing_Constant) {
  5727. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5728. if (print_err && call_expr) error(call_expr, "at caller location");
  5729. return false;
  5730. } else if (o.value.kind != ExactValue_Bool) {
  5731. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5732. if (print_err && call_expr) error(call_expr, "at caller location");
  5733. return false;
  5734. } else if (!o.value.value_bool) {
  5735. if (print_err) {
  5736. ERROR_BLOCK();
  5737. gbString str = expr_to_string(clause);
  5738. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5739. gb_string_free(str);
  5740. if (scope != nullptr) {
  5741. isize print_count = 0;
  5742. for (auto const &entry : scope->elements) {
  5743. Entity *e = entry.value;
  5744. switch (e->kind) {
  5745. case Entity_TypeName: {
  5746. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5747. gbString str = type_to_string(e->type);
  5748. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5749. gb_string_free(str);
  5750. print_count += 1;
  5751. break;
  5752. }
  5753. case Entity_Constant: {
  5754. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5755. gbString str = exact_value_to_string(e->Constant.value);
  5756. if (is_type_untyped(e->type)) {
  5757. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5758. } else {
  5759. gbString t = type_to_string(e->type);
  5760. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5761. gb_string_free(t);
  5762. }
  5763. gb_string_free(str);
  5764. print_count += 1;
  5765. break;
  5766. }
  5767. }
  5768. }
  5769. }
  5770. if (call_expr) {
  5771. TokenPos pos = ast_token(call_expr).pos;
  5772. error_line("%s at caller location\n", token_pos_to_string(pos));
  5773. }
  5774. }
  5775. return false;
  5776. }
  5777. if (ast_file_vet_style(ctx->file)) {
  5778. Ast *c = unparen_expr(clause);
  5779. if (c->kind == Ast_BinaryExpr && c->BinaryExpr.op.kind == Token_CmpAnd) {
  5780. ERROR_BLOCK();
  5781. error(c, "Prefer to separate 'where' clauses with a comma rather than '&&'");
  5782. gbString x = expr_to_string(c->BinaryExpr.left);
  5783. gbString y = expr_to_string(c->BinaryExpr.right);
  5784. error_line("\tSuggestion: '%s, %s'\n", x, y);
  5785. gb_string_free(y);
  5786. gb_string_free(x);
  5787. }
  5788. }
  5789. }
  5790. }
  5791. return true;
  5792. }
  5793. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5794. bool success = true;
  5795. type = base_type(type);
  5796. if (named_args.count > 0) {
  5797. TypeProc *pt = nullptr;
  5798. if (is_type_proc(type)) {
  5799. pt = &type->Proc;
  5800. }
  5801. for_array(i, named_args) {
  5802. Ast *arg = named_args[i];
  5803. if (arg->kind != Ast_FieldValue) {
  5804. if (show_error) {
  5805. error(arg, "Expected a 'field = value'");
  5806. }
  5807. return false;
  5808. }
  5809. ast_node(fv, FieldValue, arg);
  5810. if (fv->field->kind != Ast_Ident) {
  5811. if (show_error) {
  5812. gbString expr_str = expr_to_string(fv->field);
  5813. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5814. gb_string_free(expr_str);
  5815. }
  5816. success = false;
  5817. continue;
  5818. }
  5819. String key = fv->field->Ident.token.string;
  5820. Ast *value = fv->value;
  5821. Type *type_hint = nullptr;
  5822. if (pt) {
  5823. isize param_index = lookup_procedure_parameter(pt, key);
  5824. if (param_index < 0) {
  5825. if (show_error) {
  5826. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5827. }
  5828. success = false;
  5829. continue;
  5830. }
  5831. Entity *e = pt->params->Tuple.variables[param_index];
  5832. if (!is_type_polymorphic(e->type)) {
  5833. type_hint = e->type;
  5834. }
  5835. }
  5836. Operand o = {};
  5837. check_expr_with_type_hint(c, &o, value, type_hint);
  5838. if (o.mode == Addressing_Invalid) {
  5839. success = false;
  5840. }
  5841. array_add(named_operands, o);
  5842. }
  5843. }
  5844. return success;
  5845. }
  5846. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5847. Entity *e, Type *proc_type,
  5848. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5849. CallArgumentErrorMode show_error_mode,
  5850. CallArgumentData *data) {
  5851. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5852. Ast *ident = operand->expr;
  5853. while (ident->kind == Ast_SelectorExpr) {
  5854. Ast *s = ident->SelectorExpr.selector;
  5855. ident = s;
  5856. }
  5857. if (e == nullptr) {
  5858. e = entity_of_node(ident);
  5859. if (e != nullptr) {
  5860. proc_type = e->type;
  5861. }
  5862. }
  5863. GB_ASSERT(proc_type != nullptr);
  5864. proc_type = base_type(proc_type);
  5865. if (proc_type == t_invalid) {
  5866. return false;
  5867. }
  5868. GB_ASSERT(proc_type->kind == Type_Proc);
  5869. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5870. if (return_on_failure && err != CallArgumentError_None) {
  5871. return false;
  5872. }
  5873. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5874. if (!return_on_failure && entity_to_use != nullptr) {
  5875. add_entity_use(c, ident, entity_to_use);
  5876. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5877. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5878. }
  5879. if (data->gen_entity != nullptr) {
  5880. Entity *e = data->gen_entity;
  5881. DeclInfo *decl = data->gen_entity->decl_info;
  5882. CheckerContext ctx = *c;
  5883. ctx.scope = decl->scope;
  5884. ctx.decl = decl;
  5885. ctx.proc_name = e->token.string;
  5886. ctx.curr_proc_decl = decl;
  5887. ctx.curr_proc_sig = e->type;
  5888. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5889. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  5890. if (return_on_failure) {
  5891. if (!ok) {
  5892. return false;
  5893. }
  5894. } else {
  5895. decl->where_clauses_evaluated = true;
  5896. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  5897. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  5898. }
  5899. if (is_type_proc(data->gen_entity->type)) {
  5900. Type *t = base_type(entity_to_use->type);
  5901. data->result_type = t->Proc.results;
  5902. }
  5903. }
  5904. }
  5905. return true;
  5906. }
  5907. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  5908. ast_node(ce, CallExpr, call);
  5909. GB_ASSERT(ce->split_args != nullptr);
  5910. Slice<Ast *> const &positional_args = ce->split_args->positional;
  5911. Slice<Ast *> const &named_args = ce->split_args->named;
  5912. CallArgumentData data = {};
  5913. data.result_type = t_invalid;
  5914. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  5915. auto procs = proc_group_entities_cloned(c, *operand);
  5916. if (procs.count > 1) {
  5917. isize max_arg_count = positional_args.count + named_args.count;
  5918. for (Ast *arg : positional_args) {
  5919. // NOTE(bill): The only thing that may have multiple values
  5920. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5921. arg = strip_or_return_expr(arg);
  5922. if (arg && arg->kind == Ast_CallExpr) {
  5923. max_arg_count = ISIZE_MAX;
  5924. break;
  5925. }
  5926. }
  5927. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  5928. // NOTE(bill): The only thing that may have multiple values
  5929. // will be a call expression (assuming `or_return` and `()` will be stripped)
  5930. if (arg->kind == Ast_FieldValue) {
  5931. arg = strip_or_return_expr(arg->FieldValue.value);
  5932. if (arg && arg->kind == Ast_CallExpr) {
  5933. max_arg_count = ISIZE_MAX;
  5934. break;
  5935. }
  5936. }
  5937. }
  5938. // ignore named arguments first
  5939. for (Ast *arg : named_args) {
  5940. if (arg->kind != Ast_FieldValue) {
  5941. continue;
  5942. }
  5943. ast_node(fv, FieldValue, arg);
  5944. if (fv->field->kind != Ast_Ident) {
  5945. continue;
  5946. }
  5947. String key = fv->field->Ident.token.string;
  5948. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  5949. Type *t = procs[proc_index]->type;
  5950. if (is_type_proc(t)) {
  5951. isize param_index = lookup_procedure_parameter(t, key);
  5952. if (param_index < 0) {
  5953. array_unordered_remove(&procs, proc_index);
  5954. }
  5955. }
  5956. }
  5957. }
  5958. if (procs.count == 0) {
  5959. // if any of the named arguments are wrong, the `procs` will be empty
  5960. // just start from scratch
  5961. array_free(&procs);
  5962. procs = proc_group_entities_cloned(c, *operand);
  5963. }
  5964. // filter by positional argument length
  5965. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  5966. Entity *proc = procs[proc_index];
  5967. Type *pt = base_type(proc->type);
  5968. if (!(pt != nullptr && is_type_proc(pt))) {
  5969. proc_index++;
  5970. continue;
  5971. }
  5972. isize param_count = 0;
  5973. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  5974. if (param_count_excluding_defaults > max_arg_count) {
  5975. array_unordered_remove(&procs, proc_index);
  5976. continue;
  5977. }
  5978. proc_index++;
  5979. }
  5980. }
  5981. Entity **lhs = nullptr;
  5982. isize lhs_count = -1;
  5983. i32 variadic_index = -1;
  5984. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5985. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  5986. defer (array_free(&positional_operands));
  5987. defer (array_free(&named_operands));
  5988. if (procs.count == 1) {
  5989. Entity *e = procs[0];
  5990. Type *pt = base_type(e->type);
  5991. if (pt != nullptr && is_type_proc(pt)) {
  5992. lhs = populate_proc_parameter_list(c, pt, &lhs_count);
  5993. if (pt->Proc.variadic) {
  5994. variadic_index = pt->Proc.variadic_index;
  5995. }
  5996. }
  5997. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  5998. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  5999. check_call_arguments_single(c, call, operand,
  6000. e, e->type,
  6001. positional_operands, named_operands,
  6002. CallArgumentErrorMode::ShowErrors,
  6003. &data);
  6004. }
  6005. return data;
  6006. }
  6007. {
  6008. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  6009. // where the same positional parameter has the same type value (and ellipsis)
  6010. isize proc_arg_count = -1;
  6011. for (Entity *p : procs) {
  6012. Type *pt = base_type(p->type);
  6013. if (pt != nullptr && is_type_proc(pt)) {
  6014. if (proc_arg_count < 0) {
  6015. proc_arg_count = pt->Proc.param_count;
  6016. } else {
  6017. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  6018. }
  6019. }
  6020. }
  6021. if (proc_arg_count >= 0) {
  6022. lhs_count = proc_arg_count;
  6023. if (lhs_count > 0) {
  6024. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  6025. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  6026. Entity *e = nullptr;
  6027. for (Entity *p : procs) {
  6028. Type *pt = base_type(p->type);
  6029. if (!(pt != nullptr && is_type_proc(pt))) {
  6030. continue;
  6031. }
  6032. if (e == nullptr) {
  6033. e = pt->Proc.params->Tuple.variables[param_index];
  6034. } else {
  6035. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  6036. if (e == f) {
  6037. continue;
  6038. }
  6039. if (are_types_identical(e->type, f->type)) {
  6040. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  6041. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  6042. if (ee == fe) {
  6043. continue;
  6044. }
  6045. }
  6046. // NOTE(bill): Entities are not close enough to be used
  6047. e = nullptr;
  6048. break;
  6049. }
  6050. }
  6051. lhs[param_index] = e;
  6052. }
  6053. for (Entity *p : procs) {
  6054. Type *pt = base_type(p->type);
  6055. if (!(pt != nullptr && is_type_proc(pt))) {
  6056. continue;
  6057. }
  6058. if (pt->Proc.is_polymorphic) {
  6059. if (variadic_index == -1) {
  6060. variadic_index = pt->Proc.variadic_index;
  6061. } else if (variadic_index != pt->Proc.variadic_index) {
  6062. variadic_index = -1;
  6063. break;
  6064. }
  6065. } else {
  6066. variadic_index = -1;
  6067. break;
  6068. }
  6069. }
  6070. }
  6071. }
  6072. }
  6073. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6074. for_array(i, named_args) {
  6075. Ast *arg = named_args[i];
  6076. if (arg->kind != Ast_FieldValue) {
  6077. error(arg, "Expected a 'field = value'");
  6078. return data;
  6079. }
  6080. ast_node(fv, FieldValue, arg);
  6081. if (fv->field->kind != Ast_Ident) {
  6082. gbString expr_str = expr_to_string(fv->field);
  6083. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6084. gb_string_free(expr_str);
  6085. return data;
  6086. }
  6087. String key = fv->field->Ident.token.string;
  6088. Ast *value = fv->value;
  6089. Type *type_hint = nullptr;
  6090. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  6091. Entity *e = lhs[lhs_idx];
  6092. if (e != nullptr && e->token.string == key &&
  6093. !is_type_polymorphic(e->type)) {
  6094. type_hint = e->type;
  6095. break;
  6096. }
  6097. }
  6098. Operand o = {};
  6099. check_expr_with_type_hint(c, &o, value, type_hint);
  6100. array_add(&named_operands, o);
  6101. }
  6102. gb_free(heap_allocator(), lhs);
  6103. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  6104. defer (array_free(&valids));
  6105. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  6106. defer (array_free(&proc_entities));
  6107. for (Entity *proc : procs) {
  6108. array_add(&proc_entities, proc);
  6109. }
  6110. int max_matched_features = 0;
  6111. gbString expr_name = expr_to_string(operand->expr);
  6112. defer (gb_string_free(expr_name));
  6113. for_array(i, procs) {
  6114. Entity *p = procs[i];
  6115. if (p->flags & EntityFlag_Disabled) {
  6116. continue;
  6117. }
  6118. Type *pt = base_type(p->type);
  6119. if (pt != nullptr && is_type_proc(pt)) {
  6120. CallArgumentData data = {};
  6121. CheckerContext ctx = *c;
  6122. ctx.no_polymorphic_errors = true;
  6123. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  6124. ctx.hide_polymorphic_errors = true;
  6125. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  6126. p, pt,
  6127. positional_operands, named_operands,
  6128. CallArgumentErrorMode::NoErrors,
  6129. &data);
  6130. if (!is_a_candidate) {
  6131. continue;
  6132. }
  6133. isize index = i;
  6134. ValidIndexAndScore item = {};
  6135. item.score = data.score;
  6136. if (data.gen_entity != nullptr) {
  6137. array_add(&proc_entities, data.gen_entity);
  6138. index = proc_entities.count-1;
  6139. // prefer non-polymorphic procedures over polymorphic
  6140. item.score += assign_score_function(1);
  6141. }
  6142. max_matched_features = gb_max(max_matched_features, matched_target_features(&pt->Proc));
  6143. item.index = index;
  6144. array_add(&valids, item);
  6145. }
  6146. }
  6147. if (max_matched_features > 0) {
  6148. for_array(i, valids) {
  6149. Entity *p = procs[valids[i].index];
  6150. Type *t = base_type(p->type);
  6151. GB_ASSERT(t->kind == Type_Proc);
  6152. int matched = matched_target_features(&t->Proc);
  6153. valids[i].score += assign_score_function(max_matched_features-matched);
  6154. }
  6155. }
  6156. if (valids.count > 1) {
  6157. array_sort(valids, valid_index_and_score_cmp);
  6158. i64 best_score = valids[0].score;
  6159. Entity *best_entity = proc_entities[valids[0].index];
  6160. GB_ASSERT(best_entity != nullptr);
  6161. for (isize i = 1; i < valids.count; i++) {
  6162. if (best_score > valids[i].score) {
  6163. valids.count = i;
  6164. break;
  6165. }
  6166. if (best_entity == proc_entities[valids[i].index]) {
  6167. valids.count = i;
  6168. break;
  6169. }
  6170. }
  6171. }
  6172. auto print_argument_types = [&]() {
  6173. error_line("\tGiven argument types: (");
  6174. isize i = 0;
  6175. for (Operand const &o : positional_operands) {
  6176. if (i++ > 0) error_line(", ");
  6177. gbString type = type_to_string(o.type);
  6178. defer (gb_string_free(type));
  6179. error_line("%s", type);
  6180. }
  6181. for (Operand const &o : named_operands) {
  6182. if (i++ > 0) error_line(", ");
  6183. gbString type = type_to_string(o.type);
  6184. defer (gb_string_free(type));
  6185. if (i < ce->split_args->named.count) {
  6186. Ast *named_field = ce->split_args->named[i];
  6187. ast_node(fv, FieldValue, named_field);
  6188. gbString field = expr_to_string(fv->field);
  6189. defer (gb_string_free(field));
  6190. error_line("%s = %s", field, type);
  6191. } else {
  6192. error_line("%s", type);
  6193. }
  6194. }
  6195. error_line(")\n");
  6196. };
  6197. if (valids.count == 0) {
  6198. ERROR_BLOCK();
  6199. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  6200. if (positional_operands.count == 0 && named_operands.count == 0) {
  6201. error_line("\tNo given arguments\n");
  6202. } else {
  6203. print_argument_types();
  6204. }
  6205. if (procs.count == 0) {
  6206. procs = proc_group_entities_cloned(c, *operand);
  6207. }
  6208. if (procs.count > 0) {
  6209. error_line("Did you mean to use one of the following:\n");
  6210. }
  6211. // Try to reduce the list further for `$T: typeid` like parameters
  6212. bool *possibly_ignore = gb_alloc_array(temporary_allocator(), bool, procs.count);
  6213. isize possibly_ignore_set = 0;
  6214. if (true) {
  6215. // NOTE(bill): This currently only checks for #soa types
  6216. for_array(i, procs) {
  6217. Entity *proc = procs[i];
  6218. Type *t = base_type(proc->type);
  6219. if (t == nullptr || t->kind != Type_Proc) {
  6220. continue;
  6221. }
  6222. TypeProc *pt = &t->Proc;
  6223. if (pt->param_count == 0) {
  6224. continue;
  6225. }
  6226. for_array(j, pt->params->Tuple.variables) {
  6227. Entity *v = pt->params->Tuple.variables[j];
  6228. if (v->kind != Entity_TypeName) {
  6229. continue;
  6230. }
  6231. Type *dst_t = base_type(v->type);
  6232. while (dst_t->kind == Type_Generic && dst_t->Generic.specialized) {
  6233. dst_t = dst_t->Generic.specialized;
  6234. }
  6235. if (j >= positional_operands.count) {
  6236. continue;
  6237. }
  6238. Operand const &o = positional_operands[j];
  6239. if (o.mode != Addressing_Type) {
  6240. continue;
  6241. }
  6242. Type *t = base_type(o.type);
  6243. if (t->kind == dst_t->kind) {
  6244. continue;
  6245. }
  6246. Type *st = base_type(type_deref(o.type));
  6247. Type *dt = base_type(type_deref(dst_t));
  6248. if (st->kind == dt->kind) {
  6249. continue;
  6250. }
  6251. if (is_type_soa_struct(st)) {
  6252. possibly_ignore[i] = true;
  6253. possibly_ignore_set += 1;
  6254. continue;
  6255. }
  6256. }
  6257. }
  6258. }
  6259. if (possibly_ignore_set == procs.count) {
  6260. possibly_ignore_set = 0;
  6261. }
  6262. isize max_name_length = 0;
  6263. isize max_type_length = 0;
  6264. for_array(i, procs) {
  6265. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6266. continue;
  6267. }
  6268. Entity *proc = procs[i];
  6269. Type *t = base_type(proc->type);
  6270. if (t == t_invalid) continue;
  6271. String prefix = {};
  6272. String prefix_sep = {};
  6273. if (proc->pkg) {
  6274. prefix = proc->pkg->name;
  6275. prefix_sep = str_lit(".");
  6276. }
  6277. String name = proc->token.string;
  6278. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  6279. gbString pt;
  6280. if (t->Proc.node != nullptr) {
  6281. pt = expr_to_string(t->Proc.node);
  6282. } else {
  6283. pt = type_to_string(t);
  6284. }
  6285. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  6286. gb_string_free(pt);
  6287. }
  6288. isize max_spaces = gb_max(max_name_length, max_type_length);
  6289. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  6290. for (isize i = 0; i < max_spaces; i++) {
  6291. spaces[i] = ' ';
  6292. }
  6293. spaces[max_spaces] = 0;
  6294. for_array(i, procs) {
  6295. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6296. continue;
  6297. }
  6298. Entity *proc = procs[i];
  6299. TokenPos pos = proc->token.pos;
  6300. Type *t = base_type(proc->type);
  6301. if (t == t_invalid) continue;
  6302. GB_ASSERT(t->kind == Type_Proc);
  6303. gbString pt;
  6304. defer (gb_string_free(pt));
  6305. if (t->Proc.node != nullptr) {
  6306. pt = expr_to_string(t->Proc.node);
  6307. } else {
  6308. pt = type_to_string(t);
  6309. }
  6310. String prefix = {};
  6311. String prefix_sep = {};
  6312. if (proc->pkg) {
  6313. prefix = proc->pkg->name;
  6314. prefix_sep = str_lit(".");
  6315. }
  6316. String name = proc->token.string;
  6317. isize len = prefix.len + prefix_sep.len + name.len;
  6318. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  6319. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  6320. char const *sep = "::";
  6321. if (proc->kind == Entity_Variable) {
  6322. sep = ":=";
  6323. }
  6324. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  6325. LIT(prefix), LIT(prefix_sep), LIT(name),
  6326. name_padding, spaces,
  6327. sep,
  6328. pt,
  6329. type_padding, spaces,
  6330. token_pos_to_string(pos)
  6331. );
  6332. }
  6333. if (procs.count > 0) {
  6334. error_line("\n");
  6335. }
  6336. data.result_type = t_invalid;
  6337. } else if (valids.count > 1) {
  6338. ERROR_BLOCK();
  6339. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  6340. if (positional_operands.count == 0 && named_operands.count == 0) {
  6341. error_line("\tNo given arguments\n");
  6342. } else {
  6343. print_argument_types();
  6344. }
  6345. for (auto const &valid : valids) {
  6346. Entity *proc = proc_entities[valid.index];
  6347. GB_ASSERT(proc != nullptr);
  6348. TokenPos pos = proc->token.pos;
  6349. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  6350. gbString pt = nullptr;
  6351. defer (gb_string_free(pt));
  6352. if (t->Proc.node != nullptr) {
  6353. pt = expr_to_string(t->Proc.node);
  6354. } else {
  6355. pt = type_to_string(t);
  6356. }
  6357. String name = proc->token.string;
  6358. char const *sep = "::";
  6359. if (proc->kind == Entity_Variable) {
  6360. sep = ":=";
  6361. }
  6362. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  6363. if (proc->decl_info->proc_lit != nullptr) {
  6364. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  6365. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  6366. if (pl->where_token.kind != Token_Invalid) {
  6367. error_line("\n\t\twhere ");
  6368. for_array(j, pl->where_clauses) {
  6369. Ast *clause = pl->where_clauses[j];
  6370. if (j != 0) {
  6371. error_line("\t\t ");
  6372. }
  6373. gbString str = expr_to_string(clause);
  6374. error_line("%s", str);
  6375. gb_string_free(str);
  6376. if (j != pl->where_clauses.count-1) {
  6377. error_line(",");
  6378. }
  6379. }
  6380. error_line("\n\t");
  6381. }
  6382. }
  6383. error_line("at %s\n", token_pos_to_string(pos));
  6384. }
  6385. data.result_type = t_invalid;
  6386. } else {
  6387. GB_ASSERT(valids.count == 1);
  6388. Ast *ident = operand->expr;
  6389. while (ident->kind == Ast_SelectorExpr) {
  6390. Ast *s = ident->SelectorExpr.selector;
  6391. ident = s;
  6392. }
  6393. Entity *e = proc_entities[valids[0].index];
  6394. GB_ASSERT(e != nullptr);
  6395. Array<Operand> named_operands = {};
  6396. check_call_arguments_single(c, call, operand,
  6397. e, e->type,
  6398. positional_operands, named_operands,
  6399. CallArgumentErrorMode::ShowErrors,
  6400. &data);
  6401. return data;
  6402. }
  6403. return data;
  6404. }
  6405. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  6406. Type *proc_type = nullptr;
  6407. CallArgumentData data = {};
  6408. data.result_type = t_invalid;
  6409. proc_type = base_type(operand->type);
  6410. TypeProc *pt = nullptr;
  6411. if (proc_type) {
  6412. pt = &proc_type->Proc;
  6413. }
  6414. TEMPORARY_ALLOCATOR_GUARD();
  6415. ast_node(ce, CallExpr, call);
  6416. bool any_failure = false;
  6417. // Split positional and named args into separate arrays/slices
  6418. Slice<Ast *> positional_args = {};
  6419. Slice<Ast *> named_args = {};
  6420. if (ce->split_args == nullptr) {
  6421. positional_args = ce->args;
  6422. for (isize i = 0; i < ce->args.count; i++) {
  6423. Ast *arg = ce->args.data[i];
  6424. if (arg->kind == Ast_FieldValue) {
  6425. positional_args.count = i;
  6426. break;
  6427. }
  6428. }
  6429. named_args = slice(ce->args, positional_args.count, ce->args.count);
  6430. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  6431. split_args->positional = positional_args;
  6432. split_args->named = named_args;
  6433. ce->split_args = split_args;
  6434. } else {
  6435. positional_args = ce->split_args->positional;
  6436. named_args = ce->split_args->named;
  6437. }
  6438. if (operand->mode == Addressing_ProcGroup) {
  6439. return check_call_arguments_proc_group(c, operand, call);
  6440. }
  6441. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  6442. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6443. defer (array_free(&positional_operands));
  6444. defer (array_free(&named_operands));
  6445. if (positional_args.count > 0) {
  6446. Entity **lhs = nullptr;
  6447. isize lhs_count = -1;
  6448. i32 variadic_index = -1;
  6449. if (pt != nullptr) {
  6450. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count);
  6451. if (pt->variadic) {
  6452. variadic_index = pt->variadic_index;
  6453. }
  6454. }
  6455. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6456. }
  6457. if (named_args.count > 0) {
  6458. for_array(i, named_args) {
  6459. Ast *arg = named_args[i];
  6460. if (arg->kind != Ast_FieldValue) {
  6461. error(arg, "Expected a 'field = value'");
  6462. return data;
  6463. }
  6464. ast_node(fv, FieldValue, arg);
  6465. if (fv->field->kind != Ast_Ident) {
  6466. gbString expr_str = expr_to_string(fv->field);
  6467. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6468. any_failure = true;
  6469. gb_string_free(expr_str);
  6470. continue;
  6471. }
  6472. String key = fv->field->Ident.token.string;
  6473. Ast *value = fv->value;
  6474. isize param_index = lookup_procedure_parameter(pt, key);
  6475. Type *type_hint = nullptr;
  6476. if (param_index >= 0) {
  6477. Entity *e = pt->params->Tuple.variables[param_index];
  6478. type_hint = e->type;
  6479. }
  6480. Operand o = {};
  6481. check_expr_with_type_hint(c, &o, value, type_hint);
  6482. if (o.mode == Addressing_Invalid) {
  6483. any_failure = true;
  6484. }
  6485. array_add(&named_operands, o);
  6486. }
  6487. }
  6488. if (!any_failure) {
  6489. check_call_arguments_single(c, call, operand,
  6490. nullptr, proc_type,
  6491. positional_operands, named_operands,
  6492. CallArgumentErrorMode::ShowErrors,
  6493. &data);
  6494. } else if (pt) {
  6495. data.result_type = pt->results;
  6496. }
  6497. return data;
  6498. }
  6499. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6500. if (!is_type_polymorphic_record(t)) {
  6501. return -1;
  6502. }
  6503. TypeTuple *params = get_record_polymorphic_params(t);
  6504. if (params == nullptr) {
  6505. return -1;
  6506. }
  6507. for_array(i, params->variables) {
  6508. Entity *e = params->variables[i];
  6509. String name = e->token.string;
  6510. if (is_blank_ident(name)) {
  6511. continue;
  6512. }
  6513. if (name == parameter_name) {
  6514. return i;
  6515. }
  6516. }
  6517. return -1;
  6518. }
  6519. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6520. ast_node(ce, CallExpr, call);
  6521. Type *original_type = operand->type;
  6522. GB_ASSERT(is_type_polymorphic_record(original_type));
  6523. bool show_error = true;
  6524. Array<Operand> operands = {};
  6525. defer (array_free(&operands));
  6526. CallArgumentError err = CallArgumentError_None;
  6527. bool named_fields = false;
  6528. {
  6529. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6530. auto prev_type_path = c->type_path;
  6531. c->type_path = new_checker_type_path();
  6532. defer ({
  6533. destroy_checker_type_path(c->type_path);
  6534. c->type_path = prev_type_path;
  6535. });
  6536. if (is_call_expr_field_value(ce)) {
  6537. named_fields = true;
  6538. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6539. for_array(i, ce->args) {
  6540. Ast *arg = ce->args[i];
  6541. ast_node(fv, FieldValue, arg);
  6542. if (fv->value == nullptr) {
  6543. error(fv->eq, "Expected a value");
  6544. err = CallArgumentError_InvalidFieldValue;
  6545. continue;
  6546. }
  6547. if (fv->field->kind == Ast_Ident) {
  6548. String name = fv->field->Ident.token.string;
  6549. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6550. if (index >= 0) {
  6551. TypeTuple *params = get_record_polymorphic_params(original_type);
  6552. Entity *e = params->variables[index];
  6553. if (e->kind == Entity_Constant) {
  6554. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6555. continue;
  6556. }
  6557. }
  6558. }
  6559. check_expr_or_type(c, &operands[i], fv->value);
  6560. }
  6561. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6562. if (vari_expand) {
  6563. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6564. }
  6565. } else {
  6566. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6567. Entity **lhs = nullptr;
  6568. isize lhs_count = -1;
  6569. TypeTuple *params = get_record_polymorphic_params(original_type);
  6570. if (params != nullptr) {
  6571. lhs = params->variables.data;
  6572. lhs_count = params->variables.count;
  6573. }
  6574. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6575. }
  6576. }
  6577. if (err != 0) {
  6578. operand->mode = Addressing_Invalid;
  6579. return err;
  6580. }
  6581. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6582. isize param_count = tuple->variables.count;
  6583. isize minimum_param_count = param_count;
  6584. for (; minimum_param_count > 0; minimum_param_count--) {
  6585. Entity *e = tuple->variables[minimum_param_count-1];
  6586. if (e->kind != Entity_Constant) {
  6587. break;
  6588. }
  6589. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6590. break;
  6591. }
  6592. }
  6593. Array<Operand> ordered_operands = operands;
  6594. if (!named_fields) {
  6595. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6596. array_copy(&ordered_operands, operands, 0);
  6597. } else {
  6598. TEMPORARY_ALLOCATOR_GUARD();
  6599. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6600. // LEAK(bill)
  6601. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6602. for_array(i, ce->args) {
  6603. Ast *arg = ce->args[i];
  6604. ast_node(fv, FieldValue, arg);
  6605. if (fv->field->kind != Ast_Ident) {
  6606. if (show_error) {
  6607. gbString expr_str = expr_to_string(fv->field);
  6608. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6609. gb_string_free(expr_str);
  6610. }
  6611. err = CallArgumentError_InvalidFieldValue;
  6612. continue;
  6613. }
  6614. String name = fv->field->Ident.token.string;
  6615. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6616. if (index < 0) {
  6617. if (show_error) {
  6618. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6619. }
  6620. err = CallArgumentError_ParameterNotFound;
  6621. continue;
  6622. }
  6623. if (visited[index]) {
  6624. if (show_error) {
  6625. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6626. }
  6627. err = CallArgumentError_DuplicateParameter;
  6628. continue;
  6629. }
  6630. visited[index] = true;
  6631. ordered_operands[index] = operands[i];
  6632. }
  6633. for (isize i = 0; i < param_count; i++) {
  6634. if (!visited[i]) {
  6635. Entity *e = tuple->variables[i];
  6636. if (is_blank_ident(e->token)) {
  6637. continue;
  6638. }
  6639. if (show_error) {
  6640. if (e->kind == Entity_TypeName) {
  6641. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6642. LIT(e->token.string));
  6643. } else {
  6644. gbString str = type_to_string(e->type);
  6645. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6646. LIT(e->token.string), str);
  6647. gb_string_free(str);
  6648. }
  6649. }
  6650. err = CallArgumentError_ParameterMissing;
  6651. }
  6652. }
  6653. }
  6654. if (err != 0) {
  6655. operand->mode = Addressing_Invalid;
  6656. return err;
  6657. }
  6658. while (ordered_operands.count > 0) {
  6659. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6660. break;
  6661. }
  6662. array_pop(&ordered_operands);
  6663. }
  6664. if (minimum_param_count != param_count) {
  6665. if (param_count < ordered_operands.count) {
  6666. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6667. err = CallArgumentError_TooManyArguments;
  6668. } else if (minimum_param_count > ordered_operands.count) {
  6669. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6670. err = CallArgumentError_TooFewArguments;
  6671. }
  6672. } else {
  6673. if (param_count < ordered_operands.count) {
  6674. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6675. err = CallArgumentError_TooManyArguments;
  6676. } else if (param_count > ordered_operands.count) {
  6677. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6678. err = CallArgumentError_TooFewArguments;
  6679. }
  6680. }
  6681. if (err != 0) {
  6682. return err;
  6683. }
  6684. if (minimum_param_count != param_count) {
  6685. array_resize(&ordered_operands, param_count);
  6686. isize missing_count = 0;
  6687. // NOTE(bill): Replace missing operands with the default values (if possible)
  6688. for_array(i, ordered_operands) {
  6689. Operand *o = &ordered_operands[i];
  6690. if (o->expr == nullptr) {
  6691. Entity *e = tuple->variables[i];
  6692. if (e->kind == Entity_Constant) {
  6693. missing_count += 1;
  6694. o->mode = Addressing_Constant;
  6695. o->type = default_type(e->type);
  6696. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6697. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6698. o->value = e->Constant.param_value.value;
  6699. }
  6700. } else if (e->kind == Entity_TypeName) {
  6701. missing_count += 1;
  6702. o->mode = Addressing_Type;
  6703. o->type = e->type;
  6704. o->expr = e->identifier;
  6705. }
  6706. }
  6707. }
  6708. }
  6709. isize oo_count = gb_min(param_count, ordered_operands.count);
  6710. i64 score = 0;
  6711. for (isize i = 0; i < oo_count; i++) {
  6712. Entity *e = tuple->variables[i];
  6713. Operand *o = &ordered_operands[i];
  6714. if (o->mode == Addressing_Invalid) {
  6715. continue;
  6716. }
  6717. if (e->kind == Entity_TypeName) {
  6718. if (o->mode != Addressing_Type) {
  6719. if (show_error) {
  6720. gbString expr = expr_to_string(o->expr);
  6721. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6722. gb_string_free(expr);
  6723. }
  6724. err = CallArgumentError_WrongTypes;
  6725. }
  6726. if (are_types_identical(e->type, o->type)) {
  6727. score += assign_score_function(1);
  6728. } else {
  6729. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6730. }
  6731. } else {
  6732. i64 s = 0;
  6733. if (o->type->kind == Type_Generic) {
  6734. // Polymorphic name!
  6735. score += assign_score_function(1);
  6736. continue;
  6737. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6738. if (show_error) {
  6739. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6740. }
  6741. err = CallArgumentError_WrongTypes;
  6742. }
  6743. o->type = e->type;
  6744. if (o->mode != Addressing_Constant) {
  6745. bool valid = false;
  6746. if (is_type_proc(o->type)) {
  6747. Entity *proc_entity = entity_from_expr(o->expr);
  6748. valid = proc_entity != nullptr;
  6749. }
  6750. if (!valid) {
  6751. if (show_error) {
  6752. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6753. }
  6754. err = CallArgumentError_NoneConstantParameter;
  6755. }
  6756. }
  6757. score += s;
  6758. }
  6759. // NOTE(bill): Add type info the parameters
  6760. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6761. // add_type_info_type(c, o->type);
  6762. }
  6763. if (show_error && err) {
  6764. return err;
  6765. }
  6766. {
  6767. GenTypesData *found_gen_types = ensure_polymorphic_record_entity_has_gen_types(c, original_type);
  6768. mutex_lock(&found_gen_types->mutex);
  6769. defer (mutex_unlock(&found_gen_types->mutex));
  6770. Entity *found_entity = find_polymorphic_record_entity(found_gen_types, param_count, ordered_operands);
  6771. if (found_entity) {
  6772. operand->mode = Addressing_Type;
  6773. operand->type = found_entity->type;
  6774. return err;
  6775. }
  6776. CheckerContext ctx = *c;
  6777. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6778. ctx.scope = polymorphic_record_parent_scope(original_type);
  6779. GB_ASSERT(ctx.scope != nullptr);
  6780. Type *bt = base_type(original_type);
  6781. String generated_name = make_string_c(expr_to_string(call));
  6782. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6783. if (bt->kind == Type_Struct) {
  6784. Ast *node = clone_ast(bt->Struct.node);
  6785. Type *struct_type = alloc_type_struct();
  6786. struct_type->Struct.node = node;
  6787. struct_type->Struct.polymorphic_parent = original_type;
  6788. set_base_type(named_type, struct_type);
  6789. check_open_scope(&ctx, node);
  6790. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6791. check_close_scope(&ctx);
  6792. } else if (bt->kind == Type_Union) {
  6793. Ast *node = clone_ast(bt->Union.node);
  6794. Type *union_type = alloc_type_union();
  6795. union_type->Union.node = node;
  6796. union_type->Union.polymorphic_parent = original_type;
  6797. set_base_type(named_type, union_type);
  6798. check_open_scope(&ctx, node);
  6799. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6800. check_close_scope(&ctx);
  6801. } else {
  6802. GB_PANIC("Unsupported parametric polymorphic record type");
  6803. }
  6804. bt = base_type(named_type);
  6805. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6806. GB_ASSERT(original_type->kind == Type_Named);
  6807. Entity *e = original_type->Named.type_name;
  6808. GB_ASSERT(e->kind == Entity_TypeName);
  6809. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6810. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6811. TypeTuple *tuple = get_record_polymorphic_params(bt);
  6812. if (tuple != nullptr) for_array(i, tuple->variables) {
  6813. Entity *v = tuple->variables[i];
  6814. String name = v->token.string;
  6815. if (i > 0) {
  6816. s = gb_string_append_fmt(s, ", ");
  6817. }
  6818. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6819. if (v->kind == Entity_TypeName) {
  6820. if (v->type->kind != Type_Generic) {
  6821. s = gb_string_append_fmt(s, "=");
  6822. s = write_type_to_string(s, v->type, false);
  6823. }
  6824. } else if (v->kind == Entity_Constant) {
  6825. if (v->Constant.value.kind != ExactValue_Invalid) {
  6826. s = gb_string_append_fmt(s, "=");
  6827. s = write_exact_value_to_string(s, v->Constant.value);
  6828. }
  6829. }
  6830. }
  6831. s = gb_string_append_fmt(s, ")");
  6832. String new_name = make_string_c(s);
  6833. named_type->Named.name = new_name;
  6834. if (named_type->Named.type_name) {
  6835. named_type->Named.type_name->token.string = new_name;
  6836. }
  6837. }
  6838. operand->mode = Addressing_Type;
  6839. operand->type = named_type;
  6840. }
  6841. return err;
  6842. }
  6843. // returns true on success
  6844. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6845. bool success = true;
  6846. if (args.count > 0) {
  6847. if (allow_mixed) {
  6848. bool was_named = false;
  6849. for (Ast *arg : args) {
  6850. if (was_named && arg->kind != Ast_FieldValue) {
  6851. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6852. success = false;
  6853. break;
  6854. }
  6855. was_named = was_named || arg->kind == Ast_FieldValue;
  6856. }
  6857. } else {
  6858. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6859. for (Ast *arg : args) {
  6860. bool mix = false;
  6861. if (first_is_field_value) {
  6862. mix = arg->kind != Ast_FieldValue;
  6863. } else {
  6864. mix = arg->kind == Ast_FieldValue;
  6865. }
  6866. if (mix) {
  6867. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6868. success = false;
  6869. }
  6870. }
  6871. }
  6872. }
  6873. return success;
  6874. }
  6875. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6876. operand->mode = Addressing_Invalid; \
  6877. operand->expr = call; \
  6878. return Expr_Stmt; \
  6879. }
  6880. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  6881. if (proc != nullptr &&
  6882. proc->kind == Ast_BasicDirective) {
  6883. ast_node(bd, BasicDirective, proc);
  6884. String name = bd->name.string;
  6885. if (
  6886. name == "location" ||
  6887. name == "exists" ||
  6888. name == "assert" ||
  6889. name == "panic" ||
  6890. name == "defined" ||
  6891. name == "config" ||
  6892. name == "load" ||
  6893. name == "load_directory" ||
  6894. name == "load_hash" ||
  6895. name == "hash" ||
  6896. name == "caller_expression"
  6897. ) {
  6898. operand->mode = Addressing_Builtin;
  6899. operand->builtin_id = BuiltinProc_DIRECTIVE;
  6900. operand->expr = proc;
  6901. operand->type = t_invalid;
  6902. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  6903. } else {
  6904. error(proc, "Unknown directive: #%.*s", LIT(name));
  6905. operand->expr = proc;
  6906. operand->type = t_invalid;
  6907. operand->mode = Addressing_Invalid;
  6908. return Expr_Expr;
  6909. }
  6910. if (inlining != ProcInlining_none) {
  6911. error(call, "Inlining operators are not allowed on built-in procedures");
  6912. }
  6913. } else {
  6914. if (proc != nullptr) {
  6915. check_expr_or_type(c, operand, proc);
  6916. } else {
  6917. GB_ASSERT(operand->expr != nullptr);
  6918. }
  6919. }
  6920. if (operand->mode == Addressing_Invalid) {
  6921. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  6922. for (Ast *arg : args) {
  6923. if (arg->kind == Ast_FieldValue) {
  6924. arg = arg->FieldValue.value;
  6925. }
  6926. check_expr_base(c, operand, arg, nullptr);
  6927. }
  6928. operand->mode = Addressing_Invalid;
  6929. operand->expr = call;
  6930. return Expr_Stmt;
  6931. }
  6932. if (operand->mode == Addressing_Type) {
  6933. Type *t = operand->type;
  6934. if (is_type_polymorphic_record(t)) {
  6935. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  6936. if (!is_type_named(t)) {
  6937. gbString s = expr_to_string(operand->expr);
  6938. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  6939. gb_string_free(s);
  6940. operand->mode = Addressing_Invalid;
  6941. operand->type = t_invalid;;
  6942. return Expr_Expr;
  6943. }
  6944. auto err = check_polymorphic_record_type(c, operand, call);
  6945. if (err == 0) {
  6946. Ast *ident = operand->expr;
  6947. while (ident->kind == Ast_SelectorExpr) {
  6948. Ast *s = ident->SelectorExpr.selector;
  6949. ident = s;
  6950. }
  6951. Type *ot = operand->type;
  6952. GB_ASSERT(ot->kind == Type_Named);
  6953. Entity *e = ot->Named.type_name;
  6954. add_entity_use(c, ident, e);
  6955. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  6956. } else {
  6957. operand->mode = Addressing_Invalid;
  6958. operand->type = t_invalid;
  6959. }
  6960. } else {
  6961. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  6962. operand->mode = Addressing_Invalid;
  6963. isize arg_count = args.count;
  6964. switch (arg_count) {
  6965. case 0:
  6966. {
  6967. gbString str = type_to_string(t);
  6968. error(call, "Missing argument in conversion to '%s'", str);
  6969. gb_string_free(str);
  6970. } break;
  6971. default:
  6972. {
  6973. gbString str = type_to_string(t);
  6974. if (t->kind == Type_Basic) {
  6975. ERROR_BLOCK();
  6976. switch (t->Basic.kind) {
  6977. case Basic_complex32:
  6978. case Basic_complex64:
  6979. case Basic_complex128:
  6980. error(call, "Too many arguments in conversion to '%s'", str);
  6981. error_line("\tSuggestion: %s(1+2i) or construct with 'complex'\n", str);
  6982. break;
  6983. case Basic_quaternion64:
  6984. case Basic_quaternion128:
  6985. case Basic_quaternion256:
  6986. error(call, "Too many arguments in conversion to '%s'", str);
  6987. error_line("\tSuggestion: %s(1+2i+3j+4k) or construct with 'quaternion'\n", str);
  6988. break;
  6989. default:
  6990. error(call, "Too many arguments in conversion to '%s'", str);
  6991. }
  6992. } else {
  6993. error(call, "Too many arguments in conversion to '%s'", str);
  6994. }
  6995. gb_string_free(str);
  6996. } break;
  6997. case 1: {
  6998. Ast *arg = args[0];
  6999. if (arg->kind == Ast_FieldValue) {
  7000. error(call, "'field = value' cannot be used in a type conversion");
  7001. arg = arg->FieldValue.value;
  7002. // NOTE(bill): Carry on the cast regardless
  7003. }
  7004. check_expr_with_type_hint(c, operand, arg, t);
  7005. if (operand->mode != Addressing_Invalid) {
  7006. if (is_type_polymorphic(t)) {
  7007. error(call, "A polymorphic type cannot be used in a type conversion");
  7008. } else {
  7009. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  7010. // as it assumes it is determining the type
  7011. check_cast(c, operand, t);
  7012. }
  7013. }
  7014. operand->type = t;
  7015. operand->expr = call;
  7016. if (operand->mode != Addressing_Invalid) {
  7017. update_untyped_expr_type(c, arg, t, false);
  7018. }
  7019. break;
  7020. }
  7021. }
  7022. }
  7023. return Expr_Expr;
  7024. }
  7025. if (operand->mode == Addressing_Builtin) {
  7026. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  7027. i32 id = operand->builtin_id;
  7028. Entity *e = entity_of_node(operand->expr);
  7029. if (e != nullptr && e->token.string == "expand_to_tuple") {
  7030. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  7031. }
  7032. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  7033. operand->mode = Addressing_Invalid;
  7034. operand->type = t_invalid;
  7035. }
  7036. operand->expr = call;
  7037. return builtin_procs[id].kind;
  7038. }
  7039. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  7040. Entity *initial_entity = entity_of_node(operand->expr);
  7041. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  7042. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  7043. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  7044. if (c->decl) {
  7045. c->decl->defer_used += 1;
  7046. }
  7047. }
  7048. add_entity_use(c, operand->expr, initial_entity);
  7049. if (initial_entity->Procedure.entry_point_only) {
  7050. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  7051. // Okay
  7052. } else {
  7053. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  7054. }
  7055. }
  7056. }
  7057. if (operand->mode != Addressing_ProcGroup) {
  7058. Type *proc_type = base_type(operand->type);
  7059. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  7060. bool valid_mode = is_operand_value(*operand);
  7061. if (!valid_type || !valid_mode) {
  7062. Ast *e = operand->expr;
  7063. gbString str = expr_to_string(e);
  7064. gbString type_str = type_to_string(operand->type);
  7065. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  7066. gb_string_free(type_str);
  7067. gb_string_free(str);
  7068. operand->mode = Addressing_Invalid;
  7069. operand->expr = call;
  7070. return Expr_Stmt;
  7071. }
  7072. }
  7073. CallArgumentData data = check_call_arguments(c, operand, call);
  7074. Type *result_type = data.result_type;
  7075. gb_zero_item(operand);
  7076. operand->expr = call;
  7077. if (result_type == t_invalid) {
  7078. operand->mode = Addressing_Invalid;
  7079. operand->type = t_invalid;
  7080. return Expr_Stmt;
  7081. }
  7082. Type *pt = base_type(operand->type);
  7083. if (pt == nullptr) {
  7084. pt = t_invalid;
  7085. }
  7086. if (pt == t_invalid) {
  7087. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7088. pt = type_of_expr(operand->expr->CallExpr.proc);
  7089. }
  7090. if (pt == t_invalid && data.gen_entity) {
  7091. pt = data.gen_entity->type;
  7092. }
  7093. }
  7094. pt = base_type(pt);
  7095. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  7096. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  7097. ERROR_BLOCK();
  7098. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  7099. error_line("\tSuggestion: 'context = runtime.default_context()'");
  7100. }
  7101. }
  7102. if (result_type == nullptr) {
  7103. operand->mode = Addressing_NoValue;
  7104. } else {
  7105. GB_ASSERT(is_type_tuple(result_type));
  7106. isize count = result_type->Tuple.variables.count;
  7107. switch (count) {
  7108. case 0:
  7109. operand->mode = Addressing_NoValue;
  7110. break;
  7111. case 1:
  7112. operand->mode = Addressing_Value;
  7113. operand->type = result_type->Tuple.variables[0]->type;
  7114. break;
  7115. default:
  7116. operand->mode = Addressing_Value;
  7117. operand->type = result_type;
  7118. break;
  7119. }
  7120. }
  7121. bool is_call_inlined = false;
  7122. switch (inlining) {
  7123. case ProcInlining_inline:
  7124. is_call_inlined = true;
  7125. if (proc != nullptr) {
  7126. Entity *e = entity_from_expr(proc);
  7127. if (e != nullptr && e->kind == Entity_Procedure) {
  7128. DeclInfo *decl = e->decl_info;
  7129. if (decl->proc_lit) {
  7130. ast_node(pl, ProcLit, decl->proc_lit);
  7131. if (pl->inlining == ProcInlining_no_inline) {
  7132. error(call, "'#force_inline' cannot be applied to a procedure that has been marked as '#force_no_inline'");
  7133. }
  7134. }
  7135. }
  7136. }
  7137. break;
  7138. case ProcInlining_no_inline:
  7139. break;
  7140. case ProcInlining_none:
  7141. if (proc != nullptr) {
  7142. Entity *e = entity_from_expr(proc);
  7143. if (e != nullptr && e->kind == Entity_Procedure) {
  7144. DeclInfo *decl = e->decl_info;
  7145. if (decl->proc_lit) {
  7146. ast_node(pl, ProcLit, decl->proc_lit);
  7147. if (pl->inlining == ProcInlining_inline) {
  7148. is_call_inlined = true;
  7149. }
  7150. }
  7151. }
  7152. }
  7153. }
  7154. {
  7155. String invalid;
  7156. if (pt->kind == Type_Proc && pt->Proc.require_target_feature.len != 0) {
  7157. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.require_target_feature, &invalid)) {
  7158. error(call, "Called procedure requires target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7159. } else if (!check_target_feature_is_enabled(pt->Proc.require_target_feature, &invalid)) {
  7160. error(call, "Calling this procedure requires target feature '%.*s' to be enabled", LIT(invalid));
  7161. }
  7162. }
  7163. if (pt->kind == Type_Proc && pt->Proc.enable_target_feature.len != 0) {
  7164. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.enable_target_feature, &invalid)) {
  7165. error(call, "Called procedure enables target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7166. }
  7167. // NOTE: Due to restrictions in LLVM you can not inline calls with a superset of features.
  7168. if (is_call_inlined) {
  7169. if (c->curr_proc_decl == nullptr) {
  7170. error(call, "Calling a '#force_inline' procedure that enables target features is not allowed at file scope");
  7171. } else {
  7172. GB_ASSERT(c->curr_proc_decl->entity);
  7173. GB_ASSERT(c->curr_proc_decl->entity->type->kind == Type_Proc);
  7174. String scope_features = c->curr_proc_decl->entity->type->Proc.enable_target_feature;
  7175. if (!check_target_feature_is_superset_of(scope_features, pt->Proc.enable_target_feature, &invalid)) {
  7176. ERROR_BLOCK();
  7177. error(call, "Inlined procedure enables target feature '%.*s', this requires the calling procedure to at least enable the same feature", LIT(invalid));
  7178. error_line("\tSuggested Example: @(enable_target_feature=\"%.*s\")\n", LIT(invalid));
  7179. }
  7180. }
  7181. }
  7182. }
  7183. }
  7184. operand->expr = call;
  7185. {
  7186. Type *type = nullptr;
  7187. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7188. type = type_of_expr(operand->expr->CallExpr.proc);
  7189. }
  7190. if (type == nullptr) {
  7191. type = pt;
  7192. }
  7193. type = base_type(type);
  7194. if (type->kind == Type_Proc && type->Proc.optional_ok && type->Proc.result_count > 0) {
  7195. operand->mode = Addressing_OptionalOk;
  7196. operand->type = type->Proc.results->Tuple.variables[0]->type;
  7197. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7198. operand->expr->CallExpr.optional_ok_one = true;
  7199. }
  7200. }
  7201. }
  7202. return Expr_Expr;
  7203. }
  7204. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  7205. check_expr_base(c, o, e, t);
  7206. check_not_tuple(c, o);
  7207. char const *err_str = nullptr;
  7208. switch (o->mode) {
  7209. case Addressing_NoValue:
  7210. err_str = "used as a value";
  7211. break;
  7212. case Addressing_Type:
  7213. if (t == nullptr || !is_type_typeid(t)) {
  7214. err_str = "is not an expression but a type, in this context it is ambiguous";
  7215. }
  7216. break;
  7217. case Addressing_Builtin:
  7218. err_str = "must be called";
  7219. break;
  7220. }
  7221. if (err_str != nullptr) {
  7222. gbString str = expr_to_string(e);
  7223. error(e, "'%s' %s", str, err_str);
  7224. gb_string_free(str);
  7225. o->mode = Addressing_Invalid;
  7226. }
  7227. }
  7228. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  7229. switch (t->kind) {
  7230. case Type_Basic:
  7231. if (t->Basic.kind == Basic_string) {
  7232. if (o->mode == Addressing_Constant) {
  7233. *max_count = o->value.value_string.len;
  7234. }
  7235. if (o->mode != Addressing_Constant) {
  7236. o->mode = Addressing_Value;
  7237. }
  7238. o->type = t_u8;
  7239. return true;
  7240. } else if (t->Basic.kind == Basic_UntypedString) {
  7241. if (o->mode == Addressing_Constant) {
  7242. *max_count = o->value.value_string.len;
  7243. o->type = t_u8;
  7244. return true;
  7245. }
  7246. return false;
  7247. }
  7248. break;
  7249. case Type_MultiPointer:
  7250. o->type = t->MultiPointer.elem;
  7251. if (o->mode != Addressing_Constant) {
  7252. o->mode = Addressing_Variable;
  7253. }
  7254. return true;
  7255. case Type_Array:
  7256. *max_count = t->Array.count;
  7257. if (indirection) {
  7258. o->mode = Addressing_Variable;
  7259. } else if (o->mode != Addressing_Variable &&
  7260. o->mode != Addressing_Constant) {
  7261. o->mode = Addressing_Value;
  7262. }
  7263. o->type = t->Array.elem;
  7264. return true;
  7265. case Type_EnumeratedArray:
  7266. *max_count = t->EnumeratedArray.count;
  7267. if (indirection) {
  7268. o->mode = Addressing_Variable;
  7269. } else if (o->mode != Addressing_Variable &&
  7270. o->mode != Addressing_Constant) {
  7271. o->mode = Addressing_Value;
  7272. }
  7273. o->type = t->EnumeratedArray.elem;
  7274. return true;
  7275. case Type_Matrix:
  7276. if (indirection) {
  7277. o->mode = Addressing_Variable;
  7278. } else if (o->mode != Addressing_Variable) {
  7279. o->mode = Addressing_Value;
  7280. }
  7281. if (t->Matrix.is_row_major) {
  7282. *max_count = t->Matrix.row_count;
  7283. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.column_count);
  7284. } else {
  7285. *max_count = t->Matrix.column_count;
  7286. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  7287. }
  7288. return true;
  7289. case Type_Slice:
  7290. o->type = t->Slice.elem;
  7291. if (o->mode != Addressing_Constant) {
  7292. o->mode = Addressing_Variable;
  7293. }
  7294. return true;
  7295. case Type_DynamicArray:
  7296. o->type = t->DynamicArray.elem;
  7297. if (o->mode != Addressing_Constant) {
  7298. o->mode = Addressing_Variable;
  7299. }
  7300. return true;
  7301. case Type_Struct:
  7302. if (t->Struct.soa_kind != StructSoa_None) {
  7303. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7304. *max_count = t->Struct.soa_count;
  7305. }
  7306. o->type = t->Struct.soa_elem;
  7307. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  7308. o->mode = Addressing_SoaVariable;
  7309. } else {
  7310. o->mode = Addressing_Value;
  7311. }
  7312. return true;
  7313. }
  7314. return false;
  7315. }
  7316. if (is_type_pointer(original_type) && indirection) {
  7317. Type *ptr = base_type(original_type);
  7318. if (ptr->kind == Type_MultiPointer && o->mode == Addressing_SoaVariable) {
  7319. o->type = ptr->MultiPointer.elem;
  7320. o->mode = Addressing_Value;
  7321. return true;
  7322. }
  7323. }
  7324. return false;
  7325. }
  7326. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  7327. if (is_type_untyped_uninit(x)) {
  7328. return true;
  7329. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  7330. return true;
  7331. } else if (is_type_untyped_uninit(y)) {
  7332. return true;
  7333. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  7334. return true;
  7335. }
  7336. return are_types_identical(x, y);
  7337. }
  7338. 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) {
  7339. if (!is_ast_range(node)) {
  7340. return false;
  7341. }
  7342. ast_node(ie, BinaryExpr, node);
  7343. check_expr_with_type_hint(c, x, ie->left, type_hint);
  7344. if (x->mode == Addressing_Invalid) {
  7345. return false;
  7346. }
  7347. check_expr_with_type_hint(c, y, ie->right, type_hint);
  7348. if (y->mode == Addressing_Invalid) {
  7349. return false;
  7350. }
  7351. convert_to_typed(c, x, y->type);
  7352. if (x->mode == Addressing_Invalid) {
  7353. return false;
  7354. }
  7355. convert_to_typed(c, y, x->type);
  7356. if (y->mode == Addressing_Invalid) {
  7357. return false;
  7358. }
  7359. convert_to_typed(c, x, default_type(y->type));
  7360. if (x->mode == Addressing_Invalid) {
  7361. return false;
  7362. }
  7363. convert_to_typed(c, y, default_type(x->type));
  7364. if (y->mode == Addressing_Invalid) {
  7365. return false;
  7366. }
  7367. if (!are_types_identical(x->type, y->type)) {
  7368. if (x->type != t_invalid &&
  7369. y->type != t_invalid) {
  7370. gbString xt = type_to_string(x->type);
  7371. gbString yt = type_to_string(y->type);
  7372. gbString expr_str = expr_to_string(x->expr);
  7373. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  7374. gb_string_free(expr_str);
  7375. gb_string_free(yt);
  7376. gb_string_free(xt);
  7377. }
  7378. return false;
  7379. }
  7380. Type *type = x->type;
  7381. if (is_for_loop) {
  7382. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  7383. error(ie->op, "Only numerical types are allowed within interval expressions");
  7384. return false;
  7385. }
  7386. } else {
  7387. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  7388. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  7389. return false;
  7390. }
  7391. }
  7392. if (x->mode == Addressing_Constant &&
  7393. y->mode == Addressing_Constant) {
  7394. ExactValue a = x->value;
  7395. ExactValue b = y->value;
  7396. GB_ASSERT(are_types_identical(x->type, y->type));
  7397. TokenKind op = Token_Lt;
  7398. switch (ie->op.kind) {
  7399. case Token_Ellipsis: op = Token_LtEq; break; // ..
  7400. case Token_RangeFull: op = Token_LtEq; break; // ..=
  7401. case Token_RangeHalf: op = Token_Lt; break; // ..<
  7402. default: error(ie->op, "Invalid range operator"); break;
  7403. }
  7404. bool ok = compare_exact_values(op, a, b);
  7405. if (!ok) {
  7406. // TODO(bill): Better error message
  7407. error(ie->op, "Invalid interval range");
  7408. return false;
  7409. }
  7410. ExactValue inline_for_depth = exact_value_sub(b, a);
  7411. if (ie->op.kind != Token_RangeHalf) {
  7412. inline_for_depth = exact_value_increment_one(inline_for_depth);
  7413. }
  7414. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  7415. } else if (inline_for_depth_ != nullptr) {
  7416. error(ie->op, "Interval expressions must be constant");
  7417. return false;
  7418. }
  7419. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  7420. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  7421. return true;
  7422. }
  7423. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  7424. if (is_operand_nil(*o)) {
  7425. return true;
  7426. }
  7427. Ast *expr = unparen_expr(o->expr);
  7428. if (expr != nullptr) {
  7429. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  7430. if (e != nullptr && e->kind == Entity_Procedure) {
  7431. return true;
  7432. }
  7433. if (expr->kind == Ast_ProcLit) {
  7434. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  7435. return true;
  7436. }
  7437. }
  7438. return o->mode == Addressing_Constant;
  7439. }
  7440. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  7441. if (is_type_enum(th)) {
  7442. Type *enum_type = base_type(th);
  7443. GB_ASSERT(enum_type->kind == Type_Enum);
  7444. String name = ise->selector->Ident.token.string;
  7445. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  7446. if (e == nullptr) {
  7447. return false;
  7448. }
  7449. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  7450. GB_ASSERT(e->kind == Entity_Constant);
  7451. o->value = e->Constant.value;
  7452. o->mode = Addressing_Constant;
  7453. o->type = e->type;
  7454. return true;
  7455. }
  7456. if (is_type_union(th)) {
  7457. TEMPORARY_ALLOCATOR_GUARD();
  7458. Type *union_type = base_type(th);
  7459. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  7460. for (Type *vt : union_type->Union.variants) {
  7461. Operand x = {};
  7462. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  7463. array_add(&operands, x);
  7464. }
  7465. }
  7466. if (operands.count == 1) {
  7467. *o = operands[0];
  7468. return true;
  7469. }
  7470. }
  7471. return false;
  7472. }
  7473. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7474. ast_node(ise, ImplicitSelectorExpr, node);
  7475. o->type = t_invalid;
  7476. o->expr = node;
  7477. o->mode = Addressing_Invalid;
  7478. Type *th = type_hint;
  7479. if (th == nullptr) {
  7480. gbString str = expr_to_string(node);
  7481. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  7482. gb_string_free(str);
  7483. return Expr_Expr;
  7484. }
  7485. o->type = th;
  7486. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  7487. if (!ok) {
  7488. String name = ise->selector->Ident.token.string;
  7489. if (is_type_enum(th)) {
  7490. ERROR_BLOCK();
  7491. Type *bt = base_type(th);
  7492. GB_ASSERT(bt->kind == Type_Enum);
  7493. gbString typ = type_to_string(th);
  7494. defer (gb_string_free(typ));
  7495. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  7496. check_did_you_mean_type(name, bt->Enum.fields);
  7497. } else if (is_type_bit_set(th) && is_type_enum(th->BitSet.elem)) {
  7498. ERROR_BLOCK();
  7499. gbString typ = type_to_string(th);
  7500. gbString str = expr_to_string(node);
  7501. error(node, "Cannot convert enum value to '%s'", typ);
  7502. error_line("\tSuggestion: Did you mean '{ %s }'?\n", str);
  7503. gb_string_free(typ);
  7504. gb_string_free(str);
  7505. } else {
  7506. gbString typ = type_to_string(th);
  7507. gbString str = expr_to_string(node);
  7508. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  7509. gb_string_free(str);
  7510. gb_string_free(typ);
  7511. }
  7512. }
  7513. o->expr = node;
  7514. return Expr_Expr;
  7515. }
  7516. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  7517. switch (x->mode) {
  7518. case Addressing_MapIndex:
  7519. case Addressing_OptionalOk:
  7520. case Addressing_OptionalOkPtr:
  7521. if (val_type_) *val_type_ = x->type;
  7522. break;
  7523. default:
  7524. if (ok_type_) *ok_type_ = x->type;
  7525. return;
  7526. }
  7527. Ast *expr = unparen_expr(x->expr);
  7528. if (expr->kind == Ast_CallExpr) {
  7529. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  7530. if (is_type_proc(pt)) {
  7531. Type *tuple = pt->Proc.results;
  7532. if (pt->Proc.result_count >= 2) {
  7533. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7534. }
  7535. if (change_operand) {
  7536. expr->CallExpr.optional_ok_one = false;
  7537. x->type = tuple;
  7538. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7539. }
  7540. return;
  7541. }
  7542. }
  7543. Type *tuple = make_optional_ok_type(x->type);
  7544. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7545. if (change_operand) {
  7546. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7547. x->type = tuple;
  7548. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  7549. }
  7550. }
  7551. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7552. ast_node(ie, MatrixIndexExpr, node);
  7553. check_expr(c, o, ie->expr);
  7554. node->viral_state_flags |= ie->expr->viral_state_flags;
  7555. if (o->mode == Addressing_Invalid) {
  7556. o->expr = node;
  7557. return;
  7558. }
  7559. Type *t = base_type(type_deref(o->type));
  7560. bool is_ptr = is_type_pointer(o->type);
  7561. bool is_const = o->mode == Addressing_Constant;
  7562. if (t->kind != Type_Matrix) {
  7563. gbString str = expr_to_string(o->expr);
  7564. gbString type_str = type_to_string(o->type);
  7565. defer (gb_string_free(str));
  7566. defer (gb_string_free(type_str));
  7567. if (is_const) {
  7568. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  7569. } else {
  7570. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  7571. }
  7572. o->mode = Addressing_Invalid;
  7573. o->expr = node;
  7574. return;
  7575. }
  7576. o->type = t->Matrix.elem;
  7577. if (is_ptr) {
  7578. o->mode = Addressing_Variable;
  7579. } else if (o->mode != Addressing_Variable) {
  7580. o->mode = Addressing_Value;
  7581. }
  7582. if (ie->row_index == nullptr) {
  7583. gbString str = expr_to_string(o->expr);
  7584. error(o->expr, "Missing row index for '%s'", str);
  7585. gb_string_free(str);
  7586. o->mode = Addressing_Invalid;
  7587. o->expr = node;
  7588. return;
  7589. }
  7590. if (ie->column_index == nullptr) {
  7591. gbString str = expr_to_string(o->expr);
  7592. error(o->expr, "Missing column index for '%s'", str);
  7593. gb_string_free(str);
  7594. o->mode = Addressing_Invalid;
  7595. o->expr = node;
  7596. return;
  7597. }
  7598. i64 row_count = t->Matrix.row_count;
  7599. i64 column_count = t->Matrix.column_count;
  7600. i64 row_index = 0;
  7601. i64 column_index = 0;
  7602. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7603. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7604. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7605. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7606. }
  7607. gb_unused(row_ok);
  7608. gb_unused(column_ok);
  7609. }
  7610. struct TypeAndToken {
  7611. Type *type;
  7612. Token token;
  7613. };
  7614. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7615. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7616. if (operand.mode != Addressing_Constant) {
  7617. return;
  7618. }
  7619. if (operand.value.kind == ExactValue_Invalid) {
  7620. return;
  7621. }
  7622. uintptr key = hash_exact_value(operand.value);
  7623. GB_ASSERT(key != 0);
  7624. isize count = multi_map_count(seen, key);
  7625. if (count) {
  7626. TEMPORARY_ALLOCATOR_GUARD();
  7627. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  7628. multi_map_get_all(seen, key, taps);
  7629. for (isize i = 0; i < count; i++) {
  7630. TypeAndToken tap = taps[i];
  7631. Operand to = {};
  7632. to.mode = Addressing_Value;
  7633. to.type = tap.type;
  7634. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7635. continue;
  7636. }
  7637. TokenPos pos = tap.token.pos;
  7638. if (use_expr) {
  7639. gbString expr_str = expr_to_string(operand.expr);
  7640. error(operand.expr,
  7641. "Duplicate case '%s'\n"
  7642. "\tprevious case at %s",
  7643. expr_str,
  7644. token_pos_to_string(pos));
  7645. gb_string_free(expr_str);
  7646. } else {
  7647. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7648. }
  7649. return;
  7650. }
  7651. }
  7652. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7653. multi_map_insert(seen, key, tap);
  7654. }
  7655. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7656. if (is_type_enum(x.type)) {
  7657. // TODO(bill): Fix this logic so it's fast!!!
  7658. i64 v0 = exact_value_to_i64(lhs.value);
  7659. i64 v1 = exact_value_to_i64(rhs.value);
  7660. Operand v = {};
  7661. v.mode = Addressing_Constant;
  7662. v.type = x.type;
  7663. v.expr = x.expr;
  7664. Type *bt = base_type(x.type);
  7665. GB_ASSERT(bt->kind == Type_Enum);
  7666. for (i64 vi = v0; vi <= v1; vi++) {
  7667. if (upper_op != Token_LtEq && vi == v1) {
  7668. break;
  7669. }
  7670. v.value = exact_value_i64(vi);
  7671. add_constant_switch_case(ctx, seen, v);
  7672. }
  7673. } else {
  7674. add_constant_switch_case(ctx, seen, lhs);
  7675. if (upper_op == Token_LtEq) {
  7676. add_constant_switch_case(ctx, seen, rhs);
  7677. }
  7678. }
  7679. }
  7680. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7681. add_constant_switch_case(ctx, seen, x);
  7682. }
  7683. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7684. ast_node(bd, BasicDirective, node);
  7685. ExprKind kind = Expr_Expr;
  7686. o->mode = Addressing_Constant;
  7687. String name = bd->name.string;
  7688. if (name == "file") {
  7689. String file = get_file_path_string(bd->token.pos.file_id);
  7690. if (build_context.obfuscate_source_code_locations) {
  7691. file = obfuscate_string(file, "F");
  7692. }
  7693. o->type = t_untyped_string;
  7694. o->value = exact_value_string(file);
  7695. } else if (name == "directory") {
  7696. String file = get_file_path_string(bd->token.pos.file_id);
  7697. String path = dir_from_path(file);
  7698. if (build_context.obfuscate_source_code_locations) {
  7699. path = obfuscate_string(path, "D");
  7700. }
  7701. o->type = t_untyped_string;
  7702. o->value = exact_value_string(path);
  7703. } else if (name == "line") {
  7704. i32 line = bd->token.pos.line;
  7705. if (build_context.obfuscate_source_code_locations) {
  7706. line = obfuscate_i32(line);
  7707. }
  7708. o->type = t_untyped_integer;
  7709. o->value = exact_value_i64(line);
  7710. } else if (name == "procedure") {
  7711. if (c->curr_proc_decl == nullptr) {
  7712. error(node, "#procedure may only be used within procedures");
  7713. o->type = t_untyped_string;
  7714. o->value = exact_value_string(str_lit(""));
  7715. } else {
  7716. String p = c->proc_name;
  7717. if (build_context.obfuscate_source_code_locations) {
  7718. p = obfuscate_string(p, "P");
  7719. }
  7720. o->type = t_untyped_string;
  7721. o->value = exact_value_string(p);
  7722. }
  7723. } else if (name == "caller_location") {
  7724. init_core_source_code_location(c->checker);
  7725. error(node, "#caller_location may only be used as a default argument parameter");
  7726. o->type = t_source_code_location;
  7727. o->mode = Addressing_Value;
  7728. } else if (name == "caller_expression") {
  7729. error(node, "#caller_expression may only be used as a default argument parameter");
  7730. o->type = t_string;
  7731. o->mode = Addressing_Value;
  7732. } else if (name == "branch_location") {
  7733. if (!c->in_defer) {
  7734. error(node, "#branch_location may only be used within a 'defer' statement");
  7735. } else if (c->curr_proc_decl) {
  7736. Entity *e = c->curr_proc_decl->entity;
  7737. if (e != nullptr) {
  7738. GB_ASSERT(e->kind == Entity_Procedure);
  7739. e->Procedure.uses_branch_location = true;
  7740. }
  7741. }
  7742. o->type = t_source_code_location;
  7743. o->mode = Addressing_Value;
  7744. } else {
  7745. if (name == "location") {
  7746. init_core_source_code_location(c->checker);
  7747. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  7748. o->type = t_source_code_location;
  7749. o->mode = Addressing_Value;
  7750. } else if (
  7751. name == "assert" ||
  7752. name == "defined" ||
  7753. name == "config" ||
  7754. name == "exists" ||
  7755. name == "load" ||
  7756. name == "load_hash" ||
  7757. name == "load_directory" ||
  7758. name == "load_or"
  7759. ) {
  7760. error(node, "'#%.*s' must be used as a call", LIT(name));
  7761. o->type = t_invalid;
  7762. o->mode = Addressing_Invalid;
  7763. } else {
  7764. error(node, "Unknown directive: #%.*s", LIT(name));
  7765. o->type = t_invalid;
  7766. o->mode = Addressing_Invalid;
  7767. }
  7768. }
  7769. return kind;
  7770. }
  7771. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7772. ExprKind kind = Expr_Expr;
  7773. Operand cond = {Addressing_Invalid};
  7774. ast_node(te, TernaryIfExpr, node);
  7775. check_expr(c, &cond, te->cond);
  7776. node->viral_state_flags |= te->cond->viral_state_flags;
  7777. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7778. error(te->cond, "Non-boolean condition in ternary if expression");
  7779. }
  7780. Operand x = {Addressing_Invalid};
  7781. Operand y = {Addressing_Invalid};
  7782. check_expr_or_type(c, &x, te->x, type_hint);
  7783. node->viral_state_flags |= te->x->viral_state_flags;
  7784. if (te->y != nullptr) {
  7785. Type *th = type_hint;
  7786. if (type_hint == nullptr && is_type_typed(x.type)) {
  7787. th = x.type;
  7788. }
  7789. check_expr_or_type(c, &y, te->y, th);
  7790. node->viral_state_flags |= te->y->viral_state_flags;
  7791. } else {
  7792. error(node, "A ternary expression must have an else clause");
  7793. return kind;
  7794. }
  7795. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7796. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7797. gbString type_string = expr_to_string(type_expr);
  7798. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7799. gb_string_free(type_string);
  7800. return kind;
  7801. }
  7802. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7803. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7804. if (x.mode == Addressing_Invalid) {
  7805. return kind;
  7806. }
  7807. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7808. if (y.mode == Addressing_Invalid) {
  7809. x.mode = Addressing_Invalid;
  7810. return kind;
  7811. }
  7812. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7813. // x: union{f32} = f32(123) if cond else nil
  7814. if (type_hint && !is_type_any(type_hint)) {
  7815. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7816. check_cast(c, &x, type_hint);
  7817. check_cast(c, &y, type_hint);
  7818. }
  7819. }
  7820. if (!ternary_compare_types(x.type, y.type)) {
  7821. gbString its = type_to_string(x.type);
  7822. gbString ets = type_to_string(y.type);
  7823. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7824. gb_string_free(ets);
  7825. gb_string_free(its);
  7826. return kind;
  7827. }
  7828. o->type = x.type;
  7829. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  7830. o->type = y.type;
  7831. }
  7832. o->mode = Addressing_Value;
  7833. o->expr = node;
  7834. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  7835. if (check_cast_internal(c, &x, type_hint) &&
  7836. check_cast_internal(c, &y, type_hint)) {
  7837. convert_to_typed(c, o, type_hint);
  7838. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  7839. o->type = type_hint;
  7840. }
  7841. }
  7842. return kind;
  7843. }
  7844. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7845. ExprKind kind = Expr_Expr;
  7846. Operand cond = {};
  7847. ast_node(te, TernaryWhenExpr, node);
  7848. check_expr(c, &cond, te->cond);
  7849. node->viral_state_flags |= te->cond->viral_state_flags;
  7850. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  7851. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  7852. return kind;
  7853. }
  7854. if (cond.value.value_bool) {
  7855. check_expr_or_type(c, o, te->x, type_hint);
  7856. node->viral_state_flags |= te->x->viral_state_flags;
  7857. } else {
  7858. if (te->y != nullptr) {
  7859. check_expr_or_type(c, o, te->y, type_hint);
  7860. node->viral_state_flags |= te->y->viral_state_flags;
  7861. } else {
  7862. error(node, "A ternary when expression must have an else clause");
  7863. return kind;
  7864. }
  7865. }
  7866. return kind;
  7867. }
  7868. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7869. ast_node(oe, OrElseExpr, node);
  7870. String name = oe->token.string;
  7871. Ast *arg = oe->x;
  7872. Ast *default_value = oe->y;
  7873. Operand x = {};
  7874. Operand y = {};
  7875. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  7876. if (is_load_directive_call(arg)) {
  7877. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  7878. // Allow for chaining of '#load(path) or_else #load(path)'
  7879. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  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. if (!y_is_diverging) {
  7905. check_assignment(c, &y, x.type, name);
  7906. if (y.mode != Addressing_Constant) {
  7907. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  7908. }
  7909. }
  7910. }
  7911. if (res == LoadDirective_Success) {
  7912. *o = x;
  7913. } else {
  7914. *o = y;
  7915. }
  7916. o->expr = node;
  7917. return Expr_Expr;
  7918. }
  7919. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  7920. if (x.mode == Addressing_Invalid) {
  7921. o->mode = Addressing_Value;
  7922. o->type = t_invalid;
  7923. o->expr = node;
  7924. return Expr_Expr;
  7925. }
  7926. Type *left_type = nullptr;
  7927. Type *right_type = nullptr;
  7928. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  7929. add_type_and_value(c, arg, x.mode, x.type, x.value);
  7930. bool y_is_diverging = false;
  7931. check_expr_base(c, &y, default_value, left_type);
  7932. switch (y.mode) {
  7933. case Addressing_NoValue:
  7934. if (is_diverging_expr(y.expr)) {
  7935. // Allow
  7936. y.mode = Addressing_Value;
  7937. y_is_diverging = true;
  7938. } else {
  7939. error_operand_no_value(&y);
  7940. y.mode = Addressing_Invalid;
  7941. }
  7942. break;
  7943. case Addressing_Type:
  7944. error_operand_not_expression(&y);
  7945. y.mode = Addressing_Invalid;
  7946. break;
  7947. }
  7948. if (y.mode == Addressing_Invalid) {
  7949. o->mode = Addressing_Value;
  7950. o->type = t_invalid;
  7951. o->expr = node;
  7952. return Expr_Expr;
  7953. }
  7954. if (left_type != nullptr) {
  7955. if (!y_is_diverging) {
  7956. if (is_type_tuple(left_type)) {
  7957. if (!is_type_tuple(y.type)) {
  7958. error(y.expr, "Found a single value where a %td-valued expression was expected", left_type->Tuple.variables.count);
  7959. } else if (!are_types_identical(left_type, y.type)) {
  7960. gbString xt = type_to_string(left_type);
  7961. gbString yt = type_to_string(y.type);
  7962. error(y.expr, "Mismatched types, expected (%s), got (%s)", xt, yt);
  7963. gb_string_free(yt);
  7964. gb_string_free(xt);
  7965. }
  7966. } else {
  7967. check_assignment(c, &y, left_type, name);
  7968. }
  7969. }
  7970. } else {
  7971. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7972. }
  7973. if (left_type == nullptr) {
  7974. left_type = t_invalid;
  7975. }
  7976. o->mode = Addressing_Value;
  7977. o->type = left_type;
  7978. o->expr = node;
  7979. return Expr_Expr;
  7980. }
  7981. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7982. ast_node(re, OrReturnExpr, node);
  7983. String name = re->token.string;
  7984. Operand x = {};
  7985. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  7986. if (x.mode == Addressing_Invalid) {
  7987. o->mode = Addressing_Value;
  7988. o->type = t_invalid;
  7989. o->expr = node;
  7990. return Expr_Expr;
  7991. }
  7992. Type *left_type = nullptr;
  7993. Type *right_type = nullptr;
  7994. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  7995. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  7996. if (right_type == nullptr) {
  7997. check_or_else_expr_no_value_error(c, name, x, type_hint);
  7998. } else {
  7999. Type *proc_type = base_type(c->curr_proc_sig);
  8000. GB_ASSERT(proc_type->kind == Type_Proc);
  8001. Type *result_type = proc_type->Proc.results;
  8002. if (result_type == nullptr) {
  8003. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  8004. } else {
  8005. GB_ASSERT(result_type->kind == Type_Tuple);
  8006. auto const &vars = result_type->Tuple.variables;
  8007. Type *end_type = vars[vars.count-1]->type;
  8008. if (vars.count > 1) {
  8009. if (!proc_type->Proc.has_named_results) {
  8010. 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));
  8011. }
  8012. }
  8013. Operand rhs = {};
  8014. rhs.type = right_type;
  8015. rhs.mode = Addressing_Value;
  8016. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  8017. // NOTE(bill): allow implicit conversion between boolean types
  8018. // within 'or_return' to improve the experience using third-party code
  8019. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  8020. ERROR_BLOCK();
  8021. // TODO(bill): better error message
  8022. gbString a = type_to_string(right_type);
  8023. gbString b = type_to_string(end_type);
  8024. gbString ret_type = type_to_string(result_type);
  8025. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  8026. if (vars.count == 1) {
  8027. error_line("\tProcedure return value type: %s\n", ret_type);
  8028. } else {
  8029. error_line("\tProcedure return value types: (%s)\n", ret_type);
  8030. }
  8031. gb_string_free(ret_type);
  8032. gb_string_free(b);
  8033. gb_string_free(a);
  8034. }
  8035. }
  8036. }
  8037. o->expr = node;
  8038. o->type = left_type;
  8039. if (left_type != nullptr) {
  8040. o->mode = Addressing_Value;
  8041. } else {
  8042. o->mode = Addressing_NoValue;
  8043. }
  8044. if (c->curr_proc_sig == nullptr) {
  8045. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8046. }
  8047. if (c->in_defer) {
  8048. error(node, "'or_return' cannot be used within a defer statement");
  8049. }
  8050. return Expr_Expr;
  8051. }
  8052. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8053. ast_node(be, OrBranchExpr, node);
  8054. String name = be->token.string;
  8055. Operand x = {};
  8056. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  8057. if (x.mode == Addressing_Invalid) {
  8058. o->mode = Addressing_Value;
  8059. o->type = t_invalid;
  8060. o->expr = node;
  8061. return Expr_Expr;
  8062. }
  8063. Type *left_type = nullptr;
  8064. Type *right_type = nullptr;
  8065. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8066. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  8067. if (right_type == nullptr) {
  8068. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8069. } else {
  8070. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  8071. // okay
  8072. } else {
  8073. gbString s = type_to_string(right_type);
  8074. error(node, "'%.*s' requires a boolean or nil-able type, got %s", LIT(name), s);
  8075. gb_string_free(s);
  8076. }
  8077. }
  8078. o->expr = node;
  8079. o->type = left_type;
  8080. if (left_type != nullptr) {
  8081. o->mode = Addressing_Value;
  8082. } else {
  8083. o->mode = Addressing_NoValue;
  8084. }
  8085. if (c->curr_proc_sig == nullptr) {
  8086. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8087. }
  8088. Ast *label = be->label;
  8089. switch (be->token.kind) {
  8090. case Token_or_break:
  8091. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  8092. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  8093. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  8094. }
  8095. break;
  8096. case Token_or_continue:
  8097. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  8098. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  8099. }
  8100. break;
  8101. }
  8102. if (label != nullptr) {
  8103. if (c->in_defer) {
  8104. error(label, "A labelled '%.*s' cannot be used within a 'defer'", LIT(name));
  8105. return Expr_Expr;
  8106. }
  8107. if (label->kind != Ast_Ident) {
  8108. error(label, "A branch statement's label name must be an identifier");
  8109. return Expr_Expr;
  8110. }
  8111. Ast *ident = label;
  8112. String name = ident->Ident.token.string;
  8113. Operand o = {};
  8114. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  8115. if (e == nullptr) {
  8116. error(ident, "Undeclared label name: %.*s", LIT(name));
  8117. return Expr_Expr;
  8118. }
  8119. add_entity_use(c, ident, e);
  8120. if (e->kind != Entity_Label) {
  8121. error(ident, "'%.*s' is not a label", LIT(name));
  8122. return Expr_Expr;
  8123. }
  8124. Ast *parent = e->Label.parent;
  8125. GB_ASSERT(parent != nullptr);
  8126. switch (parent->kind) {
  8127. case Ast_BlockStmt:
  8128. case Ast_IfStmt:
  8129. case Ast_SwitchStmt:
  8130. if (be->token.kind != Token_or_break) {
  8131. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  8132. }
  8133. break;
  8134. case Ast_RangeStmt:
  8135. case Ast_ForStmt:
  8136. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  8137. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  8138. }
  8139. break;
  8140. }
  8141. }
  8142. return Expr_Expr;
  8143. }
  8144. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  8145. Type *bt = base_type(type);
  8146. StringSet fields_visited = {};
  8147. defer (string_set_destroy(&fields_visited));
  8148. StringMap<String> fields_visited_through_raw_union = {};
  8149. defer (string_map_destroy(&fields_visited_through_raw_union));
  8150. String assignment_str = str_lit("structure literal");
  8151. if (bt->kind == Type_BitField) {
  8152. assignment_str = str_lit("bit_field literal");
  8153. }
  8154. for (Ast *elem : elems) {
  8155. if (elem->kind != Ast_FieldValue) {
  8156. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8157. continue;
  8158. }
  8159. ast_node(fv, FieldValue, elem);
  8160. Ast *ident = fv->field;
  8161. if (ident->kind == Ast_ImplicitSelectorExpr) {
  8162. gbString expr_str = expr_to_string(ident);
  8163. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  8164. gb_string_free(expr_str);
  8165. ident = ident->ImplicitSelectorExpr.selector;
  8166. }
  8167. if (ident->kind != Ast_Ident) {
  8168. gbString expr_str = expr_to_string(ident);
  8169. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  8170. gb_string_free(expr_str);
  8171. continue;
  8172. }
  8173. String name = ident->Ident.token.string;
  8174. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8175. bool is_unknown = sel.entity == nullptr;
  8176. if (is_unknown) {
  8177. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  8178. continue;
  8179. }
  8180. Entity *field = nullptr;
  8181. if (bt->kind == Type_Struct) {
  8182. field = bt->Struct.fields[sel.index[0]];
  8183. } else if (bt->kind == Type_BitField) {
  8184. field = bt->BitField.fields[sel.index[0]];
  8185. } else {
  8186. GB_PANIC("Unknown type");
  8187. }
  8188. add_entity_use(c, ident, field);
  8189. if (string_set_update(&fields_visited, name)) {
  8190. if (sel.index.count > 1) {
  8191. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8192. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8193. } else {
  8194. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  8195. }
  8196. } else {
  8197. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  8198. }
  8199. continue;
  8200. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8201. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8202. continue;
  8203. }
  8204. if (sel.indirect) {
  8205. 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));
  8206. continue;
  8207. }
  8208. if (sel.index.count > 1) {
  8209. GB_ASSERT(bt->kind == Type_Struct);
  8210. if (is_constant) {
  8211. Type *ft = type;
  8212. for (i32 index : sel.index) {
  8213. Type *bt = base_type(ft);
  8214. switch (bt->kind) {
  8215. case Type_Struct:
  8216. if (bt->Struct.is_raw_union) {
  8217. is_constant = false;
  8218. break;
  8219. }
  8220. ft = bt->Struct.fields[index]->type;
  8221. break;
  8222. case Type_Array:
  8223. ft = bt->Array.elem;
  8224. break;
  8225. case Type_BitField:
  8226. is_constant = false;
  8227. ft = bt->BitField.fields[index]->type;
  8228. break;
  8229. default:
  8230. GB_PANIC("invalid type: %s", type_to_string(ft));
  8231. break;
  8232. }
  8233. }
  8234. if (is_constant &&
  8235. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  8236. is_constant = false;
  8237. }
  8238. }
  8239. Type *nested_ft = bt;
  8240. for (i32 index : sel.index) {
  8241. Type *bt = base_type(nested_ft);
  8242. switch (bt->kind) {
  8243. case Type_Struct:
  8244. if (bt->Struct.is_raw_union) {
  8245. for (Entity *re : bt->Struct.fields) {
  8246. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  8247. }
  8248. }
  8249. nested_ft = bt->Struct.fields[index]->type;
  8250. break;
  8251. case Type_Array:
  8252. nested_ft = bt->Array.elem;
  8253. break;
  8254. case Type_BitField:
  8255. nested_ft = bt->BitField.fields[index]->type;
  8256. break;
  8257. default:
  8258. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  8259. break;
  8260. }
  8261. }
  8262. field = sel.entity;
  8263. }
  8264. Operand o = {};
  8265. check_expr_or_type(c, &o, fv->value, field->type);
  8266. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8267. is_constant = false;
  8268. }
  8269. if (is_constant) {
  8270. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8271. }
  8272. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  8273. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  8274. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  8275. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  8276. }
  8277. check_assignment(c, &o, field->type, assignment_str);
  8278. c->bit_field_bit_size = prev_bit_field_bit_size;
  8279. }
  8280. }
  8281. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  8282. type_expr = unparen_expr(type_expr);
  8283. if (type_expr == nullptr) {
  8284. return false;
  8285. }
  8286. // [?]Type
  8287. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  8288. Ast *count = type_expr->ArrayType.count;
  8289. if (count->kind == Ast_UnaryExpr &&
  8290. count->UnaryExpr.op.kind == Token_Question) {
  8291. return true;
  8292. }
  8293. }
  8294. return false;
  8295. }
  8296. gb_internal bool check_for_dynamic_literals(CheckerContext *c, Ast *node, AstCompoundLit *cl) {
  8297. if (cl->elems.count > 0 && (check_feature_flags(c, node) & OptInFeatureFlag_DynamicLiterals) == 0 && !build_context.dynamic_literals) {
  8298. ERROR_BLOCK();
  8299. error(node, "Compound literals of dynamic types are disabled by default");
  8300. error_line("\tSuggestion: If you want to enable them for this specific file, add '#+feature dynamic-literals' at the top of the file\n");
  8301. error_line("\tWarning: Please understand that dynamic literals will implicitly allocate using the current 'context.allocator' in that scope\n");
  8302. if (build_context.ODIN_DEFAULT_TO_NIL_ALLOCATOR) {
  8303. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8304. } else if (build_context.ODIN_DEFAULT_TO_PANIC_ALLOCATOR) {
  8305. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8306. }
  8307. return false;
  8308. }
  8309. return cl->elems.count > 0;
  8310. }
  8311. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8312. ExprKind kind = Expr_Expr;
  8313. ast_node(cl, CompoundLit, node);
  8314. Type *type = type_hint;
  8315. if (type != nullptr && is_type_untyped(type)) {
  8316. type = nullptr;
  8317. }
  8318. bool is_to_be_determined_array_count = false;
  8319. bool is_constant = true;
  8320. bool is_soa = false;
  8321. Ast *type_expr = cl->type;
  8322. bool used_type_hint_expr = false;
  8323. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  8324. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  8325. type_expr = clone_ast(c->type_hint_expr);
  8326. used_type_hint_expr = true;
  8327. }
  8328. }
  8329. if (type_expr != nullptr) {
  8330. type = nullptr;
  8331. // [?]Type
  8332. if (type_expr->kind == Ast_ArrayType) {
  8333. Ast *count = type_expr->ArrayType.count;
  8334. if (count != nullptr) {
  8335. if (count->kind == Ast_UnaryExpr &&
  8336. count->UnaryExpr.op.kind == Token_Question) {
  8337. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  8338. is_to_be_determined_array_count = true;
  8339. }
  8340. } else {
  8341. type = alloc_type_slice(check_type(c, type_expr->ArrayType.elem));
  8342. }
  8343. if (cl->elems.count > 0) {
  8344. if (type_expr->ArrayType.tag != nullptr) {
  8345. Ast *tag = type_expr->ArrayType.tag;
  8346. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8347. String name = tag->BasicDirective.name.string;
  8348. if (name == "soa") {
  8349. is_soa = true;
  8350. if (count == nullptr) {
  8351. error(node, "#soa slices are not supported for compound literals");
  8352. return kind;
  8353. } else if (count->kind == Ast_UnaryExpr &&
  8354. count->UnaryExpr.op.kind == Token_Question) {
  8355. error(node, "#soa fixed length arrays must specify their length and cannot use ?");
  8356. }
  8357. }
  8358. }
  8359. }
  8360. } else if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  8361. if (cl->elems.count > 0) {
  8362. Ast *tag = type_expr->DynamicArrayType.tag;
  8363. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8364. String name = tag->BasicDirective.name.string;
  8365. if (name == "soa") {
  8366. is_soa = true;
  8367. error(node, "#soa dynamic arrays are not supported for compound literals");
  8368. return kind;
  8369. }
  8370. }
  8371. }
  8372. if (type == nullptr) {
  8373. type = check_type(c, type_expr);
  8374. }
  8375. }
  8376. if (type == nullptr) {
  8377. error(node, "Missing type in compound literal");
  8378. return kind;
  8379. }
  8380. Type *t = base_type(type);
  8381. if (is_type_polymorphic(t)) {
  8382. gbString str = type_to_string(type);
  8383. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  8384. o->expr = node;
  8385. o->type = type;
  8386. gb_string_free(str);
  8387. return kind;
  8388. }
  8389. switch (t->kind) {
  8390. case Type_Struct:
  8391. if (cl->elems.count == 0) {
  8392. break; // NOTE(bill): No need to init
  8393. }
  8394. if (t->Struct.soa_kind == StructSoa_None) {
  8395. if (t->Struct.is_raw_union) {
  8396. if (cl->elems.count > 0) {
  8397. // NOTE: unions cannot be constant
  8398. is_constant = false;
  8399. if (cl->elems[0]->kind != Ast_FieldValue) {
  8400. gbString type_str = type_to_string(type);
  8401. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  8402. gb_string_free(type_str);
  8403. } else {
  8404. if (cl->elems.count != 1) {
  8405. gbString type_str = type_to_string(type);
  8406. 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);
  8407. gb_string_free(type_str);
  8408. } else {
  8409. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8410. }
  8411. }
  8412. }
  8413. break;
  8414. }
  8415. wait_signal_until_available(&t->Struct.fields_wait_signal);
  8416. isize field_count = t->Struct.fields.count;
  8417. isize min_field_count = t->Struct.fields.count;
  8418. for (isize i = min_field_count-1; i >= 0; i--) {
  8419. Entity *e = t->Struct.fields[i];
  8420. GB_ASSERT(e->kind == Entity_Variable);
  8421. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  8422. min_field_count--;
  8423. } else {
  8424. break;
  8425. }
  8426. }
  8427. if (cl->elems[0]->kind == Ast_FieldValue) {
  8428. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8429. } else {
  8430. bool seen_field_value = false;
  8431. for_array(index, cl->elems) {
  8432. Entity *field = nullptr;
  8433. Ast *elem = cl->elems[index];
  8434. if (elem->kind == Ast_FieldValue) {
  8435. seen_field_value = true;
  8436. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8437. continue;
  8438. } else if (seen_field_value) {
  8439. error(elem, "Value elements cannot be used after a 'field = value'");
  8440. continue;
  8441. }
  8442. if (index >= field_count) {
  8443. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8444. break;
  8445. }
  8446. if (field == nullptr) {
  8447. field = t->Struct.fields[index];
  8448. }
  8449. Operand o = {};
  8450. check_expr_or_type(c, &o, elem, field->type);
  8451. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8452. is_constant = false;
  8453. }
  8454. if (is_constant) {
  8455. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8456. }
  8457. check_assignment(c, &o, field->type, str_lit("structure literal"));
  8458. }
  8459. if (cl->elems.count < field_count) {
  8460. if (min_field_count < field_count) {
  8461. if (cl->elems.count < min_field_count) {
  8462. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  8463. }
  8464. } else {
  8465. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8466. }
  8467. }
  8468. }
  8469. break;
  8470. } else if (t->Struct.soa_kind != StructSoa_Fixed) {
  8471. error(node, "#soa slices and dynamic arrays are not supported for compound literals");
  8472. break;
  8473. }
  8474. /*fallthrough*/
  8475. case Type_Slice:
  8476. case Type_Array:
  8477. case Type_DynamicArray:
  8478. case Type_SimdVector:
  8479. case Type_Matrix:
  8480. {
  8481. Type *elem_type = nullptr;
  8482. String context_name = {};
  8483. i64 max_type_count = -1;
  8484. if (t->kind == Type_Struct) {
  8485. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8486. elem_type = t->Struct.soa_elem;
  8487. context_name = str_lit("#soa array literal");
  8488. if (!is_to_be_determined_array_count) {
  8489. max_type_count = t->Struct.soa_count;
  8490. }
  8491. } else if (t->kind == Type_Slice) {
  8492. elem_type = t->Slice.elem;
  8493. context_name = str_lit("slice literal");
  8494. } else if (t->kind == Type_Array) {
  8495. elem_type = t->Array.elem;
  8496. context_name = str_lit("array literal");
  8497. if (!is_to_be_determined_array_count) {
  8498. max_type_count = t->Array.count;
  8499. }
  8500. } else if (t->kind == Type_Array) {
  8501. elem_type = t->Array.elem;
  8502. context_name = str_lit("array literal");
  8503. if (!is_to_be_determined_array_count) {
  8504. max_type_count = t->Array.count;
  8505. }
  8506. } else if (t->kind == Type_DynamicArray) {
  8507. elem_type = t->DynamicArray.elem;
  8508. context_name = str_lit("dynamic array literal");
  8509. is_constant = false;
  8510. } else if (t->kind == Type_SimdVector) {
  8511. elem_type = t->SimdVector.elem;
  8512. context_name = str_lit("simd vector literal");
  8513. max_type_count = t->SimdVector.count;
  8514. } else if (t->kind == Type_Matrix) {
  8515. elem_type = t->Matrix.elem;
  8516. context_name = str_lit("matrix literal");
  8517. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  8518. } else {
  8519. GB_PANIC("unreachable");
  8520. }
  8521. i64 max = 0;
  8522. Type *bet = base_type(elem_type);
  8523. if (!elem_type_can_be_constant(bet)) {
  8524. is_constant = false;
  8525. }
  8526. if (bet == t_invalid) {
  8527. break;
  8528. }
  8529. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8530. RangeCache rc = range_cache_make(heap_allocator());
  8531. defer (range_cache_destroy(&rc));
  8532. for (Ast *elem : cl->elems) {
  8533. if (elem->kind != Ast_FieldValue) {
  8534. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8535. continue;
  8536. }
  8537. ast_node(fv, FieldValue, elem);
  8538. if (is_ast_range(fv->field)) {
  8539. Token op = fv->field->BinaryExpr.op;
  8540. Operand x = {};
  8541. Operand y = {};
  8542. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  8543. if (!ok) {
  8544. continue;
  8545. }
  8546. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  8547. error(x.expr, "Expected a constant integer as an array field");
  8548. continue;
  8549. }
  8550. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  8551. error(y.expr, "Expected a constant integer as an array field");
  8552. continue;
  8553. }
  8554. i64 lo = exact_value_to_i64(x.value);
  8555. i64 hi = exact_value_to_i64(y.value);
  8556. i64 max_index = hi;
  8557. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  8558. hi -= 1;
  8559. } else { // .. (inclusive)
  8560. max_index += 1;
  8561. }
  8562. bool new_range = range_cache_add_range(&rc, lo, hi);
  8563. if (!new_range) {
  8564. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  8565. continue;
  8566. }
  8567. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  8568. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  8569. continue;
  8570. }
  8571. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  8572. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  8573. continue;
  8574. }
  8575. if (max < hi) {
  8576. max = max_index;
  8577. }
  8578. Operand operand = {};
  8579. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8580. check_assignment(c, &operand, elem_type, context_name);
  8581. is_constant = is_constant && operand.mode == Addressing_Constant;
  8582. } else {
  8583. Operand op_index = {};
  8584. check_expr(c, &op_index, fv->field);
  8585. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  8586. error(elem, "Expected a constant integer as an array field");
  8587. continue;
  8588. }
  8589. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  8590. i64 index = exact_value_to_i64(op_index.value);
  8591. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  8592. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  8593. continue;
  8594. }
  8595. bool new_index = range_cache_add_index(&rc, index);
  8596. if (!new_index) {
  8597. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  8598. continue;
  8599. }
  8600. if (max < index+1) {
  8601. max = index+1;
  8602. }
  8603. Operand operand = {};
  8604. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8605. check_assignment(c, &operand, elem_type, context_name);
  8606. is_constant = is_constant && operand.mode == Addressing_Constant;
  8607. }
  8608. }
  8609. cl->max_count = max;
  8610. } else {
  8611. isize index = 0;
  8612. for (; index < cl->elems.count; index++) {
  8613. Ast *e = cl->elems[index];
  8614. if (e == nullptr) {
  8615. error(node, "Invalid literal element");
  8616. continue;
  8617. }
  8618. if (e->kind == Ast_FieldValue) {
  8619. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8620. continue;
  8621. }
  8622. if (0 <= max_type_count && max_type_count <= index) {
  8623. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8624. }
  8625. Operand operand = {};
  8626. check_expr_with_type_hint(c, &operand, e, elem_type);
  8627. check_assignment(c, &operand, elem_type, context_name);
  8628. is_constant = is_constant && operand.mode == Addressing_Constant;
  8629. }
  8630. if (max < index) {
  8631. max = index;
  8632. }
  8633. }
  8634. if (t->kind == Type_Array) {
  8635. if (is_to_be_determined_array_count) {
  8636. t->Array.count = max;
  8637. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8638. if (0 < max && max < t->Array.count) {
  8639. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8640. }
  8641. }
  8642. } else if (t->kind == Type_Struct) {
  8643. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8644. if (is_to_be_determined_array_count) {
  8645. t->Struct.soa_count = cast(i32)max;
  8646. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8647. if (0 < max && max < t->Struct.soa_count) {
  8648. error(node, "Expected %lld values for this #soa array literal, got %lld", cast(long long)t->Struct.soa_count, cast(long long)max);
  8649. }
  8650. }
  8651. }
  8652. if (t->kind == Type_SimdVector) {
  8653. if (!is_constant) {
  8654. // error(node, "Expected all constant elements for a simd vector");
  8655. }
  8656. }
  8657. if (t->kind == Type_DynamicArray) {
  8658. if (check_for_dynamic_literals(c, node, cl)) {
  8659. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  8660. add_package_dependency(c, "runtime", "__dynamic_array_append");
  8661. }
  8662. }
  8663. if (t->kind == Type_Matrix) {
  8664. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8665. if (0 < max && max < max_type_count) {
  8666. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  8667. }
  8668. }
  8669. }
  8670. break;
  8671. }
  8672. case Type_EnumeratedArray:
  8673. {
  8674. Type *elem_type = t->EnumeratedArray.elem;
  8675. Type *index_type = t->EnumeratedArray.index;
  8676. String context_name = str_lit("enumerated array literal");
  8677. i64 max_type_count = t->EnumeratedArray.count;
  8678. gbString index_type_str = type_to_string(index_type);
  8679. defer (gb_string_free(index_type_str));
  8680. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  8681. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  8682. String total_lo_string = {};
  8683. String total_hi_string = {};
  8684. GB_ASSERT(is_type_enum(index_type));
  8685. {
  8686. Type *bt = base_type(index_type);
  8687. GB_ASSERT(bt->kind == Type_Enum);
  8688. for (Entity *f : bt->Enum.fields) {
  8689. if (f->kind != Entity_Constant) {
  8690. continue;
  8691. }
  8692. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  8693. total_lo_string = f->token.string;
  8694. }
  8695. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  8696. total_hi_string = f->token.string;
  8697. }
  8698. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8699. break;
  8700. }
  8701. }
  8702. }
  8703. i64 max = 0;
  8704. Type *bet = base_type(elem_type);
  8705. if (!elem_type_can_be_constant(bet)) {
  8706. is_constant = false;
  8707. }
  8708. if (bet == t_invalid) {
  8709. break;
  8710. }
  8711. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8712. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8713. defer (map_destroy(&seen));
  8714. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8715. RangeCache rc = range_cache_make(heap_allocator());
  8716. defer (range_cache_destroy(&rc));
  8717. for (Ast *elem : cl->elems) {
  8718. if (elem->kind != Ast_FieldValue) {
  8719. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8720. continue;
  8721. }
  8722. ast_node(fv, FieldValue, elem);
  8723. if (is_ast_range(fv->field)) {
  8724. Token op = fv->field->BinaryExpr.op;
  8725. Operand x = {};
  8726. Operand y = {};
  8727. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8728. if (!ok) {
  8729. continue;
  8730. }
  8731. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8732. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8733. continue;
  8734. }
  8735. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8736. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8737. continue;
  8738. }
  8739. i64 lo = exact_value_to_i64(x.value);
  8740. i64 hi = exact_value_to_i64(y.value);
  8741. i64 max_index = hi;
  8742. if (op.kind == Token_RangeHalf) {
  8743. hi -= 1;
  8744. }
  8745. bool new_range = range_cache_add_range(&rc, lo, hi);
  8746. if (!new_range) {
  8747. gbString lo_str = expr_to_string(x.expr);
  8748. gbString hi_str = expr_to_string(y.expr);
  8749. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8750. gb_string_free(hi_str);
  8751. gb_string_free(lo_str);
  8752. continue;
  8753. }
  8754. // NOTE(bill): These are sanity checks for invalid enum values
  8755. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8756. gbString lo_str = expr_to_string(x.expr);
  8757. 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));
  8758. gb_string_free(lo_str);
  8759. continue;
  8760. }
  8761. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8762. gbString hi_str = expr_to_string(y.expr);
  8763. 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));
  8764. gb_string_free(hi_str);
  8765. continue;
  8766. }
  8767. if (max < hi) {
  8768. max = max_index;
  8769. }
  8770. Operand operand = {};
  8771. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8772. check_assignment(c, &operand, elem_type, context_name);
  8773. is_constant = is_constant && operand.mode == Addressing_Constant;
  8774. TokenKind upper_op = Token_LtEq;
  8775. if (op.kind == Token_RangeHalf) {
  8776. upper_op = Token_Lt;
  8777. }
  8778. add_to_seen_map(c, &seen, upper_op, x, x, y);
  8779. } else {
  8780. Operand op_index = {};
  8781. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8782. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8783. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8784. continue;
  8785. }
  8786. i64 index = exact_value_to_i64(op_index.value);
  8787. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8788. gbString idx_str = expr_to_string(op_index.expr);
  8789. 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));
  8790. gb_string_free(idx_str);
  8791. continue;
  8792. }
  8793. bool new_index = range_cache_add_index(&rc, index);
  8794. if (!new_index) {
  8795. gbString idx_str = expr_to_string(op_index.expr);
  8796. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8797. gb_string_free(idx_str);
  8798. continue;
  8799. }
  8800. if (max < index+1) {
  8801. max = index+1;
  8802. }
  8803. Operand operand = {};
  8804. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8805. check_assignment(c, &operand, elem_type, context_name);
  8806. is_constant = is_constant && operand.mode == Addressing_Constant;
  8807. add_to_seen_map(c, &seen, op_index);
  8808. }
  8809. }
  8810. cl->max_count = max;
  8811. } else {
  8812. isize index = 0;
  8813. for (; index < cl->elems.count; index++) {
  8814. Ast *e = cl->elems[index];
  8815. if (e == nullptr) {
  8816. error(node, "Invalid literal element");
  8817. continue;
  8818. }
  8819. if (e->kind == Ast_FieldValue) {
  8820. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8821. continue;
  8822. }
  8823. if (0 <= max_type_count && max_type_count <= index) {
  8824. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8825. }
  8826. Operand operand = {};
  8827. check_expr_with_type_hint(c, &operand, e, elem_type);
  8828. check_assignment(c, &operand, elem_type, context_name);
  8829. is_constant = is_constant && operand.mode == Addressing_Constant;
  8830. }
  8831. if (max < index) {
  8832. max = index;
  8833. }
  8834. }
  8835. bool was_error = false;
  8836. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8837. if (0 < max && max < t->EnumeratedArray.count) {
  8838. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  8839. was_error = true;
  8840. } else {
  8841. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  8842. was_error = true;
  8843. }
  8844. }
  8845. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  8846. if (cl->elems.count > 0 && !was_error && !is_partial) {
  8847. TEMPORARY_ALLOCATOR_GUARD();
  8848. Type *et = base_type(index_type);
  8849. GB_ASSERT(et->kind == Type_Enum);
  8850. auto fields = et->Enum.fields;
  8851. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  8852. for (Entity *f : fields) {
  8853. if (f->kind != Entity_Constant) {
  8854. continue;
  8855. }
  8856. ExactValue v = f->Constant.value;
  8857. uintptr hash = hash_exact_value(v);
  8858. auto found = map_get(&seen, hash);
  8859. if (!found) {
  8860. array_add(&unhandled, f);
  8861. }
  8862. }
  8863. if (unhandled.count > 0) {
  8864. ERROR_BLOCK();
  8865. if (unhandled.count == 1) {
  8866. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  8867. } else {
  8868. error(node, "Unhandled enumerated array cases:");
  8869. for_array(i, unhandled) {
  8870. Entity *f = unhandled[i];
  8871. error_line("\t%.*s\n", LIT(f->token.string));
  8872. }
  8873. }
  8874. if (!build_context.terse_errors) {
  8875. error_line("\n");
  8876. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  8877. }
  8878. }
  8879. }
  8880. break;
  8881. }
  8882. case Type_Basic: {
  8883. if (!is_type_any(t)) {
  8884. if (cl->elems.count != 0) {
  8885. gbString s = type_to_string(t);
  8886. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  8887. gb_string_free(s);
  8888. is_constant = false;
  8889. }
  8890. break;
  8891. }
  8892. if (cl->elems.count == 0) {
  8893. break; // NOTE(bill): No need to init
  8894. }
  8895. { // Checker values
  8896. Type *field_types[2] = {t_rawptr, t_typeid};
  8897. isize field_count = 2;
  8898. if (cl->elems[0]->kind == Ast_FieldValue) {
  8899. bool fields_visited[2] = {};
  8900. for_array(i, cl->elems) {
  8901. Ast *elem = cl->elems[i];
  8902. if (elem->kind != Ast_FieldValue) {
  8903. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8904. continue;
  8905. }
  8906. ast_node(fv, FieldValue, elem);
  8907. if (fv->field->kind != Ast_Ident) {
  8908. gbString expr_str = expr_to_string(fv->field);
  8909. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  8910. gb_string_free(expr_str);
  8911. continue;
  8912. }
  8913. String name = fv->field->Ident.token.string;
  8914. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8915. if (sel.entity == nullptr) {
  8916. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  8917. continue;
  8918. }
  8919. isize index = sel.index[0];
  8920. if (fields_visited[index]) {
  8921. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  8922. continue;
  8923. }
  8924. fields_visited[index] = true;
  8925. check_expr(c, o, fv->value);
  8926. // NOTE(bill): 'any' literals can never be constant
  8927. is_constant = false;
  8928. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8929. }
  8930. } else {
  8931. for_array(index, cl->elems) {
  8932. Ast *elem = cl->elems[index];
  8933. if (elem->kind == Ast_FieldValue) {
  8934. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  8935. continue;
  8936. }
  8937. check_expr(c, o, elem);
  8938. if (index >= field_count) {
  8939. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  8940. break;
  8941. }
  8942. // NOTE(bill): 'any' literals can never be constant
  8943. is_constant = false;
  8944. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  8945. }
  8946. if (cl->elems.count < field_count) {
  8947. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  8948. }
  8949. }
  8950. }
  8951. break;
  8952. }
  8953. case Type_Map: {
  8954. if (cl->elems.count == 0) {
  8955. break;
  8956. }
  8957. is_constant = false;
  8958. { // Checker values
  8959. bool key_is_typeid = is_type_typeid(t->Map.key);
  8960. bool value_is_typeid = is_type_typeid(t->Map.value);
  8961. for (Ast *elem : cl->elems) {
  8962. if (elem->kind != Ast_FieldValue) {
  8963. error(elem, "Only 'field = value' elements are allowed in a map literal");
  8964. continue;
  8965. }
  8966. ast_node(fv, FieldValue, elem);
  8967. if (key_is_typeid) {
  8968. check_expr_or_type(c, o, fv->field, t->Map.key);
  8969. } else {
  8970. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  8971. }
  8972. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  8973. if (o->mode == Addressing_Invalid) {
  8974. continue;
  8975. }
  8976. if (value_is_typeid) {
  8977. check_expr_or_type(c, o, fv->value, t->Map.value);
  8978. } else {
  8979. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  8980. }
  8981. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  8982. }
  8983. }
  8984. if (check_for_dynamic_literals(c, node, cl)) {
  8985. add_map_reserve_dependencies(c);
  8986. add_map_set_dependencies(c);
  8987. }
  8988. break;
  8989. }
  8990. case Type_BitSet: {
  8991. if (cl->elems.count == 0) {
  8992. break; // NOTE(bill): No need to init
  8993. }
  8994. Type *et = base_type(t->BitSet.elem);
  8995. isize field_count = 0;
  8996. if (et != nullptr && et->kind == Type_Enum) {
  8997. field_count = et->Enum.fields.count;
  8998. }
  8999. if (is_type_array(bit_set_to_int(t))) {
  9000. is_constant = false;
  9001. }
  9002. if (cl->elems[0]->kind == Ast_FieldValue) {
  9003. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  9004. is_constant = false;
  9005. } else {
  9006. for (Ast *elem : cl->elems) {
  9007. if (elem->kind == Ast_FieldValue) {
  9008. error(elem, "'field = value' in a bit_set a literal is not allowed");
  9009. continue;
  9010. }
  9011. check_expr_with_type_hint(c, o, elem, et);
  9012. if (is_constant) {
  9013. is_constant = o->mode == Addressing_Constant;
  9014. }
  9015. if (elem->kind == Ast_BinaryExpr) {
  9016. switch (elem->BinaryExpr.op.kind) {
  9017. case Token_Or:
  9018. {
  9019. gbString x = expr_to_string(elem->BinaryExpr.left);
  9020. gbString y = expr_to_string(elem->BinaryExpr.right);
  9021. gbString e = expr_to_string(elem);
  9022. error(elem, "Was the following intended? '%s, %s'; if not, surround the expression with parentheses '(%s)'", x, y, e);
  9023. gb_string_free(e);
  9024. gb_string_free(y);
  9025. gb_string_free(x);
  9026. }
  9027. break;
  9028. }
  9029. }
  9030. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  9031. if (o->mode == Addressing_Constant) {
  9032. i64 lower = t->BitSet.lower;
  9033. i64 upper = t->BitSet.upper;
  9034. i64 v = exact_value_to_i64(o->value);
  9035. if (lower <= v && v <= upper) {
  9036. // okay
  9037. } else {
  9038. gbString s = expr_to_string(o->expr);
  9039. error(elem, "Bit field value out of bounds, %s (%lld) not in the range %lld .. %lld", s, v, lower, upper);
  9040. gb_string_free(s);
  9041. continue;
  9042. }
  9043. }
  9044. }
  9045. }
  9046. break;
  9047. }
  9048. case Type_BitField: {
  9049. if (cl->elems.count == 0) {
  9050. break; // NOTE(bill): No need to init
  9051. }
  9052. is_constant = false;
  9053. if (cl->elems[0]->kind != Ast_FieldValue) {
  9054. gbString type_str = type_to_string(type);
  9055. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  9056. gb_string_free(type_str);
  9057. } else {
  9058. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  9059. }
  9060. break;
  9061. }
  9062. default: {
  9063. if (cl->elems.count == 0) {
  9064. break; // NOTE(bill): No need to init
  9065. }
  9066. gbString str = type_to_string(type);
  9067. error(node, "Invalid compound literal type '%s'", str);
  9068. gb_string_free(str);
  9069. return kind;
  9070. }
  9071. }
  9072. if (is_constant) {
  9073. o->mode = Addressing_Constant;
  9074. if (is_type_bit_set(type)) {
  9075. // NOTE(bill): Encode as an integer
  9076. Type *bt = base_type(type);
  9077. BigInt bits = {};
  9078. BigInt one = {};
  9079. big_int_from_u64(&one, 1);
  9080. for (Ast *e : cl->elems) {
  9081. GB_ASSERT(e->kind != Ast_FieldValue);
  9082. TypeAndValue tav = e->tav;
  9083. if (tav.mode != Addressing_Constant) {
  9084. continue;
  9085. }
  9086. if (tav.value.kind != ExactValue_Integer) {
  9087. continue;
  9088. }
  9089. i64 v = big_int_to_i64(&tav.value.value_integer);
  9090. i64 lower = bt->BitSet.lower;
  9091. u64 index = cast(u64)(v-lower);
  9092. BigInt bit = {};
  9093. big_int_from_u64(&bit, index);
  9094. big_int_shl(&bit, &one, &bit);
  9095. big_int_or(&bits, &bits, &bit);
  9096. }
  9097. o->value.kind = ExactValue_Integer;
  9098. o->value.value_integer = bits;
  9099. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  9100. ExactValue value = exact_value_compound(node);
  9101. Type *bt = core_type(type);
  9102. if (bt->kind == Type_Basic) {
  9103. if (bt->Basic.flags & BasicFlag_Boolean) {
  9104. value = exact_value_bool(false);
  9105. } else if (bt->Basic.flags & BasicFlag_Integer) {
  9106. value = exact_value_i64(0);
  9107. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  9108. value = exact_value_i64(0);
  9109. } else if (bt->Basic.flags & BasicFlag_Float) {
  9110. value = exact_value_float(0);
  9111. } else if (bt->Basic.flags & BasicFlag_Complex) {
  9112. value = exact_value_complex(0, 0);
  9113. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  9114. value = exact_value_quaternion(0, 0, 0, 0);
  9115. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  9116. value = exact_value_pointer(0);
  9117. } else if (bt->Basic.flags & BasicFlag_String) {
  9118. String empty_string = {};
  9119. value = exact_value_string(empty_string);
  9120. } else if (bt->Basic.flags & BasicFlag_Rune) {
  9121. value = exact_value_i64(0);
  9122. }
  9123. }
  9124. o->value = value;
  9125. } else {
  9126. o->value = exact_value_compound(node);
  9127. }
  9128. } else {
  9129. o->mode = Addressing_Value;
  9130. }
  9131. o->type = type;
  9132. return kind;
  9133. }
  9134. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9135. ExprKind kind = Expr_Expr;
  9136. ast_node(ta, TypeAssertion, node);
  9137. check_expr(c, o, ta->expr);
  9138. node->viral_state_flags |= ta->expr->viral_state_flags;
  9139. if (o->mode == Addressing_Invalid) {
  9140. o->expr = node;
  9141. return kind;
  9142. }
  9143. if (o->mode == Addressing_Constant) {
  9144. gbString expr_str = expr_to_string(o->expr);
  9145. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  9146. gb_string_free(expr_str);
  9147. o->mode = Addressing_Invalid;
  9148. o->expr = node;
  9149. return kind;
  9150. }
  9151. if (is_type_untyped(o->type)) {
  9152. gbString expr_str = expr_to_string(o->expr);
  9153. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  9154. gb_string_free(expr_str);
  9155. o->mode = Addressing_Invalid;
  9156. o->expr = node;
  9157. return kind;
  9158. }
  9159. Type *src = type_deref(o->type);
  9160. Type *bsrc = base_type(src);
  9161. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  9162. if (!is_type_union(src)) {
  9163. gbString str = type_to_string(o->type);
  9164. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  9165. gb_string_free(str);
  9166. o->mode = Addressing_Invalid;
  9167. o->expr = node;
  9168. return kind;
  9169. }
  9170. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  9171. bool allowed = false;
  9172. for (Type *vt : bsrc->Union.variants) {
  9173. if (are_types_identical(vt, type_hint)) {
  9174. allowed = true;
  9175. add_type_info_type(c, vt);
  9176. break;
  9177. }
  9178. }
  9179. if (allowed) {
  9180. add_type_info_type(c, o->type);
  9181. o->type = type_hint;
  9182. o->mode = Addressing_OptionalOk;
  9183. goto end;
  9184. }
  9185. }
  9186. if (bsrc->Union.variants.count != 1) {
  9187. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  9188. o->mode = Addressing_Invalid;
  9189. o->expr = node;
  9190. return kind;
  9191. }
  9192. add_type_info_type(c, o->type);
  9193. add_type_info_type(c, bsrc->Union.variants[0]);
  9194. o->type = bsrc->Union.variants[0];
  9195. o->mode = Addressing_OptionalOk;
  9196. } else {
  9197. Type *t = check_type(c, ta->type);
  9198. Type *dst = t;
  9199. if (is_type_union(src)) {
  9200. bool ok = false;
  9201. for (Type *vt : bsrc->Union.variants) {
  9202. if (are_types_identical(vt, dst)) {
  9203. ok = true;
  9204. break;
  9205. }
  9206. }
  9207. if (!ok) {
  9208. gbString expr_str = expr_to_string(o->expr);
  9209. gbString dst_type_str = type_to_string(t);
  9210. defer (gb_string_free(expr_str));
  9211. defer (gb_string_free(dst_type_str));
  9212. if (bsrc->Union.variants.count == 0) {
  9213. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  9214. } else {
  9215. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  9216. }
  9217. o->mode = Addressing_Invalid;
  9218. o->expr = node;
  9219. return kind;
  9220. }
  9221. add_type_info_type(c, o->type);
  9222. add_type_info_type(c, t);
  9223. o->type = t;
  9224. o->mode = Addressing_OptionalOk;
  9225. } else if (is_type_any(src)) {
  9226. o->type = t;
  9227. o->mode = Addressing_OptionalOk;
  9228. add_type_info_type(c, o->type);
  9229. add_type_info_type(c, t);
  9230. } else {
  9231. gbString str = type_to_string(o->type);
  9232. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  9233. gb_string_free(str);
  9234. o->mode = Addressing_Invalid;
  9235. o->expr = node;
  9236. return kind;
  9237. }
  9238. }
  9239. end:;
  9240. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  9241. add_package_dependency(c, "runtime", "type_assertion_check");
  9242. add_package_dependency(c, "runtime", "type_assertion_check2");
  9243. }
  9244. return kind;
  9245. }
  9246. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9247. ast_node(se, SelectorCallExpr, node);
  9248. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  9249. // COM APIs is a great example of where this kind of thing is extremely useful
  9250. // General idea:
  9251. //
  9252. // x->y(123) == x.y(x, 123)
  9253. //
  9254. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  9255. // Just regenerating a new AST aids things
  9256. //
  9257. // TODO(bill): Is this a good hack or not?
  9258. //
  9259. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  9260. if (se->modified_call) {
  9261. // Prevent double evaluation
  9262. o->expr = node;
  9263. o->type = node->tav.type;
  9264. o->value = node->tav.value;
  9265. o->mode = node->tav.mode;
  9266. return Expr_Expr;
  9267. }
  9268. bool allow_arrow_right_selector_expr;
  9269. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9270. c->allow_arrow_right_selector_expr = true;
  9271. Operand x = {};
  9272. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  9273. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9274. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  9275. o->mode = Addressing_Invalid;
  9276. o->type = t_invalid;
  9277. o->expr = node;
  9278. return kind;
  9279. }
  9280. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  9281. gbString type_str = type_to_string(x.type);
  9282. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  9283. gb_string_free(type_str);
  9284. o->mode = Addressing_Invalid;
  9285. o->type = t_invalid;
  9286. o->expr = node;
  9287. return Expr_Stmt;
  9288. }
  9289. ast_node(ce, CallExpr, se->call);
  9290. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  9291. Ast *first_arg = x.expr->SelectorExpr.expr;
  9292. GB_ASSERT(first_arg != nullptr);
  9293. Entity *e = entity_of_node(se->expr);
  9294. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  9295. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  9296. }
  9297. if (e->kind != Entity_ProcGroup) {
  9298. Type *pt = base_type(x.type);
  9299. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  9300. Type *first_type = nullptr;
  9301. String first_arg_name = {};
  9302. if (pt->Proc.param_count > 0) {
  9303. Entity *f = pt->Proc.params->Tuple.variables[0];
  9304. first_type = f->type;
  9305. first_arg_name = f->token.string;
  9306. }
  9307. if (first_arg_name.len == 0) {
  9308. first_arg_name = str_lit("_");
  9309. }
  9310. if (first_type == nullptr) {
  9311. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  9312. o->mode = Addressing_Invalid;
  9313. o->type = t_invalid;
  9314. o->expr = node;
  9315. return Expr_Stmt;
  9316. }
  9317. Operand y = {};
  9318. y.mode = first_arg->tav.mode;
  9319. y.type = first_arg->tav.type;
  9320. y.value = first_arg->tav.value;
  9321. if (check_is_assignable_to(c, &y, first_type)) {
  9322. // Do nothing, it's valid
  9323. } else {
  9324. Operand z = y;
  9325. z.type = type_deref(y.type);
  9326. if (check_is_assignable_to(c, &z, first_type)) {
  9327. // NOTE(bill): AST GENERATION HACK!
  9328. Token op = {Token_Pointer};
  9329. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  9330. } else if (y.mode == Addressing_Variable) {
  9331. Operand w = y;
  9332. w.type = alloc_type_pointer(y.type);
  9333. if (check_is_assignable_to(c, &w, first_type)) {
  9334. // NOTE(bill): AST GENERATION HACK!
  9335. Token op = {Token_And};
  9336. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  9337. }
  9338. }
  9339. }
  9340. if (ce->args.count > 0) {
  9341. bool fail = false;
  9342. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  9343. for (Ast *arg : ce->args) {
  9344. bool mix = false;
  9345. if (first_is_field_value) {
  9346. mix = arg->kind != Ast_FieldValue;
  9347. } else {
  9348. mix = arg->kind == Ast_FieldValue;
  9349. }
  9350. if (mix) {
  9351. fail = true;
  9352. break;
  9353. }
  9354. }
  9355. if (!fail && first_is_field_value) {
  9356. Token op = {Token_Eq};
  9357. AstFile *f = first_arg->file();
  9358. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  9359. }
  9360. }
  9361. }
  9362. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  9363. modified_args[0] = first_arg;
  9364. slice_copy(&modified_args, ce->args, 1);
  9365. ce->args = modified_args;
  9366. se->modified_call = true;
  9367. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9368. c->allow_arrow_right_selector_expr = true;
  9369. check_expr_base(c, o, se->call, type_hint);
  9370. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9371. o->expr = node;
  9372. return Expr_Expr;
  9373. }
  9374. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9375. ExprKind kind = Expr_Expr;
  9376. ast_node(ie, IndexExpr, node);
  9377. check_expr(c, o, ie->expr);
  9378. node->viral_state_flags |= ie->expr->viral_state_flags;
  9379. if (o->mode == Addressing_Invalid) {
  9380. o->expr = node;
  9381. return kind;
  9382. }
  9383. Type *t = base_type(type_deref(o->type));
  9384. bool is_ptr = is_type_pointer(o->type);
  9385. bool is_const = o->mode == Addressing_Constant;
  9386. if (is_type_map(t)) {
  9387. Operand key = {};
  9388. if (is_type_typeid(t->Map.key)) {
  9389. check_expr_or_type(c, &key, ie->index, t->Map.key);
  9390. } else {
  9391. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  9392. }
  9393. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  9394. if (key.mode == Addressing_Invalid) {
  9395. o->mode = Addressing_Invalid;
  9396. o->expr = node;
  9397. return kind;
  9398. }
  9399. o->mode = Addressing_MapIndex;
  9400. o->type = t->Map.value;
  9401. o->expr = node;
  9402. add_map_get_dependencies(c);
  9403. add_map_set_dependencies(c);
  9404. return Expr_Expr;
  9405. }
  9406. i64 max_count = -1;
  9407. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  9408. if (is_const) {
  9409. if (is_type_array(t)) {
  9410. // Okay
  9411. } else if (is_type_slice(t)) {
  9412. // Okay
  9413. } else if (is_type_enumerated_array(t)) {
  9414. // Okay
  9415. } else if (is_type_string(t)) {
  9416. // Okay
  9417. } else if (is_type_matrix(t)) {
  9418. // Okay
  9419. } else {
  9420. valid = false;
  9421. }
  9422. }
  9423. if (!valid) {
  9424. gbString str = expr_to_string(o->expr);
  9425. gbString type_str = type_to_string(o->type);
  9426. defer (gb_string_free(str));
  9427. defer (gb_string_free(type_str));
  9428. if (is_const) {
  9429. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  9430. } else {
  9431. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  9432. }
  9433. o->mode = Addressing_Invalid;
  9434. o->expr = node;
  9435. return kind;
  9436. }
  9437. if (ie->index == nullptr) {
  9438. gbString str = expr_to_string(o->expr);
  9439. error(o->expr, "Missing index for '%s'", str);
  9440. gb_string_free(str);
  9441. o->mode = Addressing_Invalid;
  9442. o->expr = node;
  9443. return kind;
  9444. }
  9445. Type *index_type_hint = nullptr;
  9446. if (is_type_enumerated_array(t)) {
  9447. Type *bt = base_type(t);
  9448. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  9449. index_type_hint = bt->EnumeratedArray.index;
  9450. }
  9451. i64 index = 0;
  9452. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  9453. if (is_const) {
  9454. if (index < 0) {
  9455. ERROR_BLOCK();
  9456. gbString str = expr_to_string(o->expr);
  9457. error(o->expr, "Cannot index a constant '%s'", str);
  9458. if (!build_context.terse_errors) {
  9459. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9460. }
  9461. gb_string_free(str);
  9462. o->mode = Addressing_Invalid;
  9463. o->expr = node;
  9464. return kind;
  9465. } else if (ok && !is_type_matrix(t)) {
  9466. TypeAndValue tav = type_and_value_of_expr(ie->expr);
  9467. ExactValue value = tav.value;
  9468. o->mode = Addressing_Constant;
  9469. bool success = false;
  9470. bool finish = false;
  9471. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  9472. if (!success) {
  9473. ERROR_BLOCK();
  9474. gbString str = expr_to_string(o->expr);
  9475. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  9476. if (!build_context.terse_errors) {
  9477. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9478. }
  9479. gb_string_free(str);
  9480. o->mode = Addressing_Invalid;
  9481. o->expr = node;
  9482. return kind;
  9483. }
  9484. }
  9485. }
  9486. if (type_hint != nullptr && is_type_matrix(t)) {
  9487. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  9488. // if a type hint exists
  9489. }
  9490. return kind;
  9491. }
  9492. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9493. ExprKind kind = Expr_Stmt;
  9494. ast_node(se, SliceExpr, node);
  9495. check_expr(c, o, se->expr);
  9496. node->viral_state_flags |= se->expr->viral_state_flags;
  9497. if (o->mode == Addressing_Invalid) {
  9498. o->mode = Addressing_Invalid;
  9499. o->expr = node;
  9500. return kind;
  9501. }
  9502. bool valid = false;
  9503. i64 max_count = -1;
  9504. Type *t = base_type(type_deref(o->type));
  9505. switch (t->kind) {
  9506. case Type_Basic:
  9507. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  9508. valid = true;
  9509. if (o->mode == Addressing_Constant) {
  9510. max_count = o->value.value_string.len;
  9511. }
  9512. o->type = type_deref(o->type);
  9513. }
  9514. break;
  9515. case Type_Array:
  9516. valid = true;
  9517. max_count = t->Array.count;
  9518. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9519. gbString str = expr_to_string(node);
  9520. error(node, "Cannot slice array '%s', value is not addressable", str);
  9521. gb_string_free(str);
  9522. o->mode = Addressing_Invalid;
  9523. o->expr = node;
  9524. return kind;
  9525. }
  9526. o->type = alloc_type_slice(t->Array.elem);
  9527. break;
  9528. case Type_MultiPointer:
  9529. valid = true;
  9530. o->type = type_deref(o->type);
  9531. break;
  9532. case Type_Slice:
  9533. valid = true;
  9534. o->type = type_deref(o->type);
  9535. break;
  9536. case Type_DynamicArray:
  9537. valid = true;
  9538. o->type = alloc_type_slice(t->DynamicArray.elem);
  9539. break;
  9540. case Type_Struct:
  9541. if (is_type_soa_struct(t)) {
  9542. valid = true;
  9543. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9544. max_count = t->Struct.soa_count;
  9545. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9546. gbString str = expr_to_string(node);
  9547. error(node, "Cannot slice #soa array '%s', value is not addressable", str);
  9548. gb_string_free(str);
  9549. o->mode = Addressing_Invalid;
  9550. o->expr = node;
  9551. return kind;
  9552. }
  9553. }
  9554. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  9555. }
  9556. break;
  9557. case Type_EnumeratedArray:
  9558. {
  9559. gbString str = expr_to_string(o->expr);
  9560. gbString type_str = type_to_string(o->type);
  9561. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  9562. gb_string_free(type_str);
  9563. gb_string_free(str);
  9564. o->mode = Addressing_Invalid;
  9565. o->expr = node;
  9566. return kind;
  9567. }
  9568. break;
  9569. }
  9570. if (!valid) {
  9571. gbString str = expr_to_string(o->expr);
  9572. gbString type_str = type_to_string(o->type);
  9573. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  9574. gb_string_free(type_str);
  9575. gb_string_free(str);
  9576. o->mode = Addressing_Invalid;
  9577. o->expr = node;
  9578. return kind;
  9579. }
  9580. if (se->low == nullptr && se->high != nullptr) {
  9581. // It is okay to continue as it will assume the 1st index is zero
  9582. }
  9583. i64 indices[2] = {};
  9584. Ast *nodes[2] = {se->low, se->high};
  9585. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9586. i64 index = max_count;
  9587. if (nodes[i] != nullptr) {
  9588. i64 capacity = -1;
  9589. if (max_count >= 0) {
  9590. capacity = max_count;
  9591. }
  9592. i64 j = 0;
  9593. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  9594. index = j;
  9595. }
  9596. node->viral_state_flags |= nodes[i]->viral_state_flags;
  9597. } else if (i == 0) {
  9598. index = 0;
  9599. }
  9600. indices[i] = index;
  9601. }
  9602. for (isize i = 0; i < gb_count_of(indices); i++) {
  9603. i64 a = indices[i];
  9604. for (isize j = i+1; j < gb_count_of(indices); j++) {
  9605. i64 b = indices[j];
  9606. if (a > b && b >= 0) {
  9607. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  9608. }
  9609. }
  9610. }
  9611. if (max_count < 0) {
  9612. if (o->mode == Addressing_Constant) {
  9613. gbString s = expr_to_string(se->expr);
  9614. error(se->expr, "Cannot slice constant value '%s'", s);
  9615. gb_string_free(s);
  9616. }
  9617. }
  9618. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  9619. /*
  9620. x[:] -> [^]T
  9621. x[i:] -> [^]T
  9622. x[:n] -> []T
  9623. x[i:n] -> []T
  9624. */
  9625. o->type = alloc_type_slice(t->MultiPointer.elem);
  9626. }
  9627. o->mode = Addressing_Value;
  9628. if (is_type_string(t) && max_count >= 0) {
  9629. bool all_constant = true;
  9630. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9631. if (nodes[i] != nullptr) {
  9632. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  9633. if (tav.mode != Addressing_Constant) {
  9634. all_constant = false;
  9635. break;
  9636. }
  9637. }
  9638. }
  9639. if (!all_constant) {
  9640. ERROR_BLOCK();
  9641. gbString str = expr_to_string(o->expr);
  9642. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  9643. if (!build_context.terse_errors) {
  9644. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9645. }
  9646. gb_string_free(str);
  9647. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  9648. o->expr = node;
  9649. return kind;
  9650. }
  9651. String s = {};
  9652. if (o->value.kind == ExactValue_String) {
  9653. s = o->value.value_string;
  9654. }
  9655. o->mode = Addressing_Constant;
  9656. o->type = t;
  9657. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9658. }
  9659. return kind;
  9660. }
  9661. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9662. u32 prev_state_flags = c->state_flags;
  9663. defer (c->state_flags = prev_state_flags);
  9664. if (node->state_flags != 0) {
  9665. u32 in = node->state_flags;
  9666. u32 out = c->state_flags;
  9667. if (in & StateFlag_no_bounds_check) {
  9668. out |= StateFlag_no_bounds_check;
  9669. out &= ~StateFlag_bounds_check;
  9670. } else if (in & StateFlag_bounds_check) {
  9671. out |= StateFlag_bounds_check;
  9672. out &= ~StateFlag_no_bounds_check;
  9673. }
  9674. if (in & StateFlag_no_type_assert) {
  9675. out |= StateFlag_no_type_assert;
  9676. out &= ~StateFlag_type_assert;
  9677. } else if (in & StateFlag_type_assert) {
  9678. out |= StateFlag_type_assert;
  9679. out &= ~StateFlag_no_type_assert;
  9680. }
  9681. c->state_flags = out;
  9682. }
  9683. ExprKind kind = Expr_Stmt;
  9684. o->mode = Addressing_Invalid;
  9685. o->type = t_invalid;
  9686. o->value = {ExactValue_Invalid};
  9687. switch (node->kind) {
  9688. default:
  9689. return kind;
  9690. case_ast_node(be, BadExpr, node)
  9691. return kind;
  9692. case_end;
  9693. case_ast_node(i, Implicit, node);
  9694. switch (i->kind) {
  9695. case Token_context:
  9696. {
  9697. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  9698. error(node, "'context' is only allowed within procedures");
  9699. return kind;
  9700. }
  9701. if (unparen_expr(c->assignment_lhs_hint) == node) {
  9702. c->scope->flags |= ScopeFlag_ContextDefined;
  9703. }
  9704. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  9705. error(node, "'context' has not been defined within this scope");
  9706. // Continue with value
  9707. }
  9708. init_core_context(c->checker);
  9709. o->mode = Addressing_Context;
  9710. o->type = t_context;
  9711. }
  9712. break;
  9713. default:
  9714. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  9715. return kind;
  9716. }
  9717. case_end;
  9718. case_ast_node(i, Ident, node);
  9719. check_ident(c, o, node, nullptr, type_hint, false);
  9720. case_end;
  9721. case_ast_node(u, Uninit, node);
  9722. o->mode = Addressing_Value;
  9723. o->type = t_untyped_uninit;
  9724. error(node, "Global variables will always be zeroed if left unassigned, --- is disallowed");
  9725. case_end;
  9726. case_ast_node(bl, BasicLit, node);
  9727. Type *t = t_invalid;
  9728. switch (node->tav.value.kind) {
  9729. case ExactValue_String: t = t_untyped_string; break;
  9730. case ExactValue_Float: t = t_untyped_float; break;
  9731. case ExactValue_Complex: t = t_untyped_complex; break;
  9732. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  9733. case ExactValue_Integer:
  9734. t = t_untyped_integer;
  9735. if (bl->token.kind == Token_Rune) {
  9736. t = t_untyped_rune;
  9737. }
  9738. break;
  9739. default:
  9740. GB_PANIC("Unhandled value type for basic literal");
  9741. break;
  9742. }
  9743. o->mode = Addressing_Constant;
  9744. o->type = t;
  9745. o->value = node->tav.value;
  9746. case_end;
  9747. case_ast_node(bd, BasicDirective, node);
  9748. kind = check_basic_directive_expr(c, o, node, type_hint);
  9749. case_end;
  9750. case_ast_node(pg, ProcGroup, node);
  9751. error(node, "Illegal use of a procedure group");
  9752. o->mode = Addressing_Invalid;
  9753. case_end;
  9754. case_ast_node(pl, ProcLit, node);
  9755. CheckerContext ctx = *c;
  9756. DeclInfo *decl = nullptr;
  9757. Type *type = alloc_type(Type_Proc);
  9758. check_open_scope(&ctx, pl->type);
  9759. {
  9760. decl = make_decl_info(ctx.scope, ctx.decl);
  9761. decl->proc_lit = node;
  9762. ctx.decl = decl;
  9763. defer (ctx.decl = ctx.decl->parent);
  9764. if (pl->tags != 0) {
  9765. error(node, "A procedure literal cannot have tags");
  9766. pl->tags = 0; // TODO(bill): Should I zero this?!
  9767. }
  9768. check_procedure_type(&ctx, type, pl->type);
  9769. if (!is_type_proc(type)) {
  9770. gbString str = expr_to_string(node);
  9771. error(node, "Invalid procedure literal '%s'", str);
  9772. gb_string_free(str);
  9773. check_close_scope(&ctx);
  9774. return kind;
  9775. }
  9776. if (pl->body == nullptr) {
  9777. error(node, "A procedure literal must have a body");
  9778. return kind;
  9779. }
  9780. pl->decl = decl;
  9781. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  9782. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  9783. array_add(&ctx.checker->nested_proc_lits, decl);
  9784. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  9785. }
  9786. check_close_scope(&ctx);
  9787. o->mode = Addressing_Value;
  9788. o->type = type;
  9789. case_end;
  9790. case_ast_node(te, TernaryIfExpr, node);
  9791. kind = check_ternary_if_expr(c, o, node, type_hint);
  9792. case_end;
  9793. case_ast_node(te, TernaryWhenExpr, node);
  9794. kind = check_ternary_when_expr(c, o, node, type_hint);
  9795. case_end;
  9796. case_ast_node(oe, OrElseExpr, node);
  9797. return check_or_else_expr(c, o, node, type_hint);
  9798. case_end;
  9799. case_ast_node(re, OrReturnExpr, node);
  9800. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  9801. return check_or_return_expr(c, o, node, type_hint);
  9802. case_end;
  9803. case_ast_node(re, OrBranchExpr, node);
  9804. return check_or_branch_expr(c, o, node, type_hint);
  9805. case_end;
  9806. case_ast_node(cl, CompoundLit, node);
  9807. kind = check_compound_literal(c, o, node, type_hint);
  9808. case_end;
  9809. case_ast_node(pe, ParenExpr, node);
  9810. kind = check_expr_base(c, o, pe->expr, type_hint);
  9811. node->viral_state_flags |= pe->expr->viral_state_flags;
  9812. o->expr = node;
  9813. case_end;
  9814. case_ast_node(te, TagExpr, node);
  9815. String name = te->name.string;
  9816. error(node, "Unknown tag expression, #%.*s", LIT(name));
  9817. if (te->expr) {
  9818. kind = check_expr_base(c, o, te->expr, type_hint);
  9819. node->viral_state_flags |= te->expr->viral_state_flags;
  9820. }
  9821. o->expr = node;
  9822. case_end;
  9823. case_ast_node(ta, TypeAssertion, node);
  9824. kind = check_type_assertion(c, o, node, type_hint);
  9825. case_end;
  9826. case_ast_node(tc, TypeCast, node);
  9827. check_expr_or_type(c, o, tc->type);
  9828. if (o->mode != Addressing_Type) {
  9829. gbString str = expr_to_string(tc->type);
  9830. error(tc->type, "Expected a type, got %s", str);
  9831. gb_string_free(str);
  9832. o->mode = Addressing_Invalid;
  9833. }
  9834. if (o->mode == Addressing_Invalid) {
  9835. o->expr = node;
  9836. return kind;
  9837. }
  9838. Type *type = o->type;
  9839. check_expr_base(c, o, tc->expr, type);
  9840. node->viral_state_flags |= tc->expr->viral_state_flags;
  9841. if (o->mode != Addressing_Invalid) {
  9842. switch (tc->token.kind) {
  9843. case Token_transmute:
  9844. check_transmute(c, node, o, type, true);
  9845. break;
  9846. case Token_cast:
  9847. check_cast(c, o, type, true);
  9848. break;
  9849. default:
  9850. error(node, "Invalid AST: Invalid casting expression");
  9851. o->mode = Addressing_Invalid;
  9852. break;
  9853. }
  9854. }
  9855. return Expr_Expr;
  9856. case_end;
  9857. case_ast_node(ac, AutoCast, node);
  9858. check_expr_base(c, o, ac->expr, type_hint);
  9859. node->viral_state_flags |= ac->expr->viral_state_flags;
  9860. if (o->mode == Addressing_Invalid) {
  9861. o->expr = node;
  9862. return kind;
  9863. }
  9864. if (type_hint) {
  9865. check_cast(c, o, type_hint);
  9866. }
  9867. o->expr = node;
  9868. return Expr_Expr;
  9869. case_end;
  9870. case_ast_node(ue, UnaryExpr, node);
  9871. Type *th = type_hint;
  9872. if (ue->op.kind == Token_And) {
  9873. th = type_deref(th);
  9874. }
  9875. check_expr_base(c, o, ue->expr, th);
  9876. node->viral_state_flags |= ue->expr->viral_state_flags;
  9877. if (o->mode != Addressing_Invalid) {
  9878. check_unary_expr(c, o, ue->op, node);
  9879. }
  9880. o->expr = node;
  9881. return Expr_Expr;
  9882. case_end;
  9883. case_ast_node(be, BinaryExpr, node);
  9884. check_binary_expr(c, o, node, type_hint, true);
  9885. if (o->mode == Addressing_Invalid) {
  9886. o->expr = node;
  9887. return kind;
  9888. }
  9889. case_end;
  9890. case_ast_node(se, SelectorExpr, node);
  9891. check_selector(c, o, node, type_hint);
  9892. node->viral_state_flags |= se->expr->viral_state_flags;
  9893. case_end;
  9894. case_ast_node(se, SelectorCallExpr, node);
  9895. return check_selector_call_expr(c, o, node, type_hint);
  9896. case_end;
  9897. case_ast_node(ise, ImplicitSelectorExpr, node);
  9898. return check_implicit_selector_expr(c, o, node, type_hint);
  9899. case_end;
  9900. case_ast_node(ie, IndexExpr, node);
  9901. kind = check_index_expr(c, o, node, type_hint);
  9902. case_end;
  9903. case_ast_node(se, SliceExpr, node);
  9904. kind = check_slice_expr(c, o, node, type_hint);
  9905. case_end;
  9906. case_ast_node(mie, MatrixIndexExpr, node);
  9907. check_matrix_index_expr(c, o, node, type_hint);
  9908. o->expr = node;
  9909. return Expr_Expr;
  9910. case_end;
  9911. case_ast_node(ce, CallExpr, node);
  9912. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  9913. case_end;
  9914. case_ast_node(de, DerefExpr, node);
  9915. check_expr_or_type(c, o, de->expr);
  9916. node->viral_state_flags |= de->expr->viral_state_flags;
  9917. if (o->mode == Addressing_Invalid) {
  9918. o->mode = Addressing_Invalid;
  9919. o->expr = node;
  9920. return kind;
  9921. } else if (o->mode == Addressing_Type) {
  9922. gbString str = expr_to_string(o->expr);
  9923. error(o->expr, "Cannot dereference '%s' because it is a type", str);
  9924. o->mode = Addressing_Invalid;
  9925. o->expr = node;
  9926. return kind;
  9927. } else {
  9928. Type *t = base_type(o->type);
  9929. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  9930. o->mode = Addressing_Variable;
  9931. o->type = t->Pointer.elem;
  9932. } else if (t->kind == Type_SoaPointer) {
  9933. o->mode = Addressing_SoaVariable;
  9934. o->type = type_deref(t);
  9935. } else {
  9936. gbString str = expr_to_string(o->expr);
  9937. gbString typ = type_to_string(o->type);
  9938. ERROR_BLOCK();
  9939. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  9940. if (o->type && is_type_multi_pointer(o->type)) {
  9941. if (!build_context.terse_errors) {
  9942. error_line("\tDid you mean '%s[0]'?\n", str);
  9943. }
  9944. }
  9945. gb_string_free(typ);
  9946. gb_string_free(str);
  9947. o->mode = Addressing_Invalid;
  9948. o->expr = node;
  9949. return kind;
  9950. }
  9951. }
  9952. case_end;
  9953. case_ast_node(ia, InlineAsmExpr, node);
  9954. if (c->curr_proc_decl == nullptr) {
  9955. error(node, "Inline asm expressions are only allowed within a procedure body");
  9956. }
  9957. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  9958. Type *return_type = nullptr;
  9959. for_array(i, ia->param_types) {
  9960. param_types[i] = check_type(c, ia->param_types[i]);
  9961. }
  9962. if (ia->return_type != nullptr) {
  9963. return_type = check_type(c, ia->return_type);
  9964. }
  9965. Operand x = {};
  9966. check_expr(c, &x, ia->asm_string);
  9967. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9968. error(x.expr, "Expected a constant string for the inline asm main parameter");
  9969. }
  9970. check_expr(c, &x, ia->constraints_string);
  9971. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  9972. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  9973. }
  9974. Scope *scope = create_scope(c->info, c->scope);
  9975. scope->flags |= ScopeFlag_Proc;
  9976. Type *params = alloc_type_tuple();
  9977. Type *results = alloc_type_tuple();
  9978. if (param_types.count != 0) {
  9979. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  9980. for_array(i, param_types) {
  9981. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  9982. }
  9983. }
  9984. if (return_type != nullptr) {
  9985. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  9986. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  9987. }
  9988. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  9989. o->type = pt;
  9990. o->mode = Addressing_Value;
  9991. o->expr = node;
  9992. return Expr_Expr;
  9993. case_end;
  9994. case Ast_DistinctType:
  9995. case Ast_TypeidType:
  9996. case Ast_PolyType:
  9997. case Ast_ProcType:
  9998. case Ast_PointerType:
  9999. case Ast_MultiPointerType:
  10000. case Ast_ArrayType:
  10001. case Ast_DynamicArrayType:
  10002. case Ast_StructType:
  10003. case Ast_UnionType:
  10004. case Ast_EnumType:
  10005. case Ast_MapType:
  10006. case Ast_BitSetType:
  10007. case Ast_MatrixType:
  10008. case Ast_RelativeType:
  10009. o->mode = Addressing_Type;
  10010. o->type = check_type(c, node);
  10011. break;
  10012. }
  10013. kind = Expr_Expr;
  10014. o->expr = node;
  10015. return kind;
  10016. }
  10017. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  10018. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  10019. if (o->type != nullptr && core_type(o->type) == nullptr) {
  10020. o->type = t_invalid;
  10021. gbString xs = expr_to_string(o->expr);
  10022. if (o->mode == Addressing_Type) {
  10023. error(o->expr, "Invalid type usage '%s'", xs);
  10024. } else {
  10025. error(o->expr, "Invalid expression '%s'", xs);
  10026. }
  10027. gb_string_free(xs);
  10028. }
  10029. if (o->type != nullptr && is_type_untyped(o->type)) {
  10030. add_untyped(c, node, o->mode, o->type, o->value);
  10031. }
  10032. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  10033. add_type_and_value(c, node, o->mode, o->type, o->value);
  10034. return kind;
  10035. }
  10036. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  10037. check_expr_base(c, o, e, nullptr);
  10038. switch (o->mode) {
  10039. default:
  10040. return; // NOTE(bill): Valid
  10041. case Addressing_NoValue:
  10042. error_operand_no_value(o);
  10043. break;
  10044. }
  10045. o->mode = Addressing_Invalid;
  10046. }
  10047. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  10048. check_expr_base(c, o, e, nullptr);
  10049. switch (o->mode) {
  10050. default:
  10051. return; // NOTE(bill): Valid
  10052. case Addressing_NoValue:
  10053. error_operand_no_value(o);
  10054. break;
  10055. case Addressing_Type:
  10056. error_operand_not_expression(o);
  10057. break;
  10058. }
  10059. o->mode = Addressing_Invalid;
  10060. }
  10061. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10062. check_expr_base(c, o, e, type_hint);
  10063. switch (o->mode) {
  10064. default:
  10065. return; // NOTE(bill): Valid
  10066. case Addressing_NoValue:
  10067. error_operand_no_value(o);
  10068. break;
  10069. case Addressing_Type:
  10070. error_operand_not_expression(o);
  10071. break;
  10072. }
  10073. o->mode = Addressing_Invalid;
  10074. }
  10075. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  10076. if (o->mode == Addressing_Value) {
  10077. // NOTE(bill): Tuples are not first class thus never named
  10078. if (o->type->kind == Type_Tuple) {
  10079. isize count = o->type->Tuple.variables.count;
  10080. error(o->expr,
  10081. "%td-valued expression found where single value expected", count);
  10082. o->mode = Addressing_Invalid;
  10083. GB_ASSERT(count != 1);
  10084. }
  10085. }
  10086. }
  10087. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  10088. check_multi_expr(c, o, e);
  10089. check_not_tuple(c, o);
  10090. }
  10091. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10092. check_expr_base(c, o, e, type_hint);
  10093. check_not_tuple(c, o);
  10094. error_operand_no_value(o);
  10095. }
  10096. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  10097. switch (v.kind) {
  10098. case ExactValue_Invalid:
  10099. return true;
  10100. case ExactValue_Bool:
  10101. return !v.value_bool;
  10102. case ExactValue_String:
  10103. return v.value_string.len == 0;
  10104. case ExactValue_Integer:
  10105. return big_int_is_zero(&v.value_integer);
  10106. case ExactValue_Float:
  10107. return v.value_float == 0.0;
  10108. case ExactValue_Complex:
  10109. if (v.value_complex) {
  10110. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  10111. }
  10112. return true;
  10113. case ExactValue_Quaternion:
  10114. if (v.value_quaternion) {
  10115. return v.value_quaternion->real == 0.0 &&
  10116. v.value_quaternion->imag == 0.0 &&
  10117. v.value_quaternion->jmag == 0.0 &&
  10118. v.value_quaternion->kmag == 0.0;
  10119. }
  10120. return true;
  10121. case ExactValue_Pointer:
  10122. return v.value_pointer == 0;
  10123. case ExactValue_Compound:
  10124. if (v.value_compound == nullptr) {
  10125. return true;
  10126. } else {
  10127. ast_node(cl, CompoundLit, v.value_compound);
  10128. if (cl->elems.count == 0) {
  10129. return true;
  10130. } else {
  10131. for (Ast *elem : cl->elems) {
  10132. if (elem->tav.mode != Addressing_Constant) {
  10133. return false;
  10134. }
  10135. if (!is_exact_value_zero(elem->tav.value)) {
  10136. return false;
  10137. }
  10138. }
  10139. return true;
  10140. }
  10141. }
  10142. case ExactValue_Procedure:
  10143. return v.value_procedure == nullptr;
  10144. case ExactValue_Typeid:
  10145. return v.value_typeid == nullptr;
  10146. }
  10147. return true;
  10148. }
  10149. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  10150. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  10151. for_array(i, params) {
  10152. if (i > 0) {
  10153. str = gb_string_appendc(str, ", ");
  10154. }
  10155. str = write_expr_to_string(str, params[i], false);
  10156. }
  10157. return str;
  10158. }
  10159. gb_internal gbString string_append_string(gbString str, String string) {
  10160. if (string.len > 0) {
  10161. return gb_string_append_length(str, &string[0], string.len);
  10162. }
  10163. return str;
  10164. }
  10165. gb_internal gbString string_append_token(gbString str, Token token) {
  10166. str = string_append_string(str, token.string);
  10167. return str;
  10168. }
  10169. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  10170. if (node == nullptr)
  10171. return str;
  10172. if (is_ast_stmt(node)) {
  10173. GB_ASSERT("stmt passed to write_expr_to_string");
  10174. }
  10175. switch (node->kind) {
  10176. default:
  10177. str = gb_string_appendc(str, "(BadExpr)");
  10178. break;
  10179. case_ast_node(i, Ident, node);
  10180. str = string_append_token(str, i->token);
  10181. case_end;
  10182. case_ast_node(i, Implicit, node);
  10183. str = string_append_token(str, *i);
  10184. case_end;
  10185. case_ast_node(bl, BasicLit, node);
  10186. str = string_append_token(str, bl->token);
  10187. case_end;
  10188. case_ast_node(bd, BasicDirective, node);
  10189. str = gb_string_append_rune(str, '#');
  10190. str = string_append_string(str, bd->name.string);
  10191. case_end;
  10192. case_ast_node(ud, Uninit, node);
  10193. str = gb_string_appendc(str, "---");
  10194. case_end;
  10195. case_ast_node(pg, ProcGroup, node);
  10196. str = gb_string_appendc(str, "proc{");
  10197. for_array(i, pg->args) {
  10198. if (i > 0) str = gb_string_appendc(str, ", ");
  10199. str = write_expr_to_string(str, pg->args[i], shorthand);
  10200. }
  10201. str = gb_string_append_rune(str, '}');
  10202. case_end;
  10203. case_ast_node(pl, ProcLit, node);
  10204. str = write_expr_to_string(str, pl->type, shorthand);
  10205. if (pl->body) {
  10206. str = gb_string_appendc(str, " {...}");
  10207. } else {
  10208. str = gb_string_appendc(str, " ---");
  10209. }
  10210. case_end;
  10211. case_ast_node(cl, CompoundLit, node);
  10212. str = write_expr_to_string(str, cl->type, shorthand);
  10213. str = gb_string_append_rune(str, '{');
  10214. if (shorthand) {
  10215. str = gb_string_appendc(str, "...");
  10216. } else {
  10217. for_array(i, cl->elems) {
  10218. if (i > 0) str = gb_string_appendc(str, ", ");
  10219. str = write_expr_to_string(str, cl->elems[i], shorthand);
  10220. }
  10221. }
  10222. str = gb_string_append_rune(str, '}');
  10223. case_end;
  10224. case_ast_node(te, TagExpr, node);
  10225. str = gb_string_append_rune(str, '#');
  10226. str = string_append_token(str, te->name);
  10227. str = write_expr_to_string(str, te->expr, shorthand);
  10228. case_end;
  10229. case_ast_node(ue, UnaryExpr, node);
  10230. str = string_append_token(str, ue->op);
  10231. str = write_expr_to_string(str, ue->expr, shorthand);
  10232. case_end;
  10233. case_ast_node(de, DerefExpr, node);
  10234. str = write_expr_to_string(str, de->expr, shorthand);
  10235. str = gb_string_append_rune(str, '^');
  10236. case_end;
  10237. case_ast_node(be, BinaryExpr, node);
  10238. str = write_expr_to_string(str, be->left, shorthand);
  10239. str = gb_string_append_rune(str, ' ');
  10240. str = string_append_token(str, be->op);
  10241. str = gb_string_append_rune(str, ' ');
  10242. str = write_expr_to_string(str, be->right, shorthand);
  10243. case_end;
  10244. case_ast_node(te, TernaryIfExpr, node);
  10245. TokenPos x = ast_token(te->x).pos;
  10246. TokenPos cond = ast_token(te->cond).pos;
  10247. if (x < cond) {
  10248. str = write_expr_to_string(str, te->x, shorthand);
  10249. str = gb_string_appendc(str, " if ");
  10250. str = write_expr_to_string(str, te->cond, shorthand);
  10251. str = gb_string_appendc(str, " else ");
  10252. str = write_expr_to_string(str, te->y, shorthand);
  10253. } else {
  10254. str = write_expr_to_string(str, te->cond, shorthand);
  10255. str = gb_string_appendc(str, " ? ");
  10256. str = write_expr_to_string(str, te->x, shorthand);
  10257. str = gb_string_appendc(str, " : ");
  10258. str = write_expr_to_string(str, te->y, shorthand);
  10259. }
  10260. case_end;
  10261. case_ast_node(te, TernaryWhenExpr, node);
  10262. str = write_expr_to_string(str, te->x, shorthand);
  10263. str = gb_string_appendc(str, " when ");
  10264. str = write_expr_to_string(str, te->cond, shorthand);
  10265. str = gb_string_appendc(str, " else ");
  10266. str = write_expr_to_string(str, te->y, shorthand);
  10267. case_end;
  10268. case_ast_node(oe, OrElseExpr, node);
  10269. str = write_expr_to_string(str, oe->x, shorthand);
  10270. str = gb_string_appendc(str, " or_else ");
  10271. str = write_expr_to_string(str, oe->y, shorthand);
  10272. case_end;
  10273. case_ast_node(oe, OrReturnExpr, node);
  10274. str = write_expr_to_string(str, oe->expr, shorthand);
  10275. str = gb_string_appendc(str, " or_return");
  10276. case_end;
  10277. case_ast_node(oe, OrBranchExpr, node);
  10278. str = write_expr_to_string(str, oe->expr, shorthand);
  10279. str = gb_string_append_rune(str, ' ');
  10280. str = string_append_token(str, oe->token);
  10281. if (oe->label) {
  10282. str = gb_string_append_rune(str, ' ');
  10283. str = write_expr_to_string(str, oe->label, shorthand);
  10284. }
  10285. case_end;
  10286. case_ast_node(pe, ParenExpr, node);
  10287. str = gb_string_append_rune(str, '(');
  10288. str = write_expr_to_string(str, pe->expr, shorthand);
  10289. str = gb_string_append_rune(str, ')');
  10290. case_end;
  10291. case_ast_node(se, SelectorExpr, node);
  10292. str = write_expr_to_string(str, se->expr, shorthand);
  10293. str = string_append_token(str, se->token);
  10294. str = write_expr_to_string(str, se->selector, shorthand);
  10295. case_end;
  10296. case_ast_node(se, ImplicitSelectorExpr, node);
  10297. str = gb_string_append_rune(str, '.');
  10298. str = write_expr_to_string(str, se->selector, shorthand);
  10299. case_end;
  10300. case_ast_node(se, SelectorCallExpr, node);
  10301. str = write_expr_to_string(str, se->expr, shorthand);
  10302. str = gb_string_appendc(str, "(");
  10303. ast_node(ce, CallExpr, se->call);
  10304. isize start = se->modified_call ? 1 : 0;
  10305. for (isize i = start; i < ce->args.count; i++) {
  10306. Ast *arg = ce->args[i];
  10307. if (i > start) {
  10308. str = gb_string_appendc(str, ", ");
  10309. }
  10310. str = write_expr_to_string(str, arg, shorthand);
  10311. }
  10312. str = gb_string_appendc(str, ")");
  10313. case_end;
  10314. case_ast_node(ta, TypeAssertion, node);
  10315. str = write_expr_to_string(str, ta->expr, shorthand);
  10316. if (ta->type != nullptr &&
  10317. ta->type->kind == Ast_UnaryExpr &&
  10318. ta->type->UnaryExpr.op.kind == Token_Question) {
  10319. str = gb_string_appendc(str, ".?");
  10320. } else {
  10321. str = gb_string_appendc(str, ".(");
  10322. str = write_expr_to_string(str, ta->type, shorthand);
  10323. str = gb_string_append_rune(str, ')');
  10324. }
  10325. case_end;
  10326. case_ast_node(tc, TypeCast, node);
  10327. str = string_append_token(str, tc->token);
  10328. str = gb_string_append_rune(str, '(');
  10329. str = write_expr_to_string(str, tc->type, shorthand);
  10330. str = gb_string_append_rune(str, ')');
  10331. str = write_expr_to_string(str, tc->expr, shorthand);
  10332. case_end;
  10333. case_ast_node(ac, AutoCast, node);
  10334. str = string_append_token(str, ac->token);
  10335. str = gb_string_append_rune(str, ' ');
  10336. str = write_expr_to_string(str, ac->expr, shorthand);
  10337. case_end;
  10338. case_ast_node(ie, IndexExpr, node);
  10339. str = write_expr_to_string(str, ie->expr, shorthand);
  10340. str = gb_string_append_rune(str, '[');
  10341. str = write_expr_to_string(str, ie->index, shorthand);
  10342. str = gb_string_append_rune(str, ']');
  10343. case_end;
  10344. case_ast_node(se, SliceExpr, node);
  10345. str = write_expr_to_string(str, se->expr, shorthand);
  10346. str = gb_string_append_rune(str, '[');
  10347. str = write_expr_to_string(str, se->low, shorthand);
  10348. str = string_append_token(str, se->interval);
  10349. str = write_expr_to_string(str, se->high, shorthand);
  10350. str = gb_string_append_rune(str, ']');
  10351. case_end;
  10352. case_ast_node(mie, MatrixIndexExpr, node);
  10353. str = write_expr_to_string(str, mie->expr, shorthand);
  10354. str = gb_string_append_rune(str, '[');
  10355. str = write_expr_to_string(str, mie->row_index, shorthand);
  10356. str = gb_string_appendc(str, ", ");
  10357. str = write_expr_to_string(str, mie->column_index, shorthand);
  10358. str = gb_string_append_rune(str, ']');
  10359. case_end;
  10360. case_ast_node(e, Ellipsis, node);
  10361. str = gb_string_appendc(str, "..");
  10362. str = write_expr_to_string(str, e->expr, shorthand);
  10363. case_end;
  10364. case_ast_node(fv, FieldValue, node);
  10365. str = write_expr_to_string(str, fv->field, shorthand);
  10366. str = gb_string_appendc(str, " = ");
  10367. str = write_expr_to_string(str, fv->value, shorthand);
  10368. case_end;
  10369. case_ast_node(fv, EnumFieldValue, node);
  10370. str = write_expr_to_string(str, fv->name, shorthand);
  10371. if (fv->value) {
  10372. str = gb_string_appendc(str, " = ");
  10373. str = write_expr_to_string(str, fv->value, shorthand);
  10374. }
  10375. case_end;
  10376. case_ast_node(ht, HelperType, node);
  10377. str = gb_string_appendc(str, "#type ");
  10378. str = write_expr_to_string(str, ht->type, shorthand);
  10379. case_end;
  10380. case_ast_node(ht, DistinctType, node);
  10381. str = gb_string_appendc(str, "distinct ");
  10382. str = write_expr_to_string(str, ht->type, shorthand);
  10383. case_end;
  10384. case_ast_node(pt, PolyType, node);
  10385. str = gb_string_append_rune(str, '$');
  10386. str = write_expr_to_string(str, pt->type, shorthand);
  10387. if (pt->specialization != nullptr) {
  10388. str = gb_string_append_rune(str, '/');
  10389. str = write_expr_to_string(str, pt->specialization, shorthand);
  10390. }
  10391. case_end;
  10392. case_ast_node(pt, PointerType, node);
  10393. if (pt->tag) {
  10394. str = write_expr_to_string(str, pt->tag, false);
  10395. }
  10396. str = gb_string_append_rune(str, '^');
  10397. str = write_expr_to_string(str, pt->type, shorthand);
  10398. case_end;
  10399. case_ast_node(pt, MultiPointerType, node);
  10400. str = gb_string_appendc(str, "[^]");
  10401. str = write_expr_to_string(str, pt->type, shorthand);
  10402. case_end;
  10403. case_ast_node(at, ArrayType, node);
  10404. if (at->tag) {
  10405. str = write_expr_to_string(str, at->tag, false);
  10406. }
  10407. str = gb_string_append_rune(str, '[');
  10408. if (at->count != nullptr &&
  10409. at->count->kind == Ast_UnaryExpr &&
  10410. at->count->UnaryExpr.op.kind == Token_Question) {
  10411. str = gb_string_appendc(str, "?");
  10412. } else {
  10413. str = write_expr_to_string(str, at->count, shorthand);
  10414. }
  10415. str = gb_string_append_rune(str, ']');
  10416. str = write_expr_to_string(str, at->elem, shorthand);
  10417. case_end;
  10418. case_ast_node(at, DynamicArrayType, node);
  10419. if (at->tag) {
  10420. str = write_expr_to_string(str, at->tag, false);
  10421. }
  10422. str = gb_string_appendc(str, "[dynamic]");
  10423. str = write_expr_to_string(str, at->elem, shorthand);
  10424. case_end;
  10425. case_ast_node(bs, BitSetType, node);
  10426. str = gb_string_appendc(str, "bit_set[");
  10427. str = write_expr_to_string(str, bs->elem, shorthand);
  10428. str = gb_string_appendc(str, "]");
  10429. case_end;
  10430. case_ast_node(mt, MapType, node);
  10431. str = gb_string_appendc(str, "map[");
  10432. str = write_expr_to_string(str, mt->key, shorthand);
  10433. str = gb_string_append_rune(str, ']');
  10434. str = write_expr_to_string(str, mt->value, shorthand);
  10435. case_end;
  10436. case_ast_node(mt, MatrixType, node);
  10437. str = gb_string_appendc(str, "matrix[");
  10438. str = write_expr_to_string(str, mt->row_count, shorthand);
  10439. str = gb_string_appendc(str, ", ");
  10440. str = write_expr_to_string(str, mt->column_count, shorthand);
  10441. str = gb_string_append_rune(str, ']');
  10442. str = write_expr_to_string(str, mt->elem, shorthand);
  10443. case_end;
  10444. case_ast_node(f, Field, node);
  10445. if (f->flags&FieldFlag_using) {
  10446. str = gb_string_appendc(str, "using ");
  10447. }
  10448. if (f->flags&FieldFlag_no_alias) {
  10449. str = gb_string_appendc(str, "#no_alias ");
  10450. }
  10451. if (f->flags&FieldFlag_c_vararg) {
  10452. str = gb_string_appendc(str, "#c_vararg ");
  10453. }
  10454. if (f->flags&FieldFlag_any_int) {
  10455. str = gb_string_appendc(str, "#any_int ");
  10456. }
  10457. if (f->flags&FieldFlag_no_broadcast) {
  10458. str = gb_string_appendc(str, "#no_broadcast ");
  10459. }
  10460. if (f->flags&FieldFlag_const) {
  10461. str = gb_string_appendc(str, "#const ");
  10462. }
  10463. if (f->flags&FieldFlag_subtype) {
  10464. str = gb_string_appendc(str, "#subtype ");
  10465. }
  10466. for_array(i, f->names) {
  10467. Ast *name = f->names[i];
  10468. if (i > 0) str = gb_string_appendc(str, ", ");
  10469. str = write_expr_to_string(str, name, shorthand);
  10470. }
  10471. if (f->names.count > 0) {
  10472. if (f->type == nullptr && f->default_value != nullptr) {
  10473. str = gb_string_append_rune(str, ' ');
  10474. }
  10475. str = gb_string_appendc(str, ":");
  10476. }
  10477. if (f->type != nullptr) {
  10478. str = gb_string_append_rune(str, ' ');
  10479. str = write_expr_to_string(str, f->type, shorthand);
  10480. }
  10481. if (f->default_value != nullptr) {
  10482. if (f->type != nullptr) {
  10483. str = gb_string_append_rune(str, ' ');
  10484. }
  10485. str = gb_string_appendc(str, "= ");
  10486. str = write_expr_to_string(str, f->default_value, shorthand);
  10487. }
  10488. case_end;
  10489. case_ast_node(f, FieldList, node);
  10490. bool has_name = false;
  10491. for_array(i, f->list) {
  10492. ast_node(field, Field, f->list[i]);
  10493. if (field->names.count > 1) {
  10494. has_name = true;
  10495. break;
  10496. }
  10497. if (field->names.count == 0) {
  10498. continue;
  10499. }
  10500. if (!is_blank_ident(field->names[0])) {
  10501. has_name = true;
  10502. break;
  10503. }
  10504. }
  10505. for_array(i, f->list) {
  10506. if (i > 0) str = gb_string_appendc(str, ", ");
  10507. if (has_name) {
  10508. str = write_expr_to_string(str, f->list[i], shorthand);
  10509. } else {
  10510. ast_node(field, Field, f->list[i]);
  10511. if (field->flags&FieldFlag_using) {
  10512. str = gb_string_appendc(str, "using ");
  10513. }
  10514. if (field->flags&FieldFlag_no_alias) {
  10515. str = gb_string_appendc(str, "#no_alias ");
  10516. }
  10517. if (field->flags&FieldFlag_c_vararg) {
  10518. str = gb_string_appendc(str, "#c_vararg ");
  10519. }
  10520. if (field->flags&FieldFlag_any_int) {
  10521. str = gb_string_appendc(str, "#any_int ");
  10522. }
  10523. if (field->flags&FieldFlag_no_broadcast) {
  10524. str = gb_string_appendc(str, "#no_broadcast ");
  10525. }
  10526. if (field->flags&FieldFlag_const) {
  10527. str = gb_string_appendc(str, "#const ");
  10528. }
  10529. if (field->flags&FieldFlag_subtype) {
  10530. str = gb_string_appendc(str, "#subtype ");
  10531. }
  10532. str = write_expr_to_string(str, field->type, shorthand);
  10533. }
  10534. }
  10535. case_end;
  10536. case_ast_node(ce, CallExpr, node);
  10537. switch (ce->inlining) {
  10538. case ProcInlining_inline:
  10539. str = gb_string_appendc(str, "#force_inline ");
  10540. break;
  10541. case ProcInlining_no_inline:
  10542. str = gb_string_appendc(str, "#force_no_inline ");
  10543. break;
  10544. }
  10545. str = write_expr_to_string(str, ce->proc, shorthand);
  10546. str = gb_string_appendc(str, "(");
  10547. isize idx0 = cast(isize)ce->was_selector;
  10548. for (isize i = idx0; i < ce->args.count; i++) {
  10549. Ast *arg = ce->args[i];
  10550. if (i > idx0) {
  10551. str = gb_string_appendc(str, ", ");
  10552. }
  10553. str = write_expr_to_string(str, arg, shorthand);
  10554. }
  10555. str = gb_string_appendc(str, ")");
  10556. case_end;
  10557. case_ast_node(tt, TypeidType, node);
  10558. str = gb_string_appendc(str, "typeid");
  10559. if (tt->specialization) {
  10560. str = gb_string_appendc(str, "/");
  10561. str = write_expr_to_string(str, tt->specialization, shorthand);
  10562. }
  10563. case_end;
  10564. case_ast_node(pt, ProcType, node);
  10565. str = gb_string_appendc(str, "proc(");
  10566. str = write_expr_to_string(str, pt->params, shorthand);
  10567. str = gb_string_appendc(str, ")");
  10568. if (pt->results != nullptr) {
  10569. str = gb_string_appendc(str, " -> ");
  10570. bool parens_needed = false;
  10571. if (pt->results && pt->results->kind == Ast_FieldList) {
  10572. for (Ast *field : pt->results->FieldList.list) {
  10573. ast_node(f, Field, field);
  10574. if (f->names.count != 0) {
  10575. parens_needed = true;
  10576. break;
  10577. }
  10578. }
  10579. }
  10580. if (parens_needed) {
  10581. str = gb_string_append_rune(str, '(');
  10582. }
  10583. str = write_expr_to_string(str, pt->results, shorthand);
  10584. if (parens_needed) {
  10585. str = gb_string_append_rune(str, ')');
  10586. }
  10587. }
  10588. case_end;
  10589. case_ast_node(st, StructType, node);
  10590. str = gb_string_appendc(str, "struct ");
  10591. if (st->polymorphic_params) {
  10592. str = gb_string_append_rune(str, '(');
  10593. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10594. str = gb_string_appendc(str, ") ");
  10595. }
  10596. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  10597. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  10598. if (st->align) {
  10599. str = gb_string_appendc(str, "#align ");
  10600. str = write_expr_to_string(str, st->align, shorthand);
  10601. str = gb_string_append_rune(str, ' ');
  10602. }
  10603. str = gb_string_append_rune(str, '{');
  10604. if (shorthand) {
  10605. str = gb_string_appendc(str, "...");
  10606. } else {
  10607. str = write_struct_fields_to_string(str, st->fields);
  10608. }
  10609. str = gb_string_append_rune(str, '}');
  10610. case_end;
  10611. case_ast_node(st, UnionType, node);
  10612. str = gb_string_appendc(str, "union ");
  10613. if (st->polymorphic_params) {
  10614. str = gb_string_append_rune(str, '(');
  10615. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10616. str = gb_string_appendc(str, ") ");
  10617. }
  10618. switch (st->kind) {
  10619. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  10620. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  10621. }
  10622. if (st->align) {
  10623. str = gb_string_appendc(str, "#align ");
  10624. str = write_expr_to_string(str, st->align, shorthand);
  10625. str = gb_string_append_rune(str, ' ');
  10626. }
  10627. str = gb_string_append_rune(str, '{');
  10628. if (shorthand) {
  10629. str = gb_string_appendc(str, "...");
  10630. } else {
  10631. str = write_struct_fields_to_string(str, st->variants);
  10632. }
  10633. str = gb_string_append_rune(str, '}');
  10634. case_end;
  10635. case_ast_node(et, EnumType, node);
  10636. str = gb_string_appendc(str, "enum ");
  10637. if (et->base_type != nullptr) {
  10638. str = write_expr_to_string(str, et->base_type, shorthand);
  10639. str = gb_string_append_rune(str, ' ');
  10640. }
  10641. str = gb_string_append_rune(str, '{');
  10642. if (shorthand) {
  10643. str = gb_string_appendc(str, "...");
  10644. } else {
  10645. for_array(i, et->fields) {
  10646. if (i > 0) {
  10647. str = gb_string_appendc(str, ", ");
  10648. }
  10649. str = write_expr_to_string(str, et->fields[i], shorthand);
  10650. }
  10651. }
  10652. str = gb_string_append_rune(str, '}');
  10653. case_end;
  10654. case_ast_node(rt, RelativeType, node);
  10655. str = write_expr_to_string(str, rt->tag, shorthand);
  10656. str = gb_string_appendc(str, "" );
  10657. str = write_expr_to_string(str, rt->type, shorthand);
  10658. case_end;
  10659. case_ast_node(f, BitFieldField, node);
  10660. str = write_expr_to_string(str, f->name, shorthand);
  10661. str = gb_string_appendc(str, ": ");
  10662. str = write_expr_to_string(str, f->type, shorthand);
  10663. str = gb_string_appendc(str, " | ");
  10664. str = write_expr_to_string(str, f->bit_size, shorthand);
  10665. case_end;
  10666. case_ast_node(bf, BitFieldType, node);
  10667. str = gb_string_appendc(str, "bit_field ");
  10668. if (!shorthand) {
  10669. str = write_expr_to_string(str, bf->backing_type, shorthand);
  10670. }
  10671. str = gb_string_appendc(str, " {");
  10672. if (shorthand) {
  10673. str = gb_string_appendc(str, "...");
  10674. } else {
  10675. for_array(i, bf->fields) {
  10676. if (i > 0) {
  10677. str = gb_string_appendc(str, ", ");
  10678. }
  10679. str = write_expr_to_string(str, bf->fields[i], false);
  10680. }
  10681. }
  10682. str = gb_string_appendc(str, "}");
  10683. case_end;
  10684. case_ast_node(ia, InlineAsmExpr, node);
  10685. str = gb_string_appendc(str, "asm(");
  10686. for_array(i, ia->param_types) {
  10687. if (i > 0) {
  10688. str = gb_string_appendc(str, ", ");
  10689. }
  10690. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  10691. }
  10692. str = gb_string_appendc(str, ")");
  10693. if (ia->return_type != nullptr) {
  10694. str = gb_string_appendc(str, " -> ");
  10695. str = write_expr_to_string(str, ia->return_type, shorthand);
  10696. }
  10697. if (ia->has_side_effects) {
  10698. str = gb_string_appendc(str, " #side_effects");
  10699. }
  10700. if (ia->is_align_stack) {
  10701. str = gb_string_appendc(str, " #stack_align");
  10702. }
  10703. if (ia->dialect) {
  10704. str = gb_string_appendc(str, " #");
  10705. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  10706. }
  10707. str = gb_string_appendc(str, " {");
  10708. if (shorthand) {
  10709. str = gb_string_appendc(str, "...");
  10710. } else {
  10711. str = write_expr_to_string(str, ia->asm_string, shorthand);
  10712. str = gb_string_appendc(str, ", ");
  10713. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  10714. }
  10715. str = gb_string_appendc(str, "}");
  10716. case_end;
  10717. }
  10718. return str;
  10719. }
  10720. gb_internal gbString expr_to_string(Ast *expression) {
  10721. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  10722. }
  10723. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  10724. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  10725. }
  10726. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  10727. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  10728. }