check_expr.cpp 367 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534
  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. gb_internal IntegerDivisionByZeroKind check_for_integer_division_by_zero(CheckerContext *c, Ast *node);
  108. enum LoadDirectiveResult {
  109. LoadDirective_Success = 0,
  110. LoadDirective_Error = 1,
  111. LoadDirective_NotFound = 2,
  112. };
  113. gb_internal bool is_load_directive_call(Ast *call) {
  114. call = unparen_expr(call);
  115. if (call->kind != Ast_CallExpr) {
  116. return false;
  117. }
  118. ast_node(ce, CallExpr, call);
  119. if (ce->proc->kind != Ast_BasicDirective) {
  120. return false;
  121. }
  122. ast_node(bd, BasicDirective, ce->proc);
  123. String name = bd->name.string;
  124. return name == "load";
  125. }
  126. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  127. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  128. auto results = did_you_mean_results(d);
  129. if (results.count != 0) {
  130. error_line("\tSuggestion: Did you mean?\n");
  131. for (auto const &result : results) {
  132. String const &target = result.target;
  133. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  134. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  135. }
  136. }
  137. }
  138. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  139. if (e->kind != Entity_TypeName) {
  140. return;
  141. }
  142. if (e->TypeName.objc_metadata == nullptr) {
  143. return;
  144. }
  145. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  146. Type *t = base_type(e->type);
  147. GB_ASSERT(t->kind == Type_Struct);
  148. if (is_type) {
  149. for (auto const &entry : objc_metadata->type_entries) {
  150. string_set_add(set, entry.name);
  151. }
  152. } else {
  153. for (auto const &entry : objc_metadata->value_entries) {
  154. string_set_add(set, entry.name);
  155. }
  156. }
  157. for (Entity *f : t->Struct.fields) {
  158. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  159. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  160. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  161. }
  162. }
  163. }
  164. }
  165. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  166. if (build_context.terse_errors) { return; }
  167. ERROR_BLOCK();
  168. GB_ASSERT(e->kind == Entity_TypeName);
  169. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  170. auto *objc_metadata = e->TypeName.objc_metadata;
  171. MUTEX_GUARD(objc_metadata->mutex);
  172. StringSet set = {};
  173. defer (string_set_destroy(&set));
  174. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  175. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  176. defer (did_you_mean_destroy(&d));
  177. for (String const &target : set) {
  178. did_you_mean_append(&d, target);
  179. }
  180. check_did_you_mean_print(&d, prefix);
  181. }
  182. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  183. if (build_context.terse_errors) { return; }
  184. ERROR_BLOCK();
  185. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  186. defer (did_you_mean_destroy(&d));
  187. for (Entity *e : fields) {
  188. did_you_mean_append(&d, e->token.string);
  189. }
  190. check_did_you_mean_print(&d, prefix);
  191. }
  192. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  193. if (build_context.terse_errors) { return; }
  194. ERROR_BLOCK();
  195. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  196. defer (did_you_mean_destroy(&d));
  197. for (Entity *e : fields) {
  198. did_you_mean_append(&d, e->token.string);
  199. }
  200. check_did_you_mean_print(&d, prefix);
  201. }
  202. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  203. if (build_context.terse_errors) { return; }
  204. ERROR_BLOCK();
  205. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  206. defer (did_you_mean_destroy(&d));
  207. rw_mutex_shared_lock(&scope->mutex);
  208. for (auto const &entry : scope->elements) {
  209. Entity *e = entry.value;
  210. did_you_mean_append(&d, e->token.string);
  211. }
  212. rw_mutex_shared_unlock(&scope->mutex);
  213. check_did_you_mean_print(&d, prefix);
  214. }
  215. gb_internal Entity *entity_from_expr(Ast *expr) {
  216. expr = unparen_expr(expr);
  217. if (expr == nullptr) {
  218. return nullptr;
  219. }
  220. switch (expr->kind) {
  221. case Ast_Ident:
  222. return expr->Ident.entity;
  223. case Ast_SelectorExpr:
  224. return entity_from_expr(expr->SelectorExpr.selector);
  225. }
  226. return nullptr;
  227. }
  228. gb_internal void error_operand_not_expression(Operand *o) {
  229. if (o->mode == Addressing_Type) {
  230. gbString err = expr_to_string(o->expr);
  231. error(o->expr, "'%s' is not an expression but a type", err);
  232. gb_string_free(err);
  233. o->mode = Addressing_Invalid;
  234. }
  235. }
  236. gb_internal void error_operand_no_value(Operand *o) {
  237. if (o->mode == Addressing_NoValue) {
  238. Ast *x = unparen_expr(o->expr);
  239. if (x != nullptr && x->kind == Ast_CallExpr) {
  240. Ast *p = unparen_expr(x->CallExpr.proc);
  241. if (p->kind == Ast_BasicDirective) {
  242. String tag = p->BasicDirective.name.string;
  243. if (tag == "panic" ||
  244. tag == "assert") {
  245. return;
  246. }
  247. }
  248. }
  249. gbString err = expr_to_string(o->expr);
  250. if (x != nullptr && x->kind == Ast_CallExpr) {
  251. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  252. } else {
  253. error(o->expr, "'%s' used as a value", err);
  254. }
  255. gb_string_free(err);
  256. o->mode = Addressing_Invalid;
  257. }
  258. }
  259. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  260. if (build_context.dynamic_map_calls) {
  261. add_package_dependency(c, "runtime", "__dynamic_map_get");
  262. } else {
  263. add_package_dependency(c, "runtime", "map_desired_position");
  264. add_package_dependency(c, "runtime", "map_probe_distance");
  265. }
  266. }
  267. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  268. init_core_source_code_location(c->checker);
  269. if (t_map_set_proc == nullptr) {
  270. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  271. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  272. }
  273. if (build_context.dynamic_map_calls) {
  274. add_package_dependency(c, "runtime", "__dynamic_map_set");
  275. } else {
  276. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  277. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  278. }
  279. }
  280. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  281. init_core_source_code_location(c->checker);
  282. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  283. }
  284. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  285. Scope *s = c->scope;
  286. check_collect_entities(c, nodes);
  287. for (auto const &entry : s->elements) {
  288. Entity *e = entry.value;\
  289. switch (e->kind) {
  290. case Entity_Constant:
  291. case Entity_TypeName:
  292. case Entity_Procedure:
  293. break;
  294. default:
  295. continue;
  296. }
  297. DeclInfo *d = decl_info_of_entity(e);
  298. if (d != nullptr) {
  299. check_entity_decl(c, e, d, nullptr);
  300. }
  301. }
  302. }
  303. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  304. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  305. ///////////////////////////////////////////////////////////////////////////////
  306. // //
  307. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  308. // //
  309. ///////////////////////////////////////////////////////////////////////////////
  310. CheckerInfo *info = old_c->info;
  311. if (base_entity == nullptr) {
  312. return false;
  313. }
  314. if (!is_type_proc(base_entity->type)) {
  315. return false;
  316. }
  317. if (base_entity->flags & EntityFlag_Disabled) {
  318. return false;
  319. }
  320. String name = base_entity->token.string;
  321. Type *src = base_type(base_entity->type);
  322. Type *dst = nullptr;
  323. if (type != nullptr) {
  324. dst = base_type(type);
  325. }
  326. if (param_operands == nullptr) {
  327. GB_ASSERT(dst != nullptr);
  328. }
  329. if (param_operands != nullptr) {
  330. GB_ASSERT(dst == nullptr);
  331. }
  332. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  333. return false;
  334. }
  335. if (dst != nullptr) {
  336. if (dst->Proc.is_polymorphic) {
  337. return false;
  338. }
  339. if (dst->Proc.param_count != src->Proc.param_count ||
  340. dst->Proc.result_count != src->Proc.result_count) {
  341. return false;
  342. }
  343. }
  344. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  345. if (old_decl == nullptr) {
  346. return false;
  347. }
  348. gbAllocator a = heap_allocator();
  349. Array<Operand> operands = {};
  350. if (param_operands) {
  351. operands = *param_operands;
  352. } else {
  353. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  354. for (isize i = 0; i < dst->Proc.param_count; i++) {
  355. Entity *param = dst->Proc.params->Tuple.variables[i];
  356. Operand o = {Addressing_Value};
  357. o.type = param->type;
  358. array_add(&operands, o);
  359. }
  360. }
  361. defer (if (param_operands == nullptr) {
  362. array_free(&operands);
  363. });
  364. CheckerContext nctx = *old_c;
  365. Scope *scope = create_scope(info, base_entity->scope);
  366. scope->flags |= ScopeFlag_Proc;
  367. nctx.scope = scope;
  368. nctx.allow_polymorphic_types = true;
  369. if (nctx.polymorphic_scope == nullptr) {
  370. nctx.polymorphic_scope = scope;
  371. }
  372. auto *pt = &src->Proc;
  373. // NOTE(bill): This is slightly memory leaking if the type already exists
  374. // Maybe it's better to check with the previous types first?
  375. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  376. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  377. if (!success) {
  378. return false;
  379. }
  380. GenProcsData *gen_procs = nullptr;
  381. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  382. GB_ASSERT(base_entity->kind == Entity_Procedure);
  383. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  384. gen_procs = base_entity->Procedure.gen_procs;
  385. if (gen_procs) {
  386. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  387. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  388. for (Entity *other : gen_procs->procs) {
  389. Type *pt = base_type(other->type);
  390. if (are_types_identical(pt, final_proc_type)) {
  391. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  392. if (poly_proc_data) {
  393. poly_proc_data->gen_entity = other;
  394. }
  395. return true;
  396. }
  397. }
  398. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  399. } else {
  400. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  401. gen_procs->procs.allocator = heap_allocator();
  402. base_entity->Procedure.gen_procs = gen_procs;
  403. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  404. }
  405. {
  406. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  407. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  408. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  409. nctx.no_polymorphic_errors = false;
  410. // NOTE(bill): Reset scope from the failed procedure type
  411. scope->head_child.store(nullptr, std::memory_order_relaxed);
  412. string_map_clear(&scope->elements);
  413. ptr_set_clear(&scope->imported);
  414. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  415. Ast *cloned_proc_type_node = clone_ast(pt->node);
  416. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  417. if (!success) {
  418. return false;
  419. }
  420. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  421. for (Entity *other : gen_procs->procs) {
  422. Type *pt = base_type(other->type);
  423. if (are_types_identical(pt, final_proc_type)) {
  424. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  425. if (poly_proc_data) {
  426. poly_proc_data->gen_entity = other;
  427. }
  428. DeclInfo *decl = other->decl_info;
  429. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  430. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  431. proc_info->file = other->file;
  432. proc_info->token = other->token;
  433. proc_info->decl = decl;
  434. proc_info->type = other->type;
  435. proc_info->body = decl->proc_lit->ProcLit.body;
  436. proc_info->tags = other->Procedure.tags;;
  437. proc_info->generated_from_polymorphic = true;
  438. proc_info->poly_def_node = poly_def_node;
  439. check_procedure_later(nctx.checker, proc_info);
  440. }
  441. return true;
  442. }
  443. }
  444. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  445. }
  446. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  447. ast_node(pl, ProcLit, proc_lit);
  448. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  449. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  450. final_proc_type->Proc.is_poly_specialized = true;
  451. final_proc_type->Proc.is_polymorphic = true;
  452. final_proc_type->Proc.variadic = src->Proc.variadic;
  453. final_proc_type->Proc.require_results = src->Proc.require_results;
  454. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  455. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  456. final_proc_type->Proc.diverging = src->Proc.diverging;
  457. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  458. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  459. final_proc_type->Proc.enable_target_feature = src->Proc.enable_target_feature;
  460. final_proc_type->Proc.require_target_feature = src->Proc.require_target_feature;
  461. for (isize i = 0; i < operands.count; i++) {
  462. Operand o = operands[i];
  463. if (final_proc_type == o.type ||
  464. base_entity->type == o.type) {
  465. // NOTE(bill): Cycle
  466. final_proc_type->Proc.is_poly_specialized = false;
  467. break;
  468. }
  469. }
  470. u64 tags = base_entity->Procedure.tags;
  471. Ast *ident = clone_ast(base_entity->identifier);
  472. Token token = ident->Ident.token;
  473. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  474. d->gen_proc_type = final_proc_type;
  475. d->type_expr = pl->type;
  476. d->proc_lit = proc_lit;
  477. d->proc_checked_state = ProcCheckedState_Unchecked;
  478. d->defer_use_checked = false;
  479. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  480. entity->state.store(EntityState_Resolved);
  481. entity->identifier = ident;
  482. add_entity_and_decl_info(&nctx, ident, entity, d);
  483. // NOTE(bill): Set the scope afterwards as this is not real overloading
  484. entity->scope = scope->parent;
  485. entity->file = base_entity->file;
  486. entity->pkg = base_entity->pkg;
  487. entity->flags = 0;
  488. entity->Procedure.optimization_mode = base_entity->Procedure.optimization_mode;
  489. if (base_entity->flags & EntityFlag_Cold) {
  490. entity->flags |= EntityFlag_Cold;
  491. }
  492. if (base_entity->flags & EntityFlag_Disabled) {
  493. entity->flags |= EntityFlag_Disabled;
  494. }
  495. d->entity.store(entity);
  496. AstFile *file = nullptr;
  497. {
  498. Scope *s = entity->scope;
  499. while (s != nullptr && s->file == nullptr) {
  500. file = s->file;
  501. s = s->parent;
  502. }
  503. }
  504. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  505. array_add(&gen_procs->procs, entity);
  506. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  507. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  508. proc_info->file = file;
  509. proc_info->token = token;
  510. proc_info->decl = d;
  511. proc_info->type = final_proc_type;
  512. proc_info->body = pl->body;
  513. proc_info->tags = tags;
  514. proc_info->generated_from_polymorphic = true;
  515. proc_info->poly_def_node = poly_def_node;
  516. if (poly_proc_data) {
  517. poly_proc_data->gen_entity = entity;
  518. poly_proc_data->proc_info = proc_info;
  519. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  520. }
  521. // NOTE(bill): Check the newly generated procedure body
  522. check_procedure_later(nctx.checker, proc_info);
  523. return true;
  524. }
  525. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  526. if (operand->expr == nullptr) return false;
  527. Entity *base_entity = entity_from_expr(operand->expr);
  528. if (base_entity == nullptr) return false;
  529. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  530. }
  531. 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) {
  532. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  533. }
  534. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  535. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  536. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  537. #define MAXIMUM_TYPE_DISTANCE 10
  538. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming) {
  539. if (c == nullptr) {
  540. GB_ASSERT(operand->mode == Addressing_Value);
  541. GB_ASSERT(is_type_typed(operand->type));
  542. }
  543. if (operand->mode == Addressing_Invalid ||
  544. type == t_invalid) {
  545. return -1;
  546. }
  547. if (operand->mode == Addressing_Builtin) {
  548. return -1;
  549. }
  550. if (operand->mode == Addressing_Type) {
  551. if (is_type_typeid(type)) {
  552. if (is_type_polymorphic(operand->type)) {
  553. return -1;
  554. }
  555. add_type_info_type(c, operand->type);
  556. return 4;
  557. }
  558. return -1;
  559. }
  560. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  561. return -1;
  562. }
  563. Type *s = operand->type;
  564. if (are_types_identical(s, type)) {
  565. return 0;
  566. }
  567. Type *src = base_type(s);
  568. Type *dst = base_type(type);
  569. if (is_type_untyped_uninit(src)) {
  570. return 1;
  571. }
  572. if (is_type_untyped_nil(src)) {
  573. if (type_has_nil(dst)) {
  574. return 1;
  575. }
  576. return -1;
  577. }
  578. if (is_type_untyped(src)) {
  579. if (is_type_any(dst)) {
  580. // NOTE(bill): Anything can cast to 'Any'
  581. add_type_info_type(c, s);
  582. return MAXIMUM_TYPE_DISTANCE;
  583. }
  584. if (dst->kind == Type_Basic) {
  585. if (operand->mode == Addressing_Constant) {
  586. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  587. if (is_type_typed(dst) && src->kind == Type_Basic) {
  588. switch (src->Basic.kind) {
  589. case Basic_UntypedBool:
  590. if (is_type_boolean(dst)) {
  591. return 1;
  592. }
  593. break;
  594. case Basic_UntypedRune:
  595. if (is_type_integer(dst) || is_type_rune(dst)) {
  596. return 1;
  597. }
  598. break;
  599. case Basic_UntypedInteger:
  600. if (is_type_integer(dst) || is_type_rune(dst)) {
  601. return 1;
  602. }
  603. break;
  604. case Basic_UntypedString:
  605. if (is_type_string(dst)) {
  606. return 1;
  607. }
  608. break;
  609. case Basic_UntypedFloat:
  610. if (is_type_float(dst)) {
  611. return 1;
  612. }
  613. break;
  614. case Basic_UntypedComplex:
  615. if (is_type_complex(dst)) {
  616. return 1;
  617. }
  618. if (is_type_quaternion(dst)) {
  619. return 2;
  620. }
  621. break;
  622. case Basic_UntypedQuaternion:
  623. if (is_type_quaternion(dst)) {
  624. return 1;
  625. }
  626. break;
  627. }
  628. }
  629. return 2;
  630. }
  631. return -1;
  632. }
  633. if (src->kind == Type_Basic) {
  634. Type *d = base_array_type(dst);
  635. i64 score = -1;
  636. switch (src->Basic.kind) {
  637. case Basic_UntypedBool:
  638. if (is_type_boolean(d)) {
  639. score = 1;
  640. }
  641. break;
  642. case Basic_UntypedRune:
  643. if (is_type_integer(d) || is_type_rune(d)) {
  644. score = 1;
  645. }
  646. break;
  647. case Basic_UntypedInteger:
  648. if (is_type_integer(d) || is_type_rune(d)) {
  649. score = 1;
  650. }
  651. break;
  652. case Basic_UntypedString:
  653. if (is_type_string(d)) {
  654. score = 1;
  655. }
  656. break;
  657. case Basic_UntypedFloat:
  658. if (is_type_float(d)) {
  659. score = 1;
  660. }
  661. break;
  662. case Basic_UntypedComplex:
  663. if (is_type_complex(d)) {
  664. score = 1;
  665. }
  666. if (is_type_quaternion(d)) {
  667. score = 2;
  668. }
  669. break;
  670. case Basic_UntypedQuaternion:
  671. if (is_type_quaternion(d)) {
  672. score = 1;
  673. }
  674. break;
  675. }
  676. if (score > 0) {
  677. if (is_type_typed(d)) {
  678. score += 1;
  679. }
  680. if (d != dst) {
  681. score += 6;
  682. }
  683. }
  684. return score;
  685. }
  686. }
  687. }
  688. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  689. if (c->in_enum_type) {
  690. return 3;
  691. }
  692. }
  693. {
  694. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  695. if (subtype_level > 0) {
  696. return 4 + subtype_level;
  697. }
  698. }
  699. // rawptr <- ^T
  700. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  701. return 5;
  702. }
  703. // rawptr <- [^]T
  704. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  705. return 5;
  706. }
  707. // ^T <- [^]T
  708. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  709. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  710. return 4;
  711. }
  712. }
  713. // [^]T <- ^T
  714. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  715. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  716. return 4;
  717. }
  718. }
  719. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  720. bool modify_type = !c->no_polymorphic_errors;
  721. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  722. return 2;
  723. }
  724. }
  725. if (is_type_union(dst)) {
  726. for (Type *vt : dst->Union.variants) {
  727. if (are_types_identical(vt, s)) {
  728. return 1;
  729. }
  730. if (is_type_proc(vt)) {
  731. if (are_types_identical(base_type(vt), src)) {
  732. return 1;
  733. }
  734. }
  735. }
  736. if (dst->Union.variants.count == 1) {
  737. Type *vt = dst->Union.variants[0];
  738. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  739. if (score >= 0) {
  740. return score+2;
  741. }
  742. } else if (is_type_untyped(src)) {
  743. i64 prev_lowest_score = -1;
  744. i64 lowest_score = -1;
  745. for (Type *vt : dst->Union.variants) {
  746. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  747. if (score >= 0) {
  748. if (lowest_score < 0) {
  749. lowest_score = score;
  750. } else {
  751. if (prev_lowest_score < 0) {
  752. prev_lowest_score = lowest_score;
  753. } else {
  754. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  755. }
  756. lowest_score = gb_min(lowest_score, score);
  757. }
  758. }
  759. }
  760. if (lowest_score >= 0) {
  761. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  762. return lowest_score+2;
  763. }
  764. }
  765. }
  766. }
  767. if (is_type_proc(dst)) {
  768. if (are_types_identical(src, dst)) {
  769. return 3;
  770. }
  771. PolyProcData poly_proc_data = {};
  772. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  773. Entity *e = poly_proc_data.gen_entity;
  774. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  775. add_entity_use(c, operand->expr, e);
  776. return 4;
  777. }
  778. }
  779. if (is_type_complex_or_quaternion(dst)) {
  780. Type *elem = base_complex_elem_type(dst);
  781. if (are_types_identical(elem, base_type(src))) {
  782. return 5;
  783. }
  784. }
  785. if (allow_array_programming) {
  786. if (is_type_array(dst)) {
  787. Type *elem = base_array_type(dst);
  788. i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
  789. if (distance >= 0) {
  790. return distance + 6;
  791. }
  792. }
  793. if (is_type_simd_vector(dst)) {
  794. Type *dst_elem = base_array_type(dst);
  795. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  796. if (distance >= 0) {
  797. return distance + 6;
  798. }
  799. }
  800. }
  801. if (is_type_matrix(dst)) {
  802. if (are_types_identical(src, dst)) {
  803. return 5;
  804. }
  805. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  806. Type *dst_elem = base_array_type(dst);
  807. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  808. if (distance >= 0) {
  809. return distance + 7;
  810. }
  811. }
  812. }
  813. if (is_type_any(dst)) {
  814. if (!is_type_polymorphic(src)) {
  815. if (operand->mode == Addressing_Context && operand->type == t_context) {
  816. return -1;
  817. } else {
  818. // NOTE(bill): Anything can cast to 'Any'
  819. add_type_info_type(c, s);
  820. return MAXIMUM_TYPE_DISTANCE;
  821. }
  822. }
  823. }
  824. Ast *expr = unparen_expr(operand->expr);
  825. if (expr != nullptr) {
  826. if (expr->kind == Ast_AutoCast) {
  827. Operand x = *operand;
  828. x.expr = expr->AutoCast.expr;
  829. if (check_cast_internal(c, &x, type)) {
  830. return MAXIMUM_TYPE_DISTANCE;
  831. }
  832. }
  833. }
  834. return -1;
  835. }
  836. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  837. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  838. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  839. // TODO(bill): A decent score function
  840. i64 d = distance*distance; // x^2
  841. if (is_variadic && d >= 0) {
  842. d += distance + 1; // x^2 + x + 1
  843. }
  844. return gb_max(c - d, 0);
  845. }
  846. 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) {
  847. if (c == nullptr) {
  848. GB_ASSERT(operand->mode == Addressing_Value);
  849. GB_ASSERT(is_type_typed(operand->type));
  850. }
  851. if (operand->mode == Addressing_Invalid || type == t_invalid) {
  852. if (score_) *score_ = 0;
  853. return false;
  854. }
  855. // Handle polymorphic procedure used as default parameter
  856. if (operand->mode == Addressing_Value && is_type_proc(type) && is_type_proc(operand->type)) {
  857. Entity *e = entity_from_expr(operand->expr);
  858. if (e != nullptr && e->kind == Entity_Procedure && is_type_polymorphic(e->type) && !is_type_polymorphic(type)) {
  859. // Special case: Allow a polymorphic procedure to be used as default value for concrete proc type
  860. // during the initial check. It will be properly instantiated when actually used.
  861. if (score_) *score_ = assign_score_function(1);
  862. return true;
  863. }
  864. }
  865. i64 score = check_distance_between_types(c, operand, type, allow_array_programming);
  866. if (score >= 0) {
  867. if (score_) *score_ = assign_score_function(score, is_variadic);
  868. return true;
  869. }
  870. if (score_) *score_ = 0;
  871. return false;
  872. }
  873. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming=true) {
  874. i64 score = 0;
  875. return check_is_assignable_to_with_score(c, operand, type, &score, /*is_variadic*/false, allow_array_programming);
  876. }
  877. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  878. Operand x = {};
  879. x.type = src;
  880. x.mode = Addressing_Value;
  881. return check_is_assignable_to(nullptr, &x, dst);
  882. }
  883. gb_internal AstPackage *get_package_of_type(Type *type) {
  884. for (;;) {
  885. if (type == nullptr) {
  886. return nullptr;
  887. }
  888. switch (type->kind) {
  889. case Type_Basic:
  890. return builtin_pkg;
  891. case Type_Named:
  892. if (type->Named.type_name != nullptr) {
  893. return type->Named.type_name->pkg;
  894. }
  895. return nullptr;
  896. case Type_Pointer:
  897. type = type->Pointer.elem;
  898. continue;
  899. case Type_Array:
  900. type = type->Array.elem;
  901. continue;
  902. case Type_Slice:
  903. type = type->Slice.elem;
  904. continue;
  905. case Type_DynamicArray:
  906. type = type->DynamicArray.elem;
  907. continue;
  908. }
  909. return nullptr;
  910. }
  911. }
  912. // NOTE(bill): 'context_name' is for debugging and error messages
  913. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  914. check_not_tuple(c, operand);
  915. if (operand->mode == Addressing_Invalid) {
  916. return;
  917. }
  918. // Grab definite or indefinite article matching `context_name`, or "" if not found.
  919. String article = error_article(context_name);
  920. if (is_type_untyped(operand->type)) {
  921. Type *target_type = type;
  922. if (type == nullptr || is_type_any(type)) {
  923. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  924. error(operand->expr, "Use of --- in %.*s%.*s", LIT(article), LIT(context_name));
  925. operand->mode = Addressing_Invalid;
  926. return;
  927. }
  928. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  929. error(operand->expr, "Use of untyped nil in %.*s%.*s", LIT(article), LIT(context_name));
  930. operand->mode = Addressing_Invalid;
  931. return;
  932. }
  933. target_type = default_type(operand->type);
  934. if (type != nullptr && !is_type_any(type)) {
  935. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  936. }
  937. add_type_info_type(c, type);
  938. add_type_info_type(c, target_type);
  939. }
  940. convert_to_typed(c, operand, target_type);
  941. if (operand->mode == Addressing_Invalid) {
  942. return;
  943. }
  944. }
  945. if (type == nullptr) {
  946. return;
  947. }
  948. if (operand->mode == Addressing_ProcGroup) {
  949. bool good = false;
  950. if (type != nullptr && is_type_proc(type)) {
  951. Array<Entity *> procs = proc_group_entities(c, *operand);
  952. // NOTE(bill): These should be done
  953. for (Entity *e : procs) {
  954. Type *t = base_type(e->type);
  955. if (t == t_invalid) {
  956. continue;
  957. }
  958. Operand x = {};
  959. x.mode = Addressing_Value;
  960. x.type = t;
  961. if (check_is_assignable_to(c, &x, type)) {
  962. add_entity_use(c, operand->expr, e);
  963. good = true;
  964. break;
  965. }
  966. }
  967. }
  968. if (!good) {
  969. gbString expr_str = expr_to_string(operand->expr);
  970. gbString op_type_str = type_to_string(operand->type);
  971. gbString type_str = type_to_string(type);
  972. defer (gb_string_free(type_str));
  973. defer (gb_string_free(op_type_str));
  974. defer (gb_string_free(expr_str));
  975. // TODO(bill): is this a good enough error message?
  976. error(operand->expr,
  977. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s%.*s",
  978. expr_str,
  979. op_type_str,
  980. LIT(article),
  981. LIT(context_name));
  982. operand->mode = Addressing_Invalid;
  983. }
  984. convert_to_typed(c, operand, type);
  985. return;
  986. }
  987. if (check_is_assignable_to(c, operand, type)) {
  988. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  989. add_type_info_type(c, operand->type);
  990. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  991. }
  992. } else {
  993. gbString expr_str = expr_to_string(operand->expr);
  994. gbString op_type_str = type_to_string(operand->type);
  995. gbString type_str = type_to_string(type);
  996. defer (gb_string_free(type_str));
  997. defer (gb_string_free(op_type_str));
  998. defer (gb_string_free(expr_str));
  999. switch (operand->mode) {
  1000. case Addressing_Builtin:
  1001. error(operand->expr,
  1002. "Cannot assign built-in procedure '%s' to %.*s%.*s",
  1003. expr_str,
  1004. LIT(article),
  1005. LIT(context_name));
  1006. break;
  1007. case Addressing_Type:
  1008. if (is_type_polymorphic(operand->type)) {
  1009. error(operand->expr,
  1010. "Cannot assign '%s', a polymorphic type, to %.*s%.*s",
  1011. op_type_str,
  1012. LIT(article),
  1013. LIT(context_name));
  1014. } else {
  1015. ERROR_BLOCK();
  1016. error(operand->expr,
  1017. "Cannot assign '%s', a type, to %.*s%.*s",
  1018. op_type_str,
  1019. LIT(article),
  1020. LIT(context_name));
  1021. if (type && are_types_identical(type, t_any)) {
  1022. error_line("\tSuggestion: 'typeid_of(%s)'", expr_str);
  1023. }
  1024. }
  1025. break;
  1026. default:
  1027. // TODO(bill): is this a good enough error message?
  1028. {
  1029. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  1030. gbString type_extra = gb_string_make(heap_allocator(), "");
  1031. defer (gb_string_free(op_type_extra));
  1032. defer (gb_string_free(type_extra));
  1033. isize on = gb_string_length(op_type_str);
  1034. isize tn = gb_string_length(type_str);
  1035. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  1036. AstPackage *op_pkg = get_package_of_type(operand->type);
  1037. AstPackage *type_pkg = get_package_of_type(type);
  1038. if (op_pkg != nullptr) {
  1039. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  1040. }
  1041. if (type_pkg != nullptr) {
  1042. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  1043. }
  1044. }
  1045. ERROR_BLOCK();
  1046. error(operand->expr,
  1047. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s%.*s",
  1048. expr_str,
  1049. op_type_str, op_type_extra,
  1050. type_str, type_extra,
  1051. LIT(article),
  1052. LIT(context_name));
  1053. check_assignment_error_suggestion(c, operand, type);
  1054. Type *src = base_type(operand->type);
  1055. Type *dst = base_type(type);
  1056. if (context_name == "procedure argument") {
  1057. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  1058. gbString a = expr_to_string(operand->expr);
  1059. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  1060. gb_string_free(a);
  1061. }
  1062. }
  1063. if (src->kind == dst->kind && src->kind == Type_Proc) {
  1064. Type *x = src;
  1065. Type *y = dst;
  1066. bool same_inputs = are_types_identical_internal(x->Proc.params, y->Proc.params, false);
  1067. bool same_outputs = are_types_identical_internal(x->Proc.results, y->Proc.results, false);
  1068. if (same_inputs && same_outputs &&
  1069. x->Proc.calling_convention != y->Proc.calling_convention) {
  1070. gbString s_expected = type_to_string(y);
  1071. gbString s_got = type_to_string(x);
  1072. error_line("\tNote: The calling conventions differ between the procedure signature types\n");
  1073. error_line("\t Expected \"%s\", got \"%s\"\n",
  1074. proc_calling_convention_strings[y->Proc.calling_convention],
  1075. proc_calling_convention_strings[x->Proc.calling_convention]);
  1076. error_line("\t Expected: %s\n", s_expected);
  1077. error_line("\t Got: %s\n", s_got);
  1078. gb_string_free(s_got);
  1079. gb_string_free(s_expected);
  1080. } else if (same_inputs && same_outputs &&
  1081. x->Proc.diverging != y->Proc.diverging) {
  1082. gbString s_expected = type_to_string(y);
  1083. if (y->Proc.diverging) {
  1084. s_expected = gb_string_appendc(s_expected, " -> !");
  1085. }
  1086. gbString s_got = type_to_string(x);
  1087. if (x->Proc.diverging) {
  1088. s_got = gb_string_appendc(s_got, " -> !");
  1089. }
  1090. error_line("\tNote: One of the procedures is diverging while the other isn't\n");
  1091. error_line("\t Expected: %s\n", s_expected);
  1092. error_line("\t Got: %s\n", s_got);
  1093. gb_string_free(s_got);
  1094. gb_string_free(s_expected);
  1095. } else if (same_inputs && !same_outputs) {
  1096. gbString s_expected = type_to_string(y->Proc.results);
  1097. gbString s_got = type_to_string(x->Proc.results);
  1098. error_line("\tNote: The return types differ between the procedure signature types\n");
  1099. error_line("\t Expected: %s\n", s_expected);
  1100. error_line("\t Got: %s\n", s_got);
  1101. gb_string_free(s_got);
  1102. gb_string_free(s_expected);
  1103. } else if (!same_inputs && same_outputs) {
  1104. gbString s_expected = type_to_string(y->Proc.params);
  1105. gbString s_got = type_to_string(x->Proc.params);
  1106. error_line("\tNote: The input parameter types differ between the procedure signature types\n");
  1107. error_line("\t Expected: %s\n", s_expected);
  1108. error_line("\t Got: %s\n", s_got);
  1109. gb_string_free(s_got);
  1110. gb_string_free(s_expected);
  1111. } else {
  1112. gbString s_expected = type_to_string(y);
  1113. gbString s_got = type_to_string(x);
  1114. error_line("\tNote: The signature type do not match whatsoever\n");
  1115. error_line("\t Expected: %s\n", s_expected);
  1116. error_line("\t Got: %s\n", s_got);
  1117. gb_string_free(s_got);
  1118. gb_string_free(s_expected);
  1119. }
  1120. }
  1121. }
  1122. break;
  1123. }
  1124. operand->mode = Addressing_Invalid;
  1125. return;
  1126. }
  1127. }
  1128. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1129. Type *gt = *gt_;
  1130. GB_ASSERT(gt->kind == Type_Generic);
  1131. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1132. GB_ASSERT(e != nullptr);
  1133. if (e->kind == Entity_TypeName) {
  1134. *gt_ = nullptr;
  1135. *dst_count = source_count;
  1136. e->kind = Entity_Constant;
  1137. e->Constant.value = exact_value_i64(source_count);
  1138. e->type = t_untyped_integer;
  1139. return true;
  1140. } else if (e->kind == Entity_Constant) {
  1141. *gt_ = nullptr;
  1142. if (e->Constant.value.kind != ExactValue_Integer) {
  1143. return false;
  1144. }
  1145. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1146. if (count != source_count) {
  1147. return false;
  1148. }
  1149. *dst_count = source_count;
  1150. return true;
  1151. }
  1152. return false;
  1153. }
  1154. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1155. Operand o = {Addressing_Value};
  1156. o.type = source;
  1157. switch (poly->kind) {
  1158. case Type_Basic:
  1159. if (compound) return are_types_identical(poly, source);
  1160. return check_is_assignable_to(c, &o, poly);
  1161. case Type_Named: {
  1162. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1163. return true;
  1164. }
  1165. if (compound || !is_type_generic(poly)) {
  1166. return are_types_identical(poly, source);
  1167. }
  1168. return check_is_assignable_to(c, &o, poly);
  1169. }
  1170. case Type_Generic: {
  1171. if (poly->Generic.specialized != nullptr) {
  1172. Type *s = poly->Generic.specialized;
  1173. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1174. return false;
  1175. }
  1176. }
  1177. if (modify_type) {
  1178. Type *ds = default_type(source);
  1179. gb_memmove(poly, ds, gb_size_of(Type));
  1180. }
  1181. return true;
  1182. }
  1183. case Type_Pointer:
  1184. if (source->kind == Type_Pointer) {
  1185. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1186. if (level > 0) {
  1187. return true;
  1188. }
  1189. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1190. } else if (source->kind == Type_MultiPointer) {
  1191. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1192. if (level > 0) {
  1193. return true;
  1194. }
  1195. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1196. }
  1197. return false;
  1198. case Type_MultiPointer:
  1199. if (source->kind == Type_MultiPointer) {
  1200. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1201. if (level > 0) {
  1202. return true;
  1203. }
  1204. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1205. } else if (source->kind == Type_Pointer) {
  1206. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1207. if (level > 0) {
  1208. return true;
  1209. }
  1210. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1211. }
  1212. return false;
  1213. case Type_Array:
  1214. if (source->kind == Type_Array) {
  1215. if (poly->Array.generic_count != nullptr) {
  1216. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1217. return false;
  1218. }
  1219. }
  1220. if (poly->Array.count == source->Array.count) {
  1221. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1222. }
  1223. } else if (source->kind == Type_EnumeratedArray) {
  1224. if (poly->Array.generic_count != nullptr) {
  1225. Type *gt = poly->Array.generic_count;
  1226. GB_ASSERT(gt->kind == Type_Generic);
  1227. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1228. GB_ASSERT(e != nullptr);
  1229. if (e->kind == Entity_TypeName) {
  1230. Type *index = source->EnumeratedArray.index;
  1231. Type *it = base_type(index);
  1232. if (it->kind != Type_Enum) {
  1233. return false;
  1234. }
  1235. poly->kind = Type_EnumeratedArray;
  1236. poly->cached_size = -1;
  1237. poly->cached_align = -1;
  1238. poly->flags.exchange(source->flags);
  1239. poly->failure = false;
  1240. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1241. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1242. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1243. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1244. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1245. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1246. e->kind = Entity_TypeName;
  1247. e->TypeName.is_type_alias = true;
  1248. e->type = index;
  1249. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1250. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1251. }
  1252. }
  1253. }
  1254. }
  1255. return false;
  1256. case Type_EnumeratedArray:
  1257. if (source->kind == Type_EnumeratedArray) {
  1258. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1259. return false;
  1260. }
  1261. if (poly->EnumeratedArray.op) {
  1262. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1263. return false;
  1264. }
  1265. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1266. return false;
  1267. }
  1268. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1269. return false;
  1270. }
  1271. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1272. }
  1273. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1274. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1275. return index || elem;
  1276. }
  1277. return false;
  1278. case Type_DynamicArray:
  1279. if (source->kind == Type_DynamicArray) {
  1280. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1281. }
  1282. return false;
  1283. case Type_Slice:
  1284. if (source->kind == Type_Slice) {
  1285. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1286. }
  1287. return false;
  1288. case Type_Enum:
  1289. return false;
  1290. case Type_BitSet:
  1291. if (source->kind == Type_BitSet) {
  1292. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1293. return false;
  1294. }
  1295. // For generic types like bit_set[$T] the upper and lower of the poly type will be zeroes since
  1296. // it could not figure that stuff out when the poly type was created.
  1297. if (poly->BitSet.upper == 0 && modify_type) {
  1298. poly->BitSet.upper = source->BitSet.upper;
  1299. }
  1300. if (poly->BitSet.lower == 0 && modify_type) {
  1301. poly->BitSet.lower = source->BitSet.lower;
  1302. }
  1303. if (poly->BitSet.underlying == nullptr) {
  1304. if (modify_type) {
  1305. poly->BitSet.underlying = source->BitSet.underlying;
  1306. }
  1307. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1308. return false;
  1309. }
  1310. return true;
  1311. }
  1312. return false;
  1313. case Type_Union:
  1314. if (source->kind == Type_Union) {
  1315. TypeUnion *x = &poly->Union;
  1316. TypeUnion *y = &source->Union;
  1317. if (x->variants.count != y->variants.count) {
  1318. return false;
  1319. }
  1320. for_array(i, x->variants) {
  1321. Type *a = x->variants[i];
  1322. Type *b = y->variants[i];
  1323. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1324. if (!ok) return false;
  1325. }
  1326. return true;
  1327. }
  1328. return false;
  1329. case Type_Struct:
  1330. if (source->kind == Type_Struct) {
  1331. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1332. poly->Struct.soa_kind != StructSoa_None) {
  1333. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1334. if (ok) switch (source->Struct.soa_kind) {
  1335. case StructSoa_None:
  1336. default:
  1337. GB_PANIC("Unhandled SOA Kind");
  1338. break;
  1339. case StructSoa_Fixed:
  1340. if (modify_type) {
  1341. Type *type = make_soa_struct_fixed(c, nullptr, poly->Struct.node, poly->Struct.soa_elem, poly->Struct.soa_count, nullptr);
  1342. gb_memmove(poly, type, gb_size_of(*type));
  1343. }
  1344. break;
  1345. case StructSoa_Slice:
  1346. if (modify_type) {
  1347. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1348. gb_memmove(poly, type, gb_size_of(*type));
  1349. }
  1350. break;
  1351. case StructSoa_Dynamic:
  1352. if (modify_type) {
  1353. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1354. gb_memmove(poly, type, gb_size_of(*type));
  1355. }
  1356. break;
  1357. }
  1358. return ok;
  1359. }
  1360. // NOTE(bill): Check for subtypes of
  1361. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1362. }
  1363. return false;
  1364. case Type_BitField:
  1365. if (source->kind == Type_BitField) {
  1366. return is_polymorphic_type_assignable(c, poly->BitField.backing_type, source->BitField.backing_type, true, modify_type);
  1367. }
  1368. return false;
  1369. case Type_Tuple:
  1370. GB_PANIC("This should never happen");
  1371. return false;
  1372. case Type_Proc:
  1373. if (source->kind == Type_Proc) {
  1374. TypeProc *x = &poly->Proc;
  1375. TypeProc *y = &source->Proc;
  1376. if (x->calling_convention != y->calling_convention) {
  1377. return false;
  1378. }
  1379. if (x->c_vararg != y->c_vararg) {
  1380. return false;
  1381. }
  1382. if (x->variadic != y->variadic) {
  1383. return false;
  1384. }
  1385. if (x->param_count != y->param_count) {
  1386. return false;
  1387. }
  1388. if (x->result_count != y->result_count) {
  1389. return false;
  1390. }
  1391. for (isize i = 0; i < x->param_count; i++) {
  1392. Entity *a = x->params->Tuple.variables[i];
  1393. Entity *b = y->params->Tuple.variables[i];
  1394. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1395. if (!ok) return false;
  1396. }
  1397. for (isize i = 0; i < x->result_count; i++) {
  1398. Entity *a = x->results->Tuple.variables[i];
  1399. Entity *b = y->results->Tuple.variables[i];
  1400. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1401. if (!ok) return false;
  1402. }
  1403. return true;
  1404. }
  1405. return false;
  1406. case Type_Map:
  1407. if (source->kind == Type_Map) {
  1408. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1409. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1410. if (key || value) {
  1411. poly->Map.lookup_result_type = nullptr;
  1412. init_map_internal_types(poly);
  1413. return true;
  1414. }
  1415. }
  1416. return false;
  1417. case Type_Matrix:
  1418. if (source->kind == Type_Matrix) {
  1419. if (poly->Matrix.generic_row_count != nullptr) {
  1420. poly->Matrix.stride_in_bytes = 0;
  1421. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1422. return false;
  1423. }
  1424. }
  1425. if (poly->Matrix.generic_column_count != nullptr) {
  1426. poly->Matrix.stride_in_bytes = 0;
  1427. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1428. return false;
  1429. }
  1430. }
  1431. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1432. poly->Matrix.column_count == source->Matrix.column_count) {
  1433. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1434. }
  1435. }
  1436. return false;
  1437. case Type_SimdVector:
  1438. if (source->kind == Type_SimdVector) {
  1439. if (poly->SimdVector.generic_count != nullptr) {
  1440. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1441. return false;
  1442. }
  1443. }
  1444. if (poly->SimdVector.count == source->SimdVector.count) {
  1445. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1446. }
  1447. }
  1448. return false;
  1449. }
  1450. return false;
  1451. }
  1452. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1453. if (curr->state != EntityState_InProgress) {
  1454. return false;
  1455. }
  1456. for_array(i, *c->type_path) {
  1457. Entity *prev = c->type_path->data[i];
  1458. if (prev == curr) {
  1459. if (report) {
  1460. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1461. for (isize j = i; j < c->type_path->count; j++) {
  1462. Entity *curr = (*c->type_path)[j];
  1463. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1464. }
  1465. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1466. curr->type = t_invalid;
  1467. }
  1468. return true;
  1469. }
  1470. }
  1471. return false;
  1472. }
  1473. struct CIdentSuggestion {
  1474. String name;
  1475. String msg;
  1476. };
  1477. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1478. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1479. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1480. {str_lit("sizeof"), str_lit("'size_of'?")},
  1481. {str_lit("alignof"), str_lit("'align_of'?")},
  1482. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1483. {str_lit("_Bool"), str_lit("'bool'?")},
  1484. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1485. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1486. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1487. {str_lit("float"), str_lit("'f32'?")},
  1488. {str_lit("double"), str_lit("'f64'?")},
  1489. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1490. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1491. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1492. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1493. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1494. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1495. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1496. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1497. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1498. {str_lit("uint8_t"), str_lit("'u8'?")},
  1499. {str_lit("int8_t"), str_lit("'i8'?")},
  1500. {str_lit("uint16_t"), str_lit("'u16'?")},
  1501. {str_lit("int16_t"), str_lit("'i16'?")},
  1502. {str_lit("uint32_t"), str_lit("'u32'?")},
  1503. {str_lit("int32_t"), str_lit("'i32'?")},
  1504. {str_lit("uint64_t"), str_lit("'u64'?")},
  1505. {str_lit("int64_t"), str_lit("'i64'?")},
  1506. {str_lit("uint128_t"), str_lit("'u128'?")},
  1507. {str_lit("int128_t"), str_lit("'i128'?")},
  1508. {str_lit("float32"), str_lit("'f32'?")},
  1509. {str_lit("float64"), str_lit("'f64'?")},
  1510. {str_lit("float32_t"), str_lit("'f32'?")},
  1511. {str_lit("float64_t"), str_lit("'f64'?")},
  1512. };
  1513. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1514. GB_ASSERT(n->kind == Ast_Ident);
  1515. o->mode = Addressing_Invalid;
  1516. o->expr = n;
  1517. String name = n->Ident.token.string;
  1518. Entity *e = scope_lookup(c->scope, name, n->Ident.hash);
  1519. if (e == nullptr) {
  1520. if (is_blank_ident(name)) {
  1521. error(n, "'_' cannot be used as a value");
  1522. } else {
  1523. ERROR_BLOCK();
  1524. error(n, "Undeclared name: %.*s", LIT(name));
  1525. // NOTE(bill): Loads of checks for C programmers
  1526. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1527. if (name == suggestion.name) {
  1528. error_line("\tSuggestion: Did you mean %.*s\n", LIT(suggestion.msg));
  1529. }
  1530. }
  1531. }
  1532. o->type = t_invalid;
  1533. o->mode = Addressing_Invalid;
  1534. if (named_type != nullptr) {
  1535. set_base_type(named_type, t_invalid);
  1536. }
  1537. return nullptr;
  1538. }
  1539. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1540. if (e->parent_proc_decl != nullptr &&
  1541. e->parent_proc_decl != c->curr_proc_decl) {
  1542. if (e->kind == Entity_Variable) {
  1543. if ((e->flags & EntityFlag_Static) == 0) {
  1544. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1545. return nullptr;
  1546. }
  1547. } else if (e->kind == Entity_Label) {
  1548. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1549. return nullptr;
  1550. }
  1551. }
  1552. if (e->kind == Entity_ProcGroup) {
  1553. auto *pge = &e->ProcGroup;
  1554. DeclInfo *d = decl_info_of_entity(e);
  1555. check_entity_decl(c, e, d, nullptr);
  1556. Array<Entity *> procs = pge->entities;
  1557. bool skip = false;
  1558. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1559. // NOTE(bill): These should be done
  1560. for (Entity *proc : procs) {
  1561. Type *t = base_type(proc->type);
  1562. if (t == t_invalid) {
  1563. continue;
  1564. }
  1565. Operand x = {};
  1566. x.mode = Addressing_Value;
  1567. x.type = t;
  1568. if (check_is_assignable_to(c, &x, type_hint)) {
  1569. e = proc;
  1570. add_entity_use(c, n, e);
  1571. skip = true;
  1572. break;
  1573. }
  1574. }
  1575. }
  1576. if (!skip) {
  1577. o->mode = Addressing_ProcGroup;
  1578. o->type = t_invalid;
  1579. o->proc_group = e;
  1580. return nullptr;
  1581. }
  1582. }
  1583. add_entity_use(c, n, e);
  1584. if (e->state == EntityState_Unresolved) {
  1585. check_entity_decl(c, e, nullptr, named_type);
  1586. }
  1587. if (e->type == nullptr) {
  1588. // TODO(bill): Which is correct? return or compiler_error?
  1589. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1590. return nullptr;
  1591. }
  1592. e->flags |= EntityFlag_Used;
  1593. Type *type = e->type;
  1594. o->type = type;
  1595. switch (e->kind) {
  1596. case Entity_Constant:
  1597. if (type == t_invalid) {
  1598. o->type = t_invalid;
  1599. return e;
  1600. }
  1601. o->value = e->Constant.value;
  1602. if (o->value.kind == ExactValue_Invalid) {
  1603. return e;
  1604. }
  1605. if (o->value.kind == ExactValue_Procedure) {
  1606. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1607. if (proc != nullptr) {
  1608. o->mode = Addressing_Value;
  1609. o->type = proc->type;
  1610. return proc;
  1611. }
  1612. }
  1613. o->mode = Addressing_Constant;
  1614. break;
  1615. case Entity_Variable:
  1616. e->flags |= EntityFlag_Used;
  1617. if (type == t_invalid) {
  1618. o->type = t_invalid;
  1619. return e;
  1620. }
  1621. o->mode = Addressing_Variable;
  1622. if (e->flags & EntityFlag_Value) {
  1623. o->mode = Addressing_Value;
  1624. }
  1625. break;
  1626. case Entity_Procedure:
  1627. o->mode = Addressing_Value;
  1628. o->value = exact_value_procedure(n);
  1629. break;
  1630. case Entity_Builtin:
  1631. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1632. o->mode = Addressing_Builtin;
  1633. break;
  1634. case Entity_TypeName:
  1635. o->mode = Addressing_Type;
  1636. if (check_cycle(c, e, true)) {
  1637. o->type = t_invalid;
  1638. }
  1639. if (o->type != nullptr && o->type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1640. Type *bt = base_type(o->type);
  1641. if (bt != nullptr) {
  1642. o->type = bt;
  1643. }
  1644. }
  1645. break;
  1646. case Entity_ImportName:
  1647. if (!allow_import_name) {
  1648. error(n, "Use of import name '%.*s' not in the form of 'x.y'", LIT(name));
  1649. }
  1650. return e;
  1651. case Entity_LibraryName:
  1652. if (!allow_import_name) {
  1653. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1654. }
  1655. return e;
  1656. case Entity_Label:
  1657. o->mode = Addressing_NoValue;
  1658. break;
  1659. case Entity_Nil:
  1660. o->mode = Addressing_Value;
  1661. break;
  1662. default:
  1663. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1664. break;
  1665. }
  1666. return e;
  1667. }
  1668. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1669. if (o->type == nullptr) {
  1670. gbString str = expr_to_string(o->expr);
  1671. error(o->expr, "Expression has no value '%s'", str);
  1672. gb_string_free(str);
  1673. return false;
  1674. }
  1675. if (o->mode == Addressing_Type) {
  1676. gbString str = type_to_string(o->type);
  1677. error(o->expr, "Expected an expression for operator '%.*s', got type '%s'", LIT(op.string), str);
  1678. gb_string_free(str);
  1679. return false;
  1680. }
  1681. Type *type = base_type(core_array_type(o->type));
  1682. gbString str = nullptr;
  1683. switch (op.kind) {
  1684. case Token_Add:
  1685. case Token_Sub:
  1686. if (!is_type_numeric(type)) {
  1687. str = expr_to_string(o->expr);
  1688. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1689. gb_string_free(str);
  1690. }
  1691. break;
  1692. case Token_Xor:
  1693. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1694. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1695. }
  1696. break;
  1697. case Token_Not:
  1698. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1699. ERROR_BLOCK();
  1700. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1701. if (is_type_integer(type)) {
  1702. str = expr_to_string(o->expr);
  1703. error_line("\tSuggestion: Did you mean to do one of the following?\n");
  1704. error_line("\t\t'%s == 0'?\n", str);
  1705. error_line("\t\tUse of the bitwise not operator '~'?\n");
  1706. gb_string_free(str);
  1707. }
  1708. } else {
  1709. o->type = t_untyped_bool;
  1710. }
  1711. break;
  1712. case Token_Mul:
  1713. {
  1714. ERROR_BLOCK();
  1715. error(op, "Operator '%.*s' is not a valid unary operator in Odin", LIT(op.string));
  1716. if (is_type_pointer(o->type)) {
  1717. str = expr_to_string(o->expr);
  1718. error_line("\tSuggestion: Did you mean '%s^'?\n", str);
  1719. o->type = type_deref(o->type);
  1720. } else if (is_type_multi_pointer(o->type)) {
  1721. str = expr_to_string(o->expr);
  1722. error_line("\tSuggestion: The value is a multi-pointer, did you mean '%s[0]'?\n", str);
  1723. o->type = type_deref(o->type, true);
  1724. }
  1725. }
  1726. break;
  1727. default:
  1728. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1729. return false;
  1730. }
  1731. return true;
  1732. }
  1733. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1734. Type *main_type = o->type;
  1735. Type *type = base_type(core_array_type(main_type));
  1736. Type *ct = core_type(type);
  1737. switch (op.kind) {
  1738. case Token_Sub:
  1739. case Token_SubEq:
  1740. if (is_type_bit_set(type)) {
  1741. return true;
  1742. } else if (!is_type_numeric(type)) {
  1743. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1744. return false;
  1745. }
  1746. break;
  1747. case Token_Quo:
  1748. case Token_QuoEq:
  1749. if (is_type_matrix(main_type)) {
  1750. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1751. return false;
  1752. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1753. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1754. return false;
  1755. }
  1756. /*fallthrough*/
  1757. case Token_Mul:
  1758. case Token_MulEq:
  1759. case Token_AddEq:
  1760. if (is_type_bit_set(type)) {
  1761. return true;
  1762. } else if (!is_type_numeric(type)) {
  1763. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1764. return false;
  1765. }
  1766. break;
  1767. case Token_Add:
  1768. if (is_type_string(type)) {
  1769. if (o->mode == Addressing_Constant) {
  1770. return true;
  1771. }
  1772. error(op, "String concatenation is only allowed with constant strings");
  1773. return false;
  1774. } else if (is_type_bit_set(type)) {
  1775. return true;
  1776. } else if (!is_type_numeric(type)) {
  1777. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1778. return false;
  1779. }
  1780. break;
  1781. case Token_And:
  1782. case Token_Or:
  1783. case Token_AndEq:
  1784. case Token_OrEq:
  1785. case Token_Xor:
  1786. case Token_XorEq:
  1787. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1788. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1789. return false;
  1790. }
  1791. break;
  1792. case Token_Mod:
  1793. case Token_ModMod:
  1794. case Token_ModEq:
  1795. case Token_ModModEq:
  1796. if (is_type_matrix(main_type)) {
  1797. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1798. return false;
  1799. }
  1800. if (!is_type_integer(type)) {
  1801. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1802. return false;
  1803. } else if (is_type_simd_vector(main_type)) {
  1804. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1805. return false;
  1806. }
  1807. break;
  1808. case Token_AndNot:
  1809. case Token_AndNotEq:
  1810. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1811. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1812. return false;
  1813. }
  1814. break;
  1815. case Token_CmpAnd:
  1816. case Token_CmpOr:
  1817. case Token_CmpAndEq:
  1818. case Token_CmpOrEq:
  1819. if (!is_type_boolean(type)) {
  1820. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1821. return false;
  1822. }
  1823. break;
  1824. default:
  1825. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1826. return false;
  1827. }
  1828. return true;
  1829. }
  1830. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1831. if (in_value.kind == ExactValue_Invalid) {
  1832. // NOTE(bill): There's already been an error
  1833. return true;
  1834. }
  1835. type = core_type(type);
  1836. if (type == t_invalid) {
  1837. return false;
  1838. } else if (is_type_boolean(type)) {
  1839. return in_value.kind == ExactValue_Bool;
  1840. } else if (is_type_string(type)) {
  1841. if (in_value.kind == ExactValue_String16) {
  1842. return is_type_string16(type) || is_type_cstring16(type);
  1843. }
  1844. return in_value.kind == ExactValue_String;
  1845. } else if (is_type_integer(type) || is_type_rune(type)) {
  1846. if (in_value.kind == ExactValue_Bool) {
  1847. return false;
  1848. }
  1849. ExactValue v = exact_value_to_integer(in_value);
  1850. if (v.kind != ExactValue_Integer) {
  1851. return false;
  1852. }
  1853. if (out_value) *out_value = v;
  1854. if (is_type_untyped(type)) {
  1855. return true;
  1856. }
  1857. BigInt i = v.value_integer;
  1858. i64 byte_size = type_size_of(type);
  1859. BigInt umax = {};
  1860. BigInt imin = {};
  1861. BigInt imax = {};
  1862. if (c->bit_field_bit_size > 0) {
  1863. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1864. big_int_from_u64(&umax, 1);
  1865. big_int_from_i64(&imin, 1);
  1866. big_int_from_i64(&imax, 1);
  1867. BigInt bu = {};
  1868. BigInt bi = {};
  1869. big_int_from_i64(&bu, bit_size);
  1870. big_int_from_i64(&bi, bit_size-1);
  1871. big_int_shl_eq(&umax, &bu);
  1872. mp_decr(&umax);
  1873. big_int_shl_eq(&imin, &bi);
  1874. big_int_neg(&imin, &imin);
  1875. big_int_shl_eq(&imax, &bi);
  1876. mp_decr(&imax);
  1877. } else {
  1878. if (byte_size < 16) {
  1879. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1880. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1881. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1882. } else {
  1883. big_int_from_u64(&umax, 1);
  1884. big_int_from_i64(&imin, 1);
  1885. big_int_from_i64(&imax, 1);
  1886. BigInt bi128 = {};
  1887. BigInt bi127 = {};
  1888. big_int_from_i64(&bi128, 128);
  1889. big_int_from_i64(&bi127, 127);
  1890. big_int_shl_eq(&umax, &bi128);
  1891. mp_decr(&umax);
  1892. big_int_shl_eq(&imin, &bi127);
  1893. big_int_neg(&imin, &imin);
  1894. big_int_shl_eq(&imax, &bi127);
  1895. mp_decr(&imax);
  1896. }
  1897. }
  1898. switch (type->Basic.kind) {
  1899. case Basic_rune:
  1900. case Basic_i8:
  1901. case Basic_i16:
  1902. case Basic_i32:
  1903. case Basic_i64:
  1904. case Basic_i128:
  1905. case Basic_int:
  1906. case Basic_i16le:
  1907. case Basic_i32le:
  1908. case Basic_i64le:
  1909. case Basic_i128le:
  1910. case Basic_i16be:
  1911. case Basic_i32be:
  1912. case Basic_i64be:
  1913. case Basic_i128be:
  1914. {
  1915. // return imin <= i && i <= imax;
  1916. int a = big_int_cmp(&imin, &i);
  1917. int b = big_int_cmp(&i, &imax);
  1918. return (a <= 0) && (b <= 0);
  1919. }
  1920. case Basic_u8:
  1921. case Basic_u16:
  1922. case Basic_u32:
  1923. case Basic_u64:
  1924. case Basic_u128:
  1925. case Basic_uint:
  1926. case Basic_uintptr:
  1927. case Basic_u16le:
  1928. case Basic_u32le:
  1929. case Basic_u64le:
  1930. case Basic_u128le:
  1931. case Basic_u16be:
  1932. case Basic_u32be:
  1933. case Basic_u64be:
  1934. case Basic_u128be:
  1935. {
  1936. // return 0ull <= i && i <= umax;
  1937. int b = big_int_cmp(&i, &umax);
  1938. return !i.sign && (b <= 0);
  1939. }
  1940. case Basic_UntypedInteger:
  1941. return true;
  1942. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1943. }
  1944. } else if (is_type_float(type)) {
  1945. ExactValue v = exact_value_to_float(in_value);
  1946. if (v.kind != ExactValue_Float) {
  1947. return false;
  1948. }
  1949. if (out_value) *out_value = v;
  1950. switch (type->Basic.kind) {
  1951. case Basic_f16:
  1952. case Basic_f32:
  1953. case Basic_f64:
  1954. return true;
  1955. case Basic_f16le:
  1956. case Basic_f16be:
  1957. case Basic_f32le:
  1958. case Basic_f32be:
  1959. case Basic_f64le:
  1960. case Basic_f64be:
  1961. return true;
  1962. case Basic_UntypedFloat:
  1963. return true;
  1964. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1965. }
  1966. } else if (is_type_complex(type)) {
  1967. ExactValue v = exact_value_to_complex(in_value);
  1968. if (v.kind != ExactValue_Complex) {
  1969. return false;
  1970. }
  1971. switch (type->Basic.kind) {
  1972. case Basic_complex32:
  1973. case Basic_complex64:
  1974. case Basic_complex128: {
  1975. ExactValue real = exact_value_real(v);
  1976. ExactValue imag = exact_value_imag(v);
  1977. if (real.kind != ExactValue_Invalid &&
  1978. imag.kind != ExactValue_Invalid) {
  1979. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1980. return true;
  1981. }
  1982. break;
  1983. }
  1984. case Basic_UntypedComplex:
  1985. return true;
  1986. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1987. }
  1988. return false;
  1989. } else if (is_type_quaternion(type)) {
  1990. ExactValue v = exact_value_to_quaternion(in_value);
  1991. if (v.kind != ExactValue_Quaternion) {
  1992. return false;
  1993. }
  1994. switch (type->Basic.kind) {
  1995. case Basic_quaternion64:
  1996. case Basic_quaternion128:
  1997. case Basic_quaternion256: {
  1998. ExactValue real = exact_value_real(v);
  1999. ExactValue imag = exact_value_imag(v);
  2000. ExactValue jmag = exact_value_jmag(v);
  2001. ExactValue kmag = exact_value_kmag(v);
  2002. if (real.kind != ExactValue_Invalid &&
  2003. imag.kind != ExactValue_Invalid) {
  2004. 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));
  2005. return true;
  2006. }
  2007. break;
  2008. }
  2009. case Basic_UntypedComplex:
  2010. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  2011. return true;
  2012. case Basic_UntypedQuaternion:
  2013. return true;
  2014. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  2015. }
  2016. return false;
  2017. } else if (is_type_pointer(type)) {
  2018. if (in_value.kind == ExactValue_Pointer) {
  2019. return true;
  2020. }
  2021. if (in_value.kind == ExactValue_Integer) {
  2022. return false;
  2023. // return true;
  2024. }
  2025. if (in_value.kind == ExactValue_String) {
  2026. return false;
  2027. }
  2028. if (in_value.kind == ExactValue_String16) {
  2029. return false;
  2030. }
  2031. if (out_value) *out_value = in_value;
  2032. } else if (is_type_bit_set(type)) {
  2033. if (in_value.kind == ExactValue_Integer) {
  2034. return true;
  2035. }
  2036. }
  2037. return false;
  2038. }
  2039. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  2040. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  2041. gbString b = type_to_string(type);
  2042. defer (gb_string_free(b));
  2043. if (is_type_enum(o->type)) {
  2044. if (check_is_castable_to(c, o, type)) {
  2045. gbString ot = type_to_string(o->type);
  2046. error_line("\tSuggestion: Try casting the '%s' expression to '%s'", ot, b);
  2047. gb_string_free(ot);
  2048. }
  2049. return true;
  2050. }
  2051. i64 sz = type_size_of(type);
  2052. i64 bit_size = 8*sz;
  2053. bool size_changed = false;
  2054. if (max_bit_size > 0) {
  2055. size_changed = (bit_size != max_bit_size);
  2056. bit_size = gb_min(bit_size, max_bit_size);
  2057. }
  2058. BigInt *bi = &o->value.value_integer;
  2059. if (is_type_unsigned(type)) {
  2060. BigInt one = big_int_make_u64(1);
  2061. BigInt max_size = big_int_make_u64(1);
  2062. BigInt bits = big_int_make_i64(bit_size);
  2063. big_int_shl_eq(&max_size, &bits);
  2064. big_int_sub_eq(&max_size, &one);
  2065. if (big_int_is_neg(bi)) {
  2066. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  2067. BigInt dst = {};
  2068. big_int_neg(&dst, bi);
  2069. if (big_int_cmp(&dst, &max_size) < 0) {
  2070. big_int_sub_eq(&dst, &one);
  2071. String dst_str = big_int_to_string(temporary_allocator(), &dst);
  2072. gbString t = type_to_string(type);
  2073. error_line("\tSuggestion: ~%s(%.*s)\n", t, LIT(dst_str));
  2074. gb_string_free(t);
  2075. }
  2076. } else {
  2077. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2078. if (size_changed) {
  2079. 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));
  2080. } else {
  2081. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2082. }
  2083. }
  2084. } else {
  2085. BigInt zero = big_int_make_u64(0);
  2086. BigInt one = big_int_make_u64(1);
  2087. BigInt max_size = big_int_make_u64(1);
  2088. BigInt bits = big_int_make_i64(bit_size - 1);
  2089. big_int_shl_eq(&max_size, &bits);
  2090. String max_size_str = {};
  2091. if (big_int_is_neg(bi)) {
  2092. big_int_neg(&max_size, &max_size);
  2093. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2094. } else {
  2095. big_int_sub_eq(&max_size, &one);
  2096. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2097. }
  2098. if (size_changed) {
  2099. 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));
  2100. } else {
  2101. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2102. }
  2103. }
  2104. return true;
  2105. }
  2106. return false;
  2107. }
  2108. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  2109. gbString a = expr_to_string(o->expr);
  2110. gbString b = type_to_string(type);
  2111. defer(
  2112. gb_string_free(b);
  2113. gb_string_free(a);
  2114. );
  2115. Type *src = base_type(o->type);
  2116. Type *dst = base_type(type);
  2117. if (is_type_array(src) && is_type_slice(dst)) {
  2118. Type *s = src->Array.elem;
  2119. Type *d = dst->Slice.elem;
  2120. if (are_types_identical(s, d)) {
  2121. error_line("\tSuggestion: The array expression may be sliced with %s[:]\n", a);
  2122. }
  2123. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  2124. Type *s = src->DynamicArray.elem;
  2125. Type *d = dst->Slice.elem;
  2126. if (are_types_identical(s, d)) {
  2127. error_line("\tSuggestion: The dynamic array expression may be sliced with %s[:]\n", a);
  2128. }
  2129. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  2130. error_line("\tSuggestion: The expression may be directly casted to type %s\n", b);
  2131. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2132. error_line("\tSuggestion: A string may be transmuted to %s\n", b);
  2133. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable,\n");
  2134. error_line("\t whereas slices in general are assumed to be mutable.\n");
  2135. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  2136. error_line("\tSuggestion: The expression may be casted to %s\n", b);
  2137. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  2138. return;
  2139. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  2140. gbString s = expr_to_string(c->type_hint_expr);
  2141. error_line("\tSuggestion: Make sure that `%s` is attached to the compound literal directly\n", s);
  2142. gb_string_free(s);
  2143. } else if (is_type_pointer(type) &&
  2144. o->mode == Addressing_Variable &&
  2145. are_types_identical(type_deref(type), o->type)) {
  2146. gbString s = expr_to_string(o->expr);
  2147. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  2148. gb_string_free(s);
  2149. } else if (is_type_pointer(o->type) &&
  2150. are_types_identical(type_deref(o->type), type)) {
  2151. gbString s = expr_to_string(o->expr);
  2152. if (s[0] == '&') error_line("\tSuggestion: Did you mean `%s`\n", &s[1]);
  2153. else error_line("\tSuggestion: Did you mean `%s^`\n", s);
  2154. gb_string_free(s);
  2155. }
  2156. }
  2157. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  2158. gbString a = expr_to_string(o->expr);
  2159. gbString b = type_to_string(type);
  2160. defer(
  2161. gb_string_free(b);
  2162. gb_string_free(a);
  2163. );
  2164. Type *src = base_type(o->type);
  2165. Type *dst = base_type(type);
  2166. if (is_type_array(src) && is_type_slice(dst)) {
  2167. Type *s = src->Array.elem;
  2168. Type *d = dst->Slice.elem;
  2169. if (are_types_identical(s, d)) {
  2170. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2171. }
  2172. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  2173. if (is_type_uintptr(type)) {
  2174. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  2175. } else {
  2176. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  2177. i64 x = type_size_of(o->type);
  2178. i64 y = type_size_of(type);
  2179. if (x != y) {
  2180. 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);
  2181. }
  2182. }
  2183. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2184. if (is_type_uintptr(o->type)) {
  2185. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2186. } else {
  2187. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2188. }
  2189. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2190. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2191. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2192. return;
  2193. }
  2194. }
  2195. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2196. GB_ASSERT(o->mode == Addressing_Constant);
  2197. ExactValue out_value = o->value;
  2198. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2199. o->value = out_value;
  2200. return true;
  2201. } else {
  2202. o->value = out_value;
  2203. gbString a = expr_to_string(o->expr);
  2204. gbString b = type_to_string(type);
  2205. gbString c = type_to_string(o->type);
  2206. gbString s = exact_value_to_string(o->value);
  2207. defer(
  2208. gb_string_free(s);
  2209. gb_string_free(c);
  2210. gb_string_free(b);
  2211. gb_string_free(a);
  2212. o->mode = Addressing_Invalid;
  2213. );
  2214. ERROR_BLOCK();
  2215. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2216. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2217. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2218. } else {
  2219. i64 max_bit_size = 0;
  2220. if (ctx->bit_field_bit_size) {
  2221. max_bit_size = ctx->bit_field_bit_size;
  2222. }
  2223. if (are_types_identical(o->type, type)) {
  2224. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2225. } else {
  2226. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2227. }
  2228. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2229. }
  2230. } else {
  2231. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2232. check_assignment_error_suggestion(ctx, o, type);
  2233. }
  2234. return false;
  2235. }
  2236. }
  2237. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2238. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2239. if (o->expr->SelectorExpr.is_bit_field) {
  2240. return true;
  2241. }
  2242. }
  2243. if (o->mode == Addressing_OptionalOk) {
  2244. Ast *expr = unselector_expr(o->expr);
  2245. if (expr->kind != Ast_TypeAssertion) {
  2246. return true;
  2247. }
  2248. ast_node(ta, TypeAssertion, expr);
  2249. TypeAndValue tv = ta->expr->tav;
  2250. if (is_type_pointer(tv.type)) {
  2251. return false;
  2252. }
  2253. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2254. return false;
  2255. }
  2256. if (is_type_any(tv.type)) {
  2257. return false;
  2258. }
  2259. return true;
  2260. }
  2261. if (o->mode == Addressing_MapIndex) {
  2262. return false;
  2263. }
  2264. Ast *expr = unparen_expr(o->expr);
  2265. if (expr->kind == Ast_CompoundLit) {
  2266. return false;
  2267. }
  2268. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2269. }
  2270. gb_internal ExactValue exact_bit_set_all_set_mask(Type *type) {
  2271. type = base_type(type);
  2272. GB_ASSERT(type->kind == Type_BitSet);
  2273. i64 lower = type->BitSet.lower;
  2274. i64 upper = type->BitSet.upper;
  2275. Type *elem = type->BitSet.elem;
  2276. Type *underlying = type->BitSet.underlying;
  2277. bool is_backed = underlying != nullptr;
  2278. gb_unused(is_backed);
  2279. BigInt b_lower = {};
  2280. BigInt b_upper = {};
  2281. big_int_from_i64(&b_lower, lower);
  2282. big_int_from_i64(&b_upper, upper);
  2283. BigInt one = {};
  2284. big_int_from_u64(&one, 1);
  2285. BigInt mask = {};
  2286. if (elem == nullptr) {
  2287. big_int_from_i64(&mask, -1);
  2288. } else if (is_type_enum(elem)) {
  2289. Type *e = base_type(elem);
  2290. GB_ASSERT(e->kind == Type_Enum);
  2291. gb_unused(e);
  2292. if ((big_int_cmp(&e->Enum.min_value->value_integer, &b_lower) == 0 || is_backed) &&
  2293. big_int_cmp(&e->Enum.max_value->value_integer, &b_upper) == 0) {
  2294. i64 lower_base = is_backed ? gb_min(0, lower) : lower;
  2295. BigInt b_lower_base = {};
  2296. big_int_from_i64(&b_lower_base, lower_base);
  2297. for (Entity *f : e->Enum.fields) {
  2298. if (f->kind != Entity_Constant) {
  2299. continue;
  2300. }
  2301. if (f->Constant.value.kind != ExactValue_Integer) {
  2302. continue;
  2303. }
  2304. BigInt shift_amount = {};
  2305. big_int_sub(&shift_amount, &f->Constant.value.value_integer, &b_lower_base);
  2306. BigInt value = {};
  2307. big_int_shl(&value, &one, &shift_amount);
  2308. big_int_or(&mask, &mask, &value);
  2309. }
  2310. } else {
  2311. // TODO(bill): enum range based");
  2312. big_int_from_i64(&mask, -1);
  2313. }
  2314. } else {
  2315. i64 lower_base = lower;
  2316. for (i64 x = lower; x <= upper; x++) {
  2317. BigInt shift_amount = {};
  2318. big_int_from_i64(&shift_amount, x - lower_base);
  2319. BigInt value = {};
  2320. big_int_shl(&value, &one, &shift_amount);
  2321. big_int_or(&mask, &mask, &value);
  2322. }
  2323. }
  2324. ExactValue res = {};
  2325. res.kind = ExactValue_Integer;
  2326. res.value_integer = mask;
  2327. return res;
  2328. }
  2329. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2330. switch (op.kind) {
  2331. case Token_And: { // Pointer address
  2332. if (check_is_not_addressable(c, o)) {
  2333. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2334. ast_node(ue, UnaryExpr, node);
  2335. gbString str = expr_to_string(ue->expr);
  2336. defer (gb_string_free(str));
  2337. Entity *e = entity_of_node(ue->expr);
  2338. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2339. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2340. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2341. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2342. } else {
  2343. switch (o->mode) {
  2344. case Addressing_Constant:
  2345. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2346. break;
  2347. case Addressing_SwizzleValue:
  2348. case Addressing_SwizzleVariable:
  2349. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2350. break;
  2351. default:
  2352. {
  2353. ERROR_BLOCK();
  2354. error(op, "Cannot take the pointer address of '%s'", str);
  2355. if (e == nullptr) {
  2356. break;
  2357. }
  2358. if ((e->flags & EntityFlag_ForValue) != 0) {
  2359. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2360. if (parent_type != nullptr && is_type_string(parent_type)) {
  2361. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2362. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2363. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2364. } else {
  2365. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2366. }
  2367. if (parent_type != nullptr && is_type_map(parent_type)) {
  2368. error_line("\t Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2369. } else {
  2370. error_line("\t Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2371. }
  2372. }
  2373. if ((e->flags & EntityFlag_SwitchValue) != 0) {
  2374. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2375. error_line("\t Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2376. }
  2377. }
  2378. break;
  2379. }
  2380. }
  2381. }
  2382. o->mode = Addressing_Invalid;
  2383. return;
  2384. }
  2385. if (o->mode == Addressing_SoaVariable) {
  2386. ast_node(ue, UnaryExpr, node);
  2387. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2388. ast_node(ie, IndexExpr, ue->expr);
  2389. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2390. GB_ASSERT(is_type_soa_struct(soa_type));
  2391. o->type = alloc_type_soa_pointer(soa_type);
  2392. } else {
  2393. o->type = alloc_type_pointer(o->type);
  2394. }
  2395. } else {
  2396. o->type = alloc_type_pointer(o->type);
  2397. }
  2398. switch (o->mode) {
  2399. case Addressing_OptionalOk:
  2400. case Addressing_MapIndex:
  2401. o->mode = Addressing_OptionalOkPtr;
  2402. break;
  2403. default:
  2404. o->mode = Addressing_Value;
  2405. break;
  2406. }
  2407. return;
  2408. }
  2409. }
  2410. if (!check_unary_op(c, o, op)) {
  2411. o->mode = Addressing_Invalid;
  2412. return;
  2413. }
  2414. if (o->mode == Addressing_Constant) {
  2415. Type *type = base_type(o->type);
  2416. if (!is_type_constant_type(o->type)) {
  2417. if (is_type_array_like(o->type)) {
  2418. o->mode = Addressing_Value;
  2419. return;
  2420. }
  2421. gbString xt = type_to_string(o->type);
  2422. gbString err_str = expr_to_string(node);
  2423. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2424. gb_string_free(err_str);
  2425. gb_string_free(xt);
  2426. o->mode = Addressing_Invalid;
  2427. return;
  2428. }
  2429. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2430. gbString err_str = expr_to_string(node);
  2431. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2432. gb_string_free(err_str);
  2433. o->mode = Addressing_Invalid;
  2434. return;
  2435. }
  2436. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2437. gbString err_str = expr_to_string(node);
  2438. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2439. gb_string_free(err_str);
  2440. o->mode = Addressing_Invalid;
  2441. return;
  2442. }
  2443. i32 precision = 0;
  2444. if (is_type_typed(type)) {
  2445. precision = cast(i32)(8 * type_size_of(type));
  2446. }
  2447. bool is_unsigned = is_type_unsigned(type);
  2448. if (is_type_rune(type)) {
  2449. GB_ASSERT(!is_unsigned);
  2450. }
  2451. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2452. if (op.kind == Token_Xor && is_type_bit_set(type)) {
  2453. ExactValue mask = exact_bit_set_all_set_mask(type);
  2454. o->value = exact_binary_operator_value(Token_And, o->value, mask);
  2455. }
  2456. if (is_type_typed(type)) {
  2457. if (node != nullptr) {
  2458. o->expr = node;
  2459. }
  2460. check_is_expressible(c, o, type);
  2461. }
  2462. return;
  2463. }
  2464. o->mode = Addressing_Value;
  2465. }
  2466. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2467. if (t == nullptr) {
  2468. return;
  2469. }
  2470. t = base_type(t);
  2471. if (!is_type_comparable(t)) {
  2472. return;
  2473. }
  2474. switch (t->kind) {
  2475. case Type_Basic:
  2476. switch (t->Basic.kind) {
  2477. case Basic_complex32:
  2478. add_package_dependency(c, "runtime", "complex32_eq");
  2479. add_package_dependency(c, "runtime", "complex32_ne");
  2480. break;
  2481. case Basic_complex64:
  2482. add_package_dependency(c, "runtime", "complex64_eq");
  2483. add_package_dependency(c, "runtime", "complex64_ne");
  2484. break;
  2485. case Basic_complex128:
  2486. add_package_dependency(c, "runtime", "complex128_eq");
  2487. add_package_dependency(c, "runtime", "complex128_ne");
  2488. break;
  2489. case Basic_quaternion64:
  2490. add_package_dependency(c, "runtime", "quaternion64_eq");
  2491. add_package_dependency(c, "runtime", "quaternion64_ne");
  2492. break;
  2493. case Basic_quaternion128:
  2494. add_package_dependency(c, "runtime", "quaternion128_eq");
  2495. add_package_dependency(c, "runtime", "quaternion128_ne");
  2496. break;
  2497. case Basic_quaternion256:
  2498. add_package_dependency(c, "runtime", "quaternion256_eq");
  2499. add_package_dependency(c, "runtime", "quaternion256_ne");
  2500. break;
  2501. case Basic_cstring:
  2502. add_package_dependency(c, "runtime", "cstring_eq");
  2503. add_package_dependency(c, "runtime", "cstring_ne");
  2504. break;
  2505. case Basic_string:
  2506. add_package_dependency(c, "runtime", "string_eq");
  2507. add_package_dependency(c, "runtime", "string_ne");
  2508. break;
  2509. case Basic_cstring16:
  2510. add_package_dependency(c, "runtime", "cstring16_eq");
  2511. add_package_dependency(c, "runtime", "cstring16_ne");
  2512. break;
  2513. case Basic_string16:
  2514. add_package_dependency(c, "runtime", "string16_eq");
  2515. add_package_dependency(c, "runtime", "string16_ne");
  2516. break;
  2517. }
  2518. break;
  2519. case Type_Struct:
  2520. for (Entity *field : t->Struct.fields) {
  2521. add_comparison_procedures_for_fields(c, field->type);
  2522. }
  2523. break;
  2524. }
  2525. }
  2526. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2527. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2528. bool comp = are_types_identical(x->type, y->type);
  2529. switch (op) {
  2530. case Token_CmpEq: /* comp = comp; */ break;
  2531. case Token_NotEq: comp = !comp; break;
  2532. }
  2533. x->mode = Addressing_Constant;
  2534. x->type = t_untyped_bool;
  2535. x->value = exact_value_bool(comp);
  2536. return;
  2537. }
  2538. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2539. add_type_info_type(c, x->type);
  2540. add_type_info_type(c, y->type);
  2541. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2542. x->mode = Addressing_Value;
  2543. x->type = t_untyped_bool;
  2544. return;
  2545. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2546. add_type_info_type(c, x->type);
  2547. add_type_info_type(c, y->type);
  2548. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2549. x->mode = Addressing_Value;
  2550. x->type = t_untyped_bool;
  2551. return;
  2552. }
  2553. TEMPORARY_ALLOCATOR_GUARD();
  2554. gbString err_str = nullptr;
  2555. if (check_is_assignable_to(c, x, y->type) ||
  2556. check_is_assignable_to(c, y, x->type)) {
  2557. Type *err_type = x->type;
  2558. bool defined = false;
  2559. switch (op) {
  2560. case Token_CmpEq:
  2561. case Token_NotEq:
  2562. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2563. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2564. (is_operand_nil(*y) && type_has_nil(x->type));
  2565. break;
  2566. case Token_Lt:
  2567. case Token_Gt:
  2568. case Token_LtEq:
  2569. case Token_GtEq:
  2570. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2571. defined = true;
  2572. } else {
  2573. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2574. }
  2575. break;
  2576. }
  2577. if (!defined) {
  2578. gbString xs = type_to_string(x->type, temporary_allocator());
  2579. gbString ys = type_to_string(y->type, temporary_allocator());
  2580. if (!is_type_comparable(x->type)) {
  2581. err_str = gb_string_make(temporary_allocator(),
  2582. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", xs, LIT(token_strings[op]))
  2583. );
  2584. } else if (!is_type_comparable(y->type)) {
  2585. err_str = gb_string_make(temporary_allocator(),
  2586. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", ys, LIT(token_strings[op]))
  2587. );
  2588. } else {
  2589. err_str = gb_string_make(temporary_allocator(),
  2590. gb_bprintf("Operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2591. );
  2592. }
  2593. } else {
  2594. Type *comparison_type = x->type;
  2595. if (x->type == err_type && is_operand_nil(*x)) {
  2596. comparison_type = y->type;
  2597. }
  2598. add_comparison_procedures_for_fields(c, comparison_type);
  2599. }
  2600. } else {
  2601. gbString xt, yt;
  2602. if (x->mode == Addressing_ProcGroup) {
  2603. xt = gb_string_make(temporary_allocator(), "procedure group");
  2604. } else {
  2605. xt = type_to_string(x->type);
  2606. }
  2607. if (y->mode == Addressing_ProcGroup) {
  2608. yt = gb_string_make(temporary_allocator(), "procedure group");
  2609. } else {
  2610. yt = type_to_string(y->type);
  2611. }
  2612. err_str = gb_string_make(temporary_allocator(), gb_bprintf("Mismatched types '%s' and '%s'", xt, yt));
  2613. }
  2614. if (err_str != nullptr) {
  2615. error(node, "Cannot compare expression. %s.", err_str);
  2616. x->type = t_untyped_bool;
  2617. } else {
  2618. if (x->mode == Addressing_Constant &&
  2619. y->mode == Addressing_Constant) {
  2620. if (is_type_constant_type(x->type)) {
  2621. if (is_type_bit_set(x->type)) {
  2622. switch (op) {
  2623. case Token_CmpEq:
  2624. case Token_NotEq:
  2625. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2626. break;
  2627. case Token_Lt:
  2628. case Token_LtEq:
  2629. {
  2630. ExactValue lhs = x->value;
  2631. ExactValue rhs = y->value;
  2632. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2633. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2634. if (op == Token_Lt) {
  2635. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2636. }
  2637. x->value = res;
  2638. break;
  2639. }
  2640. case Token_Gt:
  2641. case Token_GtEq:
  2642. {
  2643. ExactValue lhs = x->value;
  2644. ExactValue rhs = y->value;
  2645. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2646. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2647. if (op == Token_Gt) {
  2648. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2649. }
  2650. x->value = res;
  2651. break;
  2652. }
  2653. }
  2654. } else {
  2655. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2656. }
  2657. } else {
  2658. x->mode = Addressing_Value;
  2659. }
  2660. } else {
  2661. x->mode = Addressing_Value;
  2662. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2663. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2664. i64 size = 0;
  2665. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2666. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2667. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2668. switch (op) {
  2669. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2670. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2671. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2672. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2673. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2674. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2675. }
  2676. } else if (is_type_cstring16(x->type) && is_type_cstring16(y->type)) {
  2677. switch (op) {
  2678. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring16_eq"); break;
  2679. case Token_NotEq: add_package_dependency(c, "runtime", "cstring16_ne"); break;
  2680. case Token_Lt: add_package_dependency(c, "runtime", "cstring16_lt"); break;
  2681. case Token_Gt: add_package_dependency(c, "runtime", "cstring16_gt"); break;
  2682. case Token_LtEq: add_package_dependency(c, "runtime", "cstring16_le"); break;
  2683. case Token_GtEq: add_package_dependency(c, "runtime", "cstring16_gt"); break;
  2684. }
  2685. } else if (is_type_string16(x->type) || is_type_string16(y->type)) {
  2686. switch (op) {
  2687. case Token_CmpEq: add_package_dependency(c, "runtime", "string16_eq"); break;
  2688. case Token_NotEq: add_package_dependency(c, "runtime", "string16_ne"); break;
  2689. case Token_Lt: add_package_dependency(c, "runtime", "string16_lt"); break;
  2690. case Token_Gt: add_package_dependency(c, "runtime", "string16_gt"); break;
  2691. case Token_LtEq: add_package_dependency(c, "runtime", "string16_le"); break;
  2692. case Token_GtEq: add_package_dependency(c, "runtime", "string16_gt"); break;
  2693. }
  2694. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2695. switch (op) {
  2696. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2697. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2698. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2699. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2700. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2701. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2702. }
  2703. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2704. switch (op) {
  2705. case Token_CmpEq:
  2706. switch (8*size) {
  2707. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2708. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2709. }
  2710. break;
  2711. case Token_NotEq:
  2712. switch (8*size) {
  2713. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2714. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2715. }
  2716. break;
  2717. }
  2718. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2719. switch (op) {
  2720. case Token_CmpEq:
  2721. switch (8*size) {
  2722. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2723. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2724. }
  2725. break;
  2726. case Token_NotEq:
  2727. switch (8*size) {
  2728. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2729. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2730. }
  2731. break;
  2732. }
  2733. }
  2734. }
  2735. x->type = t_untyped_bool;
  2736. }
  2737. }
  2738. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2739. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2740. ast_node(be, BinaryExpr, node);
  2741. bool y_is_untyped = is_type_untyped(y->type);
  2742. if (y_is_untyped) {
  2743. convert_to_typed(c, y, t_untyped_integer);
  2744. if (y->mode == Addressing_Invalid) {
  2745. x->mode = Addressing_Invalid;
  2746. return;
  2747. }
  2748. } else if (!is_type_unsigned(y->type)) {
  2749. gbString y_str = expr_to_string(y->expr);
  2750. error(y->expr, "Shift amount '%s' must be an unsigned integer", y_str);
  2751. gb_string_free(y_str);
  2752. x->mode = Addressing_Invalid;
  2753. return;
  2754. }
  2755. bool x_is_untyped = is_type_untyped(x->type);
  2756. if (!(x_is_untyped || is_type_integer(x->type))) {
  2757. gbString x_str = expr_to_string(x->expr);
  2758. error(x->expr, "Shifted operand '%s' must be an integer", x_str);
  2759. gb_string_free(x_str);
  2760. x->mode = Addressing_Invalid;
  2761. return;
  2762. }
  2763. if (y->mode == Addressing_Constant) {
  2764. if (big_int_is_neg(&y->value.value_integer)) {
  2765. gbString y_str = expr_to_string(y->expr);
  2766. error(y->expr, "Shift amount '%s' cannot be negative", y_str);
  2767. gb_string_free(y_str);
  2768. x->mode = Addressing_Invalid;
  2769. return;
  2770. }
  2771. BigInt max_shift = {};
  2772. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2773. if (big_int_cmp(&y->value.value_integer, &max_shift) > 0) {
  2774. gbString y_str = expr_to_string(y->expr);
  2775. error(y->expr, "Shift amount '%s' must be <= %u", y_str, MAX_BIG_INT_SHIFT);
  2776. gb_string_free(y_str);
  2777. x->mode = Addressing_Invalid;
  2778. return;
  2779. }
  2780. if (x->mode == Addressing_Constant) {
  2781. if (x_is_untyped) {
  2782. convert_to_typed(c, x, t_untyped_integer);
  2783. if (x->mode == Addressing_Invalid) {
  2784. return;
  2785. }
  2786. x->expr = node;
  2787. x->value = exact_value_shift(be->op.kind, exact_value_to_integer(x->value), exact_value_to_integer(y->value));
  2788. return;
  2789. }
  2790. x->expr = node;
  2791. x->value = exact_value_shift(be->op.kind, x->value, y->value);
  2792. check_is_expressible(c, x, x->type);
  2793. return;
  2794. }
  2795. if (y_is_untyped) {
  2796. convert_to_typed(c, y, t_uint);
  2797. }
  2798. return;
  2799. }
  2800. if (x->mode == Addressing_Constant) {
  2801. if (x_is_untyped) {
  2802. if (type_hint) {
  2803. if (is_type_integer(type_hint)) {
  2804. convert_to_typed(c, x, type_hint);
  2805. } else if (is_type_any(type_hint)) {
  2806. convert_to_typed(c, x, default_type(t_untyped_integer));
  2807. } else {
  2808. gbString x_str = expr_to_string(x->expr);
  2809. gbString type_str = type_to_string(type_hint);
  2810. error(x->expr, "Shifted operand '%s' cannot convert to non-integer type '%s'", x_str, type_str);
  2811. gb_string_free(x_str);
  2812. gb_string_free(type_str);
  2813. x->mode = Addressing_Invalid;
  2814. return;
  2815. }
  2816. } else {
  2817. check_is_expressible(c, x, default_type(t_untyped_integer));
  2818. }
  2819. if (x->mode == Addressing_Invalid) {
  2820. return;
  2821. }
  2822. }
  2823. x->mode = Addressing_Value;
  2824. }
  2825. }
  2826. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2827. if (check_is_assignable_to(c, operand, y)) {
  2828. return true;
  2829. }
  2830. bool is_constant = operand->mode == Addressing_Constant;
  2831. Type *x = operand->type;
  2832. Type *src = core_type(x);
  2833. Type *dst = core_type(y);
  2834. if (are_types_identical(src, dst)) {
  2835. return true;
  2836. }
  2837. // if (is_type_tuple(src)) {
  2838. // Ast *expr = unparen_expr(operand->expr);
  2839. // if (expr && expr->kind == Ast_CallExpr) {
  2840. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2841. // ast_node(ce, CallExpr, expr);
  2842. // Type *pt = base_type(type_of_expr(ce->proc));
  2843. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2844. // if (pt->Proc.result_count > 0) {
  2845. // Operand op = *operand;
  2846. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2847. // bool ok = check_is_castable_to(c, &op, y);
  2848. // if (ok) {
  2849. // ce->optional_ok_one = true;
  2850. // }
  2851. // return ok;
  2852. // }
  2853. // }
  2854. // }
  2855. // }
  2856. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2857. if (is_type_u8_array(dst)) {
  2858. String s = operand->value.value_string;
  2859. return s.len == dst->Array.count;
  2860. }
  2861. if (is_type_rune_array(dst)) {
  2862. String s = operand->value.value_string;
  2863. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2864. }
  2865. }
  2866. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2867. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2868. return dst->Array.count == src->Array.count;
  2869. }
  2870. }
  2871. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2872. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2873. }
  2874. // Cast between booleans and integers
  2875. if (is_type_boolean(src) || is_type_integer(src)) {
  2876. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2877. return true;
  2878. }
  2879. }
  2880. // Cast between numbers
  2881. if (is_type_integer(src) || is_type_float(src)) {
  2882. if (is_type_integer(dst) || is_type_float(dst)) {
  2883. return true;
  2884. }
  2885. }
  2886. if (is_type_bit_field(src)) {
  2887. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2888. }
  2889. if (is_type_bit_field(dst)) {
  2890. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2891. }
  2892. if (is_type_integer(src) && is_type_rune(dst)) {
  2893. return true;
  2894. }
  2895. if (is_type_rune(src) && is_type_integer(dst)) {
  2896. return true;
  2897. }
  2898. if (is_type_complex(src) && is_type_complex(dst)) {
  2899. return true;
  2900. }
  2901. if (is_type_float(src) && is_type_complex(dst)) {
  2902. return true;
  2903. }
  2904. if (is_type_float(src) && is_type_quaternion(dst)) {
  2905. return true;
  2906. }
  2907. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2908. return true;
  2909. }
  2910. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2911. return true;
  2912. }
  2913. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2914. GB_ASSERT(src->kind == Type_Matrix);
  2915. GB_ASSERT(dst->kind == Type_Matrix);
  2916. Operand op = *operand;
  2917. op.type = src->Matrix.elem;
  2918. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2919. return false;
  2920. }
  2921. if (src->Matrix.row_count != src->Matrix.column_count) {
  2922. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2923. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2924. return src_count == dst_count;
  2925. }
  2926. return is_matrix_square(dst) && is_matrix_square(src);
  2927. }
  2928. // Cast between pointers
  2929. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2930. return true;
  2931. }
  2932. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2933. return true;
  2934. }
  2935. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2936. return true;
  2937. }
  2938. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2939. return true;
  2940. }
  2941. // uintptr <-> pointer
  2942. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2943. return true;
  2944. }
  2945. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2946. return true;
  2947. }
  2948. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2949. return true;
  2950. }
  2951. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2952. return true;
  2953. }
  2954. // []byte/[]u8 <-> string (not cstring)
  2955. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2956. return true;
  2957. }
  2958. // []u16 <-> string16 (not cstring16)
  2959. if (is_type_u16_slice(src) && (is_type_string16(dst) && !is_type_cstring16(dst))) {
  2960. return true;
  2961. }
  2962. // cstring -> string
  2963. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2964. if (operand->mode != Addressing_Constant) {
  2965. add_package_dependency(c, "runtime", "cstring_to_string");
  2966. }
  2967. return true;
  2968. }
  2969. // cstring16 -> string16
  2970. if (are_types_identical(src, t_cstring16) && are_types_identical(dst, t_string16)) {
  2971. if (operand->mode != Addressing_Constant) {
  2972. add_package_dependency(c, "runtime", "cstring16_to_string16");
  2973. }
  2974. return true;
  2975. }
  2976. // cstring -> ^u8
  2977. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2978. return !is_constant;
  2979. }
  2980. // cstring -> [^]u8
  2981. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2982. return !is_constant;
  2983. }
  2984. // cstring -> rawptr
  2985. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2986. return !is_constant;
  2987. }
  2988. // ^u8 -> cstring
  2989. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2990. return !is_constant;
  2991. }
  2992. // [^]u8 -> cstring
  2993. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2994. return !is_constant;
  2995. }
  2996. // rawptr -> cstring
  2997. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2998. return !is_constant;
  2999. }
  3000. // cstring -> ^u16
  3001. if (are_types_identical(src, t_cstring16) && is_type_u16_ptr(dst)) {
  3002. return !is_constant;
  3003. }
  3004. // cstring -> [^]u16
  3005. if (are_types_identical(src, t_cstring16) && is_type_u16_multi_ptr(dst)) {
  3006. return !is_constant;
  3007. }
  3008. // cstring16 -> rawptr
  3009. if (are_types_identical(src, t_cstring16) && is_type_rawptr(dst)) {
  3010. return !is_constant;
  3011. }
  3012. // ^u16 -> cstring16
  3013. if (is_type_u16_ptr(src) && are_types_identical(dst, t_cstring16)) {
  3014. return !is_constant;
  3015. }
  3016. // [^]u16 -> cstring
  3017. if (is_type_u16_multi_ptr(src) && are_types_identical(dst, t_cstring16)) {
  3018. return !is_constant;
  3019. }
  3020. // rawptr -> cstring16
  3021. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring16)) {
  3022. return !is_constant;
  3023. }
  3024. // proc <-> proc
  3025. if (is_type_proc(src) && is_type_proc(dst)) {
  3026. if (is_type_polymorphic(dst)) {
  3027. if (is_type_polymorphic(src) &&
  3028. operand->mode == Addressing_Variable) {
  3029. return true;
  3030. }
  3031. return false;
  3032. }
  3033. return true;
  3034. }
  3035. // proc -> rawptr
  3036. if (is_type_proc(src) && is_type_rawptr(dst)) {
  3037. return true;
  3038. }
  3039. // rawptr -> proc
  3040. if (is_type_rawptr(src) && is_type_proc(dst)) {
  3041. return true;
  3042. }
  3043. if (is_type_array(dst)) {
  3044. Type *elem = base_array_type(dst);
  3045. if (check_is_castable_to(c, operand, elem)) {
  3046. return true;
  3047. }
  3048. }
  3049. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  3050. if (src->SimdVector.count != dst->SimdVector.count) {
  3051. return false;
  3052. }
  3053. Type *elem_src = base_array_type(src);
  3054. Type *elem_dst = base_array_type(dst);
  3055. Operand x = {};
  3056. x.type = elem_src;
  3057. x.mode = Addressing_Value;
  3058. return check_is_castable_to(c, &x, elem_dst);
  3059. }
  3060. if (is_type_simd_vector(dst)) {
  3061. Type *elem = base_array_type(dst);
  3062. if (check_is_castable_to(c, operand, elem)) {
  3063. return true;
  3064. }
  3065. }
  3066. return false;
  3067. }
  3068. gb_internal bool is_type_union_constantable(Type *type) {
  3069. Type *bt = base_type(type);
  3070. GB_ASSERT(bt->kind == Type_Union);
  3071. if (bt->Union.variants.count == 0) {
  3072. return true;
  3073. } else if (bt->Union.variants.count == 1) {
  3074. return is_type_constant_type(bt->Union.variants[0]);
  3075. }
  3076. for (Type *v : bt->Union.variants) {
  3077. if (!is_type_constant_type(v)) {
  3078. return false;
  3079. }
  3080. }
  3081. return false;
  3082. }
  3083. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  3084. bool is_const_expr = x->mode == Addressing_Constant;
  3085. Type *bt = base_type(type);
  3086. if (is_const_expr && is_type_constant_type(bt)) {
  3087. if (core_type(bt)->kind == Type_Basic) {
  3088. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  3089. return true;
  3090. } else if (check_is_castable_to(c, x, type)) {
  3091. if (is_type_pointer(type)) {
  3092. return true;
  3093. }
  3094. }
  3095. } else if (check_is_castable_to(c, x, type)) {
  3096. x->value = {};
  3097. x->mode = Addressing_Value;
  3098. return true;
  3099. }
  3100. } else if (check_is_castable_to(c, x, type)) {
  3101. if (x->mode != Addressing_Constant) {
  3102. x->mode = Addressing_Value;
  3103. } else if (is_type_slice(type) && is_type_string(x->type)) {
  3104. x->mode = Addressing_Value;
  3105. } else if (is_type_union(type)) {
  3106. if (is_type_union_constantable(type)) {
  3107. return true;
  3108. }
  3109. x->mode = Addressing_Value;
  3110. }
  3111. if (x->mode == Addressing_Value) {
  3112. x->value = {};
  3113. }
  3114. return true;
  3115. }
  3116. return false;
  3117. }
  3118. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type, bool forbid_identical = false) {
  3119. if (!is_operand_value(*x)) {
  3120. error(x->expr, "Only values can be casted");
  3121. x->mode = Addressing_Invalid;
  3122. return;
  3123. }
  3124. bool is_const_expr = x->mode == Addressing_Constant;
  3125. bool can_convert = check_cast_internal(c, x, type);
  3126. if (!can_convert) {
  3127. TEMPORARY_ALLOCATOR_GUARD();
  3128. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  3129. gbString to_type = type_to_string(type, temporary_allocator());
  3130. gbString from_type = type_to_string(x->type, temporary_allocator());
  3131. x->mode = Addressing_Invalid;
  3132. ERROR_BLOCK();
  3133. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  3134. if (is_const_expr) {
  3135. gbString val_str = exact_value_to_string(x->value);
  3136. if (is_type_float(x->type) && is_type_integer(type)) {
  3137. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  3138. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3139. x->mode = Addressing_Constant;
  3140. x->type = type;
  3141. } else {
  3142. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  3143. if (is_type_numeric(type)) {
  3144. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3145. x->mode = Addressing_Constant;
  3146. x->type = type;
  3147. }
  3148. }
  3149. gb_string_free(val_str);
  3150. }
  3151. check_cast_error_suggestion(c, x, type);
  3152. return;
  3153. }
  3154. if (is_type_untyped(x->type)) {
  3155. Type *final_type = type;
  3156. if (is_const_expr && !is_type_constant_type(type)) {
  3157. if (is_type_union(type)) {
  3158. if (is_type_union_constantable(type)) {
  3159. } else {
  3160. convert_to_typed(c, x, type);
  3161. }
  3162. }
  3163. final_type = default_type(x->type);
  3164. }
  3165. update_untyped_expr_type(c, x->expr, final_type, true);
  3166. } else {
  3167. Type *src = core_type(x->type);
  3168. Type *dst = core_type(type);
  3169. if (src != dst) {
  3170. bool const REQUIRE = true;
  3171. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  3172. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  3173. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  3174. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  3175. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  3176. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  3177. } else if (src == t_f16 && is_type_float(dst)) {
  3178. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  3179. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  3180. } else if (is_type_float(dst) && dst == t_f16) {
  3181. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  3182. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  3183. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  3184. }
  3185. }
  3186. // If we check polymorphic procedures, we risk erring on
  3187. // identical casts that cannot be foreseen or otherwise
  3188. // forbidden, so just skip them.
  3189. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3190. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig))) {
  3191. Type *src_exact = x->type;
  3192. Type *dst_exact = type;
  3193. if (src_exact != nullptr &&
  3194. dst_exact != nullptr &&
  3195. are_types_identical(src_exact, dst_exact)
  3196. ) {
  3197. gbString oper_str = expr_to_string(x->expr);
  3198. gbString to_type = type_to_string(dst_exact);
  3199. error(x->expr, "Unneeded cast of '%s' to identical type '%s'", oper_str, to_type);
  3200. gb_string_free(oper_str);
  3201. gb_string_free(to_type);
  3202. }
  3203. }
  3204. }
  3205. x->type = type;
  3206. }
  3207. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t, bool forbid_identical = false) {
  3208. if (!is_operand_value(*o)) {
  3209. error(o->expr, "'transmute' can only be applied to values");
  3210. o->mode = Addressing_Invalid;
  3211. return false;
  3212. }
  3213. Operand src = *o;
  3214. Type *src_t = o->type;
  3215. Type *dst_t = t;
  3216. Type *src_bt = base_type(src_t);
  3217. Type *dst_bt = base_type(dst_t);
  3218. if (is_type_untyped(src_t)) {
  3219. gbString expr_str = expr_to_string(o->expr);
  3220. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  3221. gb_string_free(expr_str);
  3222. o->mode = Addressing_Invalid;
  3223. o->expr = node;
  3224. return false;
  3225. }
  3226. if (dst_bt == nullptr || dst_bt == t_invalid) {
  3227. GB_ASSERT(global_error_collector.count != 0);
  3228. o->mode = Addressing_Invalid;
  3229. o->expr = node;
  3230. return false;
  3231. }
  3232. if (src_bt == nullptr || src_bt == t_invalid) {
  3233. // NOTE(bill): this should be an error
  3234. GB_ASSERT(global_error_collector.count != 0);
  3235. o->mode = Addressing_Value;
  3236. o->expr = node;
  3237. o->type = dst_t;
  3238. return true;
  3239. }
  3240. i64 srcz = type_size_of(src_t);
  3241. i64 dstz = type_size_of(dst_t);
  3242. if (srcz != dstz) {
  3243. gbString expr_str = expr_to_string(o->expr);
  3244. gbString type_str = type_to_string(dst_t);
  3245. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  3246. gb_string_free(type_str);
  3247. gb_string_free(expr_str);
  3248. o->mode = Addressing_Invalid;
  3249. o->expr = node;
  3250. return false;
  3251. }
  3252. o->expr = node;
  3253. o->type = dst_t;
  3254. if (o->mode == Addressing_Constant) {
  3255. if (are_types_identical(src_bt, dst_bt)) {
  3256. return true;
  3257. }
  3258. if ((is_type_integer(src_t) && is_type_integer(dst_t)) ||
  3259. is_type_integer(src_t) && is_type_bit_set(dst_t)) {
  3260. if (types_have_same_internal_endian(src_t, dst_t)) {
  3261. ExactValue src_v = exact_value_to_integer(o->value);
  3262. GB_ASSERT(src_v.kind == ExactValue_Integer || src_v.kind == ExactValue_Invalid);
  3263. BigInt v = src_v.value_integer;
  3264. BigInt smax = {};
  3265. BigInt umax = {};
  3266. big_int_from_u64(&smax, 0);
  3267. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  3268. big_int_from_u64(&umax, 1);
  3269. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  3270. big_int_shl_eq(&umax, &sz_in_bits);
  3271. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  3272. if (big_int_cmp(&v, &smax) >= 0) {
  3273. big_int_sub_eq(&v, &umax);
  3274. }
  3275. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  3276. if (big_int_is_neg(&v)) {
  3277. big_int_add_eq(&v, &umax);
  3278. }
  3279. }
  3280. o->value.kind = ExactValue_Integer;
  3281. o->value.value_integer = v;
  3282. return true;
  3283. }
  3284. }
  3285. } else {
  3286. // If we check polymorphic procedures, we risk erring on
  3287. // identical casts that cannot be foreseen or otherwise
  3288. // forbidden, so just skip them.
  3289. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3290. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig)) &&
  3291. check_is_castable_to(c, &src, dst_t)) {
  3292. if (are_types_identical(src_t, dst_t)) {
  3293. gbString oper_str = expr_to_string(o->expr);
  3294. gbString to_type = type_to_string(dst_t);
  3295. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3296. gb_string_free(oper_str);
  3297. gb_string_free(to_type);
  3298. } else if (is_type_internally_pointer_like(src_t) &&
  3299. is_type_internally_pointer_like(dst_t)) {
  3300. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since the types are pointer-like");
  3301. } else if (are_types_identical(src_bt, dst_bt)) {
  3302. gbString oper_str = expr_to_string(o->expr);
  3303. gbString to_type = type_to_string(dst_t);
  3304. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3305. gb_string_free(oper_str);
  3306. gb_string_free(to_type);
  3307. } else if (is_type_integer(src_t) && is_type_integer(dst_t) &&
  3308. types_have_same_internal_endian(src_t, dst_t) &&
  3309. type_endian_kind_of(src_t) == type_endian_kind_of(dst_t)) {
  3310. gbString oper_type = type_to_string(src_t);
  3311. gbString to_type = type_to_string(dst_t);
  3312. 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);
  3313. gb_string_free(to_type);
  3314. gb_string_free(oper_type);
  3315. }
  3316. }
  3317. }
  3318. o->mode = Addressing_Value;
  3319. o->value = {};
  3320. return true;
  3321. }
  3322. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  3323. if (is_type_array_like(x->type) || is_type_array_like(y->type)) {
  3324. if (op.kind == Token_CmpAnd || op.kind == Token_CmpOr) {
  3325. error(op, "Array programming is not allowed with the operator '%.*s'", LIT(op.string));
  3326. }
  3327. }
  3328. if (is_type_array(x->type) && !is_type_array(y->type)) {
  3329. if (check_is_assignable_to(c, y, x->type)) {
  3330. if (check_binary_op(c, x, op)) {
  3331. return true;
  3332. }
  3333. }
  3334. }
  3335. if (is_type_simd_vector(x->type) && !is_type_simd_vector(y->type)) {
  3336. if (check_is_assignable_to(c, y, x->type)) {
  3337. if (check_binary_op(c, x, op)) {
  3338. return true;
  3339. }
  3340. }
  3341. }
  3342. return false;
  3343. }
  3344. gb_internal bool is_ise_expr(Ast *node) {
  3345. node = unparen_expr(node);
  3346. return node->kind == Ast_ImplicitSelectorExpr;
  3347. }
  3348. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  3349. if (use_lhs_as_type_hint) { // RHS in this case
  3350. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  3351. }
  3352. return false;
  3353. }
  3354. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  3355. Type *xt = base_type(matrix);
  3356. if (type_hint != nullptr) {
  3357. Type *th = base_type(type_hint);
  3358. if (are_types_identical(th, xt)) {
  3359. return type_hint;
  3360. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  3361. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  3362. // ignore
  3363. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  3364. xt->Matrix.column_count == th->Matrix.column_count) {
  3365. return type_hint;
  3366. }
  3367. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  3368. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  3369. // ignore
  3370. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  3371. return type_hint;
  3372. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3373. return type_hint;
  3374. }
  3375. }
  3376. }
  3377. return matrix;
  3378. }
  3379. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3380. if (!check_binary_op(c, x, op)) {
  3381. x->mode = Addressing_Invalid;
  3382. return;
  3383. }
  3384. Type *xt = base_type(x->type);
  3385. Type *yt = base_type(y->type);
  3386. if (is_type_matrix(x->type)) {
  3387. GB_ASSERT(xt->kind == Type_Matrix);
  3388. if (op.kind == Token_Mul) {
  3389. if (yt->kind == Type_Matrix) {
  3390. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3391. goto matrix_error;
  3392. }
  3393. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3394. goto matrix_error;
  3395. }
  3396. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3397. goto matrix_error;
  3398. }
  3399. x->mode = Addressing_Value;
  3400. if (are_types_identical(xt, yt)) {
  3401. if (are_types_identical(x->type, y->type)) {
  3402. return;
  3403. }
  3404. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3405. // prefer the named type
  3406. x->type = y->type;
  3407. }
  3408. } else {
  3409. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3410. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3411. }
  3412. goto matrix_success;
  3413. } else if (yt->kind == Type_Array) {
  3414. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3415. goto matrix_error;
  3416. }
  3417. if (xt->Matrix.column_count != yt->Array.count) {
  3418. goto matrix_error;
  3419. }
  3420. // Treat arrays as column vectors
  3421. x->mode = Addressing_Value;
  3422. if (xt->Matrix.row_count == yt->Array.count) {
  3423. x->type = y->type;
  3424. } else {
  3425. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3426. }
  3427. goto matrix_success;
  3428. }
  3429. }
  3430. if (!are_types_identical(xt, yt)) {
  3431. goto matrix_error;
  3432. }
  3433. x->mode = Addressing_Value;
  3434. x->type = xt;
  3435. goto matrix_success;
  3436. } else {
  3437. GB_ASSERT(!is_type_matrix(xt));
  3438. GB_ASSERT(is_type_matrix(yt));
  3439. if (op.kind == Token_Mul) {
  3440. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3441. if (xt->kind == Type_Array) {
  3442. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3443. goto matrix_error;
  3444. }
  3445. if (xt->Array.count != yt->Matrix.row_count) {
  3446. goto matrix_error;
  3447. }
  3448. // Treat arrays as row vectors
  3449. x->mode = Addressing_Value;
  3450. if (yt->Matrix.column_count == xt->Array.count) {
  3451. x->type = x->type;
  3452. } else {
  3453. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3454. }
  3455. goto matrix_success;
  3456. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3457. x->type = check_matrix_type_hint(y->type, type_hint);
  3458. return;
  3459. }
  3460. }
  3461. if (!are_types_identical(xt, yt)) {
  3462. goto matrix_error;
  3463. }
  3464. x->mode = Addressing_Value;
  3465. x->type = xt;
  3466. goto matrix_success;
  3467. }
  3468. matrix_success:
  3469. x->type = check_matrix_type_hint(x->type, type_hint);
  3470. return;
  3471. matrix_error:
  3472. gbString xts = type_to_string(x->type);
  3473. gbString yts = type_to_string(y->type);
  3474. gbString expr_str = expr_to_string(x->expr);
  3475. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3476. gb_string_free(expr_str);
  3477. gb_string_free(yts);
  3478. gb_string_free(xts);
  3479. x->type = t_invalid;
  3480. x->mode = Addressing_Invalid;
  3481. return;
  3482. }
  3483. gb_internal void check_binary_expr_dependency(CheckerContext *c, Token op, Type *bt, bool REQUIRE) {
  3484. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3485. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3486. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3487. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3488. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3489. }
  3490. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3491. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3492. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3493. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3494. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3495. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3496. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3497. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3498. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3499. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3500. }
  3501. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3502. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3503. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3504. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3505. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3506. case Basic_u128:
  3507. case Basic_i128:
  3508. if (is_arch_wasm()) {
  3509. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3510. }
  3511. break;
  3512. }
  3513. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3514. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3515. case Basic_u128:
  3516. case Basic_i128:
  3517. if (is_arch_wasm()) {
  3518. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3519. }
  3520. break;
  3521. }
  3522. } else if (op.kind == Token_Shr || op.kind == Token_ShrEq) {
  3523. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3524. case Basic_u128:
  3525. case Basic_i128:
  3526. if (is_arch_wasm()) {
  3527. add_package_dependency(c, "runtime", "__lshrti3", REQUIRE);
  3528. }
  3529. break;
  3530. }
  3531. }
  3532. }
  3533. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3534. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3535. Operand y_ = {}, *y = &y_;
  3536. ast_node(be, BinaryExpr, node);
  3537. defer({
  3538. node->viral_state_flags |= be->left->viral_state_flags;
  3539. node->viral_state_flags |= be->right->viral_state_flags;
  3540. });
  3541. Token op = be->op;
  3542. switch (op.kind) {
  3543. case Token_CmpEq:
  3544. case Token_NotEq: {
  3545. // NOTE(bill): Allow comparisons between types
  3546. if (is_ise_expr(be->left)) {
  3547. // Evalute the right before the left for an '.X' expression
  3548. check_expr_or_type(c, y, be->right, nullptr /* ignore type hint */);
  3549. check_expr_or_type(c, x, be->left, y->type);
  3550. } else {
  3551. check_expr_or_type(c, x, be->left, nullptr /* ignore type hint */);
  3552. check_expr_or_type(c, y, be->right, x->type);
  3553. }
  3554. bool xt = x->mode == Addressing_Type;
  3555. bool yt = y->mode == Addressing_Type;
  3556. // If only one is a type, this is an error
  3557. if (xt ^ yt) {
  3558. GB_ASSERT(xt != yt);
  3559. if (xt) {
  3560. if (!is_type_typeid(y->type)) {
  3561. error_operand_not_expression(x);
  3562. }
  3563. }
  3564. if (yt) {
  3565. if (!is_type_typeid(x->type)) {
  3566. error_operand_not_expression(y);
  3567. }
  3568. }
  3569. }
  3570. break;
  3571. }
  3572. case Token_in:
  3573. case Token_not_in:
  3574. {
  3575. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3576. check_expr(c, y, be->right);
  3577. Type *rhs_type = type_deref(y->type);
  3578. if (rhs_type == nullptr) {
  3579. error(y->expr, "Cannot use '%.*s' on an expression with no value", LIT(op.string));
  3580. x->mode = Addressing_Invalid;
  3581. x->expr = node;
  3582. return;
  3583. }
  3584. if (is_type_bit_set(rhs_type)) {
  3585. Type *elem = base_type(rhs_type)->BitSet.elem;
  3586. check_expr_with_type_hint(c, x, be->left, elem);
  3587. } else if (is_type_map(rhs_type)) {
  3588. Type *key = base_type(rhs_type)->Map.key;
  3589. check_expr_with_type_hint(c, x, be->left, key);
  3590. } else {
  3591. check_expr(c, x, be->left);
  3592. }
  3593. if (x->mode == Addressing_Invalid) {
  3594. return;
  3595. }
  3596. if (y->mode == Addressing_Invalid) {
  3597. x->mode = Addressing_Invalid;
  3598. x->expr = y->expr;
  3599. return;
  3600. }
  3601. if (is_type_map(rhs_type)) {
  3602. Type *yt = base_type(rhs_type);
  3603. if (op.kind == Token_in) {
  3604. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3605. } else {
  3606. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3607. }
  3608. add_map_get_dependencies(c);
  3609. } else if (is_type_bit_set(rhs_type)) {
  3610. Type *yt = base_type(rhs_type);
  3611. if (op.kind == Token_in) {
  3612. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3613. } else {
  3614. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3615. }
  3616. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3617. ExactValue k = exact_value_to_integer(x->value);
  3618. ExactValue v = exact_value_to_integer(y->value);
  3619. GB_ASSERT(k.kind == ExactValue_Integer);
  3620. GB_ASSERT(v.kind == ExactValue_Integer);
  3621. i64 key = big_int_to_i64(&k.value_integer);
  3622. i64 lower = yt->BitSet.lower;
  3623. i64 upper = yt->BitSet.upper;
  3624. if (lower <= key && key <= upper) {
  3625. i64 bit = 1ll<<key;
  3626. i64 bits = big_int_to_i64(&v.value_integer);
  3627. x->mode = Addressing_Constant;
  3628. x->type = t_untyped_bool;
  3629. if (op.kind == Token_in) {
  3630. x->value = exact_value_bool((bit & bits) != 0);
  3631. } else {
  3632. x->value = exact_value_bool((bit & bits) == 0);
  3633. }
  3634. x->expr = node;
  3635. return;
  3636. } else {
  3637. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3638. x->mode = Addressing_Invalid;
  3639. }
  3640. }
  3641. } else {
  3642. gbString t = type_to_string(y->type);
  3643. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3644. gb_string_free(t);
  3645. x->expr = node;
  3646. x->mode = Addressing_Invalid;
  3647. return;
  3648. }
  3649. if (x->mode != Addressing_Invalid) {
  3650. x->mode = Addressing_Value;
  3651. x->type = t_untyped_bool;
  3652. }
  3653. x->expr = node;
  3654. return;
  3655. }
  3656. default:
  3657. if (is_ise_expr(be->left)) {
  3658. // Evalute the right before the left for an '.X' expression
  3659. check_expr_or_type(c, y, be->right, type_hint);
  3660. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3661. check_expr_or_type(c, x, be->left, y->type);
  3662. } else {
  3663. check_expr_with_type_hint(c, x, be->left, type_hint);
  3664. }
  3665. } else {
  3666. check_expr_with_type_hint(c, x, be->left, type_hint);
  3667. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3668. check_expr_with_type_hint(c, y, be->right, x->type);
  3669. } else {
  3670. check_expr_with_type_hint(c, y, be->right, type_hint);
  3671. }
  3672. }
  3673. break;
  3674. }
  3675. if (x->mode == Addressing_Invalid) {
  3676. return;
  3677. }
  3678. if (y->mode == Addressing_Invalid) {
  3679. x->mode = Addressing_Invalid;
  3680. x->expr = y->expr;
  3681. return;
  3682. }
  3683. if (x->mode == Addressing_Builtin) {
  3684. x->mode = Addressing_Invalid;
  3685. error(x->expr, "built-in expression in binary expression");
  3686. return;
  3687. }
  3688. if (y->mode == Addressing_Builtin) {
  3689. x->mode = Addressing_Invalid;
  3690. error(y->expr, "built-in expression in binary expression");
  3691. return;
  3692. }
  3693. if (x->mode == Addressing_ProcGroup) {
  3694. x->mode = Addressing_Invalid;
  3695. if (x->proc_group != nullptr) {
  3696. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3697. } else {
  3698. error(x->expr, "procedure group used in binary expression");
  3699. }
  3700. return;
  3701. }
  3702. if (y->mode == Addressing_ProcGroup) {
  3703. x->mode = Addressing_Invalid;
  3704. if (x->proc_group != nullptr) {
  3705. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3706. } else {
  3707. error(y->expr, "procedure group used in binary expression");
  3708. }
  3709. return;
  3710. }
  3711. bool REQUIRE = true;
  3712. Type *btx = base_type(x->type);
  3713. Type *bty = base_type(y->type);
  3714. check_binary_expr_dependency(c, op, btx, REQUIRE);
  3715. check_binary_expr_dependency(c, op, bty, REQUIRE);
  3716. if (token_is_shift(op.kind)) {
  3717. check_shift(c, x, y, node, type_hint);
  3718. return;
  3719. }
  3720. switch (op.kind) {
  3721. case Token_Quo:
  3722. case Token_Mod:
  3723. case Token_ModMod:
  3724. case Token_QuoEq:
  3725. case Token_ModEq:
  3726. case Token_ModModEq:
  3727. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3728. is_type_float(x->type) && is_type_untyped(x->type)) {
  3729. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3730. gbString t = type_to_string(y->type);
  3731. if (x->value.kind != ExactValue_Invalid) {
  3732. gbString s = exact_value_to_string(x->value);
  3733. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3734. gb_string_free(s);
  3735. } else {
  3736. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3737. }
  3738. gb_string_free(t);
  3739. }
  3740. break;
  3741. }
  3742. convert_to_typed(c, x, y->type);
  3743. if (x->mode == Addressing_Invalid) {
  3744. return;
  3745. }
  3746. convert_to_typed(c, y, x->type);
  3747. if (y->mode == Addressing_Invalid) {
  3748. x->mode = Addressing_Invalid;
  3749. return;
  3750. }
  3751. if (token_is_comparison(op.kind)) {
  3752. check_comparison(c, node, x, y, op.kind);
  3753. return;
  3754. }
  3755. if (check_binary_array_expr(c, op, x, y)) {
  3756. x->mode = Addressing_Value;
  3757. x->type = x->type;
  3758. return;
  3759. }
  3760. if (check_binary_array_expr(c, op, y, x)) {
  3761. x->mode = Addressing_Value;
  3762. x->type = y->type;
  3763. return;
  3764. }
  3765. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3766. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3767. x->expr = node;
  3768. return;
  3769. }
  3770. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3771. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3772. // NOTE(bill, 2022-06-26)
  3773. // Allow any boolean types within `&&` and `||`
  3774. // This is an exception to all other binary expressions since the result
  3775. // of a comparison will always be an untyped boolean, and allowing
  3776. // any boolean between these two simplifies a lot of expressions
  3777. } else if (!are_types_identical(x->type, y->type)) {
  3778. if (x->type != t_invalid &&
  3779. y->type != t_invalid) {
  3780. gbString xt = type_to_string(x->type);
  3781. gbString yt = type_to_string(y->type);
  3782. gbString expr_str = expr_to_string(node);
  3783. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3784. gb_string_free(expr_str);
  3785. gb_string_free(yt);
  3786. gb_string_free(xt);
  3787. }
  3788. x->mode = Addressing_Invalid;
  3789. return;
  3790. }
  3791. if (!check_binary_op(c, x, op)) {
  3792. x->mode = Addressing_Invalid;
  3793. return;
  3794. }
  3795. switch (op.kind) {
  3796. case Token_Quo:
  3797. case Token_Mod:
  3798. case Token_ModMod:
  3799. case Token_QuoEq:
  3800. case Token_ModEq:
  3801. case Token_ModModEq:
  3802. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3803. y->mode == Addressing_Constant) {
  3804. bool fail = false;
  3805. switch (y->value.kind) {
  3806. case ExactValue_Integer:
  3807. if (big_int_is_zero(&y->value.value_integer)) {
  3808. fail = true;
  3809. }
  3810. break;
  3811. case ExactValue_Float:
  3812. if (y->value.value_float == 0.0) {
  3813. fail = true;
  3814. }
  3815. break;
  3816. }
  3817. if (fail) {
  3818. if (is_type_integer(x->type) || (x->mode == Addressing_Constant && x->value.kind == ExactValue_Integer)) {
  3819. if (check_for_integer_division_by_zero(c, node) != IntegerDivisionByZero_Trap) {
  3820. // Okay
  3821. break;
  3822. }
  3823. }
  3824. switch (op.kind) {
  3825. case Token_Mod:
  3826. case Token_ModMod:
  3827. case Token_ModEq:
  3828. case Token_ModModEq:
  3829. error(y->expr, "Division by zero through '%.*s' not allowed", LIT(token_strings[op.kind]));
  3830. break;
  3831. case Token_Quo:
  3832. case Token_QuoEq:
  3833. error(y->expr, "Division by zero not allowed");
  3834. break;
  3835. }
  3836. x->mode = Addressing_Invalid;
  3837. return;
  3838. }
  3839. }
  3840. break;
  3841. case Token_CmpAnd:
  3842. case Token_CmpOr:
  3843. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3844. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3845. }
  3846. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3847. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3848. }
  3849. break;
  3850. }
  3851. if (x->mode == Addressing_Constant &&
  3852. y->mode == Addressing_Constant) {
  3853. ExactValue a = x->value;
  3854. ExactValue b = y->value;
  3855. if (!is_type_constant_type(x->type)) {
  3856. x->mode = Addressing_Value;
  3857. return;
  3858. }
  3859. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3860. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3861. }
  3862. if (is_type_bit_set(x->type)) {
  3863. switch (op.kind) {
  3864. case Token_Add: op.kind = Token_Or; break;
  3865. case Token_Sub: op.kind = Token_AndNot; break;
  3866. }
  3867. }
  3868. match_exact_values(&a, &b);
  3869. IntegerDivisionByZeroKind zero_behaviour = check_for_integer_division_by_zero(c, node);
  3870. if (zero_behaviour != IntegerDivisionByZero_Trap &&
  3871. b.kind == ExactValue_Integer && big_int_is_zero(&b.value_integer) &&
  3872. (op.kind == Token_QuoEq || op.kind == Token_Mod || op.kind == Token_ModMod)) {
  3873. if (op.kind == Token_QuoEq) {
  3874. switch (zero_behaviour) {
  3875. case IntegerDivisionByZero_Zero:
  3876. // x/0 == 0
  3877. x->value = b;
  3878. break;
  3879. case IntegerDivisionByZero_Self:
  3880. // x/0 == x
  3881. x->value = a;
  3882. break;
  3883. case IntegerDivisionByZero_AllBits:
  3884. // x/0 == 0b111...111
  3885. if (is_type_untyped(x->type)) {
  3886. x->value = exact_value_i64(-1);
  3887. } else {
  3888. x->value = exact_unary_operator_value(Token_Xor, b, cast(i32)(8*type_size_of(x->type)), is_type_unsigned(x->type));
  3889. }
  3890. break;
  3891. }
  3892. } else {
  3893. /*
  3894. NOTE(bill): @integer division by zero rules
  3895. truncated: r = a - b*trunc(a/b)
  3896. floored: r = a - b*floor(a/b)
  3897. IFF a/0 == 0, then (a%0 == a) or (a%%0 == a)
  3898. IFF a/0 == a, then (a%0 == 0) or (a%%0 == 0)
  3899. IFF a/0 == 0b111..., then (a%0 == a) or (a%%0 == a)
  3900. */
  3901. switch (zero_behaviour) {
  3902. case IntegerDivisionByZero_Zero:
  3903. case IntegerDivisionByZero_AllBits:
  3904. // x%0 == x
  3905. x->value = a;
  3906. break;
  3907. case IntegerDivisionByZero_Self:
  3908. // x%0 == 0
  3909. x->value = b;
  3910. break;
  3911. }
  3912. }
  3913. } else {
  3914. x->value = exact_binary_operator_value(op.kind, a, b);
  3915. }
  3916. if (is_type_typed(x->type)) {
  3917. if (node != nullptr) {
  3918. x->expr = node;
  3919. }
  3920. check_is_expressible(c, x, x->type);
  3921. }
  3922. return;
  3923. } else if (is_type_string(x->type)) {
  3924. error(node, "String concatenation is only allowed with constant strings");
  3925. x->mode = Addressing_Invalid;
  3926. return;
  3927. }
  3928. x->mode = Addressing_Value;
  3929. }
  3930. gb_internal Operand make_operand_from_node(Ast *node) {
  3931. GB_ASSERT(node != nullptr);
  3932. Operand x = {};
  3933. x.expr = node;
  3934. x.mode = node->tav.mode;
  3935. x.type = node->tav.type;
  3936. x.value = node->tav.value;
  3937. return x;
  3938. }
  3939. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3940. GB_ASSERT(e != nullptr);
  3941. ExprInfo *old = check_get_expr_info(c, e);
  3942. if (old == nullptr) {
  3943. if (type != nullptr && type != t_invalid) {
  3944. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3945. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3946. if (e->kind == Ast_TernaryIfExpr) {
  3947. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3948. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3949. }
  3950. }
  3951. }
  3952. return;
  3953. }
  3954. switch (e->kind) {
  3955. case_ast_node(ue, UnaryExpr, e);
  3956. if (old->value.kind != ExactValue_Invalid) {
  3957. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3958. // They don't need to be updated as they will be updated later and
  3959. // checked at the end of general checking stage.
  3960. break;
  3961. }
  3962. update_untyped_expr_type(c, ue->expr, type, final);
  3963. case_end;
  3964. case_ast_node(be, BinaryExpr, e);
  3965. if (old->value.kind != ExactValue_Invalid) {
  3966. // See above note in UnaryExpr case
  3967. break;
  3968. }
  3969. if (token_is_comparison(be->op.kind)) {
  3970. // NOTE(bill): Do nothing as the types are fine
  3971. } else if (token_is_shift(be->op.kind)) {
  3972. update_untyped_expr_type(c, be->left, type, final);
  3973. } else {
  3974. update_untyped_expr_type(c, be->left, type, final);
  3975. update_untyped_expr_type(c, be->right, type, final);
  3976. }
  3977. case_end;
  3978. case_ast_node(te, TernaryIfExpr, e);
  3979. if (old->value.kind != ExactValue_Invalid) {
  3980. // See above note in UnaryExpr case
  3981. break;
  3982. }
  3983. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3984. // having an untyped value
  3985. Operand x = make_operand_from_node(te->x);
  3986. Operand y = make_operand_from_node(te->y);
  3987. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3988. update_untyped_expr_type(c, te->x, type, final);
  3989. }
  3990. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3991. update_untyped_expr_type(c, te->y, type, final);
  3992. }
  3993. case_end;
  3994. case_ast_node(te, TernaryWhenExpr, e);
  3995. if (old->value.kind != ExactValue_Invalid) {
  3996. // See above note in UnaryExpr case
  3997. break;
  3998. }
  3999. update_untyped_expr_type(c, te->x, type, final);
  4000. update_untyped_expr_type(c, te->y, type, final);
  4001. case_end;
  4002. case_ast_node(ore, OrReturnExpr, e);
  4003. if (old->value.kind != ExactValue_Invalid) {
  4004. // See above note in UnaryExpr case
  4005. break;
  4006. }
  4007. update_untyped_expr_type(c, ore->expr, type, final);
  4008. case_end;
  4009. case_ast_node(obe, OrBranchExpr, e);
  4010. if (old->value.kind != ExactValue_Invalid) {
  4011. // See above note in UnaryExpr case
  4012. break;
  4013. }
  4014. update_untyped_expr_type(c, obe->expr, type, final);
  4015. case_end;
  4016. case_ast_node(oee, OrElseExpr, e);
  4017. if (old->value.kind != ExactValue_Invalid) {
  4018. // See above note in UnaryExpr case
  4019. break;
  4020. }
  4021. update_untyped_expr_type(c, oee->x, type, final);
  4022. update_untyped_expr_type(c, oee->y, type, final);
  4023. case_end;
  4024. case_ast_node(pe, ParenExpr, e);
  4025. update_untyped_expr_type(c, pe->expr, type, final);
  4026. case_end;
  4027. }
  4028. if (!final && is_type_untyped(type)) {
  4029. old->type = base_type(type);
  4030. return;
  4031. }
  4032. // We need to remove it and then give it a new one
  4033. check_remove_expr_info(c, e);
  4034. if (old->is_lhs && !is_type_integer(type)) {
  4035. gbString expr_str = expr_to_string(e);
  4036. gbString type_str = type_to_string(type);
  4037. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  4038. gb_string_free(type_str);
  4039. gb_string_free(expr_str);
  4040. return;
  4041. }
  4042. add_type_and_value(c, e, old->mode, type, old->value);
  4043. }
  4044. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  4045. GB_ASSERT(e != nullptr);
  4046. ExprInfo *found = check_get_expr_info(c, e);
  4047. if (found) {
  4048. found->value = value;
  4049. }
  4050. }
  4051. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type, bool ignore_error_block=false) {
  4052. gbString expr_str = expr_to_string(operand->expr);
  4053. gbString type_str = type_to_string(target_type);
  4054. gbString from_type_str = type_to_string(operand->type);
  4055. char const *extra_text = "";
  4056. if (operand->mode == Addressing_Constant) {
  4057. if (big_int_is_zero(&operand->value.value_integer)) {
  4058. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  4059. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  4060. extra_text = " - Did you want 'nil'?";
  4061. }
  4062. }
  4063. }
  4064. if (!ignore_error_block) {
  4065. begin_error_block();
  4066. }
  4067. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  4068. if (operand->value.kind == ExactValue_String) {
  4069. String key = operand->value.value_string;
  4070. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  4071. Type *et = base_type(target_type);
  4072. check_did_you_mean_type(key, et->Enum.fields, ".");
  4073. }
  4074. }
  4075. gb_string_free(from_type_str);
  4076. gb_string_free(type_str);
  4077. gb_string_free(expr_str);
  4078. operand->mode = Addressing_Invalid;
  4079. if (!ignore_error_block) {
  4080. end_error_block();
  4081. }
  4082. }
  4083. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  4084. Type *t = core_type(type);
  4085. if (is_type_boolean(t)) {
  4086. // v = exact_value_to_boolean(v);
  4087. } else if (is_type_float(t)) {
  4088. v = exact_value_to_float(v);
  4089. } else if (is_type_integer(t)) {
  4090. v = exact_value_to_integer(v);
  4091. } else if (is_type_pointer(t)) {
  4092. v = exact_value_to_integer(v);
  4093. } else if (is_type_complex(t)) {
  4094. v = exact_value_to_complex(v);
  4095. } else if (is_type_quaternion(t)) {
  4096. v = exact_value_to_quaternion(v);
  4097. }
  4098. return v;
  4099. }
  4100. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  4101. if (target_type == nullptr || operand->mode == Addressing_Invalid ||
  4102. operand->mode == Addressing_Type ||
  4103. is_type_typed(operand->type) ||
  4104. target_type == t_invalid) {
  4105. return;
  4106. }
  4107. if (is_type_untyped(target_type)) {
  4108. GB_ASSERT(operand->type->kind == Type_Basic);
  4109. GB_ASSERT(target_type->kind == Type_Basic);
  4110. BasicKind x_kind = operand->type->Basic.kind;
  4111. BasicKind y_kind = target_type->Basic.kind;
  4112. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  4113. if (x_kind < y_kind) {
  4114. operand->type = target_type;
  4115. update_untyped_expr_type(c, operand->expr, target_type, false);
  4116. }
  4117. } else if (x_kind != y_kind) {
  4118. operand->mode = Addressing_Invalid;
  4119. convert_untyped_error(c, operand, target_type);
  4120. return;
  4121. }
  4122. return;
  4123. }
  4124. Type *t = base_type(target_type);
  4125. if (c->in_enum_type) {
  4126. t = core_type(target_type);
  4127. }
  4128. switch (t->kind) {
  4129. case Type_Basic:
  4130. if (operand->mode == Addressing_Constant) {
  4131. check_is_expressible(c, operand, t);
  4132. if (operand->mode == Addressing_Invalid) {
  4133. return;
  4134. }
  4135. update_untyped_expr_value(c, operand->expr, operand->value);
  4136. } else {
  4137. switch (operand->type->Basic.kind) {
  4138. case Basic_UntypedBool:
  4139. if (!is_type_boolean(target_type)) {
  4140. operand->mode = Addressing_Invalid;
  4141. convert_untyped_error(c, operand, target_type);
  4142. return;
  4143. }
  4144. break;
  4145. case Basic_UntypedInteger:
  4146. case Basic_UntypedFloat:
  4147. case Basic_UntypedComplex:
  4148. case Basic_UntypedQuaternion:
  4149. case Basic_UntypedRune:
  4150. if (!is_type_numeric(target_type)) {
  4151. operand->mode = Addressing_Invalid;
  4152. convert_untyped_error(c, operand, target_type);
  4153. return;
  4154. }
  4155. break;
  4156. case Basic_UntypedNil:
  4157. if (is_type_any(target_type)) {
  4158. // target_type = t_untyped_nil;
  4159. } else if (is_type_cstring(target_type)) {
  4160. // target_type = t_untyped_nil;
  4161. } else if (is_type_cstring16(target_type)) {
  4162. // target_type = t_untyped_nil;
  4163. } else if (!type_has_nil(target_type)) {
  4164. operand->mode = Addressing_Invalid;
  4165. convert_untyped_error(c, operand, target_type);
  4166. return;
  4167. }
  4168. break;
  4169. }
  4170. }
  4171. break;
  4172. case Type_Array: {
  4173. Type *elem = base_array_type(t);
  4174. if (check_is_assignable_to(c, operand, elem)) {
  4175. operand->mode = Addressing_Value;
  4176. } else {
  4177. if (operand->value.kind == ExactValue_String) {
  4178. String s = operand->value.value_string;
  4179. if (is_type_u8_array(t)) {
  4180. if (s.len == t->Array.count) {
  4181. break;
  4182. }
  4183. } else if (is_type_rune_array(t)) {
  4184. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  4185. if (rune_count == t->Array.count) {
  4186. break;
  4187. }
  4188. }
  4189. } else if (operand->value.kind == ExactValue_String16) {
  4190. String16 s = operand->value.value_string16;
  4191. if (is_type_u16_array(t)) {
  4192. if (s.len == t->Array.count) {
  4193. break;
  4194. }
  4195. }
  4196. }
  4197. operand->mode = Addressing_Invalid;
  4198. convert_untyped_error(c, operand, target_type);
  4199. return;
  4200. }
  4201. break;
  4202. }
  4203. case Type_SimdVector: {
  4204. Type *elem = base_array_type(t);
  4205. if (check_is_assignable_to(c, operand, elem)) {
  4206. operand->mode = Addressing_Value;
  4207. } else {
  4208. operand->mode = Addressing_Invalid;
  4209. convert_untyped_error(c, operand, target_type);
  4210. return;
  4211. }
  4212. break;
  4213. }
  4214. case Type_Matrix: {
  4215. Type *elem = base_array_type(t);
  4216. if (check_is_assignable_to(c, operand, elem)) {
  4217. if (t->Matrix.row_count != t->Matrix.column_count) {
  4218. operand->mode = Addressing_Invalid;
  4219. ERROR_BLOCK();
  4220. convert_untyped_error(c, operand, target_type, true);
  4221. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  4222. return;
  4223. } else {
  4224. operand->mode = Addressing_Value;
  4225. }
  4226. } else {
  4227. operand->mode = Addressing_Invalid;
  4228. convert_untyped_error(c, operand, target_type);
  4229. return;
  4230. }
  4231. break;
  4232. }
  4233. case Type_Union:
  4234. // IMPORTANT NOTE HACK(bill): This is just to allow for comparisons against `0` with the `os.Error` type
  4235. // as a kind of transition period
  4236. if (!build_context.strict_style &&
  4237. operand->mode == Addressing_Constant &&
  4238. target_type->kind == Type_Named &&
  4239. (c->pkg == nullptr || c->pkg->name != "os") &&
  4240. target_type->Named.name == "Error") {
  4241. Entity *e = target_type->Named.type_name;
  4242. if (e->pkg && e->pkg->name == "os") {
  4243. if (is_exact_value_zero(operand->value) &&
  4244. (operand->value.kind == ExactValue_Integer ||
  4245. operand->value.kind == ExactValue_Float)) {
  4246. operand->mode = Addressing_Value;
  4247. // target_type = t_untyped_nil;
  4248. operand->value = empty_exact_value;
  4249. update_untyped_expr_value(c, operand->expr, operand->value);
  4250. break;
  4251. }
  4252. }
  4253. }
  4254. // "fallthrough"
  4255. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  4256. TEMPORARY_ALLOCATOR_GUARD();
  4257. isize count = t->Union.variants.count;
  4258. ValidIndexAndScore *valids = temporary_alloc_array<ValidIndexAndScore>(count);
  4259. isize valid_count = 0;
  4260. isize first_success_index = -1;
  4261. for_array(i, t->Union.variants) {
  4262. Type *vt = t->Union.variants[i];
  4263. i64 score = 0;
  4264. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  4265. valids[valid_count].index = i;
  4266. valids[valid_count].score = score;
  4267. valid_count += 1;
  4268. if (first_success_index < 0) {
  4269. first_success_index = i;
  4270. }
  4271. }
  4272. }
  4273. if (valid_count > 1) {
  4274. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  4275. i64 best_score = valids[0].score;
  4276. for (isize i = 1; i < valid_count; i++) {
  4277. auto v = valids[i];
  4278. if (best_score > v.score) {
  4279. valid_count = i;
  4280. break;
  4281. }
  4282. best_score = v.score;
  4283. }
  4284. first_success_index = valids[0].index;
  4285. }
  4286. gbString type_str = type_to_string(target_type);
  4287. defer (gb_string_free(type_str));
  4288. if (valid_count == 1) {
  4289. Type *new_type = t->Union.variants[first_success_index];
  4290. target_type = new_type;
  4291. if (is_type_union(new_type)) {
  4292. convert_to_typed(c, operand, new_type);
  4293. break;
  4294. }
  4295. operand->type = new_type;
  4296. operand->mode = Addressing_Value;
  4297. break;
  4298. } else if (valid_count > 1) {
  4299. ERROR_BLOCK();
  4300. GB_ASSERT(first_success_index >= 0);
  4301. operand->mode = Addressing_Invalid;
  4302. convert_untyped_error(c, operand, target_type, true);
  4303. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  4304. i32 j = 0;
  4305. for (i32 i = 0; i < valid_count; i++) {
  4306. ValidIndexAndScore valid = valids[i];
  4307. if (j > 0 && valid_count > 2) error_line(", ");
  4308. if (j == valid_count-1) {
  4309. if (valid_count == 2) error_line(" ");
  4310. error_line("or ");
  4311. }
  4312. gbString str = type_to_string(t->Union.variants[valid.index]);
  4313. error_line("'%s'", str);
  4314. gb_string_free(str);
  4315. j++;
  4316. }
  4317. error_line("\n\n");
  4318. return;
  4319. } else if (is_type_untyped_uninit(operand->type)) {
  4320. target_type = t_untyped_uninit;
  4321. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  4322. ERROR_BLOCK();
  4323. operand->mode = Addressing_Invalid;
  4324. convert_untyped_error(c, operand, target_type, true);
  4325. if (count > 0) {
  4326. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  4327. error_line("\t");
  4328. for (i32 i = 0; i < count; i++) {
  4329. Type *v = t->Union.variants[i];
  4330. if (i > 0 && count > 2) error_line(", ");
  4331. if (i == count-1) {
  4332. if (count == 2) error_line(" ");
  4333. if (count > 1) {
  4334. error_line("or ");
  4335. }
  4336. }
  4337. gbString str = type_to_string(v);
  4338. error_line("'%s'", str);
  4339. gb_string_free(str);
  4340. }
  4341. error_line("\n\n");
  4342. }
  4343. return;
  4344. }
  4345. }
  4346. /* fallthrough */
  4347. default:
  4348. if (is_type_untyped_uninit(operand->type)) {
  4349. target_type = t_untyped_uninit;
  4350. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  4351. target_type = t_untyped_nil;
  4352. } else {
  4353. operand->mode = Addressing_Invalid;
  4354. convert_untyped_error(c, operand, target_type);
  4355. return;
  4356. }
  4357. break;
  4358. }
  4359. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  4360. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  4361. } else {
  4362. target_type = default_type(operand->type);
  4363. }
  4364. }
  4365. update_untyped_expr_type(c, operand->expr, target_type, true);
  4366. operand->type = target_type;
  4367. }
  4368. 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) {
  4369. Operand operand = {Addressing_Invalid};
  4370. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  4371. if (operand.mode == Addressing_Invalid) {
  4372. if (value) *value = 0;
  4373. // NOTE(bill): return true here to propagate the errors better
  4374. return true;
  4375. }
  4376. Type *index_type = t_int;
  4377. if (type_hint != nullptr) {
  4378. index_type = type_hint;
  4379. }
  4380. convert_to_typed(c, &operand, index_type);
  4381. if (operand.mode == Addressing_Invalid) {
  4382. if (value) *value = 0;
  4383. return false;
  4384. }
  4385. if (type_hint != nullptr) {
  4386. if (!check_is_assignable_to(c, &operand, type_hint)) {
  4387. gbString expr_str = expr_to_string(operand.expr);
  4388. gbString index_type_str = type_to_string(type_hint);
  4389. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  4390. gb_string_free(index_type_str);
  4391. gb_string_free(expr_str);
  4392. if (value) *value = 0;
  4393. return false;
  4394. }
  4395. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  4396. gbString expr_str = expr_to_string(operand.expr);
  4397. gbString type_str = type_to_string(operand.type);
  4398. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  4399. gb_string_free(type_str);
  4400. gb_string_free(expr_str);
  4401. if (value) *value = 0;
  4402. return false;
  4403. }
  4404. if (operand.mode == Addressing_Constant &&
  4405. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  4406. BigInt i = exact_value_to_integer(operand.value).value_integer;
  4407. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  4408. TEMPORARY_ALLOCATOR_GUARD();
  4409. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4410. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4411. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  4412. if (value) *value = 0;
  4413. return false;
  4414. }
  4415. if (max_count >= 0) {
  4416. if (is_type_enum(index_type)) {
  4417. Type *bt = base_type(index_type);
  4418. GB_ASSERT(bt->kind == Type_Enum);
  4419. ExactValue const &lo = *bt->Enum.min_value;
  4420. ExactValue const &hi = *bt->Enum.max_value;
  4421. String lo_str = {};
  4422. String hi_str = {};
  4423. if (bt->Enum.fields.count > 0) {
  4424. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  4425. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  4426. lo_str = bt->Enum.fields[lo_idx]->token.string;
  4427. hi_str = bt->Enum.fields[hi_idx]->token.string;
  4428. }
  4429. bool out_of_bounds = false;
  4430. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  4431. out_of_bounds = true;
  4432. }
  4433. if (out_of_bounds) {
  4434. gbString expr_str = expr_to_string(operand.expr);
  4435. if (lo_str.len > 0) {
  4436. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  4437. } else {
  4438. gbString index_type_str = type_to_string(index_type);
  4439. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  4440. gb_string_free(index_type_str);
  4441. }
  4442. gb_string_free(expr_str);
  4443. return false;
  4444. }
  4445. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  4446. return true;
  4447. } else { // NOTE(bill): Do array bound checking
  4448. i64 v = -1;
  4449. if (i.used <= 1) {
  4450. v = big_int_to_i64(&i);
  4451. }
  4452. if (value) *value = v;
  4453. bool out_of_bounds = false;
  4454. if (v < 0) {
  4455. out_of_bounds = true;
  4456. } else if (open_range) {
  4457. out_of_bounds = v > max_count;
  4458. } else {
  4459. out_of_bounds = v >= max_count;
  4460. }
  4461. if (out_of_bounds) {
  4462. TEMPORARY_ALLOCATOR_GUARD();
  4463. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4464. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4465. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  4466. return false;
  4467. }
  4468. return true;
  4469. }
  4470. } else {
  4471. if (value) *value = exact_value_to_i64(operand.value);
  4472. return true;
  4473. }
  4474. }
  4475. // NOTE(bill): It's alright :D
  4476. if (value) *value = -1;
  4477. return true;
  4478. }
  4479. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  4480. if (value.kind == ExactValue_String) {
  4481. GB_ASSERT(0 <= index && index < value.value_string.len);
  4482. u8 val = value.value_string[index];
  4483. if (success_) *success_ = true;
  4484. if (finish_) *finish_ = true;
  4485. return exact_value_u64(val);
  4486. } else if (value.kind == ExactValue_String16) {
  4487. GB_ASSERT(0 <= index && index < value.value_string.len);
  4488. u16 val = value.value_string16[index];
  4489. if (success_) *success_ = true;
  4490. if (finish_) *finish_ = true;
  4491. return exact_value_u64(val);
  4492. }
  4493. if (value.kind != ExactValue_Compound) {
  4494. if (success_) *success_ = true;
  4495. if (finish_) *finish_ = true;
  4496. return value;
  4497. }
  4498. Ast *node = value.value_compound;
  4499. switch (node->kind) {
  4500. case_ast_node(cl, CompoundLit, node);
  4501. if (cl->elems.count == 0) {
  4502. if (success_) *success_ = true;
  4503. if (finish_) *finish_ = true;
  4504. return empty_exact_value;
  4505. }
  4506. if (cl->elems[0]->kind == Ast_FieldValue) {
  4507. if (is_type_struct(node->tav.type)) {
  4508. bool found = false;
  4509. for (Ast *elem : cl->elems) {
  4510. if (elem->kind != Ast_FieldValue) {
  4511. continue;
  4512. }
  4513. ast_node(fv, FieldValue, elem);
  4514. String name = fv->field->Ident.token.string;
  4515. Selection sub_sel = lookup_field(node->tav.type, name, false);
  4516. if (sub_sel.index.count > 0 &&
  4517. sub_sel.index[0] == index) {
  4518. value = fv->value->tav.value;
  4519. found = true;
  4520. break;
  4521. }
  4522. }
  4523. if (!found) {
  4524. // Use the zero value if it is not found
  4525. value = {};
  4526. }
  4527. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4528. for (Ast *elem : cl->elems) {
  4529. if (elem->kind != Ast_FieldValue) {
  4530. continue;
  4531. }
  4532. ast_node(fv, FieldValue, elem);
  4533. if (is_ast_range(fv->field)) {
  4534. ast_node(ie, BinaryExpr, fv->field);
  4535. TypeAndValue lo_tav = ie->left->tav;
  4536. TypeAndValue hi_tav = ie->right->tav;
  4537. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4538. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4539. TokenKind op = ie->op.kind;
  4540. i64 lo = exact_value_to_i64(lo_tav.value);
  4541. i64 hi = exact_value_to_i64(hi_tav.value);
  4542. i64 corrected_index = index;
  4543. if (is_type_enumerated_array(node->tav.type)) {
  4544. Type *bt = base_type(node->tav.type);
  4545. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4546. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4547. }
  4548. if (op != Token_RangeHalf) {
  4549. if (lo <= corrected_index && corrected_index <= hi) {
  4550. TypeAndValue tav = fv->value->tav;
  4551. if (success_) *success_ = true;
  4552. if (finish_) *finish_ = false;
  4553. return tav.value;
  4554. }
  4555. } else {
  4556. if (lo <= corrected_index && corrected_index < hi) {
  4557. TypeAndValue tav = fv->value->tav;
  4558. if (success_) *success_ = true;
  4559. if (finish_) *finish_ = false;
  4560. return tav.value;
  4561. }
  4562. }
  4563. } else {
  4564. TypeAndValue index_tav = fv->field->tav;
  4565. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4566. ExactValue index_value = index_tav.value;
  4567. if (is_type_enumerated_array(node->tav.type)) {
  4568. Type *bt = base_type(node->tav.type);
  4569. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4570. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4571. }
  4572. i64 field_index = exact_value_to_i64(index_value);
  4573. if (index == field_index) {
  4574. TypeAndValue tav = fv->value->tav;
  4575. if (success_) *success_ = true;
  4576. if (finish_) *finish_ = false;
  4577. return tav.value;
  4578. }
  4579. }
  4580. }
  4581. }
  4582. } else {
  4583. i32 count = (i32)cl->elems.count;
  4584. if (count < index) {
  4585. if (success_) *success_ = false;
  4586. if (finish_) *finish_ = true;
  4587. return empty_exact_value;
  4588. }
  4589. if (cl->elems.count <= index) {
  4590. if (success_) *success_ = false;
  4591. if (finish_) *finish_ = false;
  4592. return value;
  4593. }
  4594. TypeAndValue tav = cl->elems[index]->tav;
  4595. if (tav.mode == Addressing_Constant) {
  4596. if (success_) *success_ = true;
  4597. if (finish_) *finish_ = false;
  4598. return tav.value;
  4599. } else if (is_type_proc(tav.type)) {
  4600. if (success_) *success_ = true;
  4601. if (finish_) *finish_ = false;
  4602. return tav.value;
  4603. } else {
  4604. GB_ASSERT_MSG(is_type_untyped_nil(tav.type), "%s", type_to_string(tav.type));
  4605. if (success_) *success_ = true;
  4606. if (finish_) *finish_ = false;
  4607. return tav.value;
  4608. }
  4609. }
  4610. case_end;
  4611. default:
  4612. if (success_) *success_ = true;
  4613. if (finish_) *finish_ = true;
  4614. return empty_exact_value;
  4615. }
  4616. if (finish_) *finish_ = false;
  4617. return value;
  4618. }
  4619. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4620. if (operand->mode != Addressing_Constant) {
  4621. if (success_) *success_ = false;
  4622. return empty_exact_value;
  4623. }
  4624. if (sel.indirect) {
  4625. if (success_) *success_ = false;
  4626. return empty_exact_value;
  4627. }
  4628. if (sel.index.count == 0) {
  4629. if (success_) *success_ = false;
  4630. return empty_exact_value;
  4631. }
  4632. ExactValue value = operand->value;
  4633. if (value.kind == ExactValue_Compound) {
  4634. while (sel.index.count > 0) {
  4635. i32 index = sel.index[0];
  4636. sel = sub_selection(sel, 1);
  4637. bool finish = false;
  4638. value = get_constant_field_single(c, value, index, success_, &finish);
  4639. if (finish) {
  4640. return value;
  4641. }
  4642. }
  4643. if (success_) *success_ = true;
  4644. return value;
  4645. } else if (value.kind == ExactValue_Quaternion) {
  4646. // @QuaternionLayout
  4647. Quaternion256 q = *value.value_quaternion;
  4648. GB_ASSERT(sel.index.count == 1);
  4649. switch (sel.index[0]) {
  4650. case 3: // w
  4651. if (success_) *success_ = true;
  4652. return exact_value_float(q.real);
  4653. case 0: // x
  4654. if (success_) *success_ = true;
  4655. return exact_value_float(q.imag);
  4656. case 1: // y
  4657. if (success_) *success_ = true;
  4658. return exact_value_float(q.jmag);
  4659. case 2: // z
  4660. if (success_) *success_ = true;
  4661. return exact_value_float(q.kmag);
  4662. }
  4663. if (success_) *success_ = false;
  4664. return empty_exact_value;
  4665. } else if (value.kind == ExactValue_Complex) {
  4666. // @QuaternionLayout
  4667. Complex128 c = *value.value_complex;
  4668. GB_ASSERT(sel.index.count == 1);
  4669. switch (sel.index[0]) {
  4670. case 0: // real
  4671. if (success_) *success_ = true;
  4672. return exact_value_float(c.real);
  4673. case 1: // imag
  4674. if (success_) *success_ = true;
  4675. return exact_value_float(c.imag);
  4676. }
  4677. if (success_) *success_ = false;
  4678. return empty_exact_value;
  4679. }
  4680. if (success_) *success_ = true;
  4681. return empty_exact_value;
  4682. }
  4683. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4684. Type *array_type = base_type(type_deref(original_type));
  4685. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4686. if (array_type->kind == Type_SimdVector) {
  4687. Type *elem_type = array_type->SimdVector.elem;
  4688. return alloc_type_simd_vector(new_count, elem_type);
  4689. }
  4690. Type *elem_type = array_type->Array.elem;
  4691. Type *swizzle_array_type = nullptr;
  4692. Type *bth = base_type(type_deref(type_hint));
  4693. if (bth != nullptr && bth->kind == Type_Array &&
  4694. bth->Array.count == new_count &&
  4695. are_types_identical(bth->Array.elem, elem_type)) {
  4696. swizzle_array_type = type_hint;
  4697. } else {
  4698. i64 max_count = array_type->Array.count;
  4699. if (new_count == max_count) {
  4700. swizzle_array_type = original_type;
  4701. } else {
  4702. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4703. }
  4704. }
  4705. return swizzle_array_type;
  4706. }
  4707. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4708. bool is_declared = entity != nullptr;
  4709. if (is_declared) {
  4710. if (entity->kind == Entity_Builtin) {
  4711. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4712. // This means that we should just ignore the found result through it
  4713. *allow_builtin = entity->scope == import_scope ||
  4714. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4715. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4716. is_declared = false;
  4717. }
  4718. }
  4719. return is_declared;
  4720. }
  4721. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4722. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4723. if (node == nullptr) {
  4724. return nullptr;
  4725. }
  4726. /*if (node->kind == Ast_TernaryWhenExpr) {
  4727. ast_node(we, TernaryWhenExpr, node);
  4728. if (we->cond == nullptr) {
  4729. return nullptr;
  4730. }
  4731. if (we->cond->tav.mode != Addressing_Constant) {
  4732. return nullptr;
  4733. }
  4734. if (we->cond->tav.value.kind != ExactValue_Bool) {
  4735. return nullptr;
  4736. }
  4737. if (we->cond->tav.value.value_bool) {
  4738. return check_entity_from_ident_or_selector(c, we->x, ident_only);
  4739. } else {
  4740. Entity *e = check_entity_from_ident_or_selector(c, we->y, ident_only);
  4741. return e;
  4742. }
  4743. } else */if (node->kind == Ast_Ident) {
  4744. String name = node->Ident.token.string;
  4745. return scope_lookup(c->scope, name, node->Ident.hash);
  4746. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4747. ast_node(se, SelectorExpr, node);
  4748. if (se->token.kind == Token_ArrowRight) {
  4749. return nullptr;
  4750. }
  4751. Ast *op_expr = se->expr;
  4752. Ast *selector = unparen_expr(se->selector);
  4753. if (selector == nullptr) {
  4754. return nullptr;
  4755. }
  4756. if (selector->kind != Ast_Ident) {
  4757. return nullptr;
  4758. }
  4759. Entity *entity = nullptr;
  4760. Entity *expr_entity = nullptr;
  4761. bool check_op_expr = true;
  4762. if (op_expr->kind == Ast_Ident) {
  4763. String op_name = op_expr->Ident.token.string;
  4764. Entity *e = scope_lookup(c->scope, op_name, op_expr->Ident.hash);
  4765. if (e == nullptr) {
  4766. return nullptr;
  4767. }
  4768. add_entity_use(c, op_expr, e);
  4769. expr_entity = e;
  4770. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4771. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4772. // It pretty much needs to be in this order and this way
  4773. // If you can clean this up, please do but be really careful
  4774. String import_name = op_name;
  4775. Scope *import_scope = e->ImportName.scope;
  4776. String entity_name = selector->Ident.token.string;
  4777. check_op_expr = false;
  4778. entity = scope_lookup_current(import_scope, entity_name);
  4779. bool allow_builtin = false;
  4780. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4781. return nullptr;
  4782. }
  4783. check_entity_decl(c, entity, nullptr, nullptr);
  4784. if (entity->kind == Entity_ProcGroup) {
  4785. return entity;
  4786. }
  4787. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4788. }
  4789. }
  4790. Operand operand = {};
  4791. if (check_op_expr) {
  4792. check_expr_base(c, &operand, op_expr, nullptr);
  4793. if (operand.mode == Addressing_Invalid) {
  4794. return nullptr;
  4795. }
  4796. }
  4797. if (entity == nullptr && selector->kind == Ast_Ident) {
  4798. String field_name = selector->Ident.token.string;
  4799. if (is_type_dynamic_array(type_deref(operand.type))) {
  4800. init_mem_allocator(c->checker);
  4801. }
  4802. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4803. entity = sel.entity;
  4804. }
  4805. if (entity != nullptr) {
  4806. return entity;
  4807. }
  4808. }
  4809. return nullptr;
  4810. }
  4811. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4812. ast_node(se, SelectorExpr, node);
  4813. bool check_op_expr = true;
  4814. Entity *expr_entity = nullptr;
  4815. Entity *entity = nullptr;
  4816. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4817. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4818. ERROR_BLOCK();
  4819. error(node, "Illegal use of -> selector shorthand outside of a call");
  4820. gbString x = expr_to_string(se->expr);
  4821. gbString y = expr_to_string(se->selector);
  4822. error_line("\tSuggestion: Did you mean '%s.%s'?\n", x, y);
  4823. gb_string_free(y);
  4824. gb_string_free(x);
  4825. // TODO(bill): Should this terminate here or propagate onwards?
  4826. // operand->mode = Addressing_Invalid;
  4827. // operand->expr = node;
  4828. // return nullptr;
  4829. }
  4830. operand->expr = node;
  4831. Ast *op_expr = se->expr;
  4832. Ast *selector = unparen_expr(se->selector);
  4833. if (selector == nullptr) {
  4834. operand->mode = Addressing_Invalid;
  4835. operand->expr = node;
  4836. return nullptr;
  4837. }
  4838. if (selector->kind != Ast_Ident) {
  4839. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4840. operand->mode = Addressing_Invalid;
  4841. operand->expr = node;
  4842. return nullptr;
  4843. }
  4844. if (op_expr->kind == Ast_Ident) {
  4845. String op_name = op_expr->Ident.token.string;
  4846. Entity *e = scope_lookup(c->scope, op_name, op_expr->Ident.hash);
  4847. add_entity_use(c, op_expr, e);
  4848. expr_entity = e;
  4849. if (e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup) && selector->kind == Ast_Ident) {
  4850. gbString sel_str = expr_to_string(selector);
  4851. error(node, "'%s' is not declared by by '%.*s'", sel_str, LIT(e->token.string));
  4852. gb_string_free(sel_str);
  4853. operand->mode = Addressing_Invalid;
  4854. operand->expr = node;
  4855. return nullptr;
  4856. } else if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4857. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4858. // It pretty much needs to be in this order and this way
  4859. // If you can clean this up, please do but be really careful
  4860. String import_name = op_name;
  4861. Scope *import_scope = e->ImportName.scope;
  4862. String entity_name = selector->Ident.token.string;
  4863. if (import_scope == nullptr) {
  4864. ERROR_BLOCK();
  4865. error(node, "'%.*s' is not imported in this file, '%.*s' is unavailable", LIT(import_name), LIT(entity_name));
  4866. operand->mode = Addressing_Invalid;
  4867. operand->expr = node;
  4868. return nullptr;
  4869. }
  4870. check_op_expr = false;
  4871. entity = scope_lookup_current(import_scope, entity_name);
  4872. bool allow_builtin = false;
  4873. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4874. ERROR_BLOCK();
  4875. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4876. operand->mode = Addressing_Invalid;
  4877. operand->expr = node;
  4878. check_did_you_mean_scope(entity_name, import_scope);
  4879. return nullptr;
  4880. }
  4881. if (!is_entity_exported(entity, allow_builtin)) {
  4882. gbString sel_str = expr_to_string(selector);
  4883. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4884. gb_string_free(sel_str);
  4885. // NOTE(bill): make the state valid still, even if it's "invalid"
  4886. // operand->mode = Addressing_Invalid;
  4887. // operand->expr = node;
  4888. // return nullptr;
  4889. }
  4890. check_entity_decl(c, entity, nullptr, nullptr);
  4891. if (entity->kind == Entity_ProcGroup) {
  4892. operand->mode = Addressing_ProcGroup;
  4893. operand->proc_group = entity;
  4894. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4895. return entity;
  4896. }
  4897. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4898. }
  4899. }
  4900. if (check_op_expr) {
  4901. check_expr_base(c, operand, op_expr, nullptr);
  4902. if (operand->mode == Addressing_Invalid) {
  4903. operand->mode = Addressing_Invalid;
  4904. operand->expr = node;
  4905. return nullptr;
  4906. }
  4907. }
  4908. if (operand->type && is_type_soa_struct(type_deref(operand->type))) {
  4909. complete_soa_type(c->checker, type_deref(operand->type), false);
  4910. }
  4911. if (entity == nullptr && selector->kind == Ast_Ident) {
  4912. String field_name = selector->Ident.token.string;
  4913. Type *t = type_deref(operand->type);
  4914. if (t == nullptr) {
  4915. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4916. } else {
  4917. if (is_type_dynamic_array(t)) {
  4918. init_mem_allocator(c->checker);
  4919. }
  4920. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4921. entity = sel.entity;
  4922. // NOTE(bill): Add type info needed for fields like 'names'
  4923. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4924. add_type_info_type(c, operand->type);
  4925. }
  4926. if (is_type_enum(operand->type)) {
  4927. add_type_info_type(c, operand->type);
  4928. }
  4929. }
  4930. }
  4931. if (operand->type && is_type_simd_vector(type_deref(operand->type))) {
  4932. String field_name = selector->Ident.token.string;
  4933. if (field_name.len == 1) {
  4934. error(op_expr, "Extracting an element from a #simd array using .%.*s syntax is disallowed, prefer `simd.extract`", LIT(field_name));
  4935. } else {
  4936. error(op_expr, "Extracting elements from a #simd array using .%.*s syntax is disallowed, prefer `swizzle`", LIT(field_name));
  4937. }
  4938. return nullptr;
  4939. }
  4940. if (entity == nullptr && selector->kind == Ast_Ident && operand->type != nullptr &&
  4941. (is_type_array(type_deref(operand->type)))) {
  4942. String field_name = selector->Ident.token.string;
  4943. if (1 < field_name.len && field_name.len <= 4) {
  4944. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4945. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4946. bool found_xyzw = false;
  4947. bool found_rgba = false;
  4948. for (isize i = 0; i < field_name.len; i++) {
  4949. bool valid = false;
  4950. for (isize j = 0; j < 4; j++) {
  4951. if (field_name.text[i] == swizzles_xyzw[j]) {
  4952. found_xyzw = true;
  4953. valid = true;
  4954. break;
  4955. }
  4956. if (field_name.text[i] == swizzles_rgba[j]) {
  4957. found_rgba = true;
  4958. valid = true;
  4959. break;
  4960. }
  4961. }
  4962. if (!valid) {
  4963. goto end_of_array_selector_swizzle;
  4964. }
  4965. }
  4966. u8 *swizzles = nullptr;
  4967. u8 index_count = cast(u8)field_name.len;
  4968. if (found_xyzw && found_rgba) {
  4969. gbString op_str = expr_to_string(op_expr);
  4970. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4971. gb_string_free(op_str);
  4972. operand->mode = Addressing_Invalid;
  4973. operand->expr = node;
  4974. return nullptr;
  4975. }
  4976. u8 indices = 0;
  4977. if (found_xyzw) {
  4978. swizzles = swizzles_xyzw;
  4979. } else if (found_rgba) {
  4980. swizzles = swizzles_rgba;
  4981. }
  4982. for (isize i = 0; i < field_name.len; i++) {
  4983. for (isize j = 0; j < 4; j++) {
  4984. if (field_name.text[i] == swizzles[j]) {
  4985. indices |= cast(u8)(j)<<(i*2);
  4986. break;
  4987. }
  4988. }
  4989. }
  4990. Type *original_type = operand->type;
  4991. Type *array_type = base_type(type_deref(original_type));
  4992. GB_ASSERT(array_type->kind == Type_Array);
  4993. i64 array_count = get_array_type_count(array_type);
  4994. for (u8 i = 0; i < index_count; i++) {
  4995. u8 idx = indices>>(i*2) & 3;
  4996. if (idx >= array_count) {
  4997. char c = 0;
  4998. if (found_xyzw) {
  4999. c = swizzles_xyzw[idx];
  5000. } else if (found_rgba) {
  5001. c = swizzles_rgba[idx];
  5002. } else {
  5003. GB_PANIC("unknown swizzle kind");
  5004. }
  5005. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  5006. break;
  5007. }
  5008. }
  5009. se->swizzle_count = index_count;
  5010. se->swizzle_indices = indices;
  5011. AddressingMode prev_mode = operand->mode;
  5012. operand->mode = Addressing_SwizzleValue;
  5013. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  5014. operand->expr = node;
  5015. switch (prev_mode) {
  5016. case Addressing_Variable:
  5017. case Addressing_SoaVariable:
  5018. case Addressing_SwizzleVariable:
  5019. operand->mode = Addressing_SwizzleVariable;
  5020. break;
  5021. case Addressing_Value:
  5022. if (is_type_pointer(original_type)) {
  5023. operand->mode = Addressing_SwizzleVariable;
  5024. }
  5025. break;
  5026. }
  5027. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  5028. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5029. return swizzle_entity;
  5030. }
  5031. end_of_array_selector_swizzle:;
  5032. }
  5033. if (entity == nullptr) {
  5034. gbString op_str = expr_to_string(op_expr);
  5035. gbString type_str = type_to_string_shorthand(operand->type);
  5036. gbString sel_str = expr_to_string(selector);
  5037. if (operand->mode == Addressing_Type) {
  5038. if (is_type_polymorphic(operand->type, true)) {
  5039. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  5040. } else {
  5041. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  5042. }
  5043. } else {
  5044. ERROR_BLOCK();
  5045. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  5046. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  5047. String const &name = selector->Ident.token.string;
  5048. Type *bt = base_type(operand->type);
  5049. if (operand->type->kind == Type_Named &&
  5050. operand->type->Named.type_name &&
  5051. operand->type->Named.type_name->kind == Entity_TypeName &&
  5052. operand->type->Named.type_name->TypeName.objc_metadata) {
  5053. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  5054. } else if (bt->kind == Type_Struct) {
  5055. check_did_you_mean_type(name, bt->Struct.fields);
  5056. } else if (bt->kind == Type_Enum) {
  5057. check_did_you_mean_type(name, bt->Enum.fields);
  5058. }
  5059. }
  5060. }
  5061. gb_string_free(sel_str);
  5062. gb_string_free(type_str);
  5063. gb_string_free(op_str);
  5064. operand->mode = Addressing_Invalid;
  5065. operand->expr = node;
  5066. return nullptr;
  5067. }
  5068. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  5069. bool success = false;
  5070. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  5071. if (success) {
  5072. operand->mode = Addressing_Constant;
  5073. operand->expr = node;
  5074. operand->value = field_value;
  5075. operand->type = entity->type;
  5076. add_entity_use(c, selector, entity);
  5077. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5078. return entity;
  5079. }
  5080. gbString op_str = expr_to_string(op_expr);
  5081. gbString type_str = type_to_string_shorthand(operand->type);
  5082. gbString sel_str = expr_to_string(selector);
  5083. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  5084. gb_string_free(sel_str);
  5085. gb_string_free(type_str);
  5086. gb_string_free(op_str);
  5087. operand->mode = Addressing_Invalid;
  5088. operand->expr = node;
  5089. return nullptr;
  5090. }
  5091. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  5092. bool success = false;
  5093. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  5094. if (success) {
  5095. operand->mode = Addressing_Constant;
  5096. operand->expr = node;
  5097. operand->value = field_value;
  5098. operand->type = entity->type;
  5099. add_entity_use(c, selector, entity);
  5100. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5101. return entity;
  5102. }
  5103. gbString op_str = expr_to_string(op_expr);
  5104. gbString type_str = type_to_string_shorthand(operand->type);
  5105. gbString sel_str = expr_to_string(selector);
  5106. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  5107. gb_string_free(sel_str);
  5108. gb_string_free(type_str);
  5109. gb_string_free(op_str);
  5110. operand->mode = Addressing_Invalid;
  5111. operand->expr = node;
  5112. return nullptr;
  5113. }
  5114. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  5115. gbString op_str = expr_to_string(op_expr);
  5116. gbString type_str = type_to_string_shorthand(operand->type);
  5117. gbString sel_str = expr_to_string(selector);
  5118. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  5119. gb_string_free(sel_str);
  5120. gb_string_free(type_str);
  5121. gb_string_free(op_str);
  5122. operand->mode = Addressing_Invalid;
  5123. operand->expr = node;
  5124. return nullptr;
  5125. }
  5126. add_entity_use(c, selector, entity);
  5127. operand->type = entity->type;
  5128. operand->expr = node;
  5129. if (entity->flags & EntityFlag_BitFieldField) {
  5130. add_package_dependency(c, "runtime", "__write_bits");
  5131. add_package_dependency(c, "runtime", "__read_bits");
  5132. }
  5133. switch (entity->kind) {
  5134. case Entity_Constant:
  5135. operand->value = entity->Constant.value;
  5136. operand->mode = Addressing_Constant;
  5137. if (operand->value.kind == ExactValue_Procedure) {
  5138. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  5139. if (proc != nullptr) {
  5140. operand->mode = Addressing_Value;
  5141. operand->type = proc->type;
  5142. }
  5143. }
  5144. break;
  5145. case Entity_Variable:
  5146. if (sel.is_bit_field) {
  5147. se->is_bit_field = true;
  5148. }
  5149. if (sel.indirect) {
  5150. operand->mode = Addressing_Variable;
  5151. } else if (operand->mode == Addressing_Context) {
  5152. // Do nothing
  5153. } else if (operand->mode == Addressing_MapIndex) {
  5154. operand->mode = Addressing_Value;
  5155. } else if (entity->flags & EntityFlag_SoaPtrField) {
  5156. operand->mode = Addressing_SoaVariable;
  5157. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  5158. operand->mode = Addressing_Value;
  5159. } else if (operand->mode == Addressing_SoaVariable) {
  5160. operand->mode = Addressing_Variable;
  5161. } else if (operand->mode != Addressing_Value) {
  5162. operand->mode = Addressing_Variable;
  5163. } else {
  5164. operand->mode = Addressing_Value;
  5165. }
  5166. break;
  5167. case Entity_TypeName:
  5168. operand->mode = Addressing_Type;
  5169. break;
  5170. case Entity_Procedure:
  5171. operand->mode = Addressing_Value;
  5172. operand->value = exact_value_procedure(node);
  5173. break;
  5174. case Entity_Builtin:
  5175. operand->mode = Addressing_Builtin;
  5176. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  5177. break;
  5178. case Entity_ProcGroup:
  5179. operand->mode = Addressing_ProcGroup;
  5180. operand->proc_group = entity;
  5181. break;
  5182. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  5183. case Entity_Nil:
  5184. operand->mode = Addressing_Value;
  5185. break;
  5186. }
  5187. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5188. return entity;
  5189. }
  5190. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  5191. ptr = base_type(ptr);
  5192. if (is_type_pointer(ptr)) {
  5193. if (is_type_rawptr(ptr)) {
  5194. return false;
  5195. }
  5196. if (elem) *elem = ptr->Pointer.elem;
  5197. return true;
  5198. }
  5199. return false;
  5200. }
  5201. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  5202. elem = core_type(elem);
  5203. if (is_type_internally_pointer_like(elem)) {
  5204. return true;
  5205. }
  5206. if (elem->kind == Type_BitSet) {
  5207. elem = bit_set_to_int(elem);
  5208. }
  5209. if (elem->kind != Type_Basic) {
  5210. return false;
  5211. }
  5212. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  5213. }
  5214. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  5215. switch (node->kind) {
  5216. case_ast_node(i, Ident, node);
  5217. String name = i->token.string;
  5218. if (nested) {
  5219. Entity *e = scope_lookup_current(s, name);
  5220. if (e != nullptr) {
  5221. if (out_scope) *out_scope = e->scope;
  5222. return true;
  5223. }
  5224. } else {
  5225. Entity *e = scope_lookup(s, name, i->hash);
  5226. if (e != nullptr) {
  5227. if (out_scope) *out_scope = e->scope;
  5228. return true;
  5229. }
  5230. }
  5231. case_end;
  5232. case_ast_node(se, SelectorExpr, node);
  5233. Ast *lhs = se->expr;
  5234. Ast *rhs = se->selector;
  5235. Scope *lhs_scope = nullptr;
  5236. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  5237. return check_identifier_exists(lhs_scope, rhs, true);
  5238. }
  5239. case_end;
  5240. }
  5241. return false;
  5242. }
  5243. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  5244. bool optional_ok = false;
  5245. isize tuple_index = 0;
  5246. for (Ast *rhs_expr : rhs) {
  5247. CheckerContext c_ = *ctx;
  5248. CheckerContext *c = &c_;
  5249. Operand o = {};
  5250. Type *type_hint = nullptr;
  5251. if (tuple_index < lhs.count) {
  5252. type_hint = lhs[tuple_index].type;
  5253. }
  5254. check_expr_base(c, &o, rhs_expr, type_hint);
  5255. if (o.mode == Addressing_NoValue) {
  5256. error_operand_no_value(&o);
  5257. o.mode = Addressing_Invalid;
  5258. }
  5259. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5260. if (lhs.count == 2 && rhs.count == 1 &&
  5261. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5262. Ast *expr = unparen_expr(o.expr);
  5263. Operand val0 = o;
  5264. Operand val1 = o;
  5265. val0.mode = Addressing_Value;
  5266. val1.mode = Addressing_Value;
  5267. val1.type = t_untyped_bool;
  5268. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5269. if (expr->kind == Ast_TypeAssertion &&
  5270. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5271. // NOTE(bill): Used only for optimizations in the backend
  5272. if (is_blank_ident(lhs[0].expr)) {
  5273. expr->TypeAssertion.ignores[0] = true;
  5274. }
  5275. if (is_blank_ident(lhs[1].expr)) {
  5276. expr->TypeAssertion.ignores[1] = true;
  5277. }
  5278. }
  5279. array_add(operands, val0);
  5280. array_add(operands, val1);
  5281. optional_ok = true;
  5282. tuple_index += 2;
  5283. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  5284. Type *tuple = o.type;
  5285. GB_ASSERT(tuple->Tuple.variables.count == 2);
  5286. Ast *expr = unparen_expr(o.expr);
  5287. if (expr->kind == Ast_CallExpr) {
  5288. expr->CallExpr.optional_ok_one = true;
  5289. }
  5290. Operand val = o;
  5291. val.type = tuple->Tuple.variables[0]->type;
  5292. val.mode = Addressing_Value;
  5293. array_add(operands, val);
  5294. tuple_index += tuple->Tuple.variables.count;
  5295. } else {
  5296. array_add(operands, o);
  5297. tuple_index += 1;
  5298. }
  5299. } else {
  5300. TypeTuple *tuple = &o.type->Tuple;
  5301. for (Entity *e : tuple->variables) {
  5302. o.type = e->type;
  5303. array_add(operands, o);
  5304. }
  5305. tuple_index += tuple->variables.count;
  5306. }
  5307. }
  5308. return optional_ok;
  5309. }
  5310. typedef u32 UnpackFlags;
  5311. enum UnpackFlag : u32 {
  5312. UnpackFlag_None = 0,
  5313. UnpackFlag_AllowOk = 1<<0,
  5314. UnpackFlag_AllowUndef = 1<<1,
  5315. };
  5316. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags,
  5317. isize variadic_index = -1) {
  5318. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  5319. if (lhs == nullptr || c->decl == nullptr) {
  5320. return tuple_count;
  5321. }
  5322. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  5323. Entity *e = lhs[tuple_index + j];
  5324. if (e == nullptr) {
  5325. continue;
  5326. }
  5327. DeclInfo *decl = decl_info_of_entity(e);
  5328. if (decl == nullptr) {
  5329. continue;
  5330. }
  5331. rw_mutex_shared_lock(&decl->deps_mutex);
  5332. rw_mutex_lock(&c->decl->deps_mutex);
  5333. FOR_PTR_SET(dep, decl->deps) {
  5334. ptr_set_add(&c->decl->deps, dep);
  5335. }
  5336. rw_mutex_unlock(&c->decl->deps_mutex);
  5337. rw_mutex_shared_unlock(&decl->deps_mutex);
  5338. }
  5339. return tuple_count;
  5340. };
  5341. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  5342. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  5343. bool is_variadic = variadic_index > -1;
  5344. if (!is_variadic) {
  5345. variadic_index = lhs_count;
  5346. }
  5347. bool optional_ok = false;
  5348. isize tuple_index = 0;
  5349. for (Ast *rhs : rhs_arguments) {
  5350. if (rhs->kind == Ast_FieldValue) {
  5351. error(rhs, "Invalid use of 'field = value'");
  5352. rhs = rhs->FieldValue.value;
  5353. }
  5354. CheckerContext c_ = *ctx;
  5355. CheckerContext *c = &c_;
  5356. Operand o = {};
  5357. Type *type_hint = nullptr;
  5358. if (lhs != nullptr) {
  5359. if (tuple_index < variadic_index) {
  5360. // NOTE(bill): override DeclInfo for dependency
  5361. Entity *e = lhs[tuple_index];
  5362. if (e != nullptr) {
  5363. type_hint = e->type;
  5364. }
  5365. } else if (is_variadic) {
  5366. Entity *e = lhs[variadic_index];
  5367. if (e != nullptr) {
  5368. GB_ASSERT(e->flags & EntityFlag_Ellipsis);
  5369. GB_ASSERT(is_type_slice(e->type));
  5370. type_hint = e->type->Slice.elem;
  5371. }
  5372. }
  5373. }
  5374. Ast *rhs_expr = unparen_expr(rhs);
  5375. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  5376. // NOTE(bill): Just handle this very specific logic here
  5377. o.type = t_untyped_uninit;
  5378. o.mode = Addressing_Value;
  5379. o.expr = rhs;
  5380. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  5381. } else {
  5382. check_expr_base(c, &o, rhs, type_hint);
  5383. }
  5384. if (o.mode == Addressing_NoValue) {
  5385. error_operand_no_value(&o);
  5386. o.mode = Addressing_Invalid;
  5387. }
  5388. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5389. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  5390. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5391. Ast *expr = unparen_expr(o.expr);
  5392. Operand val0 = o;
  5393. Operand val1 = o;
  5394. val0.mode = Addressing_Value;
  5395. val1.mode = Addressing_Value;
  5396. val1.type = t_untyped_bool;
  5397. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5398. if (expr->kind == Ast_TypeAssertion &&
  5399. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5400. // NOTE(bill): Used only for optimizations in the backend
  5401. if (is_blank_ident(lhs[0]->token)) {
  5402. expr->TypeAssertion.ignores[0] = true;
  5403. }
  5404. if (is_blank_ident(lhs[1]->token)) {
  5405. expr->TypeAssertion.ignores[1] = true;
  5406. }
  5407. }
  5408. array_add(operands, val0);
  5409. array_add(operands, val1);
  5410. optional_ok = true;
  5411. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  5412. } else {
  5413. array_add(operands, o);
  5414. tuple_index += 1;
  5415. }
  5416. } else {
  5417. TypeTuple *tuple = &o.type->Tuple;
  5418. for (Entity *e : tuple->variables) {
  5419. o.type = e->type;
  5420. array_add(operands, o);
  5421. }
  5422. isize count = tuple->variables.count;
  5423. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  5424. }
  5425. }
  5426. return optional_ok;
  5427. }
  5428. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  5429. GB_ASSERT(pt != nullptr);
  5430. GB_ASSERT(pt->kind == Type_Proc);
  5431. isize param_count = 0;
  5432. isize param_count_excluding_defaults = 0;
  5433. bool variadic = pt->Proc.variadic;
  5434. TypeTuple *param_tuple = nullptr;
  5435. if (pt->Proc.params != nullptr) {
  5436. param_tuple = &pt->Proc.params->Tuple;
  5437. param_count = param_tuple->variables.count;
  5438. if (variadic) {
  5439. for (isize i = param_count-1; i >= 0; i--) {
  5440. Entity *e = param_tuple->variables[i];
  5441. if (e->kind == Entity_TypeName) {
  5442. break;
  5443. }
  5444. if (e->kind == Entity_Variable) {
  5445. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5446. param_count--;
  5447. continue;
  5448. }
  5449. }
  5450. break;
  5451. }
  5452. param_count--;
  5453. }
  5454. }
  5455. param_count_excluding_defaults = param_count;
  5456. if (param_tuple != nullptr) {
  5457. for (isize i = param_count-1; i >= 0; i--) {
  5458. Entity *e = param_tuple->variables[i];
  5459. if (e->kind == Entity_TypeName) {
  5460. break;
  5461. }
  5462. if (e->kind == Entity_Variable) {
  5463. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5464. param_count_excluding_defaults--;
  5465. continue;
  5466. }
  5467. }
  5468. break;
  5469. }
  5470. }
  5471. if (param_count_) *param_count_ = param_count;
  5472. return param_count_excluding_defaults;
  5473. }
  5474. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  5475. isize param_count = pt->param_count;
  5476. for (isize i = 0; i < param_count; i++) {
  5477. Entity *e = pt->params->Tuple.variables[i];
  5478. String name = e->token.string;
  5479. if (is_blank_ident(name)) {
  5480. continue;
  5481. }
  5482. if (name == parameter_name) {
  5483. return i;
  5484. }
  5485. }
  5486. return -1;
  5487. }
  5488. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  5489. type = base_type(type);
  5490. GB_ASSERT(type->kind == Type_Proc);
  5491. return lookup_procedure_parameter(&type->Proc, parameter_name);
  5492. }
  5493. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  5494. Entity *entity, Type *proc_type,
  5495. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  5496. CallArgumentErrorMode show_error_mode,
  5497. CallArgumentData *data,
  5498. bool checking_proc_group) {
  5499. TEMPORARY_ALLOCATOR_GUARD();
  5500. CallArgumentError err = CallArgumentError_None;
  5501. ast_node(ce, CallExpr, call);
  5502. GB_ASSERT(is_type_proc(proc_type));
  5503. proc_type = base_type(proc_type);
  5504. TypeProc *pt = &proc_type->Proc;
  5505. isize param_count = 0;
  5506. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  5507. bool variadic = pt->variadic;
  5508. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5509. i64 score = 0;
  5510. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  5511. Type *final_proc_type = proc_type;
  5512. Entity *gen_entity = nullptr;
  5513. if (vari_expand && !variadic) {
  5514. if (show_error) {
  5515. error(ce->ellipsis,
  5516. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  5517. LIT(ce->proc->Ident.token.string));
  5518. }
  5519. err = CallArgumentError_NonVariadicExpand;
  5520. } else if (vari_expand && pt->c_vararg) {
  5521. if (show_error) {
  5522. error(ce->ellipsis,
  5523. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  5524. LIT(ce->proc->Ident.token.string));
  5525. }
  5526. err = CallArgumentError_NonVariadicExpand;
  5527. }
  5528. GB_ASSERT(ce->split_args);
  5529. auto visited = temporary_slice_make<bool>(pt->param_count);
  5530. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  5531. defer ({
  5532. for (Operand const &o : ordered_operands) {
  5533. if (o.expr != nullptr) {
  5534. call->viral_state_flags |= o.expr->viral_state_flags;
  5535. }
  5536. }
  5537. });
  5538. isize positional_operand_count = positional_operands.count;
  5539. if (variadic) {
  5540. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5541. } else if (positional_operand_count > pt->param_count) {
  5542. err = CallArgumentError_TooManyArguments;
  5543. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5544. if (show_error) {
  5545. gbString proc_str = expr_to_string(ce->proc);
  5546. defer (gb_string_free(proc_str));
  5547. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5548. }
  5549. return err;
  5550. }
  5551. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5552. for (isize i = 0; i < positional_operand_count; i++) {
  5553. ordered_operands[i] = positional_operands[i];
  5554. visited[i] = true;
  5555. }
  5556. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5557. bool named_variadic_param = false;
  5558. if (named_operands.count != 0) {
  5559. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5560. for_array(i, ce->split_args->named) {
  5561. Ast *arg = ce->split_args->named[i];
  5562. Operand operand = named_operands[i];
  5563. ast_node(fv, FieldValue, arg);
  5564. if (fv->field->kind != Ast_Ident) {
  5565. if (show_error) {
  5566. gbString expr_str = expr_to_string(fv->field);
  5567. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5568. gb_string_free(expr_str);
  5569. }
  5570. err = CallArgumentError_InvalidFieldValue;
  5571. continue;
  5572. }
  5573. String name = fv->field->Ident.token.string;
  5574. isize param_index = lookup_procedure_parameter(pt, name);
  5575. if (param_index < 0) {
  5576. if (show_error) {
  5577. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5578. }
  5579. err = CallArgumentError_ParameterNotFound;
  5580. continue;
  5581. }
  5582. if (pt->variadic && param_index == pt->variadic_index) {
  5583. named_variadic_param = true;
  5584. }
  5585. if (visited[param_index]) {
  5586. if (show_error) {
  5587. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5588. }
  5589. err = CallArgumentError_DuplicateParameter;
  5590. continue;
  5591. }
  5592. visited[param_index] = true;
  5593. ordered_operands[param_index] = operand;
  5594. }
  5595. }
  5596. isize dummy_argument_count = 0;
  5597. bool actually_variadic = false;
  5598. if (variadic) {
  5599. if (visited[pt->variadic_index] &&
  5600. positional_operand_count < positional_operands.count) {
  5601. if (show_error) {
  5602. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5603. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5604. }
  5605. err = CallArgumentError_DuplicateParameter;
  5606. } else if (!visited[pt->variadic_index]) {
  5607. visited[pt->variadic_index] = true;
  5608. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5609. if (vari_expand) {
  5610. if (variadic_operands.count == 0) {
  5611. error(call, "'..' in the wrong position");
  5612. } else {
  5613. GB_ASSERT(variadic_operands.count != 0);
  5614. *variadic_operand = variadic_operands[0];
  5615. variadic_operand->type = default_type(variadic_operand->type);
  5616. actually_variadic = true;
  5617. }
  5618. } else {
  5619. AstFile *f = call->file();
  5620. // HACK(bill): this is an awful hack
  5621. Operand o = {};
  5622. o.mode = Addressing_Value;
  5623. o.expr = ast_ident(f, make_token_ident("nil"));
  5624. o.expr->Ident.token.pos = ast_token(call).pos;
  5625. if (variadic_operands.count != 0) {
  5626. actually_variadic = true;
  5627. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5628. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5629. o.type = vt->type;
  5630. } else {
  5631. dummy_argument_count += 1;
  5632. o.type = t_untyped_nil;
  5633. }
  5634. *variadic_operand = o;
  5635. }
  5636. }
  5637. }
  5638. for (isize i = 0; i < pt->param_count; i++) {
  5639. if (!visited[i]) {
  5640. Entity *e = pt->params->Tuple.variables[i];
  5641. bool context_allocator_error = false;
  5642. if (e->kind == Entity_Variable) {
  5643. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5644. if (ast_file_vet_explicit_allocators(c->file) && !checking_proc_group) {
  5645. // NOTE(lucas): check if we are trying to default to context.allocator or context.temp_allocator
  5646. if (e->Variable.param_value.original_ast_expr->kind == Ast_SelectorExpr) {
  5647. auto& expr = e->Variable.param_value.original_ast_expr->SelectorExpr.expr;
  5648. auto& selector = e->Variable.param_value.original_ast_expr->SelectorExpr.selector;
  5649. if (expr->kind == Ast_Implicit &&
  5650. expr->Implicit.string == STR_LIT("context") &&
  5651. selector->kind == Ast_Ident &&
  5652. (selector->Ident.token.string == STR_LIT("allocator") ||
  5653. selector->Ident.token.string == STR_LIT("temp_allocator"))) {
  5654. context_allocator_error = true;
  5655. }
  5656. }
  5657. }
  5658. if (!context_allocator_error) {
  5659. ordered_operands[i].mode = Addressing_Value;
  5660. ordered_operands[i].type = e->type;
  5661. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5662. dummy_argument_count += 1;
  5663. score += assign_score_function(1);
  5664. continue;
  5665. }
  5666. }
  5667. }
  5668. if (show_error) {
  5669. if (context_allocator_error) {
  5670. gbString str = type_to_string(e->type);
  5671. error(call, "Parameter '%.*s' of type '%s' must be explicitly provided in procedure call",
  5672. LIT(e->token.string), str);
  5673. gb_string_free(str);
  5674. } else if (e->kind == Entity_TypeName) {
  5675. error(call, "Type parameter '%.*s' is missing in procedure call",
  5676. LIT(e->token.string));
  5677. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5678. // Ignore
  5679. } else {
  5680. gbString str = type_to_string(e->type);
  5681. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5682. LIT(e->token.string), str);
  5683. gb_string_free(str);
  5684. }
  5685. }
  5686. err = CallArgumentError_ParameterMissing;
  5687. }
  5688. }
  5689. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5690. bool allow_array_programming = !(e && (e->flags & EntityFlag_NoBroadcast));
  5691. i64 s = 0;
  5692. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic, allow_array_programming)) {
  5693. bool ok = false;
  5694. if (e && (e->flags & EntityFlag_AnyInt)) {
  5695. if (is_type_integer(param_type)) {
  5696. ok = check_is_castable_to(c, o, param_type);
  5697. }
  5698. }
  5699. if (!allow_array_programming && check_is_assignable_to_with_score(c, o, param_type, nullptr, param_is_variadic, !allow_array_programming)) {
  5700. if (show_error) {
  5701. error(o->expr, "'#no_broadcast' disallows automatic broadcasting a value across all elements of an array-like type in a procedure argument");
  5702. }
  5703. }
  5704. if (ok) {
  5705. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5706. } else {
  5707. if (show_error) {
  5708. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5709. }
  5710. err = CallArgumentError_WrongTypes;
  5711. }
  5712. } else if (show_error) {
  5713. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5714. }
  5715. if (e && e->flags & EntityFlag_ConstInput) {
  5716. if (o->mode != Addressing_Constant) {
  5717. if (show_error) {
  5718. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5719. }
  5720. err = CallArgumentError_NoneConstantParameter;
  5721. }
  5722. }
  5723. if (e && e->kind == Entity_Constant && is_type_proc(e->type)) {
  5724. bool ok = false;
  5725. if (o->mode == Addressing_Constant) {
  5726. ok = true;
  5727. } else if (o->value.kind == ExactValue_Procedure) {
  5728. ok = true;
  5729. }
  5730. if (!ok) {
  5731. if (show_error) {
  5732. error(o->expr, "Expected a constant procedure value for the argument '%.*s'", LIT(e->token.string));
  5733. }
  5734. err = CallArgumentError_NoneConstantParameter;
  5735. }
  5736. }
  5737. if (!err && is_type_any(param_type)) {
  5738. add_type_info_type(c, o->type);
  5739. }
  5740. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5741. add_type_info_type(c, o->type);
  5742. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5743. } else if (show_error && is_type_untyped(o->type)) {
  5744. update_untyped_expr_type(c, o->expr, param_type, true);
  5745. }
  5746. return s;
  5747. };
  5748. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5749. err = CallArgumentError_None;
  5750. if (variadic) {
  5751. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5752. Type *t = pt->params->Tuple.variables[0]->type;
  5753. if (is_type_polymorphic(t)) {
  5754. if (show_error) {
  5755. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5756. }
  5757. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5758. }
  5759. }
  5760. } else {
  5761. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5762. PolyProcData poly_proc_data = {};
  5763. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5764. gen_entity = poly_proc_data.gen_entity;
  5765. Type *gept = base_type(gen_entity->type);
  5766. GB_ASSERT(is_type_proc(gept));
  5767. final_proc_type = gen_entity->type;
  5768. pt = &gept->Proc;
  5769. } else {
  5770. err = CallArgumentError_WrongTypes;
  5771. }
  5772. }
  5773. for (isize i = 0; i < pt->param_count; i++) {
  5774. Operand *o = &ordered_operands[i];
  5775. if (o->mode == Addressing_Invalid) {
  5776. continue;
  5777. }
  5778. Entity *e = pt->params->Tuple.variables[i];
  5779. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5780. if (e->kind == Entity_TypeName) {
  5781. GB_ASSERT(pt->is_polymorphic);
  5782. if (o->mode != Addressing_Type) {
  5783. if (show_error) {
  5784. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5785. }
  5786. err = CallArgumentError_WrongTypes;
  5787. }
  5788. if (are_types_identical(e->type, o->type)) {
  5789. score += assign_score_function(1);
  5790. } else {
  5791. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5792. }
  5793. continue;
  5794. }
  5795. if (param_is_variadic) {
  5796. if (!named_variadic_param) {
  5797. continue;
  5798. }
  5799. }
  5800. score += eval_param_and_score(c, o, e->type, err, false, e, show_error);
  5801. }
  5802. }
  5803. if (variadic) {
  5804. Entity *var_entity = pt->params->Tuple.variables[pt->variadic_index];
  5805. Type *slice = var_entity->type;
  5806. GB_ASSERT(is_type_slice(slice));
  5807. Type *elem = base_type(slice)->Slice.elem;
  5808. Type *t = elem;
  5809. if (is_type_polymorphic(t)) {
  5810. if (show_error) {
  5811. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5812. }
  5813. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5814. }
  5815. for_array(operand_index, variadic_operands) {
  5816. Operand *o = &variadic_operands[operand_index];
  5817. if (vari_expand) {
  5818. t = slice;
  5819. if (operand_index > 0) {
  5820. if (show_error) {
  5821. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5822. }
  5823. if (data) {
  5824. data->score = score;
  5825. data->result_type = final_proc_type->Proc.results;
  5826. data->gen_entity = gen_entity;
  5827. }
  5828. return CallArgumentError_MultipleVariadicExpand;
  5829. }
  5830. }
  5831. score += eval_param_and_score(c, o, t, err, true, var_entity, show_error);
  5832. }
  5833. if (!vari_expand && variadic_operands.count != 0) {
  5834. // NOTE(bill, 2024-07-14): minimize the stack usage for variadic parameters with the backing array
  5835. if (c->decl) {
  5836. bool found = false;
  5837. for (auto &vr : c->decl->variadic_reuses) {
  5838. if (are_types_identical(slice, vr.slice_type)) {
  5839. vr.max_count = gb_max(vr.max_count, variadic_operands.count);
  5840. found = true;
  5841. break;
  5842. }
  5843. }
  5844. if (!found) {
  5845. array_add(&c->decl->variadic_reuses, VariadicReuseData{slice, variadic_operands.count});
  5846. }
  5847. }
  5848. }
  5849. }
  5850. if (data) {
  5851. data->score = score;
  5852. data->result_type = final_proc_type->Proc.results;
  5853. data->gen_entity = gen_entity;
  5854. Ast *proc_lit = nullptr;
  5855. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5856. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5857. if (vp && vp->kind == Ast_ProcLit) {
  5858. proc_lit = vp;
  5859. }
  5860. }
  5861. if (proc_lit == nullptr) {
  5862. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5863. }
  5864. }
  5865. return err;
  5866. }
  5867. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5868. GB_ASSERT(ce != nullptr);
  5869. if (ce->args.count == 0) {
  5870. return false;
  5871. }
  5872. return ce->args[0]->kind == Ast_FieldValue;
  5873. }
  5874. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_) {
  5875. Entity **lhs = nullptr;
  5876. isize lhs_count = -1;
  5877. if (proc_type == nullptr || proc_type == t_invalid) {
  5878. return nullptr;
  5879. }
  5880. GB_ASSERT(is_type_proc(proc_type));
  5881. TypeProc *pt = &base_type(proc_type)->Proc;
  5882. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5883. if (pt->params != nullptr) {
  5884. lhs = pt->params->Tuple.variables.data;
  5885. lhs_count = pt->params->Tuple.variables.count;
  5886. }
  5887. } else {
  5888. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5889. if (pt->params == nullptr) {
  5890. lhs_count = 0;
  5891. } else {
  5892. lhs_count = pt->params->Tuple.variables.count;
  5893. }
  5894. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5895. for (isize i = 0; i < lhs_count; i++) {
  5896. Entity *e = pt->params->Tuple.variables[i];
  5897. if (!is_type_polymorphic(e->type)) {
  5898. lhs[i] = e;
  5899. }
  5900. }
  5901. }
  5902. if (lhs_count_) *lhs_count_ = lhs_count;
  5903. return lhs;
  5904. }
  5905. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5906. if (clauses != nullptr) {
  5907. for (Ast *clause : *clauses) {
  5908. Operand o = {};
  5909. check_expr(ctx, &o, clause);
  5910. if (o.mode != Addressing_Constant) {
  5911. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5912. if (print_err && call_expr) error(call_expr, "at caller location");
  5913. return false;
  5914. } else if (o.value.kind != ExactValue_Bool) {
  5915. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5916. if (print_err && call_expr) error(call_expr, "at caller location");
  5917. return false;
  5918. } else if (!o.value.value_bool) {
  5919. if (print_err) {
  5920. ERROR_BLOCK();
  5921. gbString str = expr_to_string(clause);
  5922. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5923. gb_string_free(str);
  5924. if (scope != nullptr) {
  5925. isize print_count = 0;
  5926. for (auto const &entry : scope->elements) {
  5927. Entity *e = entry.value;
  5928. switch (e->kind) {
  5929. case Entity_TypeName: {
  5930. // if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5931. gbString str = type_to_string(e->type);
  5932. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5933. gb_string_free(str);
  5934. print_count += 1;
  5935. break;
  5936. }
  5937. case Entity_Constant: {
  5938. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5939. gbString str = exact_value_to_string(e->Constant.value);
  5940. if (is_type_untyped(e->type)) {
  5941. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5942. } else {
  5943. gbString t = type_to_string(e->type);
  5944. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5945. gb_string_free(t);
  5946. }
  5947. gb_string_free(str);
  5948. print_count += 1;
  5949. break;
  5950. }
  5951. }
  5952. }
  5953. }
  5954. if (call_expr) {
  5955. TokenPos pos = ast_token(call_expr).pos;
  5956. error_line("%s at caller location\n", token_pos_to_string(pos));
  5957. }
  5958. }
  5959. return false;
  5960. }
  5961. if (ast_file_vet_style(ctx->file)) {
  5962. Ast *c = unparen_expr(clause);
  5963. if (c->kind == Ast_BinaryExpr && c->BinaryExpr.op.kind == Token_CmpAnd) {
  5964. ERROR_BLOCK();
  5965. error(c, "Prefer to separate 'where' clauses with a comma rather than '&&'");
  5966. gbString x = expr_to_string(c->BinaryExpr.left);
  5967. gbString y = expr_to_string(c->BinaryExpr.right);
  5968. error_line("\tSuggestion: '%s, %s'\n", x, y);
  5969. gb_string_free(y);
  5970. gb_string_free(x);
  5971. }
  5972. }
  5973. }
  5974. }
  5975. return true;
  5976. }
  5977. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5978. bool success = true;
  5979. type = base_type(type);
  5980. if (named_args.count > 0) {
  5981. TypeProc *pt = nullptr;
  5982. if (is_type_proc(type)) {
  5983. pt = &type->Proc;
  5984. }
  5985. for_array(i, named_args) {
  5986. Ast *arg = named_args[i];
  5987. if (arg->kind != Ast_FieldValue) {
  5988. if (show_error) {
  5989. error(arg, "Expected a 'field = value'");
  5990. }
  5991. return false;
  5992. }
  5993. ast_node(fv, FieldValue, arg);
  5994. if (fv->field->kind != Ast_Ident) {
  5995. if (show_error) {
  5996. gbString expr_str = expr_to_string(fv->field);
  5997. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5998. gb_string_free(expr_str);
  5999. }
  6000. success = false;
  6001. continue;
  6002. }
  6003. String key = fv->field->Ident.token.string;
  6004. Ast *value = fv->value;
  6005. Type *type_hint = nullptr;
  6006. if (pt) {
  6007. isize param_index = lookup_procedure_parameter(pt, key);
  6008. if (param_index < 0) {
  6009. if (show_error) {
  6010. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  6011. }
  6012. success = false;
  6013. continue;
  6014. }
  6015. Entity *e = pt->params->Tuple.variables[param_index];
  6016. if (!is_type_polymorphic(e->type)) {
  6017. type_hint = e->type;
  6018. }
  6019. }
  6020. Operand o = {};
  6021. check_expr_with_type_hint(c, &o, value, type_hint);
  6022. if (o.mode == Addressing_Invalid) {
  6023. success = false;
  6024. }
  6025. array_add(named_operands, o);
  6026. }
  6027. }
  6028. return success;
  6029. }
  6030. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  6031. Entity *e, Type *proc_type,
  6032. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  6033. CallArgumentErrorMode show_error_mode,
  6034. CallArgumentData *data,
  6035. bool checking_proc_group) {
  6036. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  6037. Ast *ident = operand->expr;
  6038. while (ident->kind == Ast_SelectorExpr) {
  6039. Ast *s = ident->SelectorExpr.selector;
  6040. ident = s;
  6041. }
  6042. if (e == nullptr) {
  6043. e = entity_of_node(ident);
  6044. if (e != nullptr) {
  6045. proc_type = e->type;
  6046. }
  6047. }
  6048. GB_ASSERT(proc_type != nullptr);
  6049. proc_type = base_type(proc_type);
  6050. if (proc_type == t_invalid) {
  6051. return false;
  6052. }
  6053. GB_ASSERT(proc_type->kind == Type_Proc);
  6054. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data, checking_proc_group);
  6055. if (return_on_failure && err != CallArgumentError_None) {
  6056. return false;
  6057. }
  6058. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  6059. if (!return_on_failure && entity_to_use != nullptr) {
  6060. add_entity_use(c, ident, entity_to_use);
  6061. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  6062. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  6063. }
  6064. if (data->gen_entity != nullptr) {
  6065. Entity *e = data->gen_entity;
  6066. DeclInfo *decl = data->gen_entity->decl_info;
  6067. CheckerContext ctx = *c;
  6068. ctx.scope = decl->scope;
  6069. ctx.decl = decl;
  6070. ctx.proc_name = e->token.string;
  6071. ctx.curr_proc_decl = decl;
  6072. ctx.curr_proc_sig = e->type;
  6073. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  6074. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  6075. if (return_on_failure) {
  6076. if (!ok) {
  6077. return false;
  6078. }
  6079. } else {
  6080. decl->where_clauses_evaluated = true;
  6081. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  6082. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  6083. }
  6084. if (is_type_proc(data->gen_entity->type)) {
  6085. Type *t = base_type(entity_to_use->type);
  6086. data->result_type = t->Proc.results;
  6087. }
  6088. }
  6089. }
  6090. return true;
  6091. }
  6092. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  6093. ast_node(ce, CallExpr, call);
  6094. GB_ASSERT(ce->split_args != nullptr);
  6095. Slice<Ast *> const &positional_args = ce->split_args->positional;
  6096. Slice<Ast *> const &named_args = ce->split_args->named;
  6097. CallArgumentData data = {};
  6098. data.result_type = t_invalid;
  6099. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  6100. auto procs = proc_group_entities_cloned(c, *operand);
  6101. if (procs.count > 1) {
  6102. isize max_arg_count = positional_args.count + named_args.count;
  6103. for (Ast *arg : positional_args) {
  6104. // NOTE(bill): The only thing that may have multiple values
  6105. // will be a call expression (assuming `or_return` and `()` will be stripped)
  6106. arg = strip_or_return_expr(arg);
  6107. if (arg && arg->kind == Ast_CallExpr) {
  6108. max_arg_count = ISIZE_MAX;
  6109. break;
  6110. }
  6111. }
  6112. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  6113. // NOTE(bill): The only thing that may have multiple values
  6114. // will be a call expression (assuming `or_return` and `()` will be stripped)
  6115. if (arg->kind == Ast_FieldValue) {
  6116. arg = strip_or_return_expr(arg->FieldValue.value);
  6117. if (arg && arg->kind == Ast_CallExpr) {
  6118. max_arg_count = ISIZE_MAX;
  6119. break;
  6120. }
  6121. }
  6122. }
  6123. // ignore named arguments first
  6124. for (Ast *arg : named_args) {
  6125. if (arg->kind != Ast_FieldValue) {
  6126. continue;
  6127. }
  6128. ast_node(fv, FieldValue, arg);
  6129. if (fv->field->kind != Ast_Ident) {
  6130. continue;
  6131. }
  6132. String key = fv->field->Ident.token.string;
  6133. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  6134. Type *t = procs[proc_index]->type;
  6135. if (is_type_proc(t)) {
  6136. isize param_index = lookup_procedure_parameter(t, key);
  6137. if (param_index < 0) {
  6138. array_unordered_remove(&procs, proc_index);
  6139. }
  6140. }
  6141. }
  6142. }
  6143. if (procs.count == 0) {
  6144. // if any of the named arguments are wrong, the `procs` will be empty
  6145. // just start from scratch
  6146. array_free(&procs);
  6147. procs = proc_group_entities_cloned(c, *operand);
  6148. }
  6149. // filter by positional argument length
  6150. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  6151. Entity *proc = procs[proc_index];
  6152. Type *pt = base_type(proc->type);
  6153. if (!(pt != nullptr && is_type_proc(pt))) {
  6154. proc_index++;
  6155. continue;
  6156. }
  6157. isize param_count = 0;
  6158. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  6159. if (param_count_excluding_defaults > max_arg_count) {
  6160. array_unordered_remove(&procs, proc_index);
  6161. continue;
  6162. }
  6163. if (!pt->Proc.variadic && max_arg_count != ISIZE_MAX && param_count < max_arg_count) {
  6164. array_unordered_remove(&procs, proc_index);
  6165. continue;
  6166. }
  6167. proc_index++;
  6168. }
  6169. }
  6170. Entity **lhs = nullptr;
  6171. isize lhs_count = -1;
  6172. i32 variadic_index = -1;
  6173. TEMPORARY_ALLOCATOR_GUARD();
  6174. auto positional_operands = array_make<Operand>(temporary_allocator(), 0, 0);
  6175. auto named_operands = array_make<Operand>(temporary_allocator(), 0, 0);
  6176. if (procs.count == 1) {
  6177. Entity *e = procs[0];
  6178. Type *pt = base_type(e->type);
  6179. if (pt != nullptr && is_type_proc(pt)) {
  6180. lhs = populate_proc_parameter_list(c, pt, &lhs_count);
  6181. if (pt->Proc.variadic) {
  6182. variadic_index = pt->Proc.variadic_index;
  6183. }
  6184. }
  6185. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6186. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  6187. check_call_arguments_single(c, call, operand,
  6188. e, e->type,
  6189. positional_operands, named_operands,
  6190. CallArgumentErrorMode::ShowErrors,
  6191. &data, false);
  6192. }
  6193. return data;
  6194. }
  6195. {
  6196. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  6197. // where the same positional parameter has the same type value (and ellipsis)
  6198. isize proc_arg_count = -1;
  6199. for (Entity *p : procs) {
  6200. Type *pt = base_type(p->type);
  6201. if (pt != nullptr && is_type_proc(pt)) {
  6202. if (proc_arg_count < 0) {
  6203. proc_arg_count = pt->Proc.param_count;
  6204. } else {
  6205. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  6206. }
  6207. }
  6208. }
  6209. if (proc_arg_count >= 0) {
  6210. lhs_count = proc_arg_count;
  6211. if (lhs_count > 0) {
  6212. lhs = gb_alloc_array(temporary_allocator(), Entity *, lhs_count);
  6213. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  6214. Entity *e = nullptr;
  6215. for (Entity *p : procs) {
  6216. Type *pt = base_type(p->type);
  6217. if (!(pt != nullptr && is_type_proc(pt))) {
  6218. continue;
  6219. }
  6220. if (e == nullptr) {
  6221. e = pt->Proc.params->Tuple.variables[param_index];
  6222. } else {
  6223. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  6224. if (e == f) {
  6225. continue;
  6226. }
  6227. if (are_types_identical(e->type, f->type)) {
  6228. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  6229. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  6230. if (ee == fe) {
  6231. continue;
  6232. }
  6233. }
  6234. // NOTE(bill): Entities are not close enough to be used
  6235. e = nullptr;
  6236. break;
  6237. }
  6238. }
  6239. lhs[param_index] = e;
  6240. }
  6241. for (Entity *p : procs) {
  6242. Type *pt = base_type(p->type);
  6243. if (!(pt != nullptr && is_type_proc(pt))) {
  6244. continue;
  6245. }
  6246. if (pt->Proc.is_polymorphic) {
  6247. if (variadic_index == -1) {
  6248. variadic_index = pt->Proc.variadic_index;
  6249. } else if (variadic_index != pt->Proc.variadic_index) {
  6250. variadic_index = -1;
  6251. break;
  6252. }
  6253. } else {
  6254. variadic_index = -1;
  6255. break;
  6256. }
  6257. }
  6258. }
  6259. }
  6260. }
  6261. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6262. for_array(i, named_args) {
  6263. Ast *arg = named_args[i];
  6264. if (arg->kind != Ast_FieldValue) {
  6265. error(arg, "Expected a 'field = value'");
  6266. return data;
  6267. }
  6268. ast_node(fv, FieldValue, arg);
  6269. if (fv->field->kind != Ast_Ident) {
  6270. gbString expr_str = expr_to_string(fv->field);
  6271. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6272. gb_string_free(expr_str);
  6273. return data;
  6274. }
  6275. String key = fv->field->Ident.token.string;
  6276. Ast *value = fv->value;
  6277. Type *type_hint = nullptr;
  6278. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  6279. Entity *e = lhs[lhs_idx];
  6280. if (e != nullptr && e->token.string == key &&
  6281. !is_type_polymorphic(e->type)) {
  6282. type_hint = e->type;
  6283. break;
  6284. }
  6285. }
  6286. Operand o = {};
  6287. check_expr_with_type_hint(c, &o, value, type_hint);
  6288. array_add(&named_operands, o);
  6289. }
  6290. auto valids = array_make<ValidIndexAndScore>(temporary_allocator(), 0, procs.count);
  6291. auto proc_entities = array_make<Entity *>(temporary_allocator(), 0, procs.count*2 + 1);
  6292. for (Entity *proc : procs) {
  6293. array_add(&proc_entities, proc);
  6294. }
  6295. int max_matched_features = 0;
  6296. gbString expr_name = expr_to_string(operand->expr);
  6297. defer (gb_string_free(expr_name));
  6298. c->in_proc_group = true;
  6299. for_array(i, procs) {
  6300. Entity *p = procs[i];
  6301. if (p->flags & EntityFlag_Disabled) {
  6302. continue;
  6303. }
  6304. Type *pt = base_type(p->type);
  6305. if (pt != nullptr && is_type_proc(pt)) {
  6306. CallArgumentData data = {};
  6307. CheckerContext ctx = *c;
  6308. ctx.no_polymorphic_errors = true;
  6309. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  6310. ctx.hide_polymorphic_errors = true;
  6311. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  6312. p, pt,
  6313. positional_operands, named_operands,
  6314. CallArgumentErrorMode::NoErrors,
  6315. &data, true);
  6316. if (!is_a_candidate) {
  6317. continue;
  6318. }
  6319. isize index = i;
  6320. ValidIndexAndScore item = {};
  6321. item.score = data.score;
  6322. if (data.gen_entity != nullptr) {
  6323. array_add(&proc_entities, data.gen_entity);
  6324. index = proc_entities.count-1;
  6325. // prefer non-polymorphic procedures over polymorphic
  6326. item.score += assign_score_function(1);
  6327. }
  6328. max_matched_features = gb_max(max_matched_features, matched_target_features(&pt->Proc));
  6329. item.index = index;
  6330. array_add(&valids, item);
  6331. }
  6332. }
  6333. c->in_proc_group = false;
  6334. if (max_matched_features > 0) {
  6335. for_array(i, valids) {
  6336. Entity *p = procs[valids[i].index];
  6337. Type *t = base_type(p->type);
  6338. GB_ASSERT(t->kind == Type_Proc);
  6339. int matched = matched_target_features(&t->Proc);
  6340. valids[i].score += assign_score_function(max_matched_features-matched);
  6341. }
  6342. }
  6343. if (valids.count > 1) {
  6344. array_sort(valids, valid_index_and_score_cmp);
  6345. i64 best_score = valids[0].score;
  6346. Entity *best_entity = proc_entities[valids[0].index];
  6347. GB_ASSERT(best_entity != nullptr);
  6348. for (isize i = 1; i < valids.count; i++) {
  6349. if (best_score > valids[i].score) {
  6350. valids.count = i;
  6351. break;
  6352. }
  6353. if (best_entity == proc_entities[valids[i].index]) {
  6354. valids.count = i;
  6355. break;
  6356. }
  6357. }
  6358. }
  6359. auto print_argument_types = [&]() {
  6360. error_line("\tGiven argument types: (");
  6361. isize i = 0;
  6362. for (Operand const &o : positional_operands) {
  6363. if (i++ > 0) error_line(", ");
  6364. gbString type = type_to_string(o.type);
  6365. defer (gb_string_free(type));
  6366. error_line("%s", type);
  6367. }
  6368. for (Operand const &o : named_operands) {
  6369. if (i++ > 0) error_line(", ");
  6370. gbString type = type_to_string(o.type);
  6371. defer (gb_string_free(type));
  6372. if (i < ce->split_args->named.count) {
  6373. Ast *named_field = ce->split_args->named[i];
  6374. ast_node(fv, FieldValue, named_field);
  6375. gbString field = expr_to_string(fv->field);
  6376. defer (gb_string_free(field));
  6377. error_line("%s = %s", field, type);
  6378. } else {
  6379. error_line("%s", type);
  6380. }
  6381. }
  6382. error_line(")\n");
  6383. };
  6384. if (valids.count == 0) {
  6385. ERROR_BLOCK();
  6386. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  6387. if (positional_operands.count == 0 && named_operands.count == 0) {
  6388. error_line("\tNo given arguments\n");
  6389. } else {
  6390. print_argument_types();
  6391. }
  6392. if (procs.count == 0) {
  6393. procs = proc_group_entities_cloned(c, *operand);
  6394. }
  6395. if (procs.count > 0) {
  6396. error_line("Did you mean to use one of the following:\n");
  6397. }
  6398. // Try to reduce the list further for `$T: typeid` like parameters
  6399. bool *possibly_ignore = temporary_alloc_array<bool>(procs.count);
  6400. isize possibly_ignore_set = 0;
  6401. if (true) {
  6402. // NOTE(bill): This currently only checks for #soa types
  6403. for_array(i, procs) {
  6404. Entity *proc = procs[i];
  6405. Type *t = base_type(proc->type);
  6406. if (t == nullptr || t->kind != Type_Proc) {
  6407. continue;
  6408. }
  6409. TypeProc *pt = &t->Proc;
  6410. if (pt->param_count == 0) {
  6411. continue;
  6412. }
  6413. for_array(j, pt->params->Tuple.variables) {
  6414. Entity *v = pt->params->Tuple.variables[j];
  6415. if (v->kind != Entity_TypeName) {
  6416. continue;
  6417. }
  6418. Type *dst_t = base_type(v->type);
  6419. while (dst_t->kind == Type_Generic && dst_t->Generic.specialized) {
  6420. dst_t = dst_t->Generic.specialized;
  6421. }
  6422. if (j >= positional_operands.count) {
  6423. continue;
  6424. }
  6425. Operand const &o = positional_operands[j];
  6426. if (o.mode != Addressing_Type) {
  6427. continue;
  6428. }
  6429. Type *t = base_type(o.type);
  6430. if (t->kind == dst_t->kind) {
  6431. continue;
  6432. }
  6433. Type *st = base_type(type_deref(o.type));
  6434. Type *dt = base_type(type_deref(dst_t));
  6435. if (st->kind == dt->kind) {
  6436. continue;
  6437. }
  6438. if (is_type_soa_struct(st)) {
  6439. possibly_ignore[i] = true;
  6440. possibly_ignore_set += 1;
  6441. continue;
  6442. }
  6443. }
  6444. }
  6445. }
  6446. if (possibly_ignore_set == procs.count) {
  6447. possibly_ignore_set = 0;
  6448. }
  6449. isize max_name_length = 0;
  6450. isize max_type_length = 0;
  6451. for_array(i, procs) {
  6452. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6453. continue;
  6454. }
  6455. Entity *proc = procs[i];
  6456. Type *t = base_type(proc->type);
  6457. if (t == t_invalid) continue;
  6458. String prefix = {};
  6459. String prefix_sep = {};
  6460. if (proc->pkg) {
  6461. prefix = proc->pkg->name;
  6462. prefix_sep = str_lit(".");
  6463. }
  6464. String name = proc->token.string;
  6465. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  6466. gbString pt;
  6467. if (t->Proc.node != nullptr) {
  6468. pt = expr_to_string(t->Proc.node);
  6469. } else {
  6470. pt = type_to_string(t);
  6471. }
  6472. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  6473. gb_string_free(pt);
  6474. }
  6475. isize max_spaces = gb_max(max_name_length, max_type_length);
  6476. char *spaces = temporary_alloc_array<char>(max_spaces+1);
  6477. for (isize i = 0; i < max_spaces; i++) {
  6478. spaces[i] = ' ';
  6479. }
  6480. spaces[max_spaces] = 0;
  6481. for_array(i, procs) {
  6482. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6483. continue;
  6484. }
  6485. Entity *proc = procs[i];
  6486. TokenPos pos = proc->token.pos;
  6487. Type *t = base_type(proc->type);
  6488. if (t == t_invalid) continue;
  6489. GB_ASSERT(t->kind == Type_Proc);
  6490. gbString pt;
  6491. defer (gb_string_free(pt));
  6492. if (t->Proc.node != nullptr) {
  6493. pt = expr_to_string(t->Proc.node);
  6494. } else {
  6495. pt = type_to_string(t);
  6496. }
  6497. String prefix = {};
  6498. String prefix_sep = {};
  6499. if (proc->pkg) {
  6500. prefix = proc->pkg->name;
  6501. prefix_sep = str_lit(".");
  6502. }
  6503. String name = proc->token.string;
  6504. isize len = prefix.len + prefix_sep.len + name.len;
  6505. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  6506. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  6507. char const *sep = "::";
  6508. if (proc->kind == Entity_Variable) {
  6509. sep = ":=";
  6510. }
  6511. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  6512. LIT(prefix), LIT(prefix_sep), LIT(name),
  6513. name_padding, spaces,
  6514. sep,
  6515. pt,
  6516. type_padding, spaces,
  6517. token_pos_to_string(pos)
  6518. );
  6519. }
  6520. if (procs.count > 0) {
  6521. error_line("\n");
  6522. }
  6523. data.result_type = t_invalid;
  6524. } else if (valids.count > 1) {
  6525. ERROR_BLOCK();
  6526. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  6527. if (positional_operands.count == 0 && named_operands.count == 0) {
  6528. error_line("\tNo given arguments\n");
  6529. } else {
  6530. print_argument_types();
  6531. }
  6532. for (auto const &valid : valids) {
  6533. Entity *proc = proc_entities[valid.index];
  6534. GB_ASSERT(proc != nullptr);
  6535. TokenPos pos = proc->token.pos;
  6536. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  6537. gbString pt = nullptr;
  6538. defer (gb_string_free(pt));
  6539. if (t->Proc.node != nullptr) {
  6540. pt = expr_to_string(t->Proc.node);
  6541. } else {
  6542. pt = type_to_string(t);
  6543. }
  6544. String name = proc->token.string;
  6545. char const *sep = "::";
  6546. if (proc->kind == Entity_Variable) {
  6547. sep = ":=";
  6548. }
  6549. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  6550. if (proc->decl_info->proc_lit != nullptr) {
  6551. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  6552. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  6553. if (pl->where_token.kind != Token_Invalid) {
  6554. error_line("\n\t\twhere ");
  6555. for_array(j, pl->where_clauses) {
  6556. Ast *clause = pl->where_clauses[j];
  6557. if (j != 0) {
  6558. error_line("\t\t ");
  6559. }
  6560. gbString str = expr_to_string(clause);
  6561. error_line("%s", str);
  6562. gb_string_free(str);
  6563. if (j != pl->where_clauses.count-1) {
  6564. error_line(",");
  6565. }
  6566. }
  6567. error_line("\n\t");
  6568. }
  6569. }
  6570. error_line("at %s\n", token_pos_to_string(pos));
  6571. }
  6572. data.result_type = t_invalid;
  6573. } else {
  6574. GB_ASSERT(valids.count == 1);
  6575. Ast *ident = operand->expr;
  6576. while (ident->kind == Ast_SelectorExpr) {
  6577. Ast *s = ident->SelectorExpr.selector;
  6578. ident = s;
  6579. }
  6580. Entity *e = proc_entities[valids[0].index];
  6581. GB_ASSERT(e != nullptr);
  6582. Array<Operand> named_operands = {};
  6583. check_call_arguments_single(c, call, operand,
  6584. e, e->type,
  6585. positional_operands, named_operands,
  6586. CallArgumentErrorMode::ShowErrors,
  6587. &data, false);
  6588. return data;
  6589. }
  6590. return data;
  6591. }
  6592. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  6593. Type *proc_type = nullptr;
  6594. CallArgumentData data = {};
  6595. data.result_type = t_invalid;
  6596. proc_type = base_type(operand->type);
  6597. TypeProc *pt = nullptr;
  6598. if (proc_type) {
  6599. pt = &proc_type->Proc;
  6600. }
  6601. TEMPORARY_ALLOCATOR_GUARD();
  6602. ast_node(ce, CallExpr, call);
  6603. bool any_failure = false;
  6604. // Split positional and named args into separate arrays/slices
  6605. Slice<Ast *> positional_args = {};
  6606. Slice<Ast *> named_args = {};
  6607. if (ce->split_args == nullptr) {
  6608. positional_args = ce->args;
  6609. for (isize i = 0; i < ce->args.count; i++) {
  6610. Ast *arg = ce->args.data[i];
  6611. if (arg->kind == Ast_FieldValue) {
  6612. positional_args.count = i;
  6613. break;
  6614. }
  6615. }
  6616. named_args = slice(ce->args, positional_args.count, ce->args.count);
  6617. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  6618. split_args->positional = positional_args;
  6619. split_args->named = named_args;
  6620. ce->split_args = split_args;
  6621. } else {
  6622. positional_args = ce->split_args->positional;
  6623. named_args = ce->split_args->named;
  6624. }
  6625. if (operand->mode == Addressing_ProcGroup) {
  6626. return check_call_arguments_proc_group(c, operand, call);
  6627. }
  6628. TEMPORARY_ALLOCATOR_GUARD();
  6629. auto positional_operands = array_make<Operand>(temporary_allocator(), 0, positional_args.count);
  6630. auto named_operands = array_make<Operand>(temporary_allocator(), 0, 0);
  6631. if (positional_args.count > 0) {
  6632. Entity **lhs = nullptr;
  6633. isize lhs_count = -1;
  6634. i32 variadic_index = -1;
  6635. if (pt != nullptr) {
  6636. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count);
  6637. if (pt->variadic) {
  6638. variadic_index = pt->variadic_index;
  6639. }
  6640. }
  6641. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6642. }
  6643. if (named_args.count > 0) {
  6644. for_array(i, named_args) {
  6645. Ast *arg = named_args[i];
  6646. if (arg->kind != Ast_FieldValue) {
  6647. error(arg, "Expected a 'field = value'");
  6648. return data;
  6649. }
  6650. ast_node(fv, FieldValue, arg);
  6651. if (fv->field->kind != Ast_Ident) {
  6652. gbString expr_str = expr_to_string(fv->field);
  6653. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6654. any_failure = true;
  6655. gb_string_free(expr_str);
  6656. continue;
  6657. }
  6658. String key = fv->field->Ident.token.string;
  6659. Ast *value = fv->value;
  6660. isize param_index = lookup_procedure_parameter(pt, key);
  6661. Type *type_hint = nullptr;
  6662. if (param_index >= 0) {
  6663. Entity *e = pt->params->Tuple.variables[param_index];
  6664. type_hint = e->type;
  6665. }
  6666. Operand o = {};
  6667. check_expr_with_type_hint(c, &o, value, type_hint);
  6668. if (o.mode == Addressing_Invalid) {
  6669. any_failure = true;
  6670. }
  6671. array_add(&named_operands, o);
  6672. }
  6673. }
  6674. if (!any_failure) {
  6675. check_call_arguments_single(c, call, operand,
  6676. nullptr, proc_type,
  6677. positional_operands, named_operands,
  6678. CallArgumentErrorMode::ShowErrors,
  6679. &data, false);
  6680. } else if (pt) {
  6681. data.result_type = pt->results;
  6682. }
  6683. return data;
  6684. }
  6685. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6686. if (!is_type_polymorphic_record(t)) {
  6687. return -1;
  6688. }
  6689. TypeTuple *params = get_record_polymorphic_params(t);
  6690. if (params == nullptr) {
  6691. return -1;
  6692. }
  6693. for_array(i, params->variables) {
  6694. Entity *e = params->variables[i];
  6695. String name = e->token.string;
  6696. if (is_blank_ident(name)) {
  6697. continue;
  6698. }
  6699. if (name == parameter_name) {
  6700. return i;
  6701. }
  6702. }
  6703. return -1;
  6704. }
  6705. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6706. TEMPORARY_ALLOCATOR_GUARD();
  6707. ast_node(ce, CallExpr, call);
  6708. Type *original_type = operand->type;
  6709. GB_ASSERT(is_type_polymorphic_record(original_type));
  6710. bool show_error = true;
  6711. Array<Operand> operands = {};
  6712. CallArgumentError err = CallArgumentError_None;
  6713. bool named_fields = false;
  6714. {
  6715. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6716. auto prev_type_path = c->type_path;
  6717. TEMPORARY_ALLOCATOR_GUARD();
  6718. c->type_path = new_checker_type_path(temporary_allocator());
  6719. defer (c->type_path = prev_type_path);
  6720. if (is_call_expr_field_value(ce)) {
  6721. named_fields = true;
  6722. operands = array_make<Operand>(temporary_allocator(), ce->args.count);
  6723. for_array(i, ce->args) {
  6724. Ast *arg = ce->args[i];
  6725. ast_node(fv, FieldValue, arg);
  6726. if (fv->value == nullptr) {
  6727. error(fv->eq, "Expected a value");
  6728. err = CallArgumentError_InvalidFieldValue;
  6729. continue;
  6730. }
  6731. if (fv->field->kind == Ast_Ident) {
  6732. String name = fv->field->Ident.token.string;
  6733. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6734. if (index >= 0) {
  6735. TypeTuple *params = get_record_polymorphic_params(original_type);
  6736. Entity *e = params->variables[index];
  6737. if (e->kind == Entity_Constant) {
  6738. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6739. continue;
  6740. }
  6741. }
  6742. }
  6743. check_expr_or_type(c, &operands[i], fv->value);
  6744. }
  6745. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6746. if (vari_expand) {
  6747. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6748. }
  6749. } else {
  6750. operands = array_make<Operand>(temporary_allocator(), 0, 2*ce->args.count);
  6751. Entity **lhs = nullptr;
  6752. isize lhs_count = -1;
  6753. TypeTuple *params = get_record_polymorphic_params(original_type);
  6754. if (params != nullptr) {
  6755. lhs = params->variables.data;
  6756. lhs_count = params->variables.count;
  6757. }
  6758. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6759. }
  6760. }
  6761. if (err != 0) {
  6762. operand->mode = Addressing_Invalid;
  6763. return err;
  6764. }
  6765. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6766. isize param_count = tuple->variables.count;
  6767. isize minimum_param_count = param_count;
  6768. for (; minimum_param_count > 0; minimum_param_count--) {
  6769. Entity *e = tuple->variables[minimum_param_count-1];
  6770. if (e->kind != Entity_Constant) {
  6771. break;
  6772. }
  6773. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6774. break;
  6775. }
  6776. }
  6777. Array<Operand> ordered_operands = operands;
  6778. if (!named_fields) {
  6779. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6780. array_copy(&ordered_operands, operands, 0);
  6781. } else {
  6782. TEMPORARY_ALLOCATOR_GUARD();
  6783. bool *visited = temporary_alloc_array<bool>(param_count);
  6784. // LEAK(bill)
  6785. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6786. for_array(i, ce->args) {
  6787. Ast *arg = ce->args[i];
  6788. ast_node(fv, FieldValue, arg);
  6789. if (fv->field->kind != Ast_Ident) {
  6790. if (show_error) {
  6791. gbString expr_str = expr_to_string(fv->field);
  6792. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6793. gb_string_free(expr_str);
  6794. }
  6795. err = CallArgumentError_InvalidFieldValue;
  6796. continue;
  6797. }
  6798. String name = fv->field->Ident.token.string;
  6799. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6800. if (index < 0) {
  6801. if (show_error) {
  6802. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6803. }
  6804. err = CallArgumentError_ParameterNotFound;
  6805. continue;
  6806. }
  6807. if (visited[index]) {
  6808. if (show_error) {
  6809. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6810. }
  6811. err = CallArgumentError_DuplicateParameter;
  6812. continue;
  6813. }
  6814. visited[index] = true;
  6815. ordered_operands[index] = operands[i];
  6816. }
  6817. for (isize i = 0; i < param_count; i++) {
  6818. if (!visited[i]) {
  6819. Entity *e = tuple->variables[i];
  6820. if (is_blank_ident(e->token)) {
  6821. continue;
  6822. }
  6823. if (show_error) {
  6824. if (e->kind == Entity_TypeName) {
  6825. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6826. LIT(e->token.string));
  6827. } else {
  6828. gbString str = type_to_string(e->type);
  6829. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6830. LIT(e->token.string), str);
  6831. gb_string_free(str);
  6832. }
  6833. }
  6834. err = CallArgumentError_ParameterMissing;
  6835. }
  6836. }
  6837. }
  6838. if (err != 0) {
  6839. operand->mode = Addressing_Invalid;
  6840. return err;
  6841. }
  6842. while (ordered_operands.count > 0) {
  6843. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6844. break;
  6845. }
  6846. array_pop(&ordered_operands);
  6847. }
  6848. if (minimum_param_count != param_count) {
  6849. if (param_count < ordered_operands.count) {
  6850. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6851. err = CallArgumentError_TooManyArguments;
  6852. } else if (minimum_param_count > ordered_operands.count) {
  6853. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6854. err = CallArgumentError_TooFewArguments;
  6855. }
  6856. } else {
  6857. if (param_count < ordered_operands.count) {
  6858. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6859. err = CallArgumentError_TooManyArguments;
  6860. } else if (param_count > ordered_operands.count) {
  6861. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6862. err = CallArgumentError_TooFewArguments;
  6863. }
  6864. }
  6865. if (err != 0) {
  6866. return err;
  6867. }
  6868. if (minimum_param_count != param_count) {
  6869. array_resize(&ordered_operands, param_count);
  6870. isize missing_count = 0;
  6871. // NOTE(bill): Replace missing operands with the default values (if possible)
  6872. for_array(i, ordered_operands) {
  6873. Operand *o = &ordered_operands[i];
  6874. if (o->expr == nullptr) {
  6875. Entity *e = tuple->variables[i];
  6876. if (e->kind == Entity_Constant) {
  6877. missing_count += 1;
  6878. o->mode = Addressing_Constant;
  6879. o->type = default_type(e->type);
  6880. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6881. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6882. o->value = e->Constant.param_value.value;
  6883. }
  6884. } else if (e->kind == Entity_TypeName) {
  6885. missing_count += 1;
  6886. o->mode = Addressing_Type;
  6887. o->type = e->type;
  6888. o->expr = e->identifier;
  6889. }
  6890. }
  6891. }
  6892. }
  6893. isize oo_count = gb_min(param_count, ordered_operands.count);
  6894. i64 score = 0;
  6895. for (isize i = 0; i < oo_count; i++) {
  6896. Entity *e = tuple->variables[i];
  6897. Operand *o = &ordered_operands[i];
  6898. if (o->mode == Addressing_Invalid) {
  6899. continue;
  6900. }
  6901. if (e->kind == Entity_TypeName) {
  6902. if (o->mode != Addressing_Type) {
  6903. if (show_error) {
  6904. gbString expr = expr_to_string(o->expr);
  6905. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6906. gb_string_free(expr);
  6907. }
  6908. err = CallArgumentError_WrongTypes;
  6909. }
  6910. if (are_types_identical(e->type, o->type)) {
  6911. score += assign_score_function(1);
  6912. } else {
  6913. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6914. }
  6915. } else {
  6916. i64 s = 0;
  6917. if (o->type->kind == Type_Generic) {
  6918. // Polymorphic name!
  6919. score += assign_score_function(1);
  6920. continue;
  6921. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6922. if (show_error) {
  6923. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6924. }
  6925. err = CallArgumentError_WrongTypes;
  6926. }
  6927. o->type = e->type;
  6928. if (o->mode != Addressing_Constant) {
  6929. bool valid = false;
  6930. if (is_type_proc(o->type)) {
  6931. Entity *proc_entity = entity_from_expr(o->expr);
  6932. valid = proc_entity != nullptr;
  6933. }
  6934. if (!valid) {
  6935. if (show_error) {
  6936. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6937. }
  6938. err = CallArgumentError_NoneConstantParameter;
  6939. }
  6940. }
  6941. score += s;
  6942. }
  6943. // NOTE(bill): Add type info the parameters
  6944. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6945. // add_type_info_type(c, o->type);
  6946. }
  6947. if (show_error && err) {
  6948. return err;
  6949. }
  6950. {
  6951. GenTypesData *found_gen_types = ensure_polymorphic_record_entity_has_gen_types(c, original_type);
  6952. rw_mutex_shared_lock(&found_gen_types->mutex);
  6953. Entity *found_entity = find_polymorphic_record_entity(found_gen_types, param_count, ordered_operands);
  6954. rw_mutex_shared_unlock(&found_gen_types->mutex);
  6955. if (found_entity) {
  6956. operand->mode = Addressing_Type;
  6957. operand->type = found_entity->type;
  6958. return err;
  6959. }
  6960. CheckerContext ctx = *c;
  6961. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6962. ctx.scope = polymorphic_record_parent_scope(original_type);
  6963. GB_ASSERT(ctx.scope != nullptr);
  6964. Type *bt = base_type(original_type);
  6965. String generated_name = make_string_c(expr_to_string(call));
  6966. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6967. if (bt->kind == Type_Struct) {
  6968. Ast *node = clone_ast(bt->Struct.node);
  6969. Type *struct_type = alloc_type_struct();
  6970. struct_type->Struct.node = node;
  6971. struct_type->Struct.polymorphic_parent = original_type;
  6972. set_base_type(named_type, struct_type);
  6973. check_open_scope(&ctx, node);
  6974. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6975. check_close_scope(&ctx);
  6976. } else if (bt->kind == Type_Union) {
  6977. Ast *node = clone_ast(bt->Union.node);
  6978. Type *union_type = alloc_type_union();
  6979. union_type->Union.node = node;
  6980. union_type->Union.polymorphic_parent = original_type;
  6981. set_base_type(named_type, union_type);
  6982. check_open_scope(&ctx, node);
  6983. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6984. check_close_scope(&ctx);
  6985. } else {
  6986. GB_PANIC("Unsupported parametric polymorphic record type");
  6987. }
  6988. bt = base_type(named_type);
  6989. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6990. GB_ASSERT(original_type->kind == Type_Named);
  6991. Entity *e = original_type->Named.type_name;
  6992. GB_ASSERT(e->kind == Entity_TypeName);
  6993. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6994. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6995. TypeTuple *tuple = get_record_polymorphic_params(bt);
  6996. if (tuple != nullptr) for_array(i, tuple->variables) {
  6997. Entity *v = tuple->variables[i];
  6998. String name = v->token.string;
  6999. if (i > 0) {
  7000. s = gb_string_append_fmt(s, ", ");
  7001. }
  7002. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  7003. if (v->kind == Entity_TypeName) {
  7004. if (v->type != nullptr && v->type->kind != Type_Generic) {
  7005. s = gb_string_append_fmt(s, "=");
  7006. s = write_type_to_string(s, v->type, false);
  7007. }
  7008. } else if (v->kind == Entity_Constant) {
  7009. if (v->Constant.value.kind != ExactValue_Invalid) {
  7010. s = gb_string_append_fmt(s, "=");
  7011. s = write_exact_value_to_string(s, v->Constant.value);
  7012. }
  7013. }
  7014. }
  7015. s = gb_string_append_fmt(s, ")");
  7016. String new_name = make_string_c(s);
  7017. named_type->Named.name = new_name;
  7018. if (named_type->Named.type_name) {
  7019. named_type->Named.type_name->token.string = new_name;
  7020. }
  7021. }
  7022. operand->mode = Addressing_Type;
  7023. operand->type = named_type;
  7024. }
  7025. return err;
  7026. }
  7027. // returns true on success
  7028. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  7029. bool success = true;
  7030. if (args.count > 0) {
  7031. if (allow_mixed) {
  7032. bool was_named = false;
  7033. for (Ast *arg : args) {
  7034. if (was_named && arg->kind != Ast_FieldValue) {
  7035. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  7036. success = false;
  7037. break;
  7038. }
  7039. was_named = was_named || arg->kind == Ast_FieldValue;
  7040. }
  7041. } else {
  7042. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  7043. for (Ast *arg : args) {
  7044. bool mix = false;
  7045. if (first_is_field_value) {
  7046. mix = arg->kind != Ast_FieldValue;
  7047. } else {
  7048. mix = arg->kind == Ast_FieldValue;
  7049. }
  7050. if (mix) {
  7051. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  7052. success = false;
  7053. }
  7054. }
  7055. }
  7056. }
  7057. return success;
  7058. }
  7059. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  7060. operand->mode = Addressing_Invalid; \
  7061. operand->expr = call; \
  7062. return Expr_Stmt; \
  7063. }
  7064. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  7065. if (proc != nullptr &&
  7066. proc->kind == Ast_BasicDirective) {
  7067. ast_node(bd, BasicDirective, proc);
  7068. String name = bd->name.string;
  7069. if (
  7070. name == "location" ||
  7071. name == "exists" ||
  7072. name == "assert" ||
  7073. name == "panic" ||
  7074. name == "defined" ||
  7075. name == "config" ||
  7076. name == "load" ||
  7077. name == "load_directory" ||
  7078. name == "load_hash" ||
  7079. name == "hash" ||
  7080. name == "caller_expression"
  7081. ) {
  7082. operand->mode = Addressing_Builtin;
  7083. operand->builtin_id = BuiltinProc_DIRECTIVE;
  7084. operand->expr = proc;
  7085. operand->type = t_invalid;
  7086. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  7087. } else {
  7088. error(proc, "Unknown directive: #%.*s", LIT(name));
  7089. operand->expr = proc;
  7090. operand->type = t_invalid;
  7091. operand->mode = Addressing_Invalid;
  7092. return Expr_Expr;
  7093. }
  7094. if (inlining != ProcInlining_none) {
  7095. error(call, "Inlining operators are not allowed on built-in procedures");
  7096. }
  7097. } else {
  7098. if (proc != nullptr) {
  7099. check_expr_or_type(c, operand, proc);
  7100. } else {
  7101. GB_ASSERT(operand->expr != nullptr);
  7102. }
  7103. }
  7104. if (operand->mode == Addressing_Invalid) {
  7105. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  7106. for (Ast *arg : args) {
  7107. if (arg->kind == Ast_FieldValue) {
  7108. arg = arg->FieldValue.value;
  7109. }
  7110. check_expr_base(c, operand, arg, nullptr);
  7111. }
  7112. operand->mode = Addressing_Invalid;
  7113. operand->expr = call;
  7114. return Expr_Stmt;
  7115. }
  7116. if (operand->mode == Addressing_Type) {
  7117. Type *t = operand->type;
  7118. if (is_type_polymorphic_record(t)) {
  7119. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  7120. if (!is_type_named(t)) {
  7121. gbString s = expr_to_string(operand->expr);
  7122. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  7123. gb_string_free(s);
  7124. operand->mode = Addressing_Invalid;
  7125. operand->type = t_invalid;;
  7126. return Expr_Expr;
  7127. }
  7128. auto err = check_polymorphic_record_type(c, operand, call);
  7129. if (err == 0) {
  7130. Ast *ident = operand->expr;
  7131. while (ident->kind == Ast_SelectorExpr) {
  7132. Ast *s = ident->SelectorExpr.selector;
  7133. ident = s;
  7134. }
  7135. Type *ot = operand->type;
  7136. GB_ASSERT(ot->kind == Type_Named);
  7137. Entity *e = ot->Named.type_name;
  7138. add_entity_use(c, ident, e);
  7139. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  7140. } else {
  7141. operand->mode = Addressing_Invalid;
  7142. operand->type = t_invalid;
  7143. }
  7144. } else {
  7145. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  7146. operand->mode = Addressing_Invalid;
  7147. isize arg_count = args.count;
  7148. switch (arg_count) {
  7149. case 0:
  7150. {
  7151. gbString str = type_to_string(t);
  7152. error(call, "Missing argument in conversion to '%s'", str);
  7153. gb_string_free(str);
  7154. } break;
  7155. default:
  7156. {
  7157. gbString str = type_to_string(t);
  7158. if (t->kind == Type_Basic) {
  7159. ERROR_BLOCK();
  7160. switch (t->Basic.kind) {
  7161. case Basic_complex32:
  7162. case Basic_complex64:
  7163. case Basic_complex128:
  7164. error(call, "Too many arguments in conversion to '%s'", str);
  7165. error_line("\tSuggestion: %s(1+2i) or construct with 'complex'\n", str);
  7166. break;
  7167. case Basic_quaternion64:
  7168. case Basic_quaternion128:
  7169. case Basic_quaternion256:
  7170. error(call, "Too many arguments in conversion to '%s'", str);
  7171. error_line("\tSuggestion: %s(1+2i+3j+4k) or construct with 'quaternion'\n", str);
  7172. break;
  7173. default:
  7174. error(call, "Too many arguments in conversion to '%s'", str);
  7175. }
  7176. } else {
  7177. error(call, "Too many arguments in conversion to '%s'", str);
  7178. }
  7179. gb_string_free(str);
  7180. } break;
  7181. case 1: {
  7182. Ast *arg = args[0];
  7183. if (arg->kind == Ast_FieldValue) {
  7184. error(call, "'field = value' cannot be used in a type conversion");
  7185. arg = arg->FieldValue.value;
  7186. // NOTE(bill): Carry on the cast regardless
  7187. }
  7188. check_expr_with_type_hint(c, operand, arg, t);
  7189. if (operand->mode != Addressing_Invalid) {
  7190. if (is_type_polymorphic(t)) {
  7191. error(call, "A polymorphic type cannot be used in a type conversion");
  7192. } else {
  7193. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  7194. // as it assumes it is determining the type
  7195. check_cast(c, operand, t);
  7196. }
  7197. }
  7198. operand->type = t;
  7199. operand->expr = call;
  7200. if (operand->mode != Addressing_Invalid) {
  7201. update_untyped_expr_type(c, arg, t, false);
  7202. }
  7203. break;
  7204. }
  7205. }
  7206. }
  7207. return Expr_Expr;
  7208. }
  7209. if (operand->mode == Addressing_Builtin) {
  7210. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  7211. i32 id = operand->builtin_id;
  7212. Entity *e = entity_of_node(operand->expr);
  7213. if (e != nullptr && e->token.string == "expand_to_tuple") {
  7214. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  7215. }
  7216. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  7217. operand->mode = Addressing_Invalid;
  7218. operand->type = t_invalid;
  7219. }
  7220. operand->expr = call;
  7221. return builtin_procs[id].kind;
  7222. }
  7223. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  7224. Entity *initial_entity = entity_of_node(operand->expr);
  7225. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  7226. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  7227. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  7228. if (c->decl) {
  7229. c->decl->defer_used += 1;
  7230. }
  7231. }
  7232. add_entity_use(c, operand->expr, initial_entity);
  7233. if (initial_entity->Procedure.entry_point_only) {
  7234. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  7235. // Okay
  7236. } else {
  7237. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  7238. }
  7239. }
  7240. }
  7241. if (operand->mode != Addressing_ProcGroup) {
  7242. Type *proc_type = base_type(operand->type);
  7243. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  7244. bool valid_mode = is_operand_value(*operand);
  7245. if (!valid_type || !valid_mode) {
  7246. Ast *e = operand->expr;
  7247. gbString str = expr_to_string(e);
  7248. gbString type_str = type_to_string(operand->type);
  7249. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  7250. gb_string_free(type_str);
  7251. gb_string_free(str);
  7252. operand->mode = Addressing_Invalid;
  7253. operand->expr = call;
  7254. return Expr_Stmt;
  7255. }
  7256. }
  7257. CallArgumentData data = check_call_arguments(c, operand, call);
  7258. Type *result_type = data.result_type;
  7259. gb_zero_item(operand);
  7260. operand->expr = call;
  7261. if (result_type == t_invalid) {
  7262. operand->mode = Addressing_Invalid;
  7263. operand->type = t_invalid;
  7264. return Expr_Stmt;
  7265. }
  7266. Type *pt = base_type(operand->type);
  7267. if (pt == nullptr) {
  7268. pt = t_invalid;
  7269. }
  7270. if (pt == t_invalid) {
  7271. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7272. pt = type_of_expr(operand->expr->CallExpr.proc);
  7273. }
  7274. if (pt == t_invalid && data.gen_entity) {
  7275. pt = data.gen_entity->type;
  7276. }
  7277. }
  7278. pt = base_type(pt);
  7279. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  7280. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  7281. ERROR_BLOCK();
  7282. if (c->scope->flags & ScopeFlag_File) {
  7283. error(call, "Procedures requiring a 'context' cannot be called at the global scope");
  7284. } else {
  7285. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  7286. error_line("\tSuggestion: 'context = runtime.default_context()'");
  7287. }
  7288. }
  7289. }
  7290. if (result_type == nullptr) {
  7291. operand->mode = Addressing_NoValue;
  7292. } else {
  7293. GB_ASSERT(is_type_tuple(result_type));
  7294. isize count = result_type->Tuple.variables.count;
  7295. switch (count) {
  7296. case 0:
  7297. operand->mode = Addressing_NoValue;
  7298. break;
  7299. case 1:
  7300. operand->mode = Addressing_Value;
  7301. operand->type = result_type->Tuple.variables[0]->type;
  7302. break;
  7303. default:
  7304. operand->mode = Addressing_Value;
  7305. operand->type = result_type;
  7306. break;
  7307. }
  7308. }
  7309. bool is_call_inlined = false;
  7310. switch (inlining) {
  7311. case ProcInlining_inline:
  7312. is_call_inlined = true;
  7313. if (proc != nullptr) {
  7314. Entity *e = entity_from_expr(proc);
  7315. if (e != nullptr && e->kind == Entity_Procedure) {
  7316. DeclInfo *decl = e->decl_info;
  7317. if (decl->proc_lit) {
  7318. ast_node(pl, ProcLit, decl->proc_lit);
  7319. if (pl->inlining == ProcInlining_no_inline) {
  7320. error(call, "'#force_inline' cannot be applied to a procedure that has been marked as '#force_no_inline'");
  7321. }
  7322. }
  7323. }
  7324. }
  7325. break;
  7326. case ProcInlining_no_inline:
  7327. break;
  7328. case ProcInlining_none:
  7329. if (proc != nullptr) {
  7330. Entity *e = entity_from_expr(proc);
  7331. if (e != nullptr && e->kind == Entity_Procedure) {
  7332. DeclInfo *decl = e->decl_info;
  7333. if (decl->proc_lit) {
  7334. ast_node(pl, ProcLit, decl->proc_lit);
  7335. if (pl->inlining == ProcInlining_inline) {
  7336. is_call_inlined = true;
  7337. }
  7338. }
  7339. }
  7340. }
  7341. }
  7342. {
  7343. String invalid;
  7344. if (pt->kind == Type_Proc && pt->Proc.require_target_feature.len != 0) {
  7345. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.require_target_feature, &invalid)) {
  7346. error(call, "Called procedure requires target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7347. } else if (!check_target_feature_is_enabled(pt->Proc.require_target_feature, &invalid)) {
  7348. error(call, "Calling this procedure requires target feature '%.*s' to be enabled", LIT(invalid));
  7349. }
  7350. }
  7351. if (pt->kind == Type_Proc && pt->Proc.enable_target_feature.len != 0) {
  7352. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.enable_target_feature, &invalid)) {
  7353. error(call, "Called procedure enables target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7354. }
  7355. // NOTE: Due to restrictions in LLVM you can not inline calls with a superset of features.
  7356. if (is_call_inlined) {
  7357. if (c->curr_proc_decl == nullptr) {
  7358. error(call, "Calling a '#force_inline' procedure that enables target features is not allowed at file scope");
  7359. } else {
  7360. Entity *e = c->curr_proc_decl->entity.load();
  7361. GB_ASSERT(e);
  7362. GB_ASSERT(e->type->kind == Type_Proc);
  7363. String scope_features = e->type->Proc.enable_target_feature;
  7364. if (!check_target_feature_is_superset_of(scope_features, pt->Proc.enable_target_feature, &invalid)) {
  7365. ERROR_BLOCK();
  7366. error(call, "Inlined procedure enables target feature '%.*s', this requires the calling procedure to at least enable the same feature", LIT(invalid));
  7367. error_line("\tSuggested Example: @(enable_target_feature=\"%.*s\")\n", LIT(invalid));
  7368. }
  7369. }
  7370. }
  7371. }
  7372. }
  7373. operand->expr = call;
  7374. {
  7375. Type *type = nullptr;
  7376. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7377. type = type_of_expr(operand->expr->CallExpr.proc);
  7378. }
  7379. if (type == nullptr) {
  7380. type = pt;
  7381. }
  7382. type = base_type(type);
  7383. if (type->kind == Type_Proc && type->Proc.optional_ok && type->Proc.result_count > 0) {
  7384. operand->mode = Addressing_OptionalOk;
  7385. operand->type = type->Proc.results->Tuple.variables[0]->type;
  7386. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7387. operand->expr->CallExpr.optional_ok_one = true;
  7388. }
  7389. }
  7390. }
  7391. return Expr_Expr;
  7392. }
  7393. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  7394. check_expr_base(c, o, e, t);
  7395. check_not_tuple(c, o);
  7396. char const *err_str = nullptr;
  7397. switch (o->mode) {
  7398. case Addressing_NoValue:
  7399. err_str = "used as a value";
  7400. break;
  7401. case Addressing_Type:
  7402. if (t == nullptr || !is_type_typeid(t)) {
  7403. err_str = "is not an expression but a type, in this context it is ambiguous";
  7404. }
  7405. break;
  7406. case Addressing_Builtin:
  7407. err_str = "must be called";
  7408. break;
  7409. }
  7410. if (err_str != nullptr) {
  7411. gbString str = expr_to_string(e);
  7412. error(e, "'%s' %s", str, err_str);
  7413. gb_string_free(str);
  7414. o->mode = Addressing_Invalid;
  7415. }
  7416. }
  7417. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  7418. switch (t->kind) {
  7419. case Type_Basic:
  7420. if (t->Basic.kind == Basic_string) {
  7421. if (o->mode == Addressing_Constant) {
  7422. GB_ASSERT(o->value.kind == ExactValue_String);
  7423. *max_count = o->value.value_string.len;
  7424. }
  7425. if (o->mode != Addressing_Constant) {
  7426. o->mode = Addressing_Value;
  7427. }
  7428. o->type = t_u8;
  7429. return true;
  7430. } else if (t->Basic.kind == Basic_string16) {
  7431. if (o->mode == Addressing_Constant) {
  7432. GB_ASSERT(o->value.kind == ExactValue_String16);
  7433. *max_count = o->value.value_string16.len;
  7434. }
  7435. if (o->mode != Addressing_Constant) {
  7436. o->mode = Addressing_Value;
  7437. }
  7438. o->type = t_u16;
  7439. return true;
  7440. } else if (t->Basic.kind == Basic_UntypedString) {
  7441. if (o->mode == Addressing_Constant) {
  7442. *max_count = o->value.value_string.len;
  7443. o->type = t_u8;
  7444. return true;
  7445. }
  7446. return false;
  7447. }
  7448. break;
  7449. case Type_MultiPointer:
  7450. o->type = t->MultiPointer.elem;
  7451. if (o->mode != Addressing_Constant) {
  7452. o->mode = Addressing_Variable;
  7453. }
  7454. return true;
  7455. case Type_Array:
  7456. *max_count = t->Array.count;
  7457. if (indirection) {
  7458. o->mode = Addressing_Variable;
  7459. } else if (o->mode != Addressing_Variable &&
  7460. o->mode != Addressing_Constant) {
  7461. o->mode = Addressing_Value;
  7462. }
  7463. o->type = t->Array.elem;
  7464. return true;
  7465. case Type_EnumeratedArray:
  7466. *max_count = t->EnumeratedArray.count;
  7467. if (indirection) {
  7468. o->mode = Addressing_Variable;
  7469. } else if (o->mode != Addressing_Variable &&
  7470. o->mode != Addressing_Constant) {
  7471. o->mode = Addressing_Value;
  7472. }
  7473. o->type = t->EnumeratedArray.elem;
  7474. return true;
  7475. case Type_Matrix:
  7476. if (indirection) {
  7477. o->mode = Addressing_Variable;
  7478. } else if (o->mode != Addressing_Variable) {
  7479. o->mode = Addressing_Value;
  7480. }
  7481. if (t->Matrix.is_row_major) {
  7482. *max_count = t->Matrix.row_count;
  7483. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.column_count);
  7484. } else {
  7485. *max_count = t->Matrix.column_count;
  7486. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  7487. }
  7488. return true;
  7489. case Type_Slice:
  7490. o->type = t->Slice.elem;
  7491. if (o->mode != Addressing_Constant) {
  7492. o->mode = Addressing_Variable;
  7493. }
  7494. return true;
  7495. case Type_DynamicArray:
  7496. o->type = t->DynamicArray.elem;
  7497. if (o->mode != Addressing_Constant) {
  7498. o->mode = Addressing_Variable;
  7499. }
  7500. return true;
  7501. case Type_Struct:
  7502. if (t->Struct.soa_kind != StructSoa_None) {
  7503. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7504. *max_count = t->Struct.soa_count;
  7505. }
  7506. o->type = t->Struct.soa_elem;
  7507. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  7508. o->mode = Addressing_SoaVariable;
  7509. } else {
  7510. o->mode = Addressing_Value;
  7511. }
  7512. return true;
  7513. }
  7514. return false;
  7515. }
  7516. if (is_type_pointer(original_type) && indirection) {
  7517. Type *ptr = base_type(original_type);
  7518. if (ptr->kind == Type_MultiPointer && o->mode == Addressing_SoaVariable) {
  7519. o->type = ptr->MultiPointer.elem;
  7520. o->mode = Addressing_Value;
  7521. return true;
  7522. }
  7523. }
  7524. return false;
  7525. }
  7526. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  7527. if (is_type_untyped_uninit(x)) {
  7528. return true;
  7529. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  7530. return true;
  7531. } else if (is_type_untyped_uninit(y)) {
  7532. return true;
  7533. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  7534. return true;
  7535. }
  7536. return are_types_identical(x, y);
  7537. }
  7538. 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) {
  7539. if (!is_ast_range(node)) {
  7540. return false;
  7541. }
  7542. ast_node(ie, BinaryExpr, node);
  7543. check_expr_with_type_hint(c, x, ie->left, type_hint);
  7544. if (x->mode == Addressing_Invalid) {
  7545. return false;
  7546. }
  7547. check_expr_with_type_hint(c, y, ie->right, type_hint);
  7548. if (y->mode == Addressing_Invalid) {
  7549. return false;
  7550. }
  7551. convert_to_typed(c, x, y->type);
  7552. if (x->mode == Addressing_Invalid) {
  7553. return false;
  7554. }
  7555. convert_to_typed(c, y, x->type);
  7556. if (y->mode == Addressing_Invalid) {
  7557. return false;
  7558. }
  7559. convert_to_typed(c, x, default_type(y->type));
  7560. if (x->mode == Addressing_Invalid) {
  7561. return false;
  7562. }
  7563. convert_to_typed(c, y, default_type(x->type));
  7564. if (y->mode == Addressing_Invalid) {
  7565. return false;
  7566. }
  7567. if (!are_types_identical(x->type, y->type)) {
  7568. if (x->type != t_invalid &&
  7569. y->type != t_invalid) {
  7570. gbString xt = type_to_string(x->type);
  7571. gbString yt = type_to_string(y->type);
  7572. gbString expr_str = expr_to_string(x->expr);
  7573. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  7574. gb_string_free(expr_str);
  7575. gb_string_free(yt);
  7576. gb_string_free(xt);
  7577. }
  7578. return false;
  7579. }
  7580. Type *type = x->type;
  7581. if (is_for_loop) {
  7582. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  7583. error(ie->op, "Only numerical types are allowed within interval expressions");
  7584. return false;
  7585. }
  7586. } else {
  7587. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  7588. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  7589. return false;
  7590. }
  7591. }
  7592. if (x->mode == Addressing_Constant &&
  7593. y->mode == Addressing_Constant) {
  7594. ExactValue a = x->value;
  7595. ExactValue b = y->value;
  7596. GB_ASSERT(are_types_identical(x->type, y->type));
  7597. TokenKind op = Token_Lt;
  7598. switch (ie->op.kind) {
  7599. case Token_Ellipsis: op = Token_LtEq; break; // ..
  7600. case Token_RangeFull: op = Token_LtEq; break; // ..=
  7601. case Token_RangeHalf: op = Token_Lt; break; // ..<
  7602. default: error(ie->op, "Invalid range operator"); break;
  7603. }
  7604. bool ok = compare_exact_values(op, a, b);
  7605. if (!ok) {
  7606. // TODO(bill): Better error message
  7607. error(ie->op, "Invalid interval range");
  7608. return false;
  7609. }
  7610. ExactValue inline_for_depth = exact_value_sub(b, a);
  7611. if (ie->op.kind != Token_RangeHalf) {
  7612. inline_for_depth = exact_value_increment_one(inline_for_depth);
  7613. }
  7614. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  7615. } else if (inline_for_depth_ != nullptr) {
  7616. error(ie->op, "Interval expressions must be constant");
  7617. return false;
  7618. }
  7619. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  7620. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  7621. return true;
  7622. }
  7623. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  7624. if (is_operand_nil(*o)) {
  7625. return true;
  7626. }
  7627. Ast *expr = unparen_expr(o->expr);
  7628. if (expr != nullptr) {
  7629. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  7630. if (e != nullptr && e->kind == Entity_Procedure) {
  7631. return true;
  7632. }
  7633. if (expr->kind == Ast_ProcLit) {
  7634. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  7635. return true;
  7636. }
  7637. }
  7638. return o->mode == Addressing_Constant;
  7639. }
  7640. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  7641. if (is_type_enum(th)) {
  7642. Type *enum_type = base_type(th);
  7643. GB_ASSERT(enum_type->kind == Type_Enum);
  7644. String name = ise->selector->Ident.token.string;
  7645. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  7646. if (e == nullptr) {
  7647. return false;
  7648. }
  7649. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  7650. GB_ASSERT(e->kind == Entity_Constant);
  7651. o->value = e->Constant.value;
  7652. o->mode = Addressing_Constant;
  7653. o->type = e->type;
  7654. return true;
  7655. }
  7656. if (is_type_union(th)) {
  7657. TEMPORARY_ALLOCATOR_GUARD();
  7658. Type *union_type = base_type(th);
  7659. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  7660. for (Type *vt : union_type->Union.variants) {
  7661. Operand x = {};
  7662. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  7663. array_add(&operands, x);
  7664. }
  7665. }
  7666. if (operands.count == 1) {
  7667. *o = operands[0];
  7668. return true;
  7669. }
  7670. }
  7671. return false;
  7672. }
  7673. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7674. ast_node(ise, ImplicitSelectorExpr, node);
  7675. o->type = t_invalid;
  7676. o->expr = node;
  7677. o->mode = Addressing_Invalid;
  7678. Type *th = type_hint;
  7679. if (th == nullptr) {
  7680. gbString str = expr_to_string(node);
  7681. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  7682. gb_string_free(str);
  7683. return Expr_Expr;
  7684. }
  7685. o->type = th;
  7686. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  7687. if (!ok) {
  7688. String name = ise->selector->Ident.token.string;
  7689. if (is_type_enum(th)) {
  7690. ERROR_BLOCK();
  7691. Type *bt = base_type(th);
  7692. GB_ASSERT(bt->kind == Type_Enum);
  7693. gbString typ = type_to_string(th);
  7694. defer (gb_string_free(typ));
  7695. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  7696. check_did_you_mean_type(name, bt->Enum.fields);
  7697. } else if (is_type_bit_set(th) && is_type_enum(th->BitSet.elem)) {
  7698. ERROR_BLOCK();
  7699. gbString typ = type_to_string(th);
  7700. gbString str = expr_to_string(node);
  7701. error(node, "Cannot convert enum value to '%s'", typ);
  7702. error_line("\tSuggestion: Did you mean '{ %s }'?\n", str);
  7703. gb_string_free(typ);
  7704. gb_string_free(str);
  7705. } else {
  7706. gbString typ = type_to_string(th);
  7707. gbString str = expr_to_string(node);
  7708. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  7709. gb_string_free(str);
  7710. gb_string_free(typ);
  7711. }
  7712. }
  7713. o->expr = node;
  7714. return Expr_Expr;
  7715. }
  7716. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  7717. switch (x->mode) {
  7718. case Addressing_MapIndex:
  7719. case Addressing_OptionalOk:
  7720. case Addressing_OptionalOkPtr:
  7721. if (val_type_) *val_type_ = x->type;
  7722. break;
  7723. default:
  7724. if (ok_type_) *ok_type_ = x->type;
  7725. return;
  7726. }
  7727. Ast *expr = unparen_expr(x->expr);
  7728. if (expr->kind == Ast_CallExpr) {
  7729. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  7730. if (is_type_proc(pt)) {
  7731. Type *tuple = pt->Proc.results;
  7732. if (pt->Proc.result_count >= 2) {
  7733. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7734. }
  7735. if (change_operand) {
  7736. expr->CallExpr.optional_ok_one = false;
  7737. x->type = tuple;
  7738. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7739. }
  7740. return;
  7741. }
  7742. }
  7743. Type *tuple = make_optional_ok_type(x->type);
  7744. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7745. if (change_operand) {
  7746. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7747. x->type = tuple;
  7748. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  7749. }
  7750. }
  7751. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7752. ast_node(ie, MatrixIndexExpr, node);
  7753. check_expr(c, o, ie->expr);
  7754. node->viral_state_flags |= ie->expr->viral_state_flags;
  7755. if (o->mode == Addressing_Invalid) {
  7756. o->expr = node;
  7757. return;
  7758. }
  7759. Type *t = base_type(type_deref(o->type));
  7760. bool is_ptr = is_type_pointer(o->type);
  7761. bool is_const = o->mode == Addressing_Constant;
  7762. if (t->kind != Type_Matrix) {
  7763. gbString str = expr_to_string(o->expr);
  7764. gbString type_str = type_to_string(o->type);
  7765. defer (gb_string_free(str));
  7766. defer (gb_string_free(type_str));
  7767. if (is_const) {
  7768. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  7769. } else {
  7770. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  7771. }
  7772. o->mode = Addressing_Invalid;
  7773. o->expr = node;
  7774. return;
  7775. }
  7776. o->type = t->Matrix.elem;
  7777. if (is_ptr) {
  7778. o->mode = Addressing_Variable;
  7779. } else if (o->mode != Addressing_Variable) {
  7780. o->mode = Addressing_Value;
  7781. }
  7782. if (ie->row_index == nullptr) {
  7783. gbString str = expr_to_string(o->expr);
  7784. error(o->expr, "Missing row index for '%s'", str);
  7785. gb_string_free(str);
  7786. o->mode = Addressing_Invalid;
  7787. o->expr = node;
  7788. return;
  7789. }
  7790. if (ie->column_index == nullptr) {
  7791. gbString str = expr_to_string(o->expr);
  7792. error(o->expr, "Missing column index for '%s'", str);
  7793. gb_string_free(str);
  7794. o->mode = Addressing_Invalid;
  7795. o->expr = node;
  7796. return;
  7797. }
  7798. i64 row_count = t->Matrix.row_count;
  7799. i64 column_count = t->Matrix.column_count;
  7800. i64 row_index = 0;
  7801. i64 column_index = 0;
  7802. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7803. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7804. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7805. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7806. }
  7807. gb_unused(row_ok);
  7808. gb_unused(column_ok);
  7809. }
  7810. struct TypeAndToken {
  7811. Type *type;
  7812. Token token;
  7813. };
  7814. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7815. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7816. if (operand.mode != Addressing_Constant) {
  7817. return;
  7818. }
  7819. if (operand.value.kind == ExactValue_Invalid) {
  7820. return;
  7821. }
  7822. uintptr key = hash_exact_value(operand.value);
  7823. GB_ASSERT(key != 0);
  7824. isize count = multi_map_count(seen, key);
  7825. if (count) {
  7826. TEMPORARY_ALLOCATOR_GUARD();
  7827. TypeAndToken *taps = temporary_alloc_array<TypeAndToken>(count);
  7828. multi_map_get_all(seen, key, taps);
  7829. for (isize i = 0; i < count; i++) {
  7830. TypeAndToken tap = taps[i];
  7831. Operand to = {};
  7832. to.mode = Addressing_Value;
  7833. to.type = tap.type;
  7834. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7835. continue;
  7836. }
  7837. TokenPos pos = tap.token.pos;
  7838. if (use_expr) {
  7839. gbString expr_str = expr_to_string(operand.expr);
  7840. error(operand.expr,
  7841. "Duplicate case '%s'\n"
  7842. "\tprevious case at %s",
  7843. expr_str,
  7844. token_pos_to_string(pos));
  7845. gb_string_free(expr_str);
  7846. } else {
  7847. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7848. }
  7849. return;
  7850. }
  7851. }
  7852. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7853. multi_map_insert(seen, key, tap);
  7854. }
  7855. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7856. if (is_type_enum(x.type)) {
  7857. // TODO(bill): Fix this logic so it's fast!!!
  7858. i64 v0 = exact_value_to_i64(lhs.value);
  7859. i64 v1 = exact_value_to_i64(rhs.value);
  7860. Operand v = {};
  7861. v.mode = Addressing_Constant;
  7862. v.type = x.type;
  7863. v.expr = x.expr;
  7864. Type *bt = base_type(x.type);
  7865. GB_ASSERT(bt->kind == Type_Enum);
  7866. for (i64 vi = v0; vi <= v1; vi++) {
  7867. if (upper_op != Token_LtEq && vi == v1) {
  7868. break;
  7869. }
  7870. v.value = exact_value_i64(vi);
  7871. add_constant_switch_case(ctx, seen, v);
  7872. }
  7873. } else {
  7874. add_constant_switch_case(ctx, seen, lhs);
  7875. if (upper_op == Token_LtEq) {
  7876. add_constant_switch_case(ctx, seen, rhs);
  7877. }
  7878. }
  7879. }
  7880. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7881. add_constant_switch_case(ctx, seen, x);
  7882. }
  7883. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7884. ast_node(bd, BasicDirective, node);
  7885. ExprKind kind = Expr_Expr;
  7886. o->mode = Addressing_Constant;
  7887. String name = bd->name.string;
  7888. if (name == "file") {
  7889. String file = get_file_path_string(bd->token.pos.file_id);
  7890. switch (build_context.source_code_location_info) {
  7891. case SourceCodeLocationInfo_Normal:
  7892. break;
  7893. case SourceCodeLocationInfo_Obfuscated:
  7894. file = obfuscate_string(file, "F");
  7895. break;
  7896. case SourceCodeLocationInfo_Filename:
  7897. file = last_path_element(file);
  7898. break;
  7899. case SourceCodeLocationInfo_None:
  7900. file = str_lit("");
  7901. break;
  7902. }
  7903. o->type = t_untyped_string;
  7904. o->value = exact_value_string(file);
  7905. } else if (name == "directory") {
  7906. String file = get_file_path_string(bd->token.pos.file_id);
  7907. String path = dir_from_path(file);
  7908. switch (build_context.source_code_location_info) {
  7909. case SourceCodeLocationInfo_Normal:
  7910. break;
  7911. case SourceCodeLocationInfo_Obfuscated:
  7912. path = obfuscate_string(path, "D");
  7913. break;
  7914. case SourceCodeLocationInfo_Filename:
  7915. path = last_path_element(path);
  7916. break;
  7917. case SourceCodeLocationInfo_None:
  7918. path = str_lit("");
  7919. break;
  7920. }
  7921. o->type = t_untyped_string;
  7922. o->value = exact_value_string(path);
  7923. } else if (name == "line") {
  7924. i32 line = bd->token.pos.line;
  7925. switch (build_context.source_code_location_info) {
  7926. case SourceCodeLocationInfo_Normal:
  7927. break;
  7928. case SourceCodeLocationInfo_Obfuscated:
  7929. line = obfuscate_i32(line);
  7930. break;
  7931. case SourceCodeLocationInfo_Filename:
  7932. break;
  7933. case SourceCodeLocationInfo_None:
  7934. line = 0;
  7935. break;
  7936. }
  7937. o->type = t_untyped_integer;
  7938. o->value = exact_value_i64(line);
  7939. } else if (name == "procedure") {
  7940. if (c->curr_proc_decl == nullptr) {
  7941. error(node, "#procedure may only be used within procedures");
  7942. o->type = t_untyped_string;
  7943. o->value = exact_value_string(str_lit(""));
  7944. } else {
  7945. String p = c->proc_name;
  7946. switch (build_context.source_code_location_info) {
  7947. case SourceCodeLocationInfo_Normal:
  7948. break;
  7949. case SourceCodeLocationInfo_Obfuscated:
  7950. p = obfuscate_string(p, "P");
  7951. break;
  7952. case SourceCodeLocationInfo_Filename:
  7953. break;
  7954. case SourceCodeLocationInfo_None:
  7955. p = str_lit("");
  7956. break;
  7957. }
  7958. o->type = t_untyped_string;
  7959. o->value = exact_value_string(p);
  7960. }
  7961. } else if (name == "caller_location") {
  7962. init_core_source_code_location(c->checker);
  7963. error(node, "#caller_location may only be used as a default argument parameter");
  7964. o->type = t_source_code_location;
  7965. o->mode = Addressing_Value;
  7966. } else if (name == "caller_expression") {
  7967. error(node, "#caller_expression may only be used as a default argument parameter");
  7968. o->type = t_string;
  7969. o->mode = Addressing_Value;
  7970. } else if (name == "branch_location") {
  7971. if (!c->in_defer) {
  7972. error(node, "#branch_location may only be used within a 'defer' statement");
  7973. } else if (c->curr_proc_decl) {
  7974. Entity *e = c->curr_proc_decl->entity;
  7975. if (e != nullptr) {
  7976. GB_ASSERT(e->kind == Entity_Procedure);
  7977. e->Procedure.uses_branch_location = true;
  7978. }
  7979. }
  7980. o->type = t_source_code_location;
  7981. o->mode = Addressing_Value;
  7982. } else {
  7983. if (name == "location") {
  7984. init_core_source_code_location(c->checker);
  7985. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  7986. o->type = t_source_code_location;
  7987. o->mode = Addressing_Value;
  7988. } else if (
  7989. name == "assert" ||
  7990. name == "defined" ||
  7991. name == "config" ||
  7992. name == "exists" ||
  7993. name == "load" ||
  7994. name == "load_hash" ||
  7995. name == "load_directory" ||
  7996. name == "load_or"
  7997. ) {
  7998. error(node, "'#%.*s' must be used as a call", LIT(name));
  7999. o->type = t_invalid;
  8000. o->mode = Addressing_Invalid;
  8001. } else {
  8002. error(node, "Unknown directive: #%.*s", LIT(name));
  8003. o->type = t_invalid;
  8004. o->mode = Addressing_Invalid;
  8005. }
  8006. }
  8007. return kind;
  8008. }
  8009. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8010. ExprKind kind = Expr_Expr;
  8011. Operand cond = {Addressing_Invalid};
  8012. ast_node(te, TernaryIfExpr, node);
  8013. check_expr(c, &cond, te->cond);
  8014. node->viral_state_flags |= te->cond->viral_state_flags;
  8015. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  8016. error(te->cond, "Non-boolean condition in ternary if expression");
  8017. }
  8018. Operand x = {Addressing_Invalid};
  8019. Operand y = {Addressing_Invalid};
  8020. check_expr_or_type(c, &x, te->x, type_hint);
  8021. node->viral_state_flags |= te->x->viral_state_flags;
  8022. if (te->y != nullptr) {
  8023. Type *th = type_hint;
  8024. if (type_hint == nullptr && is_type_typed(x.type)) {
  8025. th = x.type;
  8026. }
  8027. check_expr_or_type(c, &y, te->y, th);
  8028. node->viral_state_flags |= te->y->viral_state_flags;
  8029. } else {
  8030. error(node, "A ternary expression must have an else clause");
  8031. return kind;
  8032. }
  8033. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  8034. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  8035. gbString type_string = expr_to_string(type_expr);
  8036. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  8037. gb_string_free(type_string);
  8038. return kind;
  8039. }
  8040. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  8041. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  8042. if (x.mode == Addressing_Invalid) {
  8043. return kind;
  8044. }
  8045. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  8046. if (y.mode == Addressing_Invalid) {
  8047. x.mode = Addressing_Invalid;
  8048. return kind;
  8049. }
  8050. // NOTE(bill, 2023-01-30): Allow for expression like this:
  8051. // x: union{f32} = f32(123) if cond else nil
  8052. if (type_hint && !is_type_any(type_hint)) {
  8053. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  8054. check_cast(c, &x, type_hint);
  8055. check_cast(c, &y, type_hint);
  8056. }
  8057. }
  8058. if (!ternary_compare_types(x.type, y.type)) {
  8059. gbString its = type_to_string(x.type);
  8060. gbString ets = type_to_string(y.type);
  8061. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  8062. gb_string_free(ets);
  8063. gb_string_free(its);
  8064. return kind;
  8065. }
  8066. o->type = x.type;
  8067. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  8068. o->type = y.type;
  8069. }
  8070. o->mode = Addressing_Value;
  8071. o->expr = node;
  8072. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  8073. if (check_cast_internal(c, &x, type_hint) &&
  8074. check_cast_internal(c, &y, type_hint)) {
  8075. convert_to_typed(c, o, type_hint);
  8076. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  8077. o->type = type_hint;
  8078. }
  8079. }
  8080. return kind;
  8081. }
  8082. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8083. ExprKind kind = Expr_Expr;
  8084. Operand cond = {};
  8085. ast_node(te, TernaryWhenExpr, node);
  8086. check_expr(c, &cond, te->cond);
  8087. node->viral_state_flags |= te->cond->viral_state_flags;
  8088. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  8089. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  8090. return kind;
  8091. }
  8092. if (cond.value.value_bool) {
  8093. check_expr_or_type(c, o, te->x, type_hint);
  8094. node->viral_state_flags |= te->x->viral_state_flags;
  8095. } else {
  8096. if (te->y != nullptr) {
  8097. check_expr_or_type(c, o, te->y, type_hint);
  8098. node->viral_state_flags |= te->y->viral_state_flags;
  8099. } else {
  8100. error(node, "A ternary when expression must have an else clause");
  8101. return kind;
  8102. }
  8103. }
  8104. return kind;
  8105. }
  8106. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8107. ast_node(oe, OrElseExpr, node);
  8108. String name = oe->token.string;
  8109. Ast *arg = oe->x;
  8110. Ast *default_value = oe->y;
  8111. Operand x = {};
  8112. Operand y = {};
  8113. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  8114. if (is_load_directive_call(arg)) {
  8115. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  8116. // Allow for chaining of '#load(path) or_else #load(path)'
  8117. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  8118. bool y_is_diverging = false;
  8119. check_expr_base(c, &y, default_value, x.type);
  8120. switch (y.mode) {
  8121. case Addressing_NoValue:
  8122. if (is_diverging_expr(y.expr)) {
  8123. // Allow
  8124. y.mode = Addressing_Value;
  8125. y_is_diverging = true;
  8126. } else {
  8127. error_operand_no_value(&y);
  8128. y.mode = Addressing_Invalid;
  8129. }
  8130. break;
  8131. case Addressing_Type:
  8132. error_operand_not_expression(&y);
  8133. y.mode = Addressing_Invalid;
  8134. break;
  8135. }
  8136. if (y.mode == Addressing_Invalid) {
  8137. o->mode = Addressing_Value;
  8138. o->type = t_invalid;
  8139. o->expr = node;
  8140. return Expr_Expr;
  8141. }
  8142. if (!y_is_diverging) {
  8143. check_assignment(c, &y, x.type, name);
  8144. if (y.mode != Addressing_Constant) {
  8145. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  8146. }
  8147. }
  8148. }
  8149. if (res == LoadDirective_Success) {
  8150. *o = x;
  8151. } else {
  8152. *o = y;
  8153. }
  8154. o->expr = node;
  8155. return Expr_Expr;
  8156. }
  8157. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  8158. if (x.mode == Addressing_Invalid) {
  8159. o->mode = Addressing_Value;
  8160. o->type = t_invalid;
  8161. o->expr = node;
  8162. return Expr_Expr;
  8163. }
  8164. Type *left_type = nullptr;
  8165. Type *right_type = nullptr;
  8166. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  8167. add_type_and_value(c, arg, x.mode, x.type, x.value);
  8168. bool y_is_diverging = false;
  8169. check_expr_base(c, &y, default_value, left_type);
  8170. switch (y.mode) {
  8171. case Addressing_NoValue:
  8172. if (is_diverging_expr(y.expr)) {
  8173. // Allow
  8174. y.mode = Addressing_Value;
  8175. y_is_diverging = true;
  8176. } else {
  8177. error_operand_no_value(&y);
  8178. y.mode = Addressing_Invalid;
  8179. }
  8180. break;
  8181. case Addressing_Type:
  8182. error_operand_not_expression(&y);
  8183. y.mode = Addressing_Invalid;
  8184. break;
  8185. }
  8186. if (y.mode == Addressing_Invalid) {
  8187. o->mode = Addressing_Value;
  8188. o->type = t_invalid;
  8189. o->expr = node;
  8190. return Expr_Expr;
  8191. }
  8192. if (left_type != nullptr) {
  8193. if (!y_is_diverging) {
  8194. if (is_type_tuple(left_type)) {
  8195. if (!is_type_tuple(y.type)) {
  8196. error(y.expr, "Found a single value where a %td-valued expression was expected", left_type->Tuple.variables.count);
  8197. } else if (!are_types_identical(left_type, y.type)) {
  8198. gbString xt = type_to_string(left_type);
  8199. gbString yt = type_to_string(y.type);
  8200. error(y.expr, "Mismatched types, expected (%s), got (%s)", xt, yt);
  8201. gb_string_free(yt);
  8202. gb_string_free(xt);
  8203. }
  8204. } else {
  8205. check_assignment(c, &y, left_type, name);
  8206. }
  8207. }
  8208. } else {
  8209. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8210. }
  8211. if (left_type == nullptr) {
  8212. left_type = t_invalid;
  8213. }
  8214. o->mode = Addressing_Value;
  8215. o->type = left_type;
  8216. o->expr = node;
  8217. return Expr_Expr;
  8218. }
  8219. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8220. ast_node(re, OrReturnExpr, node);
  8221. String name = re->token.string;
  8222. Operand x = {};
  8223. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  8224. if (x.mode == Addressing_Invalid) {
  8225. o->mode = Addressing_Value;
  8226. o->type = t_invalid;
  8227. o->expr = node;
  8228. return Expr_Expr;
  8229. }
  8230. Type *left_type = nullptr;
  8231. Type *right_type = nullptr;
  8232. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8233. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  8234. if (right_type == nullptr) {
  8235. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8236. } else {
  8237. Type *proc_type = base_type(c->curr_proc_sig);
  8238. GB_ASSERT(proc_type->kind == Type_Proc);
  8239. Type *result_type = proc_type->Proc.results;
  8240. if (result_type == nullptr) {
  8241. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  8242. } else {
  8243. GB_ASSERT(result_type->kind == Type_Tuple);
  8244. auto const &vars = result_type->Tuple.variables;
  8245. Type *end_type = vars[vars.count-1]->type;
  8246. if (vars.count > 1) {
  8247. if (!proc_type->Proc.has_named_results) {
  8248. 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));
  8249. }
  8250. }
  8251. Operand rhs = {};
  8252. rhs.type = right_type;
  8253. rhs.mode = Addressing_Value;
  8254. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  8255. // NOTE(bill): allow implicit conversion between boolean types
  8256. // within 'or_return' to improve the experience using third-party code
  8257. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  8258. ERROR_BLOCK();
  8259. // TODO(bill): better error message
  8260. gbString a = type_to_string(right_type);
  8261. gbString b = type_to_string(end_type);
  8262. gbString ret_type = type_to_string(result_type);
  8263. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  8264. if (vars.count == 1) {
  8265. error_line("\tProcedure return value type: %s\n", ret_type);
  8266. } else {
  8267. error_line("\tProcedure return value types: (%s)\n", ret_type);
  8268. }
  8269. gb_string_free(ret_type);
  8270. gb_string_free(b);
  8271. gb_string_free(a);
  8272. }
  8273. }
  8274. }
  8275. o->expr = node;
  8276. o->type = left_type;
  8277. if (left_type != nullptr) {
  8278. o->mode = Addressing_Value;
  8279. } else {
  8280. o->mode = Addressing_NoValue;
  8281. }
  8282. if (c->curr_proc_sig == nullptr) {
  8283. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8284. }
  8285. if (c->in_defer) {
  8286. error(node, "'or_return' cannot be used within a defer statement");
  8287. }
  8288. return Expr_Expr;
  8289. }
  8290. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8291. ast_node(be, OrBranchExpr, node);
  8292. String name = be->token.string;
  8293. Operand x = {};
  8294. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  8295. if (x.mode == Addressing_Invalid) {
  8296. o->mode = Addressing_Value;
  8297. o->type = t_invalid;
  8298. o->expr = node;
  8299. return Expr_Expr;
  8300. }
  8301. Type *left_type = nullptr;
  8302. Type *right_type = nullptr;
  8303. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8304. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  8305. if (right_type == nullptr) {
  8306. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8307. } else {
  8308. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  8309. // okay
  8310. } else {
  8311. gbString s = type_to_string(right_type);
  8312. error(node, "'%.*s' requires a boolean or nil-able type, got %s", LIT(name), s);
  8313. gb_string_free(s);
  8314. }
  8315. }
  8316. o->expr = node;
  8317. o->type = left_type;
  8318. if (left_type != nullptr) {
  8319. o->mode = Addressing_Value;
  8320. } else {
  8321. o->mode = Addressing_NoValue;
  8322. }
  8323. if (c->curr_proc_sig == nullptr) {
  8324. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8325. }
  8326. Ast *label = be->label;
  8327. switch (be->token.kind) {
  8328. case Token_or_break:
  8329. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  8330. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  8331. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  8332. }
  8333. break;
  8334. case Token_or_continue:
  8335. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  8336. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  8337. }
  8338. break;
  8339. }
  8340. if (label != nullptr) {
  8341. if (c->in_defer) {
  8342. error(label, "A labelled '%.*s' cannot be used within a 'defer'", LIT(name));
  8343. return Expr_Expr;
  8344. }
  8345. if (label->kind != Ast_Ident) {
  8346. error(label, "A branch statement's label name must be an identifier");
  8347. return Expr_Expr;
  8348. }
  8349. Ast *ident = label;
  8350. String name = ident->Ident.token.string;
  8351. Operand o = {};
  8352. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  8353. if (e == nullptr) {
  8354. error(ident, "Undeclared label name: %.*s", LIT(name));
  8355. return Expr_Expr;
  8356. }
  8357. add_entity_use(c, ident, e);
  8358. if (e->kind != Entity_Label) {
  8359. error(ident, "'%.*s' is not a label", LIT(name));
  8360. return Expr_Expr;
  8361. }
  8362. Ast *parent = e->Label.parent;
  8363. GB_ASSERT(parent != nullptr);
  8364. switch (parent->kind) {
  8365. case Ast_BlockStmt:
  8366. case Ast_IfStmt:
  8367. case Ast_SwitchStmt:
  8368. if (be->token.kind != Token_or_break) {
  8369. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  8370. }
  8371. break;
  8372. case Ast_RangeStmt:
  8373. case Ast_ForStmt:
  8374. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  8375. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  8376. }
  8377. break;
  8378. }
  8379. }
  8380. return Expr_Expr;
  8381. }
  8382. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  8383. Type *bt = base_type(type);
  8384. StringSet fields_visited = {};
  8385. defer (string_set_destroy(&fields_visited));
  8386. StringMap<String> fields_visited_through_raw_union = {};
  8387. defer (string_map_destroy(&fields_visited_through_raw_union));
  8388. String assignment_str = str_lit("structure literal");
  8389. if (bt->kind == Type_BitField) {
  8390. assignment_str = str_lit("bit_field literal");
  8391. }
  8392. for (Ast *elem : elems) {
  8393. if (elem->kind != Ast_FieldValue) {
  8394. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8395. continue;
  8396. }
  8397. ast_node(fv, FieldValue, elem);
  8398. Ast *ident = fv->field;
  8399. if (ident->kind == Ast_ImplicitSelectorExpr) {
  8400. gbString expr_str = expr_to_string(ident);
  8401. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  8402. gb_string_free(expr_str);
  8403. ident = ident->ImplicitSelectorExpr.selector;
  8404. }
  8405. if (ident->kind != Ast_Ident) {
  8406. gbString expr_str = expr_to_string(ident);
  8407. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  8408. gb_string_free(expr_str);
  8409. continue;
  8410. }
  8411. String name = ident->Ident.token.string;
  8412. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8413. bool is_unknown = sel.entity == nullptr;
  8414. if (is_unknown) {
  8415. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  8416. continue;
  8417. }
  8418. Entity *field = nullptr;
  8419. if (bt->kind == Type_Struct) {
  8420. field = bt->Struct.fields[sel.index[0]];
  8421. } else if (bt->kind == Type_BitField) {
  8422. field = bt->BitField.fields[sel.index[0]];
  8423. } else {
  8424. GB_PANIC("Unknown type");
  8425. }
  8426. add_entity_use(c, ident, field);
  8427. if (string_set_update(&fields_visited, name)) {
  8428. if (sel.index.count > 1) {
  8429. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8430. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8431. } else {
  8432. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  8433. }
  8434. } else {
  8435. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  8436. }
  8437. continue;
  8438. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8439. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8440. continue;
  8441. }
  8442. if (sel.indirect) {
  8443. 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));
  8444. continue;
  8445. }
  8446. if (sel.index.count > 1) {
  8447. GB_ASSERT(bt->kind == Type_Struct);
  8448. if (is_constant) {
  8449. Type *ft = type;
  8450. for (i32 index : sel.index) {
  8451. Type *bt = base_type(ft);
  8452. switch (bt->kind) {
  8453. case Type_Struct:
  8454. if (bt->Struct.is_raw_union) {
  8455. is_constant = false;
  8456. break;
  8457. }
  8458. ft = bt->Struct.fields[index]->type;
  8459. break;
  8460. case Type_Array:
  8461. ft = bt->Array.elem;
  8462. break;
  8463. case Type_BitField:
  8464. is_constant = false;
  8465. ft = bt->BitField.fields[index]->type;
  8466. break;
  8467. default:
  8468. GB_PANIC("invalid type: %s", type_to_string(ft));
  8469. break;
  8470. }
  8471. }
  8472. if (is_constant &&
  8473. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  8474. is_constant = false;
  8475. }
  8476. }
  8477. Type *nested_ft = bt;
  8478. for (i32 index : sel.index) {
  8479. Type *bt = base_type(nested_ft);
  8480. switch (bt->kind) {
  8481. case Type_Struct:
  8482. if (bt->Struct.is_raw_union) {
  8483. for (Entity *re : bt->Struct.fields) {
  8484. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  8485. }
  8486. }
  8487. nested_ft = bt->Struct.fields[index]->type;
  8488. break;
  8489. case Type_Array:
  8490. nested_ft = bt->Array.elem;
  8491. break;
  8492. case Type_BitField:
  8493. nested_ft = bt->BitField.fields[index]->type;
  8494. break;
  8495. default:
  8496. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  8497. break;
  8498. }
  8499. }
  8500. field = sel.entity;
  8501. }
  8502. Operand o = {};
  8503. check_expr_or_type(c, &o, fv->value, field->type);
  8504. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8505. is_constant = false;
  8506. }
  8507. if (is_constant) {
  8508. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8509. }
  8510. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  8511. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  8512. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  8513. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  8514. }
  8515. check_assignment(c, &o, field->type, assignment_str);
  8516. c->bit_field_bit_size = prev_bit_field_bit_size;
  8517. }
  8518. }
  8519. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  8520. type_expr = unparen_expr(type_expr);
  8521. if (type_expr == nullptr) {
  8522. return false;
  8523. }
  8524. // [?]Type
  8525. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  8526. Ast *count = type_expr->ArrayType.count;
  8527. if (count->kind == Ast_UnaryExpr &&
  8528. count->UnaryExpr.op.kind == Token_Question) {
  8529. return true;
  8530. }
  8531. }
  8532. return false;
  8533. }
  8534. gb_internal bool check_for_dynamic_literals(CheckerContext *c, Ast *node, AstCompoundLit *cl) {
  8535. if (cl->elems.count > 0 && (check_feature_flags(c, node) & OptInFeatureFlag_DynamicLiterals) == 0 && !build_context.dynamic_literals) {
  8536. ERROR_BLOCK();
  8537. error(node, "Compound literals of dynamic types are disabled by default");
  8538. error_line("\tSuggestion: If you want to enable them for this specific file, add '#+feature dynamic-literals' at the top of the file\n");
  8539. error_line("\tWarning: Please understand that dynamic literals will implicitly allocate using the current 'context.allocator' in that scope\n");
  8540. if (build_context.ODIN_DEFAULT_TO_NIL_ALLOCATOR) {
  8541. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8542. } else if (build_context.ODIN_DEFAULT_TO_PANIC_ALLOCATOR) {
  8543. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8544. }
  8545. return false;
  8546. }
  8547. return cl->elems.count > 0;
  8548. }
  8549. gb_internal IntegerDivisionByZeroKind check_for_integer_division_by_zero(CheckerContext *c, Ast *node) {
  8550. // TODO(bill): per file `#+feature` flags
  8551. u64 flags = check_feature_flags(c, node);
  8552. if ((flags & OptInFeatureFlag_IntegerDivisionByZero_Trap) != 0) {
  8553. return IntegerDivisionByZero_Trap;
  8554. }
  8555. if ((flags & OptInFeatureFlag_IntegerDivisionByZero_Zero) != 0) {
  8556. return IntegerDivisionByZero_Zero;
  8557. }
  8558. if ((flags & OptInFeatureFlag_IntegerDivisionByZero_Self) != 0) {
  8559. return IntegerDivisionByZero_Self;
  8560. }
  8561. if ((flags & OptInFeatureFlag_IntegerDivisionByZero_AllBits) != 0) {
  8562. return IntegerDivisionByZero_AllBits;
  8563. }
  8564. return build_context.integer_division_by_zero_behaviour;
  8565. }
  8566. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8567. ExprKind kind = Expr_Expr;
  8568. ast_node(cl, CompoundLit, node);
  8569. Type *type = type_hint;
  8570. if (type != nullptr && is_type_untyped(type)) {
  8571. type = nullptr;
  8572. }
  8573. bool is_to_be_determined_array_count = false;
  8574. bool is_constant = true;
  8575. bool is_soa = false;
  8576. Ast *type_expr = cl->type;
  8577. bool used_type_hint_expr = false;
  8578. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  8579. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  8580. type_expr = clone_ast(c->type_hint_expr);
  8581. used_type_hint_expr = true;
  8582. }
  8583. }
  8584. if (type_expr != nullptr) {
  8585. type = nullptr;
  8586. // [?]Type
  8587. if (type_expr->kind == Ast_ArrayType) {
  8588. Ast *count = type_expr->ArrayType.count;
  8589. if (count != nullptr) {
  8590. if (count->kind == Ast_UnaryExpr &&
  8591. count->UnaryExpr.op.kind == Token_Question) {
  8592. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  8593. is_to_be_determined_array_count = true;
  8594. }
  8595. } else {
  8596. type = alloc_type_slice(check_type(c, type_expr->ArrayType.elem));
  8597. }
  8598. if (cl->elems.count > 0) {
  8599. if (type_expr->ArrayType.tag != nullptr) {
  8600. Ast *tag = type_expr->ArrayType.tag;
  8601. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8602. String name = tag->BasicDirective.name.string;
  8603. if (name == "soa") {
  8604. is_soa = true;
  8605. if (count == nullptr) {
  8606. error(node, "#soa slices are not supported for compound literals");
  8607. return kind;
  8608. } else if (count->kind == Ast_UnaryExpr &&
  8609. count->UnaryExpr.op.kind == Token_Question) {
  8610. error(node, "#soa fixed length arrays must specify their length and cannot use ?");
  8611. }
  8612. }
  8613. }
  8614. }
  8615. } else if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  8616. if (cl->elems.count > 0) {
  8617. Ast *tag = type_expr->DynamicArrayType.tag;
  8618. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8619. String name = tag->BasicDirective.name.string;
  8620. if (name == "soa") {
  8621. is_soa = true;
  8622. error(node, "#soa dynamic arrays are not supported for compound literals");
  8623. return kind;
  8624. }
  8625. }
  8626. }
  8627. if (type == nullptr) {
  8628. type = check_type(c, type_expr);
  8629. }
  8630. }
  8631. if (type == nullptr) {
  8632. error(node, "Missing type in compound literal");
  8633. return kind;
  8634. }
  8635. Type *t = base_type(type);
  8636. if (is_type_polymorphic(t)) {
  8637. gbString str = type_to_string(type);
  8638. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  8639. o->expr = node;
  8640. o->type = type;
  8641. gb_string_free(str);
  8642. return kind;
  8643. }
  8644. switch (t->kind) {
  8645. case Type_Struct:
  8646. if (cl->elems.count == 0) {
  8647. break; // NOTE(bill): No need to init
  8648. }
  8649. if (t->Struct.soa_kind == StructSoa_None) {
  8650. if (t->Struct.is_raw_union) {
  8651. if (cl->elems.count > 0) {
  8652. // NOTE: unions cannot be constant
  8653. is_constant = false;
  8654. if (cl->elems[0]->kind != Ast_FieldValue) {
  8655. gbString type_str = type_to_string(type);
  8656. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  8657. gb_string_free(type_str);
  8658. } else {
  8659. if (cl->elems.count != 1) {
  8660. gbString type_str = type_to_string(type);
  8661. 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);
  8662. gb_string_free(type_str);
  8663. } else {
  8664. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8665. }
  8666. }
  8667. }
  8668. break;
  8669. }
  8670. wait_signal_until_available(&t->Struct.fields_wait_signal);
  8671. isize field_count = t->Struct.fields.count;
  8672. isize min_field_count = t->Struct.fields.count;
  8673. for (isize i = min_field_count-1; i >= 0; i--) {
  8674. Entity *e = t->Struct.fields[i];
  8675. GB_ASSERT(e->kind == Entity_Variable);
  8676. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  8677. min_field_count--;
  8678. } else {
  8679. break;
  8680. }
  8681. }
  8682. if (cl->elems[0]->kind == Ast_FieldValue) {
  8683. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8684. } else {
  8685. bool seen_field_value = false;
  8686. for_array(index, cl->elems) {
  8687. Entity *field = nullptr;
  8688. Ast *elem = cl->elems[index];
  8689. if (elem->kind == Ast_FieldValue) {
  8690. seen_field_value = true;
  8691. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8692. continue;
  8693. } else if (seen_field_value) {
  8694. error(elem, "Value elements cannot be used after a 'field = value'");
  8695. continue;
  8696. }
  8697. if (index >= field_count) {
  8698. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8699. break;
  8700. }
  8701. if (field == nullptr) {
  8702. field = t->Struct.fields[index];
  8703. }
  8704. Operand o = {};
  8705. check_expr_or_type(c, &o, elem, field->type);
  8706. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8707. is_constant = false;
  8708. }
  8709. if (is_constant) {
  8710. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8711. }
  8712. check_assignment(c, &o, field->type, str_lit("structure literal"));
  8713. }
  8714. if (cl->elems.count < field_count) {
  8715. if (min_field_count < field_count) {
  8716. if (cl->elems.count < min_field_count) {
  8717. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  8718. }
  8719. } else {
  8720. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8721. }
  8722. }
  8723. }
  8724. break;
  8725. } else if (t->Struct.soa_kind != StructSoa_Fixed) {
  8726. error(node, "#soa slices and dynamic arrays are not supported for compound literals");
  8727. break;
  8728. }
  8729. /*fallthrough*/
  8730. case Type_Slice:
  8731. case Type_Array:
  8732. case Type_DynamicArray:
  8733. case Type_SimdVector:
  8734. case Type_Matrix:
  8735. {
  8736. Type *elem_type = nullptr;
  8737. String context_name = {};
  8738. i64 max_type_count = -1;
  8739. if (t->kind == Type_Struct) {
  8740. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8741. elem_type = t->Struct.soa_elem;
  8742. context_name = str_lit("#soa array literal");
  8743. if (!is_to_be_determined_array_count) {
  8744. max_type_count = t->Struct.soa_count;
  8745. }
  8746. } else if (t->kind == Type_Slice) {
  8747. elem_type = t->Slice.elem;
  8748. context_name = str_lit("slice literal");
  8749. } else if (t->kind == Type_Array) {
  8750. elem_type = t->Array.elem;
  8751. context_name = str_lit("array literal");
  8752. if (!is_to_be_determined_array_count) {
  8753. max_type_count = t->Array.count;
  8754. }
  8755. } else if (t->kind == Type_Array) {
  8756. elem_type = t->Array.elem;
  8757. context_name = str_lit("array literal");
  8758. if (!is_to_be_determined_array_count) {
  8759. max_type_count = t->Array.count;
  8760. }
  8761. } else if (t->kind == Type_DynamicArray) {
  8762. elem_type = t->DynamicArray.elem;
  8763. context_name = str_lit("dynamic array literal");
  8764. is_constant = false;
  8765. } else if (t->kind == Type_SimdVector) {
  8766. elem_type = t->SimdVector.elem;
  8767. context_name = str_lit("simd vector literal");
  8768. max_type_count = t->SimdVector.count;
  8769. } else if (t->kind == Type_Matrix) {
  8770. elem_type = t->Matrix.elem;
  8771. context_name = str_lit("matrix literal");
  8772. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  8773. } else {
  8774. GB_PANIC("unreachable");
  8775. }
  8776. i64 max = 0;
  8777. Type *bet = base_type(elem_type);
  8778. if (!elem_type_can_be_constant(bet)) {
  8779. is_constant = false;
  8780. }
  8781. if (bet == t_invalid) {
  8782. break;
  8783. }
  8784. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8785. RangeCache rc = range_cache_make(heap_allocator());
  8786. defer (range_cache_destroy(&rc));
  8787. for (Ast *elem : cl->elems) {
  8788. if (elem->kind != Ast_FieldValue) {
  8789. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8790. continue;
  8791. }
  8792. ast_node(fv, FieldValue, elem);
  8793. if (is_ast_range(fv->field)) {
  8794. Token op = fv->field->BinaryExpr.op;
  8795. Operand x = {};
  8796. Operand y = {};
  8797. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  8798. if (!ok) {
  8799. continue;
  8800. }
  8801. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  8802. error(x.expr, "Expected a constant integer as an array field");
  8803. continue;
  8804. }
  8805. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  8806. error(y.expr, "Expected a constant integer as an array field");
  8807. continue;
  8808. }
  8809. i64 lo = exact_value_to_i64(x.value);
  8810. i64 hi = exact_value_to_i64(y.value);
  8811. i64 max_index = hi;
  8812. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  8813. hi -= 1;
  8814. } else { // .. (inclusive)
  8815. max_index += 1;
  8816. }
  8817. bool new_range = range_cache_add_range(&rc, lo, hi);
  8818. if (!new_range) {
  8819. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  8820. continue;
  8821. }
  8822. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  8823. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  8824. continue;
  8825. }
  8826. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  8827. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  8828. continue;
  8829. }
  8830. if (max < hi) {
  8831. max = max_index;
  8832. }
  8833. Operand operand = {};
  8834. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8835. check_assignment(c, &operand, elem_type, context_name);
  8836. is_constant = is_constant && operand.mode == Addressing_Constant;
  8837. } else {
  8838. Operand op_index = {};
  8839. check_expr(c, &op_index, fv->field);
  8840. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  8841. error(elem, "Expected a constant integer as an array field");
  8842. continue;
  8843. }
  8844. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  8845. i64 index = exact_value_to_i64(op_index.value);
  8846. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  8847. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  8848. continue;
  8849. }
  8850. bool new_index = range_cache_add_index(&rc, index);
  8851. if (!new_index) {
  8852. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  8853. continue;
  8854. }
  8855. if (max < index+1) {
  8856. max = index+1;
  8857. }
  8858. Operand operand = {};
  8859. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8860. check_assignment(c, &operand, elem_type, context_name);
  8861. is_constant = is_constant && operand.mode == Addressing_Constant;
  8862. }
  8863. }
  8864. cl->max_count = max;
  8865. } else {
  8866. isize index = 0;
  8867. for (; index < cl->elems.count; index++) {
  8868. Ast *e = cl->elems[index];
  8869. if (e == nullptr) {
  8870. error(node, "Invalid literal element");
  8871. continue;
  8872. }
  8873. if (e->kind == Ast_FieldValue) {
  8874. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8875. continue;
  8876. }
  8877. if (0 <= max_type_count && max_type_count <= index) {
  8878. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8879. }
  8880. Operand operand = {};
  8881. check_expr_with_type_hint(c, &operand, e, elem_type);
  8882. check_assignment(c, &operand, elem_type, context_name);
  8883. is_constant = is_constant && operand.mode == Addressing_Constant;
  8884. }
  8885. if (max < index) {
  8886. max = index;
  8887. }
  8888. }
  8889. if (t->kind == Type_Array) {
  8890. if (is_to_be_determined_array_count) {
  8891. t->Array.count = max;
  8892. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8893. if (0 < max && max < t->Array.count) {
  8894. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8895. }
  8896. }
  8897. } else if (t->kind == Type_Struct) {
  8898. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8899. if (is_to_be_determined_array_count) {
  8900. t->Struct.soa_count = cast(i32)max;
  8901. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8902. if (0 < max && max < t->Struct.soa_count) {
  8903. error(node, "Expected %lld values for this #soa array literal, got %lld", cast(long long)t->Struct.soa_count, cast(long long)max);
  8904. }
  8905. }
  8906. }
  8907. if (t->kind == Type_SimdVector) {
  8908. if (!is_constant) {
  8909. // error(node, "Expected all constant elements for a simd vector");
  8910. }
  8911. }
  8912. if (t->kind == Type_DynamicArray) {
  8913. if (check_for_dynamic_literals(c, node, cl)) {
  8914. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  8915. add_package_dependency(c, "runtime", "__dynamic_array_append");
  8916. }
  8917. }
  8918. if (t->kind == Type_Matrix) {
  8919. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8920. if (0 < max && max < max_type_count) {
  8921. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  8922. }
  8923. }
  8924. }
  8925. break;
  8926. }
  8927. case Type_EnumeratedArray:
  8928. {
  8929. Type *elem_type = t->EnumeratedArray.elem;
  8930. Type *index_type = t->EnumeratedArray.index;
  8931. String context_name = str_lit("enumerated array literal");
  8932. i64 max_type_count = t->EnumeratedArray.count;
  8933. gbString index_type_str = type_to_string(index_type);
  8934. defer (gb_string_free(index_type_str));
  8935. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  8936. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  8937. String total_lo_string = {};
  8938. String total_hi_string = {};
  8939. GB_ASSERT(is_type_enum(index_type));
  8940. {
  8941. Type *bt = base_type(index_type);
  8942. GB_ASSERT(bt->kind == Type_Enum);
  8943. for (Entity *f : bt->Enum.fields) {
  8944. if (f->kind != Entity_Constant) {
  8945. continue;
  8946. }
  8947. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  8948. total_lo_string = f->token.string;
  8949. }
  8950. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  8951. total_hi_string = f->token.string;
  8952. }
  8953. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8954. break;
  8955. }
  8956. }
  8957. }
  8958. i64 max = 0;
  8959. Type *bet = base_type(elem_type);
  8960. if (!elem_type_can_be_constant(bet)) {
  8961. is_constant = false;
  8962. }
  8963. if (bet == t_invalid) {
  8964. break;
  8965. }
  8966. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8967. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8968. defer (map_destroy(&seen));
  8969. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8970. RangeCache rc = range_cache_make(heap_allocator());
  8971. defer (range_cache_destroy(&rc));
  8972. for (Ast *elem : cl->elems) {
  8973. if (elem->kind != Ast_FieldValue) {
  8974. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8975. continue;
  8976. }
  8977. ast_node(fv, FieldValue, elem);
  8978. if (is_ast_range(fv->field)) {
  8979. Token op = fv->field->BinaryExpr.op;
  8980. Operand x = {};
  8981. Operand y = {};
  8982. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8983. if (!ok) {
  8984. continue;
  8985. }
  8986. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8987. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8988. continue;
  8989. }
  8990. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8991. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8992. continue;
  8993. }
  8994. i64 lo = exact_value_to_i64(x.value);
  8995. i64 hi = exact_value_to_i64(y.value);
  8996. i64 max_index = hi;
  8997. if (op.kind == Token_RangeHalf) {
  8998. hi -= 1;
  8999. }
  9000. bool new_range = range_cache_add_range(&rc, lo, hi);
  9001. if (!new_range) {
  9002. gbString lo_str = expr_to_string(x.expr);
  9003. gbString hi_str = expr_to_string(y.expr);
  9004. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  9005. gb_string_free(hi_str);
  9006. gb_string_free(lo_str);
  9007. continue;
  9008. }
  9009. // NOTE(bill): These are sanity checks for invalid enum values
  9010. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  9011. gbString lo_str = expr_to_string(x.expr);
  9012. 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));
  9013. gb_string_free(lo_str);
  9014. continue;
  9015. }
  9016. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  9017. gbString hi_str = expr_to_string(y.expr);
  9018. 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));
  9019. gb_string_free(hi_str);
  9020. continue;
  9021. }
  9022. if (max < hi) {
  9023. max = max_index;
  9024. }
  9025. Operand operand = {};
  9026. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  9027. check_assignment(c, &operand, elem_type, context_name);
  9028. is_constant = is_constant && operand.mode == Addressing_Constant;
  9029. TokenKind upper_op = Token_LtEq;
  9030. if (op.kind == Token_RangeHalf) {
  9031. upper_op = Token_Lt;
  9032. }
  9033. add_to_seen_map(c, &seen, upper_op, x, x, y);
  9034. } else {
  9035. Operand op_index = {};
  9036. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  9037. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  9038. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  9039. continue;
  9040. }
  9041. i64 index = exact_value_to_i64(op_index.value);
  9042. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  9043. gbString idx_str = expr_to_string(op_index.expr);
  9044. 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));
  9045. gb_string_free(idx_str);
  9046. continue;
  9047. }
  9048. bool new_index = range_cache_add_index(&rc, index);
  9049. if (!new_index) {
  9050. gbString idx_str = expr_to_string(op_index.expr);
  9051. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  9052. gb_string_free(idx_str);
  9053. continue;
  9054. }
  9055. if (max < index+1) {
  9056. max = index+1;
  9057. }
  9058. Operand operand = {};
  9059. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  9060. check_assignment(c, &operand, elem_type, context_name);
  9061. is_constant = is_constant && operand.mode == Addressing_Constant;
  9062. add_to_seen_map(c, &seen, op_index);
  9063. }
  9064. }
  9065. cl->max_count = max;
  9066. } else {
  9067. isize index = 0;
  9068. for (; index < cl->elems.count; index++) {
  9069. Ast *e = cl->elems[index];
  9070. if (e == nullptr) {
  9071. error(node, "Invalid literal element");
  9072. continue;
  9073. }
  9074. if (e->kind == Ast_FieldValue) {
  9075. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  9076. continue;
  9077. }
  9078. if (0 <= max_type_count && max_type_count <= index) {
  9079. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  9080. }
  9081. Operand operand = {};
  9082. check_expr_with_type_hint(c, &operand, e, elem_type);
  9083. check_assignment(c, &operand, elem_type, context_name);
  9084. is_constant = is_constant && operand.mode == Addressing_Constant;
  9085. }
  9086. if (max < index) {
  9087. max = index;
  9088. }
  9089. }
  9090. bool was_error = false;
  9091. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  9092. if (0 < max && max < t->EnumeratedArray.count) {
  9093. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  9094. was_error = true;
  9095. } else {
  9096. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  9097. was_error = true;
  9098. }
  9099. }
  9100. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  9101. if (cl->elems.count > 0 && !was_error && !is_partial) {
  9102. TEMPORARY_ALLOCATOR_GUARD();
  9103. Type *et = base_type(index_type);
  9104. GB_ASSERT(et->kind == Type_Enum);
  9105. auto fields = et->Enum.fields;
  9106. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  9107. for (Entity *f : fields) {
  9108. if (f->kind != Entity_Constant) {
  9109. continue;
  9110. }
  9111. ExactValue v = f->Constant.value;
  9112. uintptr hash = hash_exact_value(v);
  9113. auto found = map_get(&seen, hash);
  9114. if (!found) {
  9115. array_add(&unhandled, f);
  9116. }
  9117. }
  9118. if (unhandled.count > 0) {
  9119. ERROR_BLOCK();
  9120. if (unhandled.count == 1) {
  9121. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  9122. } else {
  9123. error(node, "Unhandled enumerated array cases:");
  9124. for_array(i, unhandled) {
  9125. Entity *f = unhandled[i];
  9126. error_line("\t%.*s\n", LIT(f->token.string));
  9127. }
  9128. }
  9129. if (!build_context.terse_errors) {
  9130. error_line("\n");
  9131. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  9132. }
  9133. }
  9134. }
  9135. break;
  9136. }
  9137. case Type_Basic: {
  9138. if (!is_type_any(t)) {
  9139. if (cl->elems.count != 0) {
  9140. gbString s = type_to_string(t);
  9141. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  9142. gb_string_free(s);
  9143. is_constant = false;
  9144. }
  9145. break;
  9146. }
  9147. if (cl->elems.count == 0) {
  9148. break; // NOTE(bill): No need to init
  9149. }
  9150. { // Checker values
  9151. Type *field_types[2] = {t_rawptr, t_typeid};
  9152. isize field_count = 2;
  9153. if (cl->elems[0]->kind == Ast_FieldValue) {
  9154. bool fields_visited[2] = {};
  9155. for_array(i, cl->elems) {
  9156. Ast *elem = cl->elems[i];
  9157. if (elem->kind != Ast_FieldValue) {
  9158. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  9159. continue;
  9160. }
  9161. ast_node(fv, FieldValue, elem);
  9162. if (fv->field->kind != Ast_Ident) {
  9163. gbString expr_str = expr_to_string(fv->field);
  9164. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  9165. gb_string_free(expr_str);
  9166. continue;
  9167. }
  9168. String name = fv->field->Ident.token.string;
  9169. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  9170. if (sel.entity == nullptr) {
  9171. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  9172. continue;
  9173. }
  9174. isize index = sel.index[0];
  9175. if (fields_visited[index]) {
  9176. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  9177. continue;
  9178. }
  9179. fields_visited[index] = true;
  9180. check_expr(c, o, fv->value);
  9181. // NOTE(bill): 'any' literals can never be constant
  9182. is_constant = false;
  9183. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  9184. }
  9185. } else {
  9186. for_array(index, cl->elems) {
  9187. Ast *elem = cl->elems[index];
  9188. if (elem->kind == Ast_FieldValue) {
  9189. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  9190. continue;
  9191. }
  9192. check_expr(c, o, elem);
  9193. if (index >= field_count) {
  9194. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  9195. break;
  9196. }
  9197. // NOTE(bill): 'any' literals can never be constant
  9198. is_constant = false;
  9199. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  9200. }
  9201. if (cl->elems.count < field_count) {
  9202. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  9203. }
  9204. }
  9205. }
  9206. break;
  9207. }
  9208. case Type_Map: {
  9209. if (cl->elems.count == 0) {
  9210. break;
  9211. }
  9212. is_constant = false;
  9213. { // Checker values
  9214. bool key_is_typeid = is_type_typeid(t->Map.key);
  9215. bool value_is_typeid = is_type_typeid(t->Map.value);
  9216. for (Ast *elem : cl->elems) {
  9217. if (elem->kind != Ast_FieldValue) {
  9218. error(elem, "Only 'field = value' elements are allowed in a map literal");
  9219. continue;
  9220. }
  9221. ast_node(fv, FieldValue, elem);
  9222. if (key_is_typeid) {
  9223. check_expr_or_type(c, o, fv->field, t->Map.key);
  9224. } else {
  9225. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  9226. }
  9227. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  9228. if (o->mode == Addressing_Invalid) {
  9229. continue;
  9230. }
  9231. if (value_is_typeid) {
  9232. check_expr_or_type(c, o, fv->value, t->Map.value);
  9233. } else {
  9234. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  9235. }
  9236. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  9237. }
  9238. }
  9239. if (check_for_dynamic_literals(c, node, cl)) {
  9240. add_map_reserve_dependencies(c);
  9241. add_map_set_dependencies(c);
  9242. }
  9243. break;
  9244. }
  9245. case Type_BitSet: {
  9246. if (cl->elems.count == 0) {
  9247. break; // NOTE(bill): No need to init
  9248. }
  9249. Type *et = base_type(t->BitSet.elem);
  9250. isize field_count = 0;
  9251. if (et != nullptr && et->kind == Type_Enum) {
  9252. field_count = et->Enum.fields.count;
  9253. }
  9254. if (is_type_array(bit_set_to_int(t))) {
  9255. is_constant = false;
  9256. }
  9257. for (Ast *elem : cl->elems) {
  9258. if (elem->kind == Ast_FieldValue) {
  9259. error(elem, "'field = value' in a bit_set literal is not allowed");
  9260. is_constant = false;
  9261. continue;
  9262. }
  9263. check_expr_with_type_hint(c, o, elem, et);
  9264. if (is_constant) {
  9265. is_constant = o->mode == Addressing_Constant;
  9266. }
  9267. if (elem->kind == Ast_BinaryExpr) {
  9268. switch (elem->BinaryExpr.op.kind) {
  9269. case Token_Or:
  9270. {
  9271. gbString x = expr_to_string(elem->BinaryExpr.left);
  9272. gbString y = expr_to_string(elem->BinaryExpr.right);
  9273. gbString e = expr_to_string(elem);
  9274. error(elem, "Was the following intended? '%s, %s'; if not, surround the expression with parentheses '(%s)'", x, y, e);
  9275. gb_string_free(e);
  9276. gb_string_free(y);
  9277. gb_string_free(x);
  9278. }
  9279. break;
  9280. }
  9281. }
  9282. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  9283. if (o->mode == Addressing_Constant) {
  9284. i64 lower = t->BitSet.lower;
  9285. i64 upper = t->BitSet.upper;
  9286. i64 v = exact_value_to_i64(o->value);
  9287. if (lower <= v && v <= upper) {
  9288. // okay
  9289. } else {
  9290. gbString s = expr_to_string(o->expr);
  9291. error(elem, "Bit field value out of bounds, %s (%lld) not in the range %lld .. %lld", s, v, lower, upper);
  9292. gb_string_free(s);
  9293. continue;
  9294. }
  9295. }
  9296. }
  9297. break;
  9298. }
  9299. case Type_BitField: {
  9300. if (cl->elems.count == 0) {
  9301. break; // NOTE(bill): No need to init
  9302. }
  9303. is_constant = false;
  9304. if (cl->elems[0]->kind != Ast_FieldValue) {
  9305. gbString type_str = type_to_string(type);
  9306. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  9307. gb_string_free(type_str);
  9308. } else {
  9309. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  9310. }
  9311. break;
  9312. }
  9313. default: {
  9314. if (cl->elems.count == 0) {
  9315. break; // NOTE(bill): No need to init
  9316. }
  9317. gbString str = type_to_string(type);
  9318. error(node, "Invalid compound literal type '%s'", str);
  9319. gb_string_free(str);
  9320. return kind;
  9321. }
  9322. }
  9323. if (is_constant) {
  9324. o->mode = Addressing_Constant;
  9325. if (is_type_bit_set(type)) {
  9326. // NOTE(bill): Encode as an integer
  9327. Type *bt = base_type(type);
  9328. BigInt bits = {};
  9329. BigInt one = {};
  9330. big_int_from_u64(&one, 1);
  9331. for (Ast *e : cl->elems) {
  9332. GB_ASSERT(e->kind != Ast_FieldValue);
  9333. TypeAndValue tav = e->tav;
  9334. if (tav.mode != Addressing_Constant) {
  9335. continue;
  9336. }
  9337. if (tav.value.kind != ExactValue_Integer) {
  9338. continue;
  9339. }
  9340. i64 v = big_int_to_i64(&tav.value.value_integer);
  9341. i64 lower = bt->BitSet.lower;
  9342. u64 index = cast(u64)(v-lower);
  9343. BigInt bit = {};
  9344. big_int_from_u64(&bit, index);
  9345. big_int_shl(&bit, &one, &bit);
  9346. big_int_or(&bits, &bits, &bit);
  9347. }
  9348. o->value.kind = ExactValue_Integer;
  9349. o->value.value_integer = bits;
  9350. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  9351. ExactValue value = exact_value_compound(node);
  9352. Type *bt = core_type(type);
  9353. if (bt->kind == Type_Basic) {
  9354. if (bt->Basic.flags & BasicFlag_Boolean) {
  9355. value = exact_value_bool(false);
  9356. } else if (bt->Basic.flags & BasicFlag_Integer) {
  9357. value = exact_value_i64(0);
  9358. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  9359. value = exact_value_i64(0);
  9360. } else if (bt->Basic.flags & BasicFlag_Float) {
  9361. value = exact_value_float(0);
  9362. } else if (bt->Basic.flags & BasicFlag_Complex) {
  9363. value = exact_value_complex(0, 0);
  9364. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  9365. value = exact_value_quaternion(0, 0, 0, 0);
  9366. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  9367. value = exact_value_pointer(0);
  9368. } else if (bt->Basic.flags & BasicFlag_String) {
  9369. String empty_string = {};
  9370. value = exact_value_string(empty_string);
  9371. } else if (bt->Basic.flags & BasicFlag_Rune) {
  9372. value = exact_value_i64(0);
  9373. }
  9374. }
  9375. o->value = value;
  9376. } else {
  9377. o->value = exact_value_compound(node);
  9378. }
  9379. } else {
  9380. o->mode = Addressing_Value;
  9381. }
  9382. o->type = type;
  9383. return kind;
  9384. }
  9385. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9386. ExprKind kind = Expr_Expr;
  9387. ast_node(ta, TypeAssertion, node);
  9388. check_expr(c, o, ta->expr);
  9389. node->viral_state_flags |= ta->expr->viral_state_flags;
  9390. if (o->mode == Addressing_Invalid) {
  9391. o->expr = node;
  9392. return kind;
  9393. }
  9394. if (o->mode == Addressing_Constant) {
  9395. gbString expr_str = expr_to_string(o->expr);
  9396. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  9397. gb_string_free(expr_str);
  9398. o->mode = Addressing_Invalid;
  9399. o->expr = node;
  9400. return kind;
  9401. }
  9402. if (is_type_untyped(o->type)) {
  9403. gbString expr_str = expr_to_string(o->expr);
  9404. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  9405. gb_string_free(expr_str);
  9406. o->mode = Addressing_Invalid;
  9407. o->expr = node;
  9408. return kind;
  9409. }
  9410. Type *src = type_deref(o->type);
  9411. Type *bsrc = base_type(src);
  9412. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  9413. if (!is_type_union(src)) {
  9414. gbString str = type_to_string(o->type);
  9415. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  9416. gb_string_free(str);
  9417. o->mode = Addressing_Invalid;
  9418. o->expr = node;
  9419. return kind;
  9420. }
  9421. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  9422. bool allowed = false;
  9423. for (Type *vt : bsrc->Union.variants) {
  9424. if (are_types_identical(vt, type_hint)) {
  9425. allowed = true;
  9426. add_type_info_type(c, vt);
  9427. break;
  9428. }
  9429. }
  9430. if (allowed) {
  9431. add_type_info_type(c, o->type);
  9432. o->type = type_hint;
  9433. o->mode = Addressing_OptionalOk;
  9434. goto end;
  9435. }
  9436. }
  9437. if (bsrc->Union.variants.count != 1) {
  9438. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  9439. o->mode = Addressing_Invalid;
  9440. o->expr = node;
  9441. return kind;
  9442. }
  9443. add_type_info_type(c, o->type);
  9444. add_type_info_type(c, bsrc->Union.variants[0]);
  9445. o->type = bsrc->Union.variants[0];
  9446. o->mode = Addressing_OptionalOk;
  9447. } else {
  9448. Type *t = check_type(c, ta->type);
  9449. Type *dst = t;
  9450. if (is_type_union(src)) {
  9451. bool ok = false;
  9452. for (Type *vt : bsrc->Union.variants) {
  9453. if (are_types_identical(vt, dst)) {
  9454. ok = true;
  9455. break;
  9456. }
  9457. }
  9458. if (!ok) {
  9459. gbString expr_str = expr_to_string(o->expr);
  9460. gbString dst_type_str = type_to_string(t);
  9461. defer (gb_string_free(expr_str));
  9462. defer (gb_string_free(dst_type_str));
  9463. if (bsrc->Union.variants.count == 0) {
  9464. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  9465. } else {
  9466. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  9467. }
  9468. o->mode = Addressing_Invalid;
  9469. o->expr = node;
  9470. return kind;
  9471. }
  9472. add_type_info_type(c, o->type);
  9473. add_type_info_type(c, t);
  9474. o->type = t;
  9475. o->mode = Addressing_OptionalOk;
  9476. } else if (is_type_any(src)) {
  9477. o->type = t;
  9478. o->mode = Addressing_OptionalOk;
  9479. add_type_info_type(c, o->type);
  9480. add_type_info_type(c, t);
  9481. } else {
  9482. gbString str = type_to_string(o->type);
  9483. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  9484. gb_string_free(str);
  9485. o->mode = Addressing_Invalid;
  9486. o->expr = node;
  9487. return kind;
  9488. }
  9489. }
  9490. end:;
  9491. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  9492. add_package_dependency(c, "runtime", "type_assertion_check");
  9493. add_package_dependency(c, "runtime", "type_assertion_check2");
  9494. }
  9495. return kind;
  9496. }
  9497. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9498. ast_node(se, SelectorCallExpr, node);
  9499. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  9500. // COM APIs is a great example of where this kind of thing is extremely useful
  9501. // General idea:
  9502. //
  9503. // x->y(123) == x.y(x, 123)
  9504. //
  9505. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  9506. // Just regenerating a new AST aids things
  9507. //
  9508. // TODO(bill): Is this a good hack or not?
  9509. //
  9510. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  9511. if (se->modified_call) {
  9512. // Prevent double evaluation
  9513. o->expr = node;
  9514. o->type = node->tav.type;
  9515. o->value = node->tav.value;
  9516. o->mode = node->tav.mode;
  9517. return Expr_Expr;
  9518. }
  9519. bool allow_arrow_right_selector_expr;
  9520. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9521. c->allow_arrow_right_selector_expr = true;
  9522. Operand x = {};
  9523. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  9524. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9525. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  9526. o->mode = Addressing_Invalid;
  9527. o->type = t_invalid;
  9528. o->expr = node;
  9529. return kind;
  9530. }
  9531. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  9532. gbString type_str = type_to_string(x.type);
  9533. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  9534. gb_string_free(type_str);
  9535. o->mode = Addressing_Invalid;
  9536. o->type = t_invalid;
  9537. o->expr = node;
  9538. return Expr_Stmt;
  9539. }
  9540. ast_node(ce, CallExpr, se->call);
  9541. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  9542. Ast *first_arg = x.expr->SelectorExpr.expr;
  9543. GB_ASSERT(first_arg != nullptr);
  9544. Entity *e = entity_of_node(se->expr);
  9545. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  9546. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  9547. }
  9548. if (e->kind != Entity_ProcGroup) {
  9549. Type *pt = base_type(x.type);
  9550. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  9551. Type *first_type = nullptr;
  9552. String first_arg_name = {};
  9553. if (pt->Proc.param_count > 0) {
  9554. Entity *f = pt->Proc.params->Tuple.variables[0];
  9555. first_type = f->type;
  9556. first_arg_name = f->token.string;
  9557. }
  9558. if (first_arg_name.len == 0) {
  9559. first_arg_name = str_lit("_");
  9560. }
  9561. if (first_type == nullptr) {
  9562. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  9563. o->mode = Addressing_Invalid;
  9564. o->type = t_invalid;
  9565. o->expr = node;
  9566. return Expr_Stmt;
  9567. }
  9568. Operand y = {};
  9569. y.mode = first_arg->tav.mode;
  9570. y.type = first_arg->tav.type;
  9571. y.value = first_arg->tav.value;
  9572. if (check_is_assignable_to(c, &y, first_type)) {
  9573. // Do nothing, it's valid
  9574. } else {
  9575. Operand z = y;
  9576. z.type = type_deref(y.type);
  9577. if (check_is_assignable_to(c, &z, first_type)) {
  9578. // NOTE(bill): AST GENERATION HACK!
  9579. Token op = {Token_Pointer};
  9580. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  9581. } else if (y.mode == Addressing_Variable) {
  9582. Operand w = y;
  9583. w.type = alloc_type_pointer(y.type);
  9584. if (check_is_assignable_to(c, &w, first_type)) {
  9585. // NOTE(bill): AST GENERATION HACK!
  9586. Token op = {Token_And};
  9587. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  9588. }
  9589. }
  9590. }
  9591. if (ce->args.count > 0) {
  9592. bool fail = false;
  9593. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  9594. for (Ast *arg : ce->args) {
  9595. bool mix = false;
  9596. if (first_is_field_value) {
  9597. mix = arg->kind != Ast_FieldValue;
  9598. } else {
  9599. mix = arg->kind == Ast_FieldValue;
  9600. }
  9601. if (mix) {
  9602. fail = true;
  9603. break;
  9604. }
  9605. }
  9606. if (!fail && first_is_field_value) {
  9607. Token op = {Token_Eq};
  9608. AstFile *f = first_arg->file();
  9609. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  9610. }
  9611. }
  9612. }
  9613. auto modified_args = permanent_slice_make<Ast *>(ce->args.count+1);
  9614. modified_args[0] = first_arg;
  9615. slice_copy(&modified_args, ce->args, 1);
  9616. ce->args = modified_args;
  9617. se->modified_call = true;
  9618. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9619. c->allow_arrow_right_selector_expr = true;
  9620. check_expr_base(c, o, se->call, type_hint);
  9621. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9622. o->expr = node;
  9623. return Expr_Expr;
  9624. }
  9625. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9626. ExprKind kind = Expr_Expr;
  9627. ast_node(ie, IndexExpr, node);
  9628. check_expr(c, o, ie->expr);
  9629. node->viral_state_flags |= ie->expr->viral_state_flags;
  9630. if (o->mode == Addressing_Invalid) {
  9631. o->expr = node;
  9632. return kind;
  9633. }
  9634. Type *t = base_type(type_deref(o->type));
  9635. bool is_ptr = is_type_pointer(o->type);
  9636. bool is_const = o->mode == Addressing_Constant;
  9637. if (is_type_map(t)) {
  9638. Operand key = {};
  9639. if (is_type_typeid(t->Map.key)) {
  9640. check_expr_or_type(c, &key, ie->index, t->Map.key);
  9641. } else {
  9642. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  9643. }
  9644. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  9645. if (key.mode == Addressing_Invalid) {
  9646. o->mode = Addressing_Invalid;
  9647. o->expr = node;
  9648. return kind;
  9649. }
  9650. o->mode = Addressing_MapIndex;
  9651. o->type = t->Map.value;
  9652. o->expr = node;
  9653. add_map_get_dependencies(c);
  9654. add_map_set_dependencies(c);
  9655. return Expr_Expr;
  9656. }
  9657. i64 max_count = -1;
  9658. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  9659. if (is_const) {
  9660. if (is_type_array(t)) {
  9661. // Okay
  9662. } else if (is_type_slice(t)) {
  9663. // Okay
  9664. } else if (is_type_enumerated_array(t)) {
  9665. // Okay
  9666. } else if (is_type_string(t)) {
  9667. // Okay
  9668. } else if (is_type_matrix(t)) {
  9669. // Okay
  9670. } else {
  9671. valid = false;
  9672. }
  9673. }
  9674. if (!valid) {
  9675. gbString str = expr_to_string(o->expr);
  9676. gbString type_str = type_to_string(o->type);
  9677. defer (gb_string_free(str));
  9678. defer (gb_string_free(type_str));
  9679. if (is_const) {
  9680. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  9681. } else {
  9682. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  9683. }
  9684. o->mode = Addressing_Invalid;
  9685. o->expr = node;
  9686. return kind;
  9687. }
  9688. if (ie->index == nullptr) {
  9689. gbString str = expr_to_string(o->expr);
  9690. error(o->expr, "Missing index for '%s'", str);
  9691. gb_string_free(str);
  9692. o->mode = Addressing_Invalid;
  9693. o->expr = node;
  9694. return kind;
  9695. }
  9696. Type *index_type_hint = nullptr;
  9697. if (is_type_enumerated_array(t)) {
  9698. Type *bt = base_type(t);
  9699. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  9700. index_type_hint = bt->EnumeratedArray.index;
  9701. }
  9702. i64 index = 0;
  9703. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  9704. if (is_const) {
  9705. if (index < 0) {
  9706. ERROR_BLOCK();
  9707. gbString str = expr_to_string(o->expr);
  9708. error(o->expr, "Cannot index a constant '%s'", str);
  9709. if (!build_context.terse_errors) {
  9710. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9711. }
  9712. gb_string_free(str);
  9713. o->mode = Addressing_Invalid;
  9714. o->expr = node;
  9715. return kind;
  9716. } else if (ok && !is_type_matrix(t)) {
  9717. TypeAndValue tav = type_and_value_of_expr(ie->expr);
  9718. ExactValue value = tav.value;
  9719. o->mode = Addressing_Constant;
  9720. bool success = false;
  9721. bool finish = false;
  9722. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  9723. if (!success) {
  9724. ERROR_BLOCK();
  9725. gbString str = expr_to_string(o->expr);
  9726. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  9727. if (!build_context.terse_errors) {
  9728. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9729. }
  9730. gb_string_free(str);
  9731. o->mode = Addressing_Invalid;
  9732. o->expr = node;
  9733. return kind;
  9734. }
  9735. }
  9736. }
  9737. if (type_hint != nullptr && is_type_matrix(t)) {
  9738. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  9739. // if a type hint exists
  9740. }
  9741. return kind;
  9742. }
  9743. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9744. ExprKind kind = Expr_Stmt;
  9745. ast_node(se, SliceExpr, node);
  9746. check_expr(c, o, se->expr);
  9747. node->viral_state_flags |= se->expr->viral_state_flags;
  9748. if (o->mode == Addressing_Invalid) {
  9749. o->mode = Addressing_Invalid;
  9750. o->expr = node;
  9751. return kind;
  9752. }
  9753. bool valid = false;
  9754. i64 max_count = -1;
  9755. Type *t = base_type(type_deref(o->type));
  9756. switch (t->kind) {
  9757. case Type_Basic:
  9758. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  9759. valid = true;
  9760. if (o->mode == Addressing_Constant) {
  9761. GB_ASSERT(o->value.kind == ExactValue_String);
  9762. max_count = o->value.value_string.len;
  9763. }
  9764. o->type = type_deref(o->type);
  9765. } else if (t->Basic.kind == Basic_string16) {
  9766. valid = true;
  9767. if (o->mode == Addressing_Constant) {
  9768. GB_ASSERT(o->value.kind == ExactValue_String16);
  9769. max_count = o->value.value_string16.len;
  9770. }
  9771. o->type = type_deref(o->type);
  9772. }
  9773. break;
  9774. case Type_Array:
  9775. valid = true;
  9776. max_count = t->Array.count;
  9777. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9778. gbString str = expr_to_string(node);
  9779. error(node, "Cannot slice array '%s', value is not addressable", str);
  9780. gb_string_free(str);
  9781. o->mode = Addressing_Invalid;
  9782. o->expr = node;
  9783. return kind;
  9784. }
  9785. o->type = alloc_type_slice(t->Array.elem);
  9786. break;
  9787. case Type_MultiPointer:
  9788. valid = true;
  9789. o->type = type_deref(o->type);
  9790. break;
  9791. case Type_Slice:
  9792. valid = true;
  9793. o->type = type_deref(o->type);
  9794. break;
  9795. case Type_DynamicArray:
  9796. valid = true;
  9797. o->type = alloc_type_slice(t->DynamicArray.elem);
  9798. break;
  9799. case Type_Struct:
  9800. if (is_type_soa_struct(t)) {
  9801. valid = true;
  9802. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9803. max_count = t->Struct.soa_count;
  9804. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9805. gbString str = expr_to_string(node);
  9806. error(node, "Cannot slice #soa array '%s', value is not addressable", str);
  9807. gb_string_free(str);
  9808. o->mode = Addressing_Invalid;
  9809. o->expr = node;
  9810. return kind;
  9811. }
  9812. }
  9813. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  9814. }
  9815. break;
  9816. case Type_EnumeratedArray:
  9817. {
  9818. gbString str = expr_to_string(o->expr);
  9819. gbString type_str = type_to_string(o->type);
  9820. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  9821. gb_string_free(type_str);
  9822. gb_string_free(str);
  9823. o->mode = Addressing_Invalid;
  9824. o->expr = node;
  9825. return kind;
  9826. }
  9827. break;
  9828. }
  9829. if (!valid) {
  9830. gbString str = expr_to_string(o->expr);
  9831. gbString type_str = type_to_string(o->type);
  9832. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  9833. gb_string_free(type_str);
  9834. gb_string_free(str);
  9835. o->mode = Addressing_Invalid;
  9836. o->expr = node;
  9837. return kind;
  9838. }
  9839. if (se->low == nullptr && se->high != nullptr) {
  9840. // It is okay to continue as it will assume the 1st index is zero
  9841. }
  9842. i64 indices[2] = {};
  9843. Ast *nodes[2] = {se->low, se->high};
  9844. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9845. i64 index = max_count;
  9846. if (nodes[i] != nullptr) {
  9847. i64 capacity = -1;
  9848. if (max_count >= 0) {
  9849. capacity = max_count;
  9850. }
  9851. i64 j = 0;
  9852. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  9853. index = j;
  9854. }
  9855. node->viral_state_flags |= nodes[i]->viral_state_flags;
  9856. } else if (i == 0) {
  9857. index = 0;
  9858. }
  9859. indices[i] = index;
  9860. }
  9861. for (isize i = 0; i < gb_count_of(indices); i++) {
  9862. i64 a = indices[i];
  9863. for (isize j = i+1; j < gb_count_of(indices); j++) {
  9864. i64 b = indices[j];
  9865. if (a > b && b >= 0) {
  9866. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  9867. }
  9868. }
  9869. }
  9870. if (max_count < 0) {
  9871. if (o->mode == Addressing_Constant) {
  9872. gbString s = expr_to_string(se->expr);
  9873. error(se->expr, "Cannot slice constant value '%s'", s);
  9874. gb_string_free(s);
  9875. }
  9876. }
  9877. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  9878. /*
  9879. x[:] -> [^]T
  9880. x[i:] -> [^]T
  9881. x[:n] -> []T
  9882. x[i:n] -> []T
  9883. */
  9884. o->type = alloc_type_slice(t->MultiPointer.elem);
  9885. }
  9886. o->mode = Addressing_Value;
  9887. if (is_type_string(t) && max_count >= 0) {
  9888. bool all_constant = true;
  9889. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9890. if (nodes[i] != nullptr) {
  9891. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  9892. if (tav.mode != Addressing_Constant) {
  9893. all_constant = false;
  9894. break;
  9895. }
  9896. }
  9897. }
  9898. if (!all_constant) {
  9899. ERROR_BLOCK();
  9900. gbString str = expr_to_string(o->expr);
  9901. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  9902. if (!build_context.terse_errors) {
  9903. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9904. }
  9905. gb_string_free(str);
  9906. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  9907. o->expr = node;
  9908. return kind;
  9909. }
  9910. o->mode = Addressing_Constant;
  9911. o->type = t;
  9912. if (o->value.kind == ExactValue_String16) {
  9913. String16 s = o->value.value_string16;
  9914. o->value = exact_value_string16(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9915. } else {
  9916. String s = {};
  9917. if (o->value.kind == ExactValue_String) {
  9918. s = o->value.value_string;
  9919. }
  9920. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9921. }
  9922. }
  9923. return kind;
  9924. }
  9925. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9926. u32 prev_state_flags = c->state_flags;
  9927. defer (c->state_flags = prev_state_flags);
  9928. if (node->state_flags != 0) {
  9929. u32 in = node->state_flags;
  9930. u32 out = c->state_flags;
  9931. if (in & StateFlag_no_bounds_check) {
  9932. out |= StateFlag_no_bounds_check;
  9933. out &= ~StateFlag_bounds_check;
  9934. } else if (in & StateFlag_bounds_check) {
  9935. out |= StateFlag_bounds_check;
  9936. out &= ~StateFlag_no_bounds_check;
  9937. }
  9938. if (in & StateFlag_no_type_assert) {
  9939. out |= StateFlag_no_type_assert;
  9940. out &= ~StateFlag_type_assert;
  9941. } else if (in & StateFlag_type_assert) {
  9942. out |= StateFlag_type_assert;
  9943. out &= ~StateFlag_no_type_assert;
  9944. }
  9945. c->state_flags = out;
  9946. }
  9947. ExprKind kind = Expr_Stmt;
  9948. o->mode = Addressing_Invalid;
  9949. o->type = t_invalid;
  9950. o->value = {ExactValue_Invalid};
  9951. switch (node->kind) {
  9952. default:
  9953. return kind;
  9954. case_ast_node(be, BadExpr, node)
  9955. return kind;
  9956. case_end;
  9957. case_ast_node(i, Implicit, node);
  9958. switch (i->kind) {
  9959. case Token_context:
  9960. {
  9961. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  9962. error(node, "'context' is only allowed within procedures");
  9963. return kind;
  9964. }
  9965. if (unparen_expr(c->assignment_lhs_hint) == node) {
  9966. c->scope->flags |= ScopeFlag_ContextDefined;
  9967. }
  9968. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  9969. error(node, "'context' has not been defined within this scope");
  9970. // Continue with value
  9971. }
  9972. init_core_context(c->checker);
  9973. o->mode = Addressing_Context;
  9974. o->type = t_context;
  9975. }
  9976. break;
  9977. default:
  9978. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  9979. return kind;
  9980. }
  9981. case_end;
  9982. case_ast_node(i, Ident, node);
  9983. check_ident(c, o, node, nullptr, type_hint, false);
  9984. case_end;
  9985. case_ast_node(u, Uninit, node);
  9986. o->mode = Addressing_Value;
  9987. o->type = t_untyped_uninit;
  9988. error(node, "Global variables will always be zeroed if left unassigned, --- is disallowed");
  9989. case_end;
  9990. case_ast_node(bl, BasicLit, node);
  9991. Type *t = t_invalid;
  9992. switch (node->tav.value.kind) {
  9993. case ExactValue_String: t = t_untyped_string; break;
  9994. case ExactValue_String16: t = t_string16; break; // TODO(bill): determine this correctly
  9995. case ExactValue_Float: t = t_untyped_float; break;
  9996. case ExactValue_Complex: t = t_untyped_complex; break;
  9997. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  9998. case ExactValue_Integer:
  9999. t = t_untyped_integer;
  10000. if (bl->token.kind == Token_Rune) {
  10001. t = t_untyped_rune;
  10002. }
  10003. break;
  10004. default:
  10005. GB_PANIC("Unhandled value type for basic literal");
  10006. break;
  10007. }
  10008. o->mode = Addressing_Constant;
  10009. o->type = t;
  10010. o->value = node->tav.value;
  10011. case_end;
  10012. case_ast_node(bd, BasicDirective, node);
  10013. kind = check_basic_directive_expr(c, o, node, type_hint);
  10014. case_end;
  10015. case_ast_node(pg, ProcGroup, node);
  10016. error(node, "Illegal use of a procedure group");
  10017. o->mode = Addressing_Invalid;
  10018. case_end;
  10019. case_ast_node(pl, ProcLit, node);
  10020. CheckerContext ctx = *c;
  10021. DeclInfo *decl = nullptr;
  10022. Type *type = alloc_type(Type_Proc);
  10023. check_open_scope(&ctx, pl->type);
  10024. {
  10025. decl = make_decl_info(ctx.scope, ctx.decl);
  10026. decl->proc_lit = node;
  10027. ctx.decl = decl;
  10028. defer (ctx.decl = ctx.decl->parent);
  10029. if (pl->tags != 0) {
  10030. error(node, "A procedure literal cannot have tags");
  10031. pl->tags = 0; // TODO(bill): Should I zero this?!
  10032. }
  10033. check_procedure_type(&ctx, type, pl->type);
  10034. if (!is_type_proc(type)) {
  10035. gbString str = expr_to_string(node);
  10036. error(node, "Invalid procedure literal '%s'", str);
  10037. gb_string_free(str);
  10038. check_close_scope(&ctx);
  10039. return kind;
  10040. }
  10041. if (pl->body == nullptr) {
  10042. error(node, "A procedure literal must have a body");
  10043. return kind;
  10044. }
  10045. pl->decl = decl;
  10046. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  10047. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  10048. array_add(&ctx.checker->nested_proc_lits, decl);
  10049. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  10050. }
  10051. check_close_scope(&ctx);
  10052. o->mode = Addressing_Value;
  10053. o->type = type;
  10054. o->value = exact_value_procedure(node);
  10055. case_end;
  10056. case_ast_node(te, TernaryIfExpr, node);
  10057. kind = check_ternary_if_expr(c, o, node, type_hint);
  10058. case_end;
  10059. case_ast_node(te, TernaryWhenExpr, node);
  10060. kind = check_ternary_when_expr(c, o, node, type_hint);
  10061. case_end;
  10062. case_ast_node(oe, OrElseExpr, node);
  10063. return check_or_else_expr(c, o, node, type_hint);
  10064. case_end;
  10065. case_ast_node(re, OrReturnExpr, node);
  10066. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  10067. return check_or_return_expr(c, o, node, type_hint);
  10068. case_end;
  10069. case_ast_node(re, OrBranchExpr, node);
  10070. return check_or_branch_expr(c, o, node, type_hint);
  10071. case_end;
  10072. case_ast_node(cl, CompoundLit, node);
  10073. kind = check_compound_literal(c, o, node, type_hint);
  10074. case_end;
  10075. case_ast_node(pe, ParenExpr, node);
  10076. kind = check_expr_base(c, o, pe->expr, type_hint);
  10077. node->viral_state_flags |= pe->expr->viral_state_flags;
  10078. o->expr = node;
  10079. case_end;
  10080. case_ast_node(te, TagExpr, node);
  10081. String name = te->name.string;
  10082. error(node, "Unknown tag expression, #%.*s", LIT(name));
  10083. if (te->expr) {
  10084. kind = check_expr_base(c, o, te->expr, type_hint);
  10085. node->viral_state_flags |= te->expr->viral_state_flags;
  10086. }
  10087. o->expr = node;
  10088. case_end;
  10089. case_ast_node(ta, TypeAssertion, node);
  10090. kind = check_type_assertion(c, o, node, type_hint);
  10091. case_end;
  10092. case_ast_node(tc, TypeCast, node);
  10093. check_expr_or_type(c, o, tc->type);
  10094. if (o->mode != Addressing_Type) {
  10095. gbString str = expr_to_string(tc->type);
  10096. error(tc->type, "Expected a type, got %s", str);
  10097. gb_string_free(str);
  10098. o->mode = Addressing_Invalid;
  10099. }
  10100. if (o->mode == Addressing_Invalid) {
  10101. o->expr = node;
  10102. return kind;
  10103. }
  10104. Type *type = o->type;
  10105. check_expr_base(c, o, tc->expr, type);
  10106. node->viral_state_flags |= tc->expr->viral_state_flags;
  10107. if (o->mode != Addressing_Invalid) {
  10108. switch (tc->token.kind) {
  10109. case Token_transmute:
  10110. check_transmute(c, node, o, type, true);
  10111. break;
  10112. case Token_cast:
  10113. check_cast(c, o, type, true);
  10114. break;
  10115. default:
  10116. error(node, "Invalid AST: Invalid casting expression");
  10117. o->mode = Addressing_Invalid;
  10118. break;
  10119. }
  10120. }
  10121. return Expr_Expr;
  10122. case_end;
  10123. case_ast_node(ac, AutoCast, node);
  10124. check_expr_base(c, o, ac->expr, type_hint);
  10125. node->viral_state_flags |= ac->expr->viral_state_flags;
  10126. if (o->mode == Addressing_Invalid) {
  10127. o->expr = node;
  10128. return kind;
  10129. }
  10130. if (type_hint) {
  10131. check_cast(c, o, type_hint);
  10132. }
  10133. o->expr = node;
  10134. return Expr_Expr;
  10135. case_end;
  10136. case_ast_node(ue, UnaryExpr, node);
  10137. Type *th = type_hint;
  10138. if (ue->op.kind == Token_And) {
  10139. th = type_deref(th);
  10140. }
  10141. check_expr_base(c, o, ue->expr, th);
  10142. node->viral_state_flags |= ue->expr->viral_state_flags;
  10143. if (o->mode != Addressing_Invalid) {
  10144. check_unary_expr(c, o, ue->op, node);
  10145. }
  10146. o->expr = node;
  10147. return Expr_Expr;
  10148. case_end;
  10149. case_ast_node(be, BinaryExpr, node);
  10150. check_binary_expr(c, o, node, type_hint, true);
  10151. if (o->mode == Addressing_Invalid) {
  10152. o->expr = node;
  10153. return kind;
  10154. }
  10155. case_end;
  10156. case_ast_node(se, SelectorExpr, node);
  10157. check_selector(c, o, node, type_hint);
  10158. node->viral_state_flags |= se->expr->viral_state_flags;
  10159. case_end;
  10160. case_ast_node(se, SelectorCallExpr, node);
  10161. return check_selector_call_expr(c, o, node, type_hint);
  10162. case_end;
  10163. case_ast_node(ise, ImplicitSelectorExpr, node);
  10164. return check_implicit_selector_expr(c, o, node, type_hint);
  10165. case_end;
  10166. case_ast_node(ie, IndexExpr, node);
  10167. kind = check_index_expr(c, o, node, type_hint);
  10168. case_end;
  10169. case_ast_node(se, SliceExpr, node);
  10170. kind = check_slice_expr(c, o, node, type_hint);
  10171. case_end;
  10172. case_ast_node(mie, MatrixIndexExpr, node);
  10173. check_matrix_index_expr(c, o, node, type_hint);
  10174. o->expr = node;
  10175. return Expr_Expr;
  10176. case_end;
  10177. case_ast_node(ce, CallExpr, node);
  10178. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  10179. case_end;
  10180. case_ast_node(de, DerefExpr, node);
  10181. check_expr_or_type(c, o, de->expr);
  10182. node->viral_state_flags |= de->expr->viral_state_flags;
  10183. if (o->mode == Addressing_Invalid) {
  10184. o->mode = Addressing_Invalid;
  10185. o->expr = node;
  10186. return kind;
  10187. } else if (o->mode == Addressing_Type) {
  10188. gbString str = expr_to_string(o->expr);
  10189. error(o->expr, "Cannot dereference '%s' because it is a type", str);
  10190. o->mode = Addressing_Invalid;
  10191. o->expr = node;
  10192. return kind;
  10193. } else {
  10194. Type *t = base_type(o->type);
  10195. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  10196. o->mode = Addressing_Variable;
  10197. o->type = t->Pointer.elem;
  10198. } else if (t->kind == Type_SoaPointer) {
  10199. o->mode = Addressing_SoaVariable;
  10200. o->type = type_deref(t);
  10201. } else {
  10202. gbString str = expr_to_string(o->expr);
  10203. gbString typ = type_to_string(o->type);
  10204. ERROR_BLOCK();
  10205. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  10206. if (o->type && is_type_multi_pointer(o->type)) {
  10207. if (!build_context.terse_errors) {
  10208. error_line("\tDid you mean '%s[0]'?\n", str);
  10209. }
  10210. }
  10211. gb_string_free(typ);
  10212. gb_string_free(str);
  10213. o->mode = Addressing_Invalid;
  10214. o->expr = node;
  10215. return kind;
  10216. }
  10217. }
  10218. case_end;
  10219. case_ast_node(ia, InlineAsmExpr, node);
  10220. if (c->curr_proc_decl == nullptr) {
  10221. error(node, "Inline asm expressions are only allowed within a procedure body");
  10222. }
  10223. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  10224. Type *return_type = nullptr;
  10225. for_array(i, ia->param_types) {
  10226. param_types[i] = check_type(c, ia->param_types[i]);
  10227. }
  10228. if (ia->return_type != nullptr) {
  10229. return_type = check_type(c, ia->return_type);
  10230. }
  10231. Operand x = {};
  10232. check_expr(c, &x, ia->asm_string);
  10233. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  10234. error(x.expr, "Expected a constant string for the inline asm main parameter");
  10235. }
  10236. check_expr(c, &x, ia->constraints_string);
  10237. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  10238. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  10239. }
  10240. Scope *scope = create_scope(c->info, c->scope);
  10241. scope->flags |= ScopeFlag_Proc;
  10242. Type *params = alloc_type_tuple();
  10243. Type *results = alloc_type_tuple();
  10244. if (param_types.count != 0) {
  10245. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  10246. for_array(i, param_types) {
  10247. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  10248. }
  10249. }
  10250. if (return_type != nullptr) {
  10251. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  10252. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  10253. }
  10254. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  10255. o->type = pt;
  10256. o->mode = Addressing_Value;
  10257. o->expr = node;
  10258. return Expr_Expr;
  10259. case_end;
  10260. case Ast_DistinctType:
  10261. case Ast_TypeidType:
  10262. case Ast_PolyType:
  10263. case Ast_ProcType:
  10264. case Ast_PointerType:
  10265. case Ast_MultiPointerType:
  10266. case Ast_ArrayType:
  10267. case Ast_DynamicArrayType:
  10268. case Ast_StructType:
  10269. case Ast_UnionType:
  10270. case Ast_EnumType:
  10271. case Ast_MapType:
  10272. case Ast_BitSetType:
  10273. case Ast_MatrixType:
  10274. case Ast_RelativeType:
  10275. o->mode = Addressing_Type;
  10276. o->type = check_type(c, node);
  10277. break;
  10278. }
  10279. kind = Expr_Expr;
  10280. o->expr = node;
  10281. return kind;
  10282. }
  10283. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  10284. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  10285. if (o->type != nullptr && core_type(o->type) == nullptr) {
  10286. o->type = t_invalid;
  10287. gbString xs = expr_to_string(o->expr);
  10288. if (o->mode == Addressing_Type) {
  10289. error(o->expr, "Invalid type usage '%s'", xs);
  10290. } else {
  10291. error(o->expr, "Invalid expression '%s'", xs);
  10292. }
  10293. gb_string_free(xs);
  10294. }
  10295. if (o->type != nullptr && is_type_untyped(o->type)) {
  10296. add_untyped(c, node, o->mode, o->type, o->value);
  10297. }
  10298. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  10299. add_type_and_value(c, node, o->mode, o->type, o->value);
  10300. return kind;
  10301. }
  10302. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  10303. check_expr_base(c, o, e, nullptr);
  10304. switch (o->mode) {
  10305. default:
  10306. return; // NOTE(bill): Valid
  10307. case Addressing_NoValue:
  10308. error_operand_no_value(o);
  10309. break;
  10310. }
  10311. o->mode = Addressing_Invalid;
  10312. }
  10313. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  10314. check_expr_base(c, o, e, nullptr);
  10315. switch (o->mode) {
  10316. default:
  10317. return; // NOTE(bill): Valid
  10318. case Addressing_NoValue:
  10319. error_operand_no_value(o);
  10320. break;
  10321. case Addressing_Type:
  10322. error_operand_not_expression(o);
  10323. break;
  10324. }
  10325. o->mode = Addressing_Invalid;
  10326. }
  10327. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10328. check_expr_base(c, o, e, type_hint);
  10329. switch (o->mode) {
  10330. default:
  10331. return; // NOTE(bill): Valid
  10332. case Addressing_NoValue:
  10333. error_operand_no_value(o);
  10334. break;
  10335. case Addressing_Type:
  10336. error_operand_not_expression(o);
  10337. break;
  10338. }
  10339. o->mode = Addressing_Invalid;
  10340. }
  10341. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  10342. if (o->mode == Addressing_Value) {
  10343. // NOTE(bill): Tuples are not first class thus never named
  10344. if (o->type->kind == Type_Tuple) {
  10345. isize count = o->type->Tuple.variables.count;
  10346. error(o->expr,
  10347. "%td-valued expression found where single value expected", count);
  10348. o->mode = Addressing_Invalid;
  10349. GB_ASSERT(count != 1);
  10350. }
  10351. }
  10352. }
  10353. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  10354. check_multi_expr(c, o, e);
  10355. check_not_tuple(c, o);
  10356. }
  10357. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10358. check_expr_base(c, o, e, type_hint);
  10359. check_not_tuple(c, o);
  10360. error_operand_no_value(o);
  10361. }
  10362. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  10363. switch (v.kind) {
  10364. case ExactValue_Invalid:
  10365. return true;
  10366. case ExactValue_Bool:
  10367. return !v.value_bool;
  10368. case ExactValue_String:
  10369. return v.value_string.len == 0;
  10370. case ExactValue_String16:
  10371. return v.value_string16.len == 0;
  10372. case ExactValue_Integer:
  10373. return big_int_is_zero(&v.value_integer);
  10374. case ExactValue_Float:
  10375. return v.value_float == 0.0;
  10376. case ExactValue_Complex:
  10377. if (v.value_complex) {
  10378. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  10379. }
  10380. return true;
  10381. case ExactValue_Quaternion:
  10382. if (v.value_quaternion) {
  10383. return v.value_quaternion->real == 0.0 &&
  10384. v.value_quaternion->imag == 0.0 &&
  10385. v.value_quaternion->jmag == 0.0 &&
  10386. v.value_quaternion->kmag == 0.0;
  10387. }
  10388. return true;
  10389. case ExactValue_Pointer:
  10390. return v.value_pointer == 0;
  10391. case ExactValue_Compound:
  10392. if (v.value_compound == nullptr) {
  10393. return true;
  10394. } else {
  10395. ast_node(cl, CompoundLit, v.value_compound);
  10396. if (cl->elems.count == 0) {
  10397. return true;
  10398. } else {
  10399. for (Ast *elem : cl->elems) {
  10400. if (elem->tav.mode != Addressing_Constant) {
  10401. return false;
  10402. }
  10403. if (!is_exact_value_zero(elem->tav.value)) {
  10404. return false;
  10405. }
  10406. }
  10407. return true;
  10408. }
  10409. }
  10410. case ExactValue_Procedure:
  10411. return v.value_procedure == nullptr;
  10412. case ExactValue_Typeid:
  10413. return v.value_typeid == nullptr;
  10414. }
  10415. return true;
  10416. }
  10417. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  10418. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  10419. for_array(i, params) {
  10420. if (i > 0) {
  10421. str = gb_string_appendc(str, ", ");
  10422. }
  10423. str = write_expr_to_string(str, params[i], false);
  10424. }
  10425. return str;
  10426. }
  10427. gb_internal gbString string_append_string(gbString str, String string) {
  10428. if (string.len > 0) {
  10429. return gb_string_append_length(str, &string[0], string.len);
  10430. }
  10431. return str;
  10432. }
  10433. gb_internal gbString string_append_token(gbString str, Token token) {
  10434. str = string_append_string(str, token.string);
  10435. return str;
  10436. }
  10437. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  10438. if (node == nullptr)
  10439. return str;
  10440. if (is_ast_stmt(node)) {
  10441. GB_ASSERT("stmt passed to write_expr_to_string");
  10442. }
  10443. switch (node->kind) {
  10444. default:
  10445. str = gb_string_appendc(str, "(BadExpr)");
  10446. break;
  10447. case_ast_node(i, Ident, node);
  10448. str = string_append_token(str, i->token);
  10449. case_end;
  10450. case_ast_node(i, Implicit, node);
  10451. str = string_append_token(str, *i);
  10452. case_end;
  10453. case_ast_node(bl, BasicLit, node);
  10454. str = string_append_token(str, bl->token);
  10455. case_end;
  10456. case_ast_node(bd, BasicDirective, node);
  10457. str = gb_string_append_rune(str, '#');
  10458. str = string_append_string(str, bd->name.string);
  10459. case_end;
  10460. case_ast_node(ud, Uninit, node);
  10461. str = gb_string_appendc(str, "---");
  10462. case_end;
  10463. case_ast_node(pg, ProcGroup, node);
  10464. str = gb_string_appendc(str, "proc{");
  10465. for_array(i, pg->args) {
  10466. if (i > 0) str = gb_string_appendc(str, ", ");
  10467. str = write_expr_to_string(str, pg->args[i], shorthand);
  10468. }
  10469. str = gb_string_append_rune(str, '}');
  10470. case_end;
  10471. case_ast_node(pl, ProcLit, node);
  10472. str = write_expr_to_string(str, pl->type, shorthand);
  10473. if (pl->body) {
  10474. str = gb_string_appendc(str, " {...}");
  10475. } else {
  10476. str = gb_string_appendc(str, " ---");
  10477. }
  10478. case_end;
  10479. case_ast_node(cl, CompoundLit, node);
  10480. str = write_expr_to_string(str, cl->type, shorthand);
  10481. str = gb_string_append_rune(str, '{');
  10482. if (shorthand) {
  10483. str = gb_string_appendc(str, "...");
  10484. } else {
  10485. for_array(i, cl->elems) {
  10486. if (i > 0) str = gb_string_appendc(str, ", ");
  10487. str = write_expr_to_string(str, cl->elems[i], shorthand);
  10488. }
  10489. }
  10490. str = gb_string_append_rune(str, '}');
  10491. case_end;
  10492. case_ast_node(te, TagExpr, node);
  10493. str = gb_string_append_rune(str, '#');
  10494. str = string_append_token(str, te->name);
  10495. str = write_expr_to_string(str, te->expr, shorthand);
  10496. case_end;
  10497. case_ast_node(ue, UnaryExpr, node);
  10498. str = string_append_token(str, ue->op);
  10499. str = write_expr_to_string(str, ue->expr, shorthand);
  10500. case_end;
  10501. case_ast_node(de, DerefExpr, node);
  10502. str = write_expr_to_string(str, de->expr, shorthand);
  10503. str = gb_string_append_rune(str, '^');
  10504. case_end;
  10505. case_ast_node(be, BinaryExpr, node);
  10506. str = write_expr_to_string(str, be->left, shorthand);
  10507. str = gb_string_append_rune(str, ' ');
  10508. str = string_append_token(str, be->op);
  10509. str = gb_string_append_rune(str, ' ');
  10510. str = write_expr_to_string(str, be->right, shorthand);
  10511. case_end;
  10512. case_ast_node(te, TernaryIfExpr, node);
  10513. TokenPos x = ast_token(te->x).pos;
  10514. TokenPos cond = ast_token(te->cond).pos;
  10515. if (x < cond) {
  10516. str = write_expr_to_string(str, te->x, shorthand);
  10517. str = gb_string_appendc(str, " if ");
  10518. str = write_expr_to_string(str, te->cond, shorthand);
  10519. str = gb_string_appendc(str, " else ");
  10520. str = write_expr_to_string(str, te->y, shorthand);
  10521. } else {
  10522. str = write_expr_to_string(str, te->cond, shorthand);
  10523. str = gb_string_appendc(str, " ? ");
  10524. str = write_expr_to_string(str, te->x, shorthand);
  10525. str = gb_string_appendc(str, " : ");
  10526. str = write_expr_to_string(str, te->y, shorthand);
  10527. }
  10528. case_end;
  10529. case_ast_node(te, TernaryWhenExpr, node);
  10530. str = write_expr_to_string(str, te->x, shorthand);
  10531. str = gb_string_appendc(str, " when ");
  10532. str = write_expr_to_string(str, te->cond, shorthand);
  10533. str = gb_string_appendc(str, " else ");
  10534. str = write_expr_to_string(str, te->y, shorthand);
  10535. case_end;
  10536. case_ast_node(oe, OrElseExpr, node);
  10537. str = write_expr_to_string(str, oe->x, shorthand);
  10538. str = gb_string_appendc(str, " or_else ");
  10539. str = write_expr_to_string(str, oe->y, shorthand);
  10540. case_end;
  10541. case_ast_node(oe, OrReturnExpr, node);
  10542. str = write_expr_to_string(str, oe->expr, shorthand);
  10543. str = gb_string_appendc(str, " or_return");
  10544. case_end;
  10545. case_ast_node(oe, OrBranchExpr, node);
  10546. str = write_expr_to_string(str, oe->expr, shorthand);
  10547. str = gb_string_append_rune(str, ' ');
  10548. str = string_append_token(str, oe->token);
  10549. if (oe->label) {
  10550. str = gb_string_append_rune(str, ' ');
  10551. str = write_expr_to_string(str, oe->label, shorthand);
  10552. }
  10553. case_end;
  10554. case_ast_node(pe, ParenExpr, node);
  10555. str = gb_string_append_rune(str, '(');
  10556. str = write_expr_to_string(str, pe->expr, shorthand);
  10557. str = gb_string_append_rune(str, ')');
  10558. case_end;
  10559. case_ast_node(se, SelectorExpr, node);
  10560. str = write_expr_to_string(str, se->expr, shorthand);
  10561. str = string_append_token(str, se->token);
  10562. str = write_expr_to_string(str, se->selector, shorthand);
  10563. case_end;
  10564. case_ast_node(se, ImplicitSelectorExpr, node);
  10565. str = gb_string_append_rune(str, '.');
  10566. str = write_expr_to_string(str, se->selector, shorthand);
  10567. case_end;
  10568. case_ast_node(se, SelectorCallExpr, node);
  10569. str = write_expr_to_string(str, se->expr, shorthand);
  10570. str = gb_string_appendc(str, "(");
  10571. ast_node(ce, CallExpr, se->call);
  10572. isize start = se->modified_call ? 1 : 0;
  10573. for (isize i = start; i < ce->args.count; i++) {
  10574. Ast *arg = ce->args[i];
  10575. if (i > start) {
  10576. str = gb_string_appendc(str, ", ");
  10577. }
  10578. str = write_expr_to_string(str, arg, shorthand);
  10579. }
  10580. str = gb_string_appendc(str, ")");
  10581. case_end;
  10582. case_ast_node(ta, TypeAssertion, node);
  10583. str = write_expr_to_string(str, ta->expr, shorthand);
  10584. if (ta->type != nullptr &&
  10585. ta->type->kind == Ast_UnaryExpr &&
  10586. ta->type->UnaryExpr.op.kind == Token_Question) {
  10587. str = gb_string_appendc(str, ".?");
  10588. } else {
  10589. str = gb_string_appendc(str, ".(");
  10590. str = write_expr_to_string(str, ta->type, shorthand);
  10591. str = gb_string_append_rune(str, ')');
  10592. }
  10593. case_end;
  10594. case_ast_node(tc, TypeCast, node);
  10595. str = string_append_token(str, tc->token);
  10596. str = gb_string_append_rune(str, '(');
  10597. str = write_expr_to_string(str, tc->type, shorthand);
  10598. str = gb_string_append_rune(str, ')');
  10599. str = write_expr_to_string(str, tc->expr, shorthand);
  10600. case_end;
  10601. case_ast_node(ac, AutoCast, node);
  10602. str = string_append_token(str, ac->token);
  10603. str = gb_string_append_rune(str, ' ');
  10604. str = write_expr_to_string(str, ac->expr, shorthand);
  10605. case_end;
  10606. case_ast_node(ie, IndexExpr, node);
  10607. str = write_expr_to_string(str, ie->expr, shorthand);
  10608. str = gb_string_append_rune(str, '[');
  10609. str = write_expr_to_string(str, ie->index, shorthand);
  10610. str = gb_string_append_rune(str, ']');
  10611. case_end;
  10612. case_ast_node(se, SliceExpr, node);
  10613. str = write_expr_to_string(str, se->expr, shorthand);
  10614. str = gb_string_append_rune(str, '[');
  10615. str = write_expr_to_string(str, se->low, shorthand);
  10616. str = string_append_token(str, se->interval);
  10617. str = write_expr_to_string(str, se->high, shorthand);
  10618. str = gb_string_append_rune(str, ']');
  10619. case_end;
  10620. case_ast_node(mie, MatrixIndexExpr, node);
  10621. str = write_expr_to_string(str, mie->expr, shorthand);
  10622. str = gb_string_append_rune(str, '[');
  10623. str = write_expr_to_string(str, mie->row_index, shorthand);
  10624. str = gb_string_appendc(str, ", ");
  10625. str = write_expr_to_string(str, mie->column_index, shorthand);
  10626. str = gb_string_append_rune(str, ']');
  10627. case_end;
  10628. case_ast_node(e, Ellipsis, node);
  10629. str = gb_string_appendc(str, "..");
  10630. str = write_expr_to_string(str, e->expr, shorthand);
  10631. case_end;
  10632. case_ast_node(fv, FieldValue, node);
  10633. str = write_expr_to_string(str, fv->field, shorthand);
  10634. str = gb_string_appendc(str, " = ");
  10635. str = write_expr_to_string(str, fv->value, shorthand);
  10636. case_end;
  10637. case_ast_node(fv, EnumFieldValue, node);
  10638. str = write_expr_to_string(str, fv->name, shorthand);
  10639. if (fv->value) {
  10640. str = gb_string_appendc(str, " = ");
  10641. str = write_expr_to_string(str, fv->value, shorthand);
  10642. }
  10643. case_end;
  10644. case_ast_node(ht, HelperType, node);
  10645. str = gb_string_appendc(str, "#type ");
  10646. str = write_expr_to_string(str, ht->type, shorthand);
  10647. case_end;
  10648. case_ast_node(ht, DistinctType, node);
  10649. str = gb_string_appendc(str, "distinct ");
  10650. str = write_expr_to_string(str, ht->type, shorthand);
  10651. case_end;
  10652. case_ast_node(pt, PolyType, node);
  10653. str = gb_string_append_rune(str, '$');
  10654. str = write_expr_to_string(str, pt->type, shorthand);
  10655. if (pt->specialization != nullptr) {
  10656. str = gb_string_append_rune(str, '/');
  10657. str = write_expr_to_string(str, pt->specialization, shorthand);
  10658. }
  10659. case_end;
  10660. case_ast_node(pt, PointerType, node);
  10661. if (pt->tag) {
  10662. str = write_expr_to_string(str, pt->tag, false);
  10663. }
  10664. str = gb_string_append_rune(str, '^');
  10665. str = write_expr_to_string(str, pt->type, shorthand);
  10666. case_end;
  10667. case_ast_node(pt, MultiPointerType, node);
  10668. str = gb_string_appendc(str, "[^]");
  10669. str = write_expr_to_string(str, pt->type, shorthand);
  10670. case_end;
  10671. case_ast_node(at, ArrayType, node);
  10672. if (at->tag) {
  10673. str = write_expr_to_string(str, at->tag, false);
  10674. }
  10675. str = gb_string_append_rune(str, '[');
  10676. if (at->count != nullptr &&
  10677. at->count->kind == Ast_UnaryExpr &&
  10678. at->count->UnaryExpr.op.kind == Token_Question) {
  10679. str = gb_string_appendc(str, "?");
  10680. } else {
  10681. str = write_expr_to_string(str, at->count, shorthand);
  10682. }
  10683. str = gb_string_append_rune(str, ']');
  10684. str = write_expr_to_string(str, at->elem, shorthand);
  10685. case_end;
  10686. case_ast_node(at, DynamicArrayType, node);
  10687. if (at->tag) {
  10688. str = write_expr_to_string(str, at->tag, false);
  10689. }
  10690. str = gb_string_appendc(str, "[dynamic]");
  10691. str = write_expr_to_string(str, at->elem, shorthand);
  10692. case_end;
  10693. case_ast_node(bs, BitSetType, node);
  10694. str = gb_string_appendc(str, "bit_set[");
  10695. str = write_expr_to_string(str, bs->elem, shorthand);
  10696. str = gb_string_appendc(str, "]");
  10697. case_end;
  10698. case_ast_node(mt, MapType, node);
  10699. str = gb_string_appendc(str, "map[");
  10700. str = write_expr_to_string(str, mt->key, shorthand);
  10701. str = gb_string_append_rune(str, ']');
  10702. str = write_expr_to_string(str, mt->value, shorthand);
  10703. case_end;
  10704. case_ast_node(mt, MatrixType, node);
  10705. str = gb_string_appendc(str, "matrix[");
  10706. str = write_expr_to_string(str, mt->row_count, shorthand);
  10707. str = gb_string_appendc(str, ", ");
  10708. str = write_expr_to_string(str, mt->column_count, shorthand);
  10709. str = gb_string_append_rune(str, ']');
  10710. str = write_expr_to_string(str, mt->elem, shorthand);
  10711. case_end;
  10712. case_ast_node(f, Field, node);
  10713. if (f->flags&FieldFlag_using) {
  10714. str = gb_string_appendc(str, "using ");
  10715. }
  10716. if (f->flags&FieldFlag_no_alias) {
  10717. str = gb_string_appendc(str, "#no_alias ");
  10718. }
  10719. if (f->flags&FieldFlag_c_vararg) {
  10720. str = gb_string_appendc(str, "#c_vararg ");
  10721. }
  10722. if (f->flags&FieldFlag_any_int) {
  10723. str = gb_string_appendc(str, "#any_int ");
  10724. }
  10725. if (f->flags&FieldFlag_no_broadcast) {
  10726. str = gb_string_appendc(str, "#no_broadcast ");
  10727. }
  10728. if (f->flags&FieldFlag_const) {
  10729. str = gb_string_appendc(str, "#const ");
  10730. }
  10731. if (f->flags&FieldFlag_subtype) {
  10732. str = gb_string_appendc(str, "#subtype ");
  10733. }
  10734. for_array(i, f->names) {
  10735. Ast *name = f->names[i];
  10736. if (i > 0) str = gb_string_appendc(str, ", ");
  10737. str = write_expr_to_string(str, name, shorthand);
  10738. }
  10739. if (f->names.count > 0) {
  10740. if (f->type == nullptr && f->default_value != nullptr) {
  10741. str = gb_string_append_rune(str, ' ');
  10742. }
  10743. str = gb_string_appendc(str, ":");
  10744. }
  10745. if (f->type != nullptr) {
  10746. str = gb_string_append_rune(str, ' ');
  10747. str = write_expr_to_string(str, f->type, shorthand);
  10748. }
  10749. if (f->default_value != nullptr) {
  10750. if (f->type != nullptr) {
  10751. str = gb_string_append_rune(str, ' ');
  10752. }
  10753. str = gb_string_appendc(str, "= ");
  10754. str = write_expr_to_string(str, f->default_value, shorthand);
  10755. }
  10756. case_end;
  10757. case_ast_node(f, FieldList, node);
  10758. bool has_name = false;
  10759. for_array(i, f->list) {
  10760. ast_node(field, Field, f->list[i]);
  10761. if (field->names.count > 1) {
  10762. has_name = true;
  10763. break;
  10764. }
  10765. if (field->names.count == 0) {
  10766. continue;
  10767. }
  10768. if (!is_blank_ident(field->names[0])) {
  10769. has_name = true;
  10770. break;
  10771. }
  10772. }
  10773. for_array(i, f->list) {
  10774. if (i > 0) str = gb_string_appendc(str, ", ");
  10775. if (has_name) {
  10776. str = write_expr_to_string(str, f->list[i], shorthand);
  10777. } else {
  10778. ast_node(field, Field, f->list[i]);
  10779. if (field->flags&FieldFlag_using) {
  10780. str = gb_string_appendc(str, "using ");
  10781. }
  10782. if (field->flags&FieldFlag_no_alias) {
  10783. str = gb_string_appendc(str, "#no_alias ");
  10784. }
  10785. if (field->flags&FieldFlag_c_vararg) {
  10786. str = gb_string_appendc(str, "#c_vararg ");
  10787. }
  10788. if (field->flags&FieldFlag_any_int) {
  10789. str = gb_string_appendc(str, "#any_int ");
  10790. }
  10791. if (field->flags&FieldFlag_no_broadcast) {
  10792. str = gb_string_appendc(str, "#no_broadcast ");
  10793. }
  10794. if (field->flags&FieldFlag_const) {
  10795. str = gb_string_appendc(str, "#const ");
  10796. }
  10797. if (field->flags&FieldFlag_subtype) {
  10798. str = gb_string_appendc(str, "#subtype ");
  10799. }
  10800. str = write_expr_to_string(str, field->type, shorthand);
  10801. }
  10802. }
  10803. case_end;
  10804. case_ast_node(ce, CallExpr, node);
  10805. switch (ce->inlining) {
  10806. case ProcInlining_inline:
  10807. str = gb_string_appendc(str, "#force_inline ");
  10808. break;
  10809. case ProcInlining_no_inline:
  10810. str = gb_string_appendc(str, "#force_no_inline ");
  10811. break;
  10812. }
  10813. str = write_expr_to_string(str, ce->proc, shorthand);
  10814. str = gb_string_appendc(str, "(");
  10815. isize idx0 = cast(isize)ce->was_selector;
  10816. for (isize i = idx0; i < ce->args.count; i++) {
  10817. Ast *arg = ce->args[i];
  10818. if (i > idx0) {
  10819. str = gb_string_appendc(str, ", ");
  10820. }
  10821. str = write_expr_to_string(str, arg, shorthand);
  10822. }
  10823. str = gb_string_appendc(str, ")");
  10824. case_end;
  10825. case_ast_node(tt, TypeidType, node);
  10826. str = gb_string_appendc(str, "typeid");
  10827. if (tt->specialization) {
  10828. str = gb_string_appendc(str, "/");
  10829. str = write_expr_to_string(str, tt->specialization, shorthand);
  10830. }
  10831. case_end;
  10832. case_ast_node(pt, ProcType, node);
  10833. str = gb_string_appendc(str, "proc(");
  10834. str = write_expr_to_string(str, pt->params, shorthand);
  10835. str = gb_string_appendc(str, ")");
  10836. if (pt->results != nullptr) {
  10837. str = gb_string_appendc(str, " -> ");
  10838. bool parens_needed = false;
  10839. if (pt->results && pt->results->kind == Ast_FieldList) {
  10840. for (Ast *field : pt->results->FieldList.list) {
  10841. ast_node(f, Field, field);
  10842. if (f->names.count != 0) {
  10843. parens_needed = true;
  10844. break;
  10845. }
  10846. }
  10847. }
  10848. if (parens_needed) {
  10849. str = gb_string_append_rune(str, '(');
  10850. }
  10851. str = write_expr_to_string(str, pt->results, shorthand);
  10852. if (parens_needed) {
  10853. str = gb_string_append_rune(str, ')');
  10854. }
  10855. }
  10856. case_end;
  10857. case_ast_node(st, StructType, node);
  10858. str = gb_string_appendc(str, "struct ");
  10859. if (st->polymorphic_params) {
  10860. str = gb_string_append_rune(str, '(');
  10861. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10862. str = gb_string_appendc(str, ") ");
  10863. }
  10864. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  10865. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  10866. if (st->align) {
  10867. str = gb_string_appendc(str, "#align ");
  10868. str = write_expr_to_string(str, st->align, shorthand);
  10869. str = gb_string_append_rune(str, ' ');
  10870. }
  10871. str = gb_string_append_rune(str, '{');
  10872. if (shorthand) {
  10873. str = gb_string_appendc(str, "...");
  10874. } else {
  10875. str = write_struct_fields_to_string(str, st->fields);
  10876. }
  10877. str = gb_string_append_rune(str, '}');
  10878. case_end;
  10879. case_ast_node(st, UnionType, node);
  10880. str = gb_string_appendc(str, "union ");
  10881. if (st->polymorphic_params) {
  10882. str = gb_string_append_rune(str, '(');
  10883. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10884. str = gb_string_appendc(str, ") ");
  10885. }
  10886. switch (st->kind) {
  10887. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  10888. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  10889. }
  10890. if (st->align) {
  10891. str = gb_string_appendc(str, "#align ");
  10892. str = write_expr_to_string(str, st->align, shorthand);
  10893. str = gb_string_append_rune(str, ' ');
  10894. }
  10895. str = gb_string_append_rune(str, '{');
  10896. if (shorthand) {
  10897. str = gb_string_appendc(str, "...");
  10898. } else {
  10899. str = write_struct_fields_to_string(str, st->variants);
  10900. }
  10901. str = gb_string_append_rune(str, '}');
  10902. case_end;
  10903. case_ast_node(et, EnumType, node);
  10904. str = gb_string_appendc(str, "enum ");
  10905. if (et->base_type != nullptr) {
  10906. str = write_expr_to_string(str, et->base_type, shorthand);
  10907. str = gb_string_append_rune(str, ' ');
  10908. }
  10909. str = gb_string_append_rune(str, '{');
  10910. if (shorthand) {
  10911. str = gb_string_appendc(str, "...");
  10912. } else {
  10913. for_array(i, et->fields) {
  10914. if (i > 0) {
  10915. str = gb_string_appendc(str, ", ");
  10916. }
  10917. str = write_expr_to_string(str, et->fields[i], shorthand);
  10918. }
  10919. }
  10920. str = gb_string_append_rune(str, '}');
  10921. case_end;
  10922. case_ast_node(rt, RelativeType, node);
  10923. str = write_expr_to_string(str, rt->tag, shorthand);
  10924. str = gb_string_appendc(str, "" );
  10925. str = write_expr_to_string(str, rt->type, shorthand);
  10926. case_end;
  10927. case_ast_node(f, BitFieldField, node);
  10928. str = write_expr_to_string(str, f->name, shorthand);
  10929. str = gb_string_appendc(str, ": ");
  10930. str = write_expr_to_string(str, f->type, shorthand);
  10931. str = gb_string_appendc(str, " | ");
  10932. str = write_expr_to_string(str, f->bit_size, shorthand);
  10933. case_end;
  10934. case_ast_node(bf, BitFieldType, node);
  10935. str = gb_string_appendc(str, "bit_field ");
  10936. if (!shorthand) {
  10937. str = write_expr_to_string(str, bf->backing_type, shorthand);
  10938. }
  10939. str = gb_string_appendc(str, " {");
  10940. if (shorthand) {
  10941. str = gb_string_appendc(str, "...");
  10942. } else {
  10943. for_array(i, bf->fields) {
  10944. if (i > 0) {
  10945. str = gb_string_appendc(str, ", ");
  10946. }
  10947. str = write_expr_to_string(str, bf->fields[i], false);
  10948. }
  10949. }
  10950. str = gb_string_appendc(str, "}");
  10951. case_end;
  10952. case_ast_node(ia, InlineAsmExpr, node);
  10953. str = gb_string_appendc(str, "asm(");
  10954. for_array(i, ia->param_types) {
  10955. if (i > 0) {
  10956. str = gb_string_appendc(str, ", ");
  10957. }
  10958. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  10959. }
  10960. str = gb_string_appendc(str, ")");
  10961. if (ia->return_type != nullptr) {
  10962. str = gb_string_appendc(str, " -> ");
  10963. str = write_expr_to_string(str, ia->return_type, shorthand);
  10964. }
  10965. if (ia->has_side_effects) {
  10966. str = gb_string_appendc(str, " #side_effects");
  10967. }
  10968. if (ia->is_align_stack) {
  10969. str = gb_string_appendc(str, " #stack_align");
  10970. }
  10971. if (ia->dialect) {
  10972. str = gb_string_appendc(str, " #");
  10973. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  10974. }
  10975. str = gb_string_appendc(str, " {");
  10976. if (shorthand) {
  10977. str = gb_string_appendc(str, "...");
  10978. } else {
  10979. str = write_expr_to_string(str, ia->asm_string, shorthand);
  10980. str = gb_string_appendc(str, ", ");
  10981. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  10982. }
  10983. str = gb_string_appendc(str, "}");
  10984. case_end;
  10985. }
  10986. return str;
  10987. }
  10988. gb_internal gbString expr_to_string(Ast *expression) {
  10989. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  10990. }
  10991. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  10992. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  10993. }
  10994. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  10995. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  10996. }